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 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import json
4
+ import logging
5
+ import torch
6
+ from PIL import Image
7
+ import spaces
8
+ from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler
9
+ from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
10
+ import copy
11
+ import random
12
+ import time
13
+ import re
14
+ import math
15
+ import numpy as np
16
+
17
+ # Load LoRAs from JSON
18
+ loras = [
19
+ {
20
+ "repo": "flymy-ai/qwen-image-realism-lora",
21
+ "image": "https://huggingface.co/flymy-ai/qwen-image-realism-lora/resolve/main/assets/flymy_realism.png",
22
+ "trigger_word": "Super Realism portrait of",
23
+ "trigger_position": "prepend",
24
+ "title": "Super Realism"
25
+ },
26
+ {
27
+ "repo": "valiantcat/Qwen-Image-Gufeng-LoRA",
28
+ "image": "https://huggingface.co/valiantcat/Qwen-Image-Gufeng-LoRA/resolve/main/result/output1.png",
29
+ "trigger_word": "gfwm, The image is a digital illustration",
30
+ "trigger_position": "prepend",
31
+ "title": "Gufeng Style"
32
+ },
33
+ {
34
+ "repo": "lichorosario/qwen-image-dottrmstr",
35
+ "image": "https://huggingface.co/lichorosario/qwen-image-dottrmstr/resolve/main/images/Day_of_the_Tentacle_Remastered_(PC)_08.jpg",
36
+ "trigger_word": "DOTTRMSTR",
37
+ "trigger_position": "prepend",
38
+ "title": "Day of the Tentacle Style"
39
+ }
40
+ ]
41
+
42
+ # Initialize the base model
43
+ dtype = torch.bfloat16
44
+ device = "cuda" if torch.cuda.is_available() else "cpu"
45
+ base_model = "Qwen/Qwen-Image"
46
+
47
+ # Scheduler configuration from the Qwen-Image-Lightning repository
48
+ scheduler_config = {
49
+ "base_image_seq_len": 256,
50
+ "base_shift": math.log(3),
51
+ "invert_sigmas": False,
52
+ "max_image_seq_len": 8192,
53
+ "max_shift": math.log(3),
54
+ "num_train_timesteps": 1000,
55
+ "shift": 1.0,
56
+ "shift_terminal": None,
57
+ "stochastic_sampling": False,
58
+ "time_shift_type": "exponential",
59
+ "use_beta_sigmas": False,
60
+ "use_dynamic_shifting": True,
61
+ "use_exponential_sigmas": False,
62
+ "use_karras_sigmas": False,
63
+ }
64
+
65
+ scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
66
+ pipe = DiffusionPipeline.from_pretrained(
67
+ base_model, scheduler=scheduler, torch_dtype=dtype
68
+ ).to(device)
69
+
70
+ # Store Lightning LoRA info
71
+ lightning_lora = {
72
+ "repo": "lightx2v/Qwen-Image-Lightning",
73
+ "weight_name": "Qwen-Image-Lightning-8steps-V1.0.safetensors",
74
+ "loaded": False
75
+ }
76
+
77
+ MAX_SEED = np.iinfo(np.int32).max
78
+
79
+ class calculateDuration:
80
+ def __init__(self, activity_name=""):
81
+ self.activity_name = activity_name
82
+
83
+ def __enter__(self):
84
+ self.start_time = time.time()
85
+ return self
86
+
87
+ def __exit__(self, exc_type, exc_value, traceback):
88
+ self.end_time = time.time()
89
+ self.elapsed_time = self.end_time - self.start_time
90
+ if self.activity_name:
91
+ print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
92
+ else:
93
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
94
+
95
+ def get_image_size(aspect_ratio):
96
+ """Converts aspect ratio string to width, height tuple."""
97
+ if aspect_ratio == "1:1":
98
+ return 1024, 1024
99
+ elif aspect_ratio == "16:9":
100
+ return 1152, 640
101
+ elif aspect_ratio == "9:16":
102
+ return 640, 1152
103
+ elif aspect_ratio == "4:3":
104
+ return 1024, 768
105
+ elif aspect_ratio == "3:4":
106
+ return 768, 1024
107
+ elif aspect_ratio == "3:2":
108
+ return 1024, 688
109
+ elif aspect_ratio == "2:3":
110
+ return 688, 1024
111
+ else:
112
+ return 1024, 1024
113
+
114
+ def update_selection(evt: gr.SelectData, aspect_ratio):
115
+ selected_lora = loras[evt.index]
116
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
117
+ lora_repo = selected_lora["repo"]
118
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
119
+
120
+ # Update aspect ratio if specified in LoRA config
121
+ if "aspect" in selected_lora:
122
+ if selected_lora["aspect"] == "portrait":
123
+ aspect_ratio = "9:16"
124
+ elif selected_lora["aspect"] == "landscape":
125
+ aspect_ratio = "16:9"
126
+ else:
127
+ aspect_ratio = "1:1"
128
+
129
+ return (
130
+ gr.update(placeholder=new_placeholder),
131
+ updated_text,
132
+ evt.index,
133
+ aspect_ratio,
134
+ )
135
+
136
+ def handle_speed_mode(speed_mode):
137
+ """Handle the speed/quality toggle for Lightning LoRA."""
138
+ global lightning_lora
139
+
140
+ if speed_mode == "Speed (8 steps)":
141
+ # Load Lightning LoRA if not already loaded
142
+ if not lightning_lora["loaded"]:
143
+ with calculateDuration("Loading Lightning LoRA"):
144
+ pipe.load_lora_weights(
145
+ lightning_lora["repo"],
146
+ weight_name=lightning_lora["weight_name"],
147
+ adapter_name="lightning"
148
+ )
149
+ lightning_lora["loaded"] = True
150
+ return gr.update(value="Lightning LoRA loaded for fast generation"), 8, 1.0
151
+ return gr.update(value="Lightning LoRA already loaded"), 8, 1.0
152
+ else: # Quality mode
153
+ # Unload Lightning LoRA if loaded
154
+ if lightning_lora["loaded"]:
155
+ with calculateDuration("Unloading Lightning LoRA"):
156
+ pipe.unload_lora_weights()
157
+ lightning_lora["loaded"] = False
158
+ return gr.update(value="Lightning LoRA unloaded for quality generation"), 28, 3.5
159
+ return gr.update(value="Quality mode active"), 28, 3.5
160
+
161
+ @spaces.GPU(duration=70)
162
+ def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, negative_prompt=""):
163
+ pipe.to("cuda")
164
+ generator = torch.Generator(device="cuda").manual_seed(seed)
165
+
166
+ with calculateDuration("Generating image"):
167
+ # Generate image
168
+ image = pipe(
169
+ prompt=prompt_mash,
170
+ negative_prompt=negative_prompt,
171
+ num_inference_steps=steps,
172
+ true_cfg_scale=cfg_scale, # Use true_cfg_scale for Qwen-Image
173
+ width=width,
174
+ height=height,
175
+ generator=generator,
176
+ ).images[0]
177
+
178
+ return image
179
+
180
+ @spaces.GPU(duration=70)
181
+ def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode, progress=gr.Progress(track_tqdm=True)):
182
+ if selected_index is None:
183
+ raise gr.Error("You must select a LoRA before proceeding.")
184
+
185
+ selected_lora = loras[selected_index]
186
+ lora_path = selected_lora["repo"]
187
+ trigger_word = selected_lora["trigger_word"]
188
+
189
+ # Prepare prompt with trigger word
190
+ if trigger_word:
191
+ if "trigger_position" in selected_lora:
192
+ if selected_lora["trigger_position"] == "prepend":
193
+ prompt_mash = f"{trigger_word} {prompt}"
194
+ else:
195
+ prompt_mash = f"{prompt} {trigger_word}"
196
+ else:
197
+ prompt_mash = f"{trigger_word} {prompt}"
198
+ else:
199
+ prompt_mash = prompt
200
+
201
+ # First, handle Lightning LoRA based on speed mode
202
+ global lightning_lora
203
+ if speed_mode == "Speed (8 steps)" and not lightning_lora["loaded"]:
204
+ with calculateDuration("Loading Lightning LoRA"):
205
+ pipe.load_lora_weights(
206
+ lightning_lora["repo"],
207
+ weight_name=lightning_lora["weight_name"],
208
+ adapter_name="lightning"
209
+ )
210
+ lightning_lora["loaded"] = True
211
+ elif speed_mode == "Quality (28 steps)" and lightning_lora["loaded"]:
212
+ with calculateDuration("Unloading Lightning LoRA"):
213
+ pipe.unload_lora_weights()
214
+ lightning_lora["loaded"] = False
215
+
216
+ # Load the selected style LoRA
217
+ with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
218
+ weight_name = selected_lora.get("weights", None)
219
+
220
+ # If Lightning is loaded, we need to handle multiple LoRAs
221
+ if lightning_lora["loaded"]:
222
+ pipe.load_lora_weights(
223
+ lora_path,
224
+ weight_name=weight_name,
225
+ low_cpu_mem_usage=True,
226
+ adapter_name="style"
227
+ )
228
+ # Set both adapters active
229
+ pipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])
230
+ else:
231
+ pipe.load_lora_weights(
232
+ lora_path,
233
+ weight_name=weight_name,
234
+ low_cpu_mem_usage=True
235
+ )
236
+
237
+ # Set random seed for reproducibility
238
+ with calculateDuration("Randomizing seed"):
239
+ if randomize_seed:
240
+ seed = random.randint(0, MAX_SEED)
241
+
242
+ # Get image dimensions from aspect ratio
243
+ width, height = get_image_size(aspect_ratio)
244
+
245
+ # Generate the image
246
+ final_image = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale)
247
+
248
+ return final_image, seed
249
+
250
+ def get_huggingface_safetensors(link):
251
+ split_link = link.split("/")
252
+ if len(split_link) != 2:
253
+ raise Exception("Invalid Hugging Face repository link format.")
254
+
255
+ print(f"Repository attempted: {split_link}")
256
+
257
+ # Load model card
258
+ model_card = ModelCard.load(link)
259
+ base_model = model_card.data.get("base_model")
260
+ print(f"Base model: {base_model}")
261
+
262
+ # Validate model type (for Qwen-Image)
263
+ acceptable_models = {"Qwen/Qwen-Image"}
264
+
265
+ models_to_check = base_model if isinstance(base_model, list) else [base_model]
266
+
267
+ if not any(model in acceptable_models for model in models_to_check):
268
+ raise Exception("Not a Qwen-Image LoRA!")
269
+
270
+ # Extract image and trigger word
271
+ image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
272
+ trigger_word = model_card.data.get("instance_prompt", "")
273
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
274
+
275
+ # Initialize Hugging Face file system
276
+ fs = HfFileSystem()
277
+ try:
278
+ list_of_files = fs.ls(link, detail=False)
279
+
280
+ # Find safetensors file
281
+ safetensors_name = None
282
+ for file in list_of_files:
283
+ filename = file.split("/")[-1]
284
+ if filename.endswith(".safetensors"):
285
+ safetensors_name = filename
286
+ break
287
+
288
+ if not safetensors_name:
289
+ raise Exception("No valid *.safetensors file found in the repository.")
290
+
291
+ except Exception as e:
292
+ print(e)
293
+ raise Exception("You didn't include a valid Hugging Face repository with a *.safetensors LoRA")
294
+
295
+ return split_link[1], link, safetensors_name, trigger_word, image_url
296
+
297
+ def check_custom_model(link):
298
+ print(f"Checking a custom model on: {link}")
299
+ if link.startswith("https://"):
300
+ if link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co"):
301
+ link_split = link.split("huggingface.co/")
302
+ return get_huggingface_safetensors(link_split[1])
303
+ else:
304
+ return get_huggingface_safetensors(link)
305
+
306
+ def add_custom_lora(custom_lora):
307
+ global loras
308
+ if custom_lora:
309
+ try:
310
+ title, repo, path, trigger_word, image = check_custom_model(custom_lora)
311
+ print(f"Loaded custom LoRA: {repo}")
312
+ card = f'''
313
+ <div class="custom_lora_card">
314
+ <span>Loaded custom LoRA:</span>
315
+ <div class="card_internal">
316
+ <img src="{image}" />
317
+ <div>
318
+ <h3>{title}</h3>
319
+ <small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small>
320
+ </div>
321
+ </div>
322
+ </div>
323
+ '''
324
+ existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
325
+ if not existing_item_index:
326
+ new_item = {
327
+ "image": image,
328
+ "title": title,
329
+ "repo": repo,
330
+ "weights": path,
331
+ "trigger_word": trigger_word
332
+ }
333
+ print(new_item)
334
+ existing_item_index = len(loras)
335
+ loras.append(new_item)
336
+
337
+ return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
338
+ except Exception as e:
339
+ gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-Qwen-Image LoRA, this was the issue: {e}")
340
+ return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-Qwen-Image LoRA"), gr.update(visible=True), gr.update(), "", None, ""
341
+ else:
342
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
343
+
344
+ def remove_custom_lora():
345
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
346
+
347
+ run_lora.zerogpu = True
348
+
349
+ css = '''
350
+ #gen_btn{height: 100%}
351
+ #gen_column{align-self: stretch}
352
+ #title{text-align: center}
353
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
354
+ #title img{width: 100px; margin-right: 0.5em}
355
+ #gallery .grid-wrap{height: 10vh}
356
+ #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
357
+ .card_internal{display: flex;height: 100px;margin-top: .5em}
358
+ .card_internal img{margin-right: 1em}
359
+ .styler{--form-gap-width: 0px !important}
360
+ #speed_status{padding: .5em; border-radius: 5px; margin: 1em 0}
361
+ '''
362
+
363
+ with gr.Blocks(theme=gr.themes.Soft(), css=css, delete_cache=(60, 60)) as app:
364
+ title = gr.HTML(
365
+ """<h1><img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_logo.png" alt="Qwen-Image" style="height: 100px; margin-right: 10px; vertical-align: middle;"> Qwen-Image LoRA Explorer</h1>""",
366
+ elem_id="title",
367
+ )
368
+
369
+ selected_index = gr.State(None)
370
+
371
+ with gr.Row():
372
+ with gr.Column(scale=3):
373
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
374
+ with gr.Column(scale=1, elem_id="gen_column"):
375
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
376
+
377
+ with gr.Row():
378
+ with gr.Column():
379
+ selected_info = gr.Markdown("")
380
+ gallery = gr.Gallery(
381
+ [(item["image"], item["title"]) for item in loras],
382
+ label="LoRA Gallery",
383
+ allow_preview=False,
384
+ columns=3,
385
+ elem_id="gallery",
386
+ show_share_button=False
387
+ )
388
+ with gr.Group():
389
+ custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="username/qwen-image-custom-lora")
390
+ gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")
391
+ custom_lora_info = gr.HTML(visible=False)
392
+ custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
393
+
394
+ with gr.Column():
395
+ result = gr.Image(label="Generated Image")
396
+
397
+ with gr.Row():
398
+ speed_mode = gr.Radio(
399
+ label="Generation Mode",
400
+ choices=["Speed (8 steps)", "Quality (28 steps)"],
401
+ value="Quality (28 steps)",
402
+ info="Speed mode uses Lightning LoRA for faster generation"
403
+ )
404
+
405
+ speed_status = gr.Markdown("Quality mode active", elem_id="speed_status")
406
+
407
+ with gr.Row():
408
+ with gr.Accordion("Advanced Settings", open=False):
409
+ with gr.Column():
410
+ with gr.Row():
411
+ aspect_ratio = gr.Radio(
412
+ label="Aspect Ratio",
413
+ choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],
414
+ value="1:1"
415
+ )
416
+
417
+ with gr.Row():
418
+ cfg_scale = gr.Slider(
419
+ label="Guidance Scale (True CFG)",
420
+ minimum=1.0,
421
+ maximum=5.0,
422
+ step=0.1,
423
+ value=3.5,
424
+ info="Lower for speed mode, higher for quality"
425
+ )
426
+ steps = gr.Slider(
427
+ label="Steps",
428
+ minimum=4,
429
+ maximum=50,
430
+ step=1,
431
+ value=28,
432
+ info="Automatically set by speed mode"
433
+ )
434
+
435
+ with gr.Row():
436
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
437
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
438
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1.0)
439
+
440
+ # Event handlers
441
+ gallery.select(
442
+ update_selection,
443
+ inputs=[aspect_ratio],
444
+ outputs=[prompt, selected_info, selected_index, aspect_ratio]
445
+ )
446
+
447
+ speed_mode.change(
448
+ handle_speed_mode,
449
+ inputs=[speed_mode],
450
+ outputs=[speed_status, steps, cfg_scale]
451
+ )
452
+
453
+ custom_lora.input(
454
+ add_custom_lora,
455
+ inputs=[custom_lora],
456
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
457
+ )
458
+
459
+ custom_lora_button.click(
460
+ remove_custom_lora,
461
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
462
+ )
463
+
464
+ gr.on(
465
+ triggers=[generate_button.click, prompt.submit],
466
+ fn=run_lora,
467
+ inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode],
468
+ outputs=[result, seed]
469
+ )
470
+
471
+ app.queue()
472
+ app.launch()