prithivMLmods commited on
Commit
62c1af6
·
verified ·
1 Parent(s): 4a81080

update app

Browse files
Files changed (1) hide show
  1. app.py +569 -313
app.py CHANGED
@@ -1,354 +1,610 @@
1
- import spaces
2
- import gradio as gr
3
- import torch
4
- from PIL import Image
5
- from diffusers import DiffusionPipeline
6
  import random
7
- import uuid
8
- from typing import Union, List, Optional
9
  import numpy as np
10
- import time
11
- import zipfile
12
- import os
 
 
 
 
 
 
 
 
 
 
 
13
  import requests
14
  from urllib.parse import urlparse
 
15
  import tempfile
16
  import shutil
 
 
17
 
18
- from typing import Iterable
 
19
 
20
- def save_image(img):
21
- unique_name = str(uuid.uuid4()) + ".png"
22
- img.save(unique_name)
23
- return unique_name
 
 
 
 
 
 
 
 
 
 
24
 
25
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
26
- if randomize_seed:
27
- seed = random.randint(0, MAX_SEED)
28
- return seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- MAX_SEED = np.iinfo(np.int32).max
31
- MAX_IMAGE_SIZE = 2048
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- # Load Qwen/Qwen-Image pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  dtype = torch.bfloat16
35
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
-
37
- # --- Model Loading ---
38
- pipe_qwen = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=dtype).to(device)
39
-
40
- # Aspect ratios
41
- aspect_ratios = {
42
- "1:1": (1328, 1328),
43
- "16:9": (1664, 928),
44
- "9:16": (928, 1664),
45
- "4:3": (1472, 1140),
46
- "3:4": (1140, 1472)
 
 
 
 
 
 
47
  }
48
 
49
- def load_lora_opt(pipe, lora_input):
50
- lora_input = lora_input.strip()
51
- if not lora_input:
52
- return
53
 
54
- # If it's just an ID like "author/model"
55
- if "/" in lora_input and not lora_input.startswith("http"):
56
- pipe.load_lora_weights(lora_input, adapter_name="default")
57
- return
58
 
59
- if lora_input.startswith("http"):
60
- url = lora_input
61
 
62
- # Repo page (no blob/resolve)
63
- if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
64
- repo_id = urlparse(url).path.strip("/")
65
- pipe.load_lora_weights(repo_id, adapter_name="default")
66
- return
67
 
68
- # Blob link → convert to resolve link
69
- if "/blob/" in url:
70
- url = url.replace("/blob/", "/resolve/")
 
 
 
 
 
 
 
 
71
 
72
- # Download direct file
73
- tmp_dir = tempfile.mkdtemp()
74
- local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- try:
77
- print(f"Downloading LoRA from {url}...")
78
- resp = requests.get(url, stream=True)
79
- resp.raise_for_status()
80
- with open(local_path, "wb") as f:
81
- for chunk in resp.iter_content(chunk_size=8192):
82
- f.write(chunk)
83
- print(f"Saved LoRA to {local_path}")
84
- pipe.load_lora_weights(local_path, adapter_name="default")
85
- finally:
86
- shutil.rmtree(tmp_dir, ignore_errors=True)
87
-
88
- # Generation function for Qwen/Qwen-Image
89
- @spaces.GPU(duration=120)
90
- def generate_qwen(
91
- prompt: str,
92
- negative_prompt: str = "",
93
- seed: int = 0,
94
- width: int = 1024,
95
- height: int = 1024,
96
- guidance_scale: float = 4.0,
97
- randomize_seed: bool = False,
98
- num_inference_steps: int = 50,
99
- num_images: int = 1,
100
- zip_images: bool = False,
101
- lora_input: str = "",
102
- lora_scale: float = 1.0,
103
- progress=gr.Progress(track_tqdm=True),
104
- ):
105
- if randomize_seed:
106
- seed = random.randint(0, MAX_SEED)
107
- generator = torch.Generator(device).manual_seed(seed)
108
 
109
- start_time = time.time()
110
-
111
- current_adapters = pipe_qwen.get_list_adapters()
112
- for adapter in current_adapters:
113
- pipe_qwen.delete_adapters(adapter)
114
- pipe_qwen.disable_lora()
115
-
116
- use_lora = False
117
- if lora_input and lora_input.strip() != "":
118
- load_lora_opt(pipe_qwen, lora_input)
119
- pipe_qwen.set_adapters(["default"], adapter_weights=[lora_scale])
120
- use_lora = True
121
 
122
- images = pipe_qwen(
123
- prompt=prompt,
124
- negative_prompt=negative_prompt if negative_prompt else "",
125
- height=height,
126
- width=width,
127
- guidance_scale=guidance_scale,
128
- num_inference_steps=num_inference_steps,
129
- num_images_per_prompt=num_images,
130
- generator=generator,
131
- output_type="pil",
132
- ).images
 
 
 
 
 
 
 
133
 
134
- end_time = time.time()
135
- duration = end_time - start_time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- image_paths = [save_image(img) for img in images]
138
- zip_path = None
139
- if zip_images:
140
- zip_name = str(uuid.uuid4()) + ".zip"
141
- with zipfile.ZipFile(zip_name, 'w') as zipf:
142
- for i, img_path in enumerate(image_paths):
143
- zipf.write(img_path, arcname=f"Img_{i}.png")
144
- zip_path = zip_name
145
-
146
- # Clean up adapters
147
- current_adapters = pipe_qwen.get_list_adapters()
148
- for adapter in current_adapters:
149
- pipe_qwen.delete_adapters(adapter)
150
- pipe_qwen.disable_lora()
151
 
152
- return image_paths, seed, f"{duration:.2f}", zip_path
153
-
154
- # Wrapper function to handle UI logic
155
- @spaces.GPU(duration=120)
156
- def generate(
157
- prompt: str,
158
- negative_prompt: str,
159
- use_negative_prompt: bool,
160
- seed: int,
161
- width: int,
162
- height: int,
163
- guidance_scale: float,
164
- randomize_seed: bool,
165
- num_inference_steps: int,
166
- num_images: int,
167
- zip_images: bool,
168
- lora_input: str,
169
- lora_scale: float,
170
- progress=gr.Progress(track_tqdm=True),
171
- ):
172
- final_negative_prompt = negative_prompt if use_negative_prompt else ""
173
- return generate_qwen(
174
- prompt=prompt,
175
- negative_prompt=final_negative_prompt,
176
- seed=seed,
177
- width=width,
178
- height=height,
179
- guidance_scale=guidance_scale,
180
- randomize_seed=randomize_seed,
181
- num_inference_steps=num_inference_steps,
182
- num_images=num_images,
183
- zip_images=zip_images,
184
- lora_input=lora_input,
185
- lora_scale=lora_scale,
186
- progress=progress,
187
- )
188
 
189
- # Examples
190
- examples = [
191
- "A decadent slice of layered chocolate cake on a ceramic plate with a drizzle of chocolate syrup and powdered sugar dusted on top. photographed from a slightly low angle with high resolution, natural soft lighting, rich contrast, shallow depth of field, and professional color grading to highlight the dessert’s textures --ar 85:128 --v 6.0 --style raw",
192
- "A beautifully decorated round chocolate birthday cake with rich chocolate frosting and elegant piping, topped with the name 'Qwen' written in white icing. placed on a wooden cake stand with scattered chocolate shavings around, softly lit with natural light, high resolution, professional food photography, clean background, no branding --ar 85:128 --v 6.0 --style raw",
193
- "Realistic still life photography style: A single, fresh apple, resting on a clean, soft-textured surface. The apple is slightly off-center, softly backlit to highlight its natural gloss and subtle color gradients—deep crimson red blending into light golden hues. Fine details such as small blemishes, dew drops, and a few light highlights enhance its lifelike appearance. A shallow depth of field gently blurs the neutral background, drawing full attention to the apple. Hyper-detailed 8K resolution, studio lighting, photorealistic render, emphasizing texture and form.",
194
- "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。",
195
- "A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text Introducing Qwen-Image, a foundational image generation model that excels in complex text rendering and precise image editing appears in neat white chalk at the center of the blackboard. Soft natural light filters through windows, casting gentle shadows. The scene is rendered in a realistic photography style with fine details, shallow depth of field, and warm tones. The girl's focused expression and chalk dust in the air add dynamism. Background elements include desks and educational posters, subtly blurred to emphasize the central action. Ultra-detailed 32K resolution, DSLR-quality, soft bokeh effect, documentary-style composition",
196
- "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。"
197
- ]
198
 
199
- css = '''
200
- .gradio-container {
201
- max-width: 590px !important;
202
- margin: 0 auto !important;
203
- }
204
- #main-title h1 { font-size: 2.3em !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  '''
207
 
208
- with gr.Blocks() as demo:
209
- gr.Markdown("# **Qwen-Image-Diffusion**", elem_id="main-title")
210
- result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
 
211
  with gr.Row():
212
- prompt = gr.Text(
213
- label="Prompt",
214
- show_label=True,
215
- max_lines=2,
216
- placeholder="Enter your prompt..",
217
- )
218
- run_button = gr.Button("Run", scale=0, variant="primary")
219
 
220
  with gr.Row():
221
- aspect_ratio = gr.Dropdown(
222
- label="Aspect Ratio",
223
- choices=list(aspect_ratios.keys()),
224
- value="1:1",
225
- )
226
- lora = gr.Textbox(label="qwen image lora (optional)", placeholder="enter the path...")
227
- with gr.Accordion("Additional Options", open=False):
228
- use_negative_prompt = gr.Checkbox(
229
- label="Use negative prompt",
230
- value=True,
231
- visible=True
232
- )
233
- negative_prompt = gr.Text(
234
- label="Negative prompt",
235
- max_lines=1,
236
- placeholder="Enter a negative prompt",
237
- value="text, watermark, copyright, blurry, low resolution",
238
- visible=True,
239
- )
240
- seed = gr.Slider(
241
- label="Seed",
242
- minimum=0,
243
- maximum=MAX_SEED,
244
- step=1,
245
- value=0,
246
- )
247
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
248
- with gr.Row():
249
- width = gr.Slider(
250
- label="Width",
251
- minimum=512,
252
- maximum=2048,
253
- step=64,
254
- value=1024,
255
- )
256
- height = gr.Slider(
257
- label="Height",
258
- minimum=512,
259
- maximum=2048,
260
- step=64,
261
- value=1024,
262
- )
263
- guidance_scale = gr.Slider(
264
- label="Guidance Scale",
265
- minimum=0.0,
266
- maximum=20.0,
267
- step=0.1,
268
- value=4.0,
269
- )
270
- num_inference_steps = gr.Slider(
271
- label="Number of inference steps",
272
- minimum=1,
273
- maximum=100,
274
- step=1,
275
- value=50,
276
- )
277
- num_images = gr.Slider(
278
- label="Number of images",
279
- minimum=1,
280
- maximum=5,
281
- step=1,
282
- value=1,
283
- )
284
- zip_images = gr.Checkbox(label="Zip generated images", value=False)
285
- with gr.Row():
286
- lora_scale = gr.Slider(
287
- label="LoRA Scale",
288
- minimum=0,
289
- maximum=2,
290
- step=0.01,
291
- value=1,
292
  )
 
 
 
 
 
293
 
294
- gr.Markdown("### Output Information")
295
- seed_display = gr.Textbox(label="Seed used", interactive=False)
296
- generation_time = gr.Textbox(label="Generation time (seconds)", interactive=False)
297
- zip_file = gr.File(label="Download ZIP")
298
-
299
- # Update aspect ratio
300
- def set_dimensions(ar):
301
- w, h = aspect_ratios[ar]
302
- return gr.update(value=w), gr.update(value=h)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
- aspect_ratio.change(
305
- fn=set_dimensions,
306
- inputs=aspect_ratio,
307
- outputs=[width, height]
308
  )
309
-
310
- # Negative prompt visibility
311
- use_negative_prompt.change(
312
- fn=lambda x: gr.update(visible=x),
313
- inputs=use_negative_prompt,
314
- outputs=negative_prompt
315
  )
316
-
317
- # Run button and prompt submit
318
- gr.on(
319
- triggers=[prompt.submit, run_button.click],
320
- fn=generate,
321
- inputs=[
322
- prompt,
323
- negative_prompt,
324
- use_negative_prompt,
325
- seed,
326
- width,
327
- height,
328
- guidance_scale,
329
- randomize_seed,
330
- num_inference_steps,
331
- num_images,
332
- zip_images,
333
- lora,
334
- lora_scale,
335
- ],
336
- outputs=[result, seed_display, generation_time, zip_file],
337
- api_name="run",
338
  )
339
-
340
- # Examples
341
- gr.Examples(
342
- examples=examples,
343
- inputs=prompt,
344
- outputs=[result, seed_display, generation_time, zip_file],
345
- fn=generate,
346
- cache_examples=False,
347
  )
348
 
349
- if __name__ == "__main__":
350
- demo.queue(max_size=30).launch(css=css, theme=gr.themes.Soft(
351
- primary_hue="blue",
352
- secondary_hue="indigo",
353
- neutral_hue="slate",
354
- ), mcp_server=True, ssr_mode=False, show_error=True)
 
1
+ import os
2
+ import json
3
+ import copy
4
+ import math
5
+ import time
6
  import random
7
+ import logging
 
8
  import numpy as np
9
+ from typing import Any, Dict, List, Optional, Union
10
+ import torch
11
+ from PIL import Image
12
+ import gradio as gr
13
+ import spaces
14
+ from diffusers import (
15
+ DiffusionPipeline,
16
+ FlowMatchEulerDiscreteScheduler)
17
+ from huggingface_hub import (
18
+ hf_hub_download,
19
+ HfFileSystem,
20
+ ModelCard,
21
+ snapshot_download)
22
+ from diffusers.utils import load_image
23
  import requests
24
  from urllib.parse import urlparse
25
+ from typing import Iterable
26
  import tempfile
27
  import shutil
28
+ import uuid
29
+ import zipfile
30
 
31
+ from gradio.themes import Soft
32
+ from gradio.themes.utils import colors, fonts, sizes
33
 
34
+ colors.orange_red = colors.Color(
35
+ name="orange_red",
36
+ c50="#FFF0E5",
37
+ c100="#FFE0CC",
38
+ c200="#FFC299",
39
+ c300="#FFA366",
40
+ c400="#FF8533",
41
+ c500="#FF4500",
42
+ c600="#E63E00",
43
+ c700="#CC3700",
44
+ c800="#B33000",
45
+ c900="#992900",
46
+ c950="#802200",
47
+ )
48
 
49
+ class OrangeRedTheme(Soft):
50
+ def __init__(
51
+ self,
52
+ *,
53
+ primary_hue: colors.Color | str = colors.gray,
54
+ secondary_hue: colors.Color | str = colors.orange_red, # Use the new color
55
+ neutral_hue: colors.Color | str = colors.slate,
56
+ text_size: sizes.Size | str = sizes.text_lg,
57
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
58
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
59
+ ),
60
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
61
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
62
+ ),
63
+ ):
64
+ super().__init__(
65
+ primary_hue=primary_hue,
66
+ secondary_hue=secondary_hue,
67
+ neutral_hue=neutral_hue,
68
+ text_size=text_size,
69
+ font=font,
70
+ font_mono=font_mono,
71
+ )
72
+ super().set(
73
+ background_fill_primary="*primary_50",
74
+ background_fill_primary_dark="*primary_900",
75
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
76
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
77
+ button_primary_text_color="white",
78
+ button_primary_text_color_hover="white",
79
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
80
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
81
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
82
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
83
+ button_secondary_text_color="black",
84
+ button_secondary_text_color_hover="white",
85
+ button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",
86
+ button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",
87
+ button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",
88
+ button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",
89
+ slider_color="*secondary_500",
90
+ slider_color_dark="*secondary_600",
91
+ block_title_text_weight="600",
92
+ block_border_width="3px",
93
+ block_shadow="*shadow_drop_lg",
94
+ button_primary_shadow="*shadow_drop_lg",
95
+ button_large_padding="11px",
96
+ color_accent_soft="*primary_100",
97
+ block_label_background_fill="*primary_200",
98
+ )
99
 
100
+ orange_red_theme = OrangeRedTheme()
101
+
102
+ # META: CUDA_CHECK / GPU_INFO
103
+ device = "cuda" if torch.cuda.is_available() else "cpu"
104
+ print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
105
+ print("torch.__version__ =", torch.__version__)
106
+ print("torch.version.cuda =", torch.version.cuda)
107
+ print("cuda available:", torch.cuda.is_available())
108
+ print("cuda device count:", torch.cuda.device_count())
109
+ if torch.cuda.is_available():
110
+ print("current device:", torch.cuda.current_device())
111
+ print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
112
+
113
+ print("Using device:", device)
114
 
115
+ loras = [
116
+ # Sample Qwen-compatible LoRAs
117
+ {
118
+ "image": "https://huggingface.co/prithivMLmods/Qwen-Image-Studio-Realism/resolve/main/images/2.png",
119
+ "title": "Studio Realism",
120
+ "repo": "prithivMLmods/Qwen-Image-Studio-Realism",
121
+ "weights": "qwen-studio-realism.safetensors",
122
+ "trigger_word": "Studio Realism"
123
+ },
124
+ {
125
+ "image": "https://huggingface.co/prithivMLmods/Qwen-Image-Sketch-Smudge/resolve/main/images/1.png",
126
+ "title": "Sketch Smudge",
127
+ "repo": "prithivMLmods/Qwen-Image-Sketch-Smudge",
128
+ "weights": "qwen-sketch-smudge.safetensors",
129
+ "trigger_word": "Sketch Smudge"
130
+ },
131
+ {
132
+ "image": "https://huggingface.co/Shakker-Labs/AWPortrait-QW/resolve/main/images/08fdaf6b644b61136340d5c908ca37993e47f34cdbe2e8e8251c4c72.jpg",
133
+ "title": "AWPortrait QW",
134
+ "repo": "Shakker-Labs/AWPortrait-QW",
135
+ "weights": "AWPortrait-QW_1.0.safetensors",
136
+ "trigger_word": "Portrait"
137
+ },
138
+ {
139
+ "image": "https://huggingface.co/prithivMLmods/Qwen-Image-Anime-LoRA/resolve/main/images/1.png",
140
+ "title": "Qwen Anime",
141
+ "repo": "prithivMLmods/Qwen-Image-Anime-LoRA",
142
+ "weights": "qwen-anime.safetensors",
143
+ "trigger_word": "Qwen Anime"
144
+ },
145
+ {
146
+ "image": "https://huggingface.co/flymy-ai/qwen-image-realism-lora/resolve/main/assets/flymy_realism.png",
147
+ "title": "Image Realism",
148
+ "repo": "flymy-ai/qwen-image-realism-lora",
149
+ "weights": "flymy_realism.safetensors",
150
+ "trigger_word": "Super Realism Portrait"
151
+ },
152
+ {
153
+ "image": "https://huggingface.co/prithivMLmods/Qwen-Image-Fragmented-Portraiture/resolve/main/images/3.png",
154
+ "title": "Fragmented Portraiture",
155
+ "repo": "prithivMLmods/Qwen-Image-Fragmented-Portraiture",
156
+ "weights": "qwen-fragmented-portraiture.safetensors",
157
+ "trigger_word": "Fragmented Portraiture"
158
+ },
159
+ {
160
+ "image": "https://huggingface.co/prithivMLmods/Qwen-Image-Synthetic-Face/resolve/main/images/2.png",
161
+ "title": "Synthetic Face",
162
+ "repo": "prithivMLmods/Qwen-Image-Synthetic-Face",
163
+ "weights": "qwen-synthetic-face.safetensors",
164
+ "trigger_word": "Synthetic Face"
165
+ },
166
+ {
167
+ "image": "https://huggingface.co/itspoidaman/qwenglitch/resolve/main/images/GyZTwJIbkAAhS4h.jpeg",
168
+ "title": "Qwen Glitch",
169
+ "repo": "itspoidaman/qwenglitch",
170
+ "weights": "qwenglitch1.safetensors",
171
+ "trigger_word": "qwenglitch"
172
+ },
173
+ {
174
+ "image": "https://huggingface.co/alfredplpl/qwen-image-modern-anime-lora/resolve/main/sample1.jpg",
175
+ "title": "Modern Anime Lora",
176
+ "repo": "alfredplpl/qwen-image-modern-anime-lora",
177
+ "weights": "lora.safetensors",
178
+ "trigger_word": "Japanese modern anime style"
179
+ },
180
+ ]
181
+
182
+ # Initialize the base model
183
  dtype = torch.bfloat16
184
+ base_model = "Qwen/Qwen-Image-2512"
185
+
186
+ # Scheduler configuration from the Qwen-Image-Lightning repository
187
+ scheduler_config = {
188
+ "base_image_seq_len": 256,
189
+ "base_shift": math.log(3),
190
+ "invert_sigmas": False,
191
+ "max_image_seq_len": 8192,
192
+ "max_shift": math.log(3),
193
+ "num_train_timesteps": 1000,
194
+ "shift": 1.0,
195
+ "shift_terminal": None,
196
+ "stochastic_sampling": False,
197
+ "time_shift_type": "exponential",
198
+ "use_beta_sigmas": False,
199
+ "use_dynamic_shifting": True,
200
+ "use_exponential_sigmas": False,
201
+ "use_karras_sigmas": False,
202
  }
203
 
204
+ scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
205
+ pipe = DiffusionPipeline.from_pretrained(
206
+ base_model, scheduler=scheduler, torch_dtype=dtype
207
+ ).to(device)
208
 
209
+ # Lightning LoRA info (no global state)
210
+ LIGHTNING_LORA_REPO = "lightx2v/Qwen-Image-2512-Lightning"
211
+ LIGHTNING_LORA_WEIGHT = "Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors"
 
212
 
213
+ MAX_SEED = np.iinfo(np.int32).max
 
214
 
215
+ class Timer:
216
+ def __init__(self, task_name=""):
217
+ self.task_name = task_name
 
 
218
 
219
+ def __enter__(self):
220
+ self.start_time = time.time()
221
+ return self
222
+
223
+ def __exit__(self, exc_type, exc_value, traceback):
224
+ self.end_time = time.time()
225
+ self.elapsed_time = self.end_time - self.start_time
226
+ if self.task_name:
227
+ print(f"Elapsed time for {self.task_name}: {self.elapsed_time:.6f} seconds")
228
+ else:
229
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
230
 
231
+ def compute_image_dimensions(aspect_ratio):
232
+ """Converts aspect ratio string to width, height tuple."""
233
+ if aspect_ratio == "1:1":
234
+ return 1024, 1024
235
+ elif aspect_ratio == "16:9":
236
+ return 1152, 640
237
+ elif aspect_ratio == "9:16":
238
+ return 640, 1152
239
+ elif aspect_ratio == "4:3":
240
+ return 1024, 768
241
+ elif aspect_ratio == "3:4":
242
+ return 768, 1024
243
+ elif aspect_ratio == "3:2":
244
+ return 1024, 688
245
+ elif aspect_ratio == "2:3":
246
+ return 688, 1024
247
+ else:
248
+ return 1024, 1024
249
 
250
+ def handle_lora_selection(evt: gr.SelectData, aspect_ratio):
251
+ selected_lora = loras[evt.index]
252
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
253
+ lora_repo = selected_lora["repo"]
254
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✅"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
+ # Update aspect ratio if specified in LoRA config
257
+ if "aspect" in selected_lora:
258
+ if selected_lora["aspect"] == "portrait":
259
+ aspect_ratio = "9:16"
260
+ elif selected_lora["aspect"] == "landscape":
261
+ aspect_ratio = "16:9"
262
+ else:
263
+ aspect_ratio = "1:1"
 
 
 
 
264
 
265
+ return (
266
+ gr.update(placeholder=new_placeholder),
267
+ updated_text,
268
+ evt.index,
269
+ aspect_ratio,
270
+ )
271
+
272
+ def adjust_generation_mode(speed_mode):
273
+ """Update UI based on speed/quality toggle."""
274
+ if speed_mode == "Fast (8 steps)":
275
+ return gr.update(value="Fast mode selected - 8 steps with Lightning LoRA"), 8, 1.0
276
+ else:
277
+ return gr.update(value="Base mode selected - 50 steps for best quality"), 50, 4.0
278
+
279
+ @spaces.GPU(duration=100)
280
+ def create_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, negative_prompt=""):
281
+ pipe.to("cuda")
282
+ generator = torch.Generator(device="cuda").manual_seed(seed)
283
 
284
+ with Timer("Generating image"):
285
+ # Generate image
286
+ image = pipe(
287
+ prompt=prompt_mash,
288
+ negative_prompt=negative_prompt,
289
+ num_inference_steps=steps,
290
+ true_cfg_scale=cfg_scale, # Use true_cfg_scale for Qwen-Image
291
+ width=width,
292
+ height=height,
293
+ generator=generator,
294
+ ).images[0]
295
+
296
+ return image
297
+
298
+ @spaces.GPU(duration=100)
299
+ def process_adapter_generation(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode, progress=gr.Progress(track_tqdm=True)):
300
+ if selected_index is None:
301
+ raise gr.Error("You must select a LoRA before proceeding.")
302
 
303
+ selected_lora = loras[selected_index]
304
+ lora_path = selected_lora["repo"]
305
+ trigger_word = selected_lora["trigger_word"]
 
 
 
 
 
 
 
 
 
 
 
306
 
307
+ # Prepare prompt with trigger word
308
+ if trigger_word:
309
+ if "trigger_position" in selected_lora:
310
+ if selected_lora["trigger_position"] == "prepend":
311
+ prompt_mash = f"{trigger_word} {prompt}"
312
+ else:
313
+ prompt_mash = f"{prompt} {trigger_word}"
314
+ else:
315
+ prompt_mash = f"{trigger_word} {prompt}"
316
+ else:
317
+ prompt_mash = prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
 
319
+ # Always unload any existing LoRAs first to avoid conflicts
320
+ with Timer("Unloading existing LoRAs"):
321
+ pipe.unload_lora_weights()
 
 
 
 
 
 
322
 
323
+ # Load LoRAs based on speed mode
324
+ if speed_mode == "Fast (8 steps)":
325
+ with Timer("Loading Lightning LoRA and style LoRA"):
326
+ # Load Lightning LoRA first
327
+ pipe.load_lora_weights(
328
+ LIGHTNING_LORA_REPO,
329
+ weight_name=LIGHTNING_LORA_WEIGHT,
330
+ adapter_name="lightning"
331
+ )
332
+
333
+ # Load the selected style LoRA
334
+ weight_name = selected_lora.get("weights", None)
335
+ pipe.load_lora_weights(
336
+ lora_path,
337
+ weight_name=weight_name,
338
+ low_cpu_mem_usage=True,
339
+ adapter_name="style"
340
+ )
341
+
342
+ # Set both adapters active with their weights
343
+ pipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])
344
+ else:
345
+ # Quality mode - only load the style LoRA
346
+ with Timer(f"Loading LoRA weights for {selected_lora['title']}"):
347
+ weight_name = selected_lora.get("weights", None)
348
+ pipe.load_lora_weights(
349
+ lora_path,
350
+ weight_name=weight_name,
351
+ low_cpu_mem_usage=True,
352
+ adapter_name="style"
353
+ )
354
+ pipe.set_adapters(["style"], adapter_weights=[lora_scale])
355
+
356
+ # Set random seed for reproducibility
357
+ with Timer("Randomizing seed"):
358
+ if randomize_seed:
359
+ seed = random.randint(0, MAX_SEED)
360
+
361
+ # Get image dimensions from aspect ratio
362
+ width, height = compute_image_dimensions(aspect_ratio)
363
+
364
+ # Generate the image
365
+ final_image = create_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale)
366
+
367
+ return final_image, seed
368
+
369
+ def fetch_hf_adapter_files(link):
370
+ split_link = link.split("/")
371
+ if len(split_link) != 2:
372
+ raise Exception("Invalid Hugging Face repository link format.")
373
 
374
+ print(f"Repository attempted: {split_link}")
375
+
376
+ # Load model card
377
+ model_card = ModelCard.load(link)
378
+ base_model = model_card.data.get("base_model")
379
+ print(f"Base model: {base_model}")
380
+
381
+ # Validate model type (for Qwen-Image)
382
+ acceptable_models = {"Qwen/Qwen-Image"}
383
+
384
+ models_to_check = base_model if isinstance(base_model, list) else [base_model]
385
+
386
+ if not any(model in acceptable_models for model in models_to_check):
387
+ raise Exception("Not a Qwen-Image LoRA!")
388
+
389
+ # Extract image and trigger word
390
+ image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
391
+ trigger_word = model_card.data.get("instance_prompt", "")
392
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
393
+
394
+ # Initialize Hugging Face file system
395
+ fs = HfFileSystem()
396
+ try:
397
+ list_of_files = fs.ls(link, detail=False)
398
+
399
+ # Find safetensors file
400
+ safetensors_name = None
401
+ for file in list_of_files:
402
+ filename = file.split("/")[-1]
403
+ if filename.endswith(".safetensors"):
404
+ safetensors_name = filename
405
+ break
406
+
407
+ if not safetensors_name:
408
+ raise Exception("No valid *.safetensors file found in the repository.")
409
+
410
+ except Exception as e:
411
+ print(e)
412
+ raise Exception("You didn't include a valid Hugging Face repository with a *.safetensors LoRA")
413
+
414
+ return split_link[1], link, safetensors_name, trigger_word, image_url
415
+
416
+ def validate_custom_adapter(link):
417
+ print(f"Checking a custom model on: {link}")
418
+
419
+ if link.endswith('.safetensors'):
420
+ if 'huggingface.co' in link:
421
+ parts = link.split('/')
422
+ try:
423
+ hf_index = parts.index('huggingface.co')
424
+ username = parts[hf_index + 1]
425
+ repo_name = parts[hf_index + 2]
426
+ repo = f"{username}/{repo_name}"
427
+
428
+ safetensors_name = parts[-1]
429
+
430
+ try:
431
+ model_card = ModelCard.load(repo)
432
+ trigger_word = model_card.data.get("instance_prompt", "")
433
+ image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
434
+ image_url = f"https://huggingface.co/{repo}/resolve/main/{image_path}" if image_path else None
435
+ except:
436
+ trigger_word = ""
437
+ image_url = None
438
+
439
+ return repo_name, repo, safetensors_name, trigger_word, image_url
440
+ except:
441
+ raise Exception("Invalid safetensors URL format")
442
+
443
+ if link.startswith("https://"):
444
+ if link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co"):
445
+ link_split = link.split("huggingface.co/")
446
+ return fetch_hf_adapter_files(link_split[1])
447
+ else:
448
+ return fetch_hf_adapter_files(link)
449
+
450
+ def incorporate_custom_adapter(custom_lora):
451
+ global loras
452
+ if custom_lora:
453
+ try:
454
+ title, repo, path, trigger_word, image = validate_custom_adapter(custom_lora)
455
+ print(f"Loaded custom LoRA: {repo}")
456
+ card = f'''
457
+ <div class="custom_lora_card">
458
+ <span>Loaded custom LoRA:</span>
459
+ <div class="card_internal">
460
+ <img src="{image}" />
461
+ <div>
462
+ <h3>{title}</h3>
463
+ <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>
464
+ </div>
465
+ </div>
466
+ </div>
467
+ '''
468
+ existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
469
+ if existing_item_index is None:
470
+ new_item = {
471
+ "image": image,
472
+ "title": title,
473
+ "repo": repo,
474
+ "weights": path,
475
+ "trigger_word": trigger_word
476
+ }
477
+ print(new_item)
478
+ loras.append(new_item)
479
+ existing_item_index = len(loras) - 1 # Get the actual index after adding
480
+
481
+ return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
482
+ except Exception as e:
483
+ gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-Qwen-Image LoRA, this was the issue: {e}")
484
+ 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, ""
485
+ else:
486
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
487
+
488
+ def discard_custom_adapter():
489
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
490
+
491
+ process_adapter_generation.zerogpu = True
492
+
493
+ css = '''
494
+ #gen_btn{height: 100%}
495
+ #gen_column{align-self: stretch}
496
+ #title{text-align: center}
497
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
498
+ #title img{width: 100px; margin-right: 0.5em}
499
+ #gallery .grid-wrap{height: 10vh}
500
+ #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
501
+ .card_internal{display: flex;height: 100px;margin-top: .5em}
502
+ .card_internal img{margin-right: 1em}
503
+ .styler{--form-gap-width: 0px !important}
504
+ #speed_status{padding: .5em; border-radius: 5px; margin: 1em 0}
505
  '''
506
 
507
+ with gr.Blocks(delete_cache=(240, 240)) as app:
508
+ title = gr.HTML("""<h1>Qwen-Image-2512 LoRA DLC⛵</h1>""", elem_id="title")
509
+ selected_index = gr.State(None)
510
+
511
  with gr.Row():
512
+ with gr.Column(scale=3):
513
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder="✦︎ Choose the LoRA and type the prompt")
514
+ with gr.Column(scale=1, elem_id="gen_column"):
515
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
 
 
 
516
 
517
  with gr.Row():
518
+ with gr.Column():
519
+ selected_info = gr.Markdown("")
520
+ gallery = gr.Gallery(
521
+ [(item["image"], item["title"]) for item in loras],
522
+ label="LoRA Gallery",
523
+ allow_preview=False,
524
+ columns=3,
525
+ elem_id="gallery",
526
+ #show_share_button=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527
  )
528
+ with gr.Group():
529
+ custom_lora = gr.Textbox(label="Custom LoRA", placeholder="username/lora-model-name")
530
+ gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")
531
+ custom_lora_info = gr.HTML(visible=False)
532
+ custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
533
 
534
+ with gr.Column():
535
+ result = gr.Image(label="Generated Image", format="png")
536
+
537
+ with gr.Row():
538
+ aspect_ratio = gr.Dropdown(
539
+ label="Aspect Ratio",
540
+ choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],
541
+ value="3:2"
542
+ )
543
+ with gr.Row():
544
+ speed_mode = gr.Dropdown(
545
+ label="Output Mode",
546
+ choices=["Fast (8 steps)", "Base (50 steps)"],
547
+ value="Base (50 steps)",
548
+ )
549
+
550
+ speed_status = gr.Markdown("Base mode selected - 50 steps for best quality", elem_id="speed_status")
551
+
552
+ with gr.Row():
553
+ with gr.Accordion("Advanced Settings", open=False):
554
+ with gr.Column():
555
+ with gr.Row():
556
+ cfg_scale = gr.Slider(
557
+ label="Guidance Scale (True CFG)",
558
+ minimum=1.0,
559
+ maximum=5.0,
560
+ step=0.1,
561
+ value=4.0,
562
+ info="Lower for speed mode, higher for quality"
563
+ )
564
+ steps = gr.Slider(
565
+ label="Steps",
566
+ minimum=4,
567
+ maximum=50,
568
+ step=1,
569
+ value=50,
570
+ info="Automatically set by speed mode"
571
+ )
572
+
573
+ with gr.Row():
574
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
575
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
576
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1.0)
577
+
578
+ # Event handlers
579
+ gallery.select(
580
+ handle_lora_selection,
581
+ inputs=[aspect_ratio],
582
+ outputs=[prompt, selected_info, selected_index, aspect_ratio]
583
+ )
584
 
585
+ speed_mode.change(
586
+ adjust_generation_mode,
587
+ inputs=[speed_mode],
588
+ outputs=[speed_status, steps, cfg_scale]
589
  )
590
+
591
+ custom_lora.input(
592
+ incorporate_custom_adapter,
593
+ inputs=[custom_lora],
594
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
 
595
  )
596
+
597
+ custom_lora_button.click(
598
+ discard_custom_adapter,
599
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
600
  )
601
+
602
+ gr.on(
603
+ triggers=[generate_button.click, prompt.submit],
604
+ fn=process_adapter_generation,
605
+ inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode],
606
+ outputs=[result, seed]
 
 
607
  )
608
 
609
+ app.queue()
610
+ app.launch(theme=orange_red_theme, css=css, mcp_server=True, ssr_mode=False, show_error=True)