File size: 11,679 Bytes
a549376
3e2d9a0
 
 
7665754
3e2d9a0
8310b47
7665754
37700b8
7665754
37700b8
3e2d9a0
 
 
 
 
7665754
 
3e2d9a0
7665754
37700b8
8310b47
37700b8
8310b47
 
3e2d9a0
7665754
 
37700b8
7665754
37700b8
7665754
 
3e2d9a0
7665754
 
5726602
 
 
8310b47
5726602
 
 
 
 
8310b47
5726602
 
 
 
 
8310b47
 
5726602
 
8310b47
 
 
5726602
8310b47
5726602
 
 
 
 
 
8310b47
5726602
 
 
8310b47
5726602
8310b47
5726602
 
 
 
 
ab410e0
8310b47
 
 
3e2d9a0
 
 
 
 
 
 
 
7665754
 
3e2d9a0
 
 
 
7665754
 
ab410e0
8310b47
37700b8
3e2d9a0
 
 
145fc8a
3e2d9a0
 
 
 
 
 
 
 
 
ba4f365
3e2d9a0
7665754
 
3e2d9a0
7665754
 
37700b8
8310b47
37700b8
 
 
8310b47
37700b8
 
 
b8da832
 
 
 
 
 
8310b47
37700b8
76523a3
 
b8da832
37700b8
8310b47
 
 
 
bc30ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88eb487
8310b47
 
 
 
 
 
 
 
 
 
 
88eb487
8310b47
 
 
 
 
37700b8
7f98012
 
 
37700b8
 
 
76523a3
7f98012
 
c74f8b8
 
 
88eb487
 
c74f8b8
 
7f98012
 
c74f8b8
7f98012
 
 
 
 
 
 
 
 
 
 
 
c74f8b8
7f98012
 
c74f8b8
88eb487
7f98012
 
 
 
37700b8
fdbf1e2
 
74ae1ea
 
 
 
fdbf1e2
 
 
 
74ae1ea
fdbf1e2
74ae1ea
fdbf1e2
 
74ae1ea
 
 
 
 
0e866d9
74ae1ea
 
2b61eb9
74ae1ea
2b61eb9
fdbf1e2
37700b8
0e866d9
37700b8
3e2d9a0
 
 
 
 
 
 
 
 
37700b8
3e2d9a0
 
 
 
37700b8
 
76523a3
37700b8
cdf9147
5726602
 
077c887
 
3e2d9a0
37700b8
3e2d9a0
37700b8
 
 
3e2d9a0
 
 
37700b8
 
 
3e2d9a0
 
 
 
8310b47
3e2d9a0
 
 
 
 
 
 
 
 
 
2b61eb9
7665754
37700b8
 
 
 
 
 
8310b47
 
3e2d9a0
 
37700b8
8310b47
37700b8
8310b47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8acb4
 
8310b47
 
 
 
 
 
7665754
37700b8
 
3e2d9a0
8310b47
e65cc57
 
 
 
 
8310b47
e65cc57
 
8310b47
e65cc57
8310b47
 
3e2d9a0
2b61eb9
3e2d9a0
2b61eb9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import spaces
import os
import io
import torch
import gradio as gr
import requests
from diffusers import DiffusionPipeline, ZImagePipeline

# =========================================================
# CONFIG
# =========================================================
SCRIPTS_REPO_API = (
    "https://api.github.com/repos/asomoza/diffusers-recipes/contents/"
    "models/z-image/scripts"
)
LOCAL_SCRIPTS_DIR = "z_image_scripts"
MODEL_ID = "Tongyi-MAI/Z-Image-Turbo"

os.makedirs(LOCAL_SCRIPTS_DIR, exist_ok=True)

# =========================================================
# GLOBAL STATE (CPU SAFE)
# =========================================================
SCRIPT_CODE = {}      # script_name -> code (CPU only)
PIPELINES = {}        # script_name -> pipeline (GPU only, lazy)
log_buffer = io.StringIO()


# =========================================================
# LOGGING
# =========================================================
def log(msg):
    print(msg)
    log_buffer.write(msg + "\n")


def pipeline_technology_info(pipe):
    tech = []

    # Device map
    if hasattr(pipe, "hf_device_map"):
        tech.append("Device map: enabled")
    else:
        tech.append(f"Device: {pipe.device}")

    # Transformer dtype
    if hasattr(pipe, "transformer"):
        try:
            tech.append(f"Transformer dtype: {pipe.transformer.dtype}")
        except Exception:
            pass

        # Layerwise casting (Z-Image specific)
        if hasattr(pipe.transformer, "layerwise_casting"):
            lw = pipe.transformer.layerwise_casting
            tech.append(
                f"Layerwise casting: storage={lw.storage_dtype}, compute={lw.compute_dtype}"
            )

    # VAE dtype
    if hasattr(pipe, "vae"):
        try:
            tech.append(f"VAE dtype: {pipe.vae.dtype}")
        except Exception:
            pass

    # Quantization / GGUF
    if hasattr(pipe, "quantization_config"):
        tech.append(f"Quantization: {pipe.quantization_config}")

    # Attention backend
    if hasattr(pipe, "config"):
        attn = getattr(pipe.config, "attn_implementation", None)
        if attn:
            tech.append(f"Attention: {attn}")

    return "\n".join(f"β€’ {t}" for t in tech)


# =========================================================
# LATENT INFO
# =========================================================
def pipeline_debug_info(pipe):
    return f"""
Pipeline Info
-------------
Device: {pipe.device}
Transformer: {pipe.transformer.__class__.__name__}
VAE: {pipe.vae.__class__.__name__}
"""


def latent_shape_info(height, width, pipe):
    h = height // pipe.vae_scale_factor
    w = width // pipe.vae_scale_factor
    return f"Expected latent size: ({h}, {w})"


# =========================================================
# DOWNLOAD SCRIPTS (CPU ONLY)
# =========================================================
def download_scripts():
    resp = requests.get(SCRIPTS_REPO_API)
    resp.raise_for_status()

    scripts = []
    for item in resp.json():
        if item["name"].endswith(".py"):
            scripts.append(item["name"])
            path = os.path.join(LOCAL_SCRIPTS_DIR, item["name"])
            if not os.path.exists(path):
                content = requests.get(item["download_url"]).text
                with open(path, "w") as f:
                    f.write(content)

    return sorted(scripts)


SCRIPT_NAMES = download_scripts()


# =========================================================
# REGISTER SCRIPTS (CPU ONLY)
# =========================================================
def register_scripts(selected_scripts):
    SCRIPT_CODE.clear()

    for name in selected_scripts:
        path = os.path.join(LOCAL_SCRIPTS_DIR, name)
        with open(path, "r") as f:
            code = f.read()
            SCRIPT_CODE[name] = code

            # Log the .py file and extract pipe lines
            log(f"=== Registering script: {name} ===")
            extract_pipe_lines(code)  # This logs the full script + pipe lines

    return f"{len(SCRIPT_CODE)} script(s) registered βœ…"



# =========================================================
# EXTRACT LINES AFTER FROM_PRETRAINED
# =========================================================
def extract_pipe_lines(script_code: str):
    lines = script_code.splitlines()
    
    # Log full .py file
    log("=== SCRIPT CONTENT START ===")
    for l in lines:
        log(l)
    log("=== SCRIPT CONTENT END ===")
    
    pipe_lines = []
    found = False

    for line in lines:
        stripped = line.strip()
        if not found and stripped.startswith("pipe = ZImagePipeline.from_pretrained"):
            found = True
            pipe_lines.append(line)
        elif found:
            # Include all subsequent lines that reference 'pipe'
            if "pipe" in stripped:
                pipe_lines.append(line)

    # Log the extracted lines after from_pretrained
    log("πŸ”§ Extracted pipe-related lines:")
    for l in pipe_lines:
        log(f"β€’ {l.strip()}")

    return pipe_lines

def extract_pipe_lines0(script_code: str):
    lines = script_code.splitlines()
    print(lines)
    pipe_lines = []
    found = False

    for line in lines:
        stripped = line.strip()
        if not found and stripped.startswith("pipe = ZImagePipeline.from_pretrained"):
            found = True
            pipe_lines.append(line)
        elif found:
            if "pipe" in stripped:
                pipe_lines.append(line)
    log(f"πŸ”§ Building pipeline from {pipe_lines}")            
    return pipe_lines


# =========================================================
# GPU-ONLY PIPELINE BUILDER
# =========================================================
# =========================================================
# GPU-ONLY PIPELINE BUILDER (CRITICAL)
# =========================================================
def get_pipeline(script_name):
    if script_name in PIPELINES:
        return PIPELINES[script_name]

    log(f"πŸ”§ Building pipeline from {script_name}")

    namespace = {
        "__file__": script_name,
        "__name__": "__main__",

        # Minimal required globals
        "torch": torch,
    }

    try:
        exec(SCRIPT_CODE[script_name], namespace)
    except Exception as e:
        log(f"❌ Script failed: {script_name}")
        raise RuntimeError(f"Pipeline build failed for {script_name}") from e

    if "pipe" not in namespace:
        raise RuntimeError(
            f"{script_name} did not define `pipe`.\n"
            f"Each script MUST assign a variable named `pipe`."
        )

    PIPELINES[script_name] = namespace["pipe"]
    log(f"βœ… Pipeline ready: {script_name}")

    return PIPELINES[script_name]



def get_pipeline_fallback(script_name):
    if script_name in PIPELINES:
        return PIPELINES[script_name]

    log(f"πŸ”§ Building pipeline from {script_name}")

    namespace = {
        "__file__": script_name,
        "__name__": "__main__",

        # Minimal required globals
        "torch": torch,
    }

    try:
        exec(SCRIPT_CODE[script_name], namespace)
    except Exception as e:
        log(f"❌ Script failed: {script_name}")
        raise RuntimeError(f"Pipeline build failed for {script_name}") from e

    if "pipe" not in namespace:
        raise RuntimeError(
            f"{script_name} did not define `pipe`.\n"
            f"Each script MUST assign a variable named `pipe`."
        )

    PIPELINES[script_name] = namespace["pipe"]
    log(f"βœ… Pipeline ready: {script_name}")

    return PIPELINES[script_name]


# =========================================================
# IMAGE GENERATION
# =========================================================
@spaces.GPU
def generate_image(
    prompt,
    height,
    width,
    num_inference_steps,
    seed,
    randomize_seed,
    num_images,
    pipeline_name,
):
    log_buffer.truncate(0)
    log_buffer.seek(0)

    if pipeline_name not in SCRIPT_CODE:
        raise RuntimeError("Pipeline not registered")

    pipe = get_pipeline(pipeline_name)

    log("=== PIPELINE TECHNOLOGY ===")
    log(pipeline_technology_info(pipe))
    if not hasattr(pipe, "hf_device_map"):
      pipe = pipe.to("cuda")
    log("=== NEW GENERATION REQUEST ===")
    log(f"Pipeline: {pipeline_name}")
    log(f"Prompt: {prompt}")
    log(f"Height: {height}, Width: {width}")
    log(f"Steps: {num_inference_steps}")
    log(f"Images: {num_images}")

    if randomize_seed:
        seed = torch.randint(0, 2**32 - 1, (1,)).item()
        log(f"Random Seed β†’ {seed}")
    else:
        log(f"Seed β†’ {seed}")

    num_images = min(max(1, int(num_images)), 3)
    generator = torch.Generator("cuda").manual_seed(int(seed))

    # Run pipeline
    result = pipe(
        prompt=prompt,
        height=int(height),
        width=int(width),
        num_inference_steps=int(num_inference_steps),
        guidance_scale=0.0,
        generator=generator,
        max_sequence_length=1024,
        num_images_per_prompt=num_images,
        output_type="pil",
    )

    try:
        log(pipeline_debug_info(pipe))
        log(latent_shape_info(height, width, pipe))
    except Exception as e:
        log(f"Diagnostics error: {e}")

    log("βœ… Generation complete")
    return result.images, seed, log_buffer.getvalue()


# =========================================================
# GRADIO UI (original layout)
# =========================================================
with gr.Blocks(title="Z-Image-Turbo Multi Image Demo") as demo:
    gr.Markdown("# 🎨 Z-Image-Turbo β€” Multi Image ")

    with gr.Row():
        with gr.Column(scale=1):
            script_selector = gr.CheckboxGroup(
                choices=SCRIPT_NAMES,
                label="Select pipeline scripts"
            )
            register_btn = gr.Button("Register Scripts")
            status = gr.Textbox(label="Status", interactive=False)

            prompt = gr.Textbox(label="Prompt", lines=4)

            with gr.Row():
                height = gr.Slider(512, 2048, 1024, step=64, label="Height")
                width = gr.Slider(512, 2048, 1024, step=64, label="Width")

            num_images = gr.Slider(1, 3, 2, step=1, label="Number of Images")

            num_inference_steps = gr.Slider(
                1, 20, 9, step=1, label="Inference Steps",
                info="9 steps = 8 DiT forward passes"
            )

            with gr.Row():
                seed = gr.Number(label="Seed", value=42, precision=0)
                randomize_seed = gr.Checkbox(label="Randomize Seed", value=False)

            generate_btn = gr.Button("πŸš€ Generate", variant="primary")

        with gr.Column(scale=1):
            pipeline_picker = gr.Dropdown(
                choices=[],
                label="Active Pipeline",
            )
            output_images = gr.Gallery(                       label="Generated Images",          type="pil",         columns=2            )

            used_seed = gr.Number(label="Seed Used", interactive=False)
            debug_log = gr.Textbox(
                label="Debug Log Output",
                lines=25,
                interactive=False
            )

    register_btn.click(
        register_scripts,
        inputs=[script_selector],
        outputs=[status]
    )

    register_btn.click(
        lambda s: gr.update(choices=s, value=s[0] if s else None),
        inputs=[script_selector],
        outputs=[pipeline_picker]
    )

    generate_btn.click(
        generate_image,
        inputs=[prompt, height, width, num_inference_steps, seed, randomize_seed, num_images, pipeline_picker],
        outputs=[output_images, used_seed, debug_log]
    )

demo.queue()
demo.launch()