prithivMLmods commited on
Commit
733d7d7
·
verified ·
1 Parent(s): c07a527

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -97
app.py CHANGED
@@ -2,62 +2,62 @@ import spaces
2
  import gradio as gr
3
  import torch
4
  from PIL import Image
5
- from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler
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 math
13
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # --- Constants ---
16
  MAX_SEED = np.iinfo(np.int32).max
17
  MAX_IMAGE_SIZE = 2048
18
 
19
- # --- Device & Type ---
20
  dtype = torch.bfloat16
21
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
 
23
  # --- Model Loading ---
24
- # 1. Setup Scheduler for Turbo (4-step) Inference
25
- scheduler_config = {
26
- "base_image_seq_len": 256,
27
- "base_shift": math.log(3),
28
- "invert_sigmas": False,
29
- "max_image_seq_len": 8192,
30
- "max_shift": math.log(3),
31
- "num_train_timesteps": 1000,
32
- "shift": 1.0,
33
- "shift_terminal": None,
34
- "stochastic_sampling": False,
35
- "time_shift_type": "exponential",
36
- "use_beta_sigmas": False,
37
- "use_dynamic_shifting": True,
38
- "use_exponential_sigmas": False,
39
- "use_karras_sigmas": False,
40
- }
41
- scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
42
-
43
- # 2. Load Base Model
44
  print("Loading Qwen-Image-2512...")
45
- pipe_qwen = DiffusionPipeline.from_pretrained(
46
- "Qwen/Qwen-Image-2512",
47
- scheduler=scheduler,
48
- torch_dtype=dtype
49
- ).to(device)
 
 
 
 
 
50
 
51
- # 3. Load & Fuse Turbo LoRA
52
- print("Loading Wuli-art Turbo LoRA...")
 
53
  try:
54
  pipe_qwen.load_lora_weights(
55
- "Wuli-art/Qwen-Image-2512-Turbo-LoRA",
56
- weight_name="Wuli-Qwen-Image-2512-Turbo-LoRA-4steps-V1.0-bf16.safetensors",
57
- adapter_name="turbo"
58
  )
59
- pipe_qwen.fuse_lora(adapter_names=["turbo"], lora_scale=1.0)
60
- print("LoRA fused successfully.")
61
  except Exception as e:
62
  print(f"Error loading LoRA: {e}")
63
 
@@ -70,12 +70,7 @@ aspect_ratios = {
70
  "3:4": (1140, 1472)
71
  }
72
 
73
- def save_image(img):
74
- unique_name = str(uuid.uuid4()) + ".png"
75
- img.save(unique_name)
76
- return unique_name
77
-
78
- # --- Generation Function ---
79
  @spaces.GPU
80
  def generate_qwen(
81
  prompt: str,
@@ -83,31 +78,26 @@ def generate_qwen(
83
  seed: int = 0,
84
  width: int = 1024,
85
  height: int = 1024,
86
- guidance_scale: float = 1.0,
87
  randomize_seed: bool = False,
88
  num_inference_steps: int = 4,
89
  num_images: int = 1,
90
  zip_images: bool = False,
91
  progress=gr.Progress(track_tqdm=True),
92
  ):
93
- # Hardcoded negative prompt for Turbo model consistency
94
- final_negative_prompt = "low quality, low resolution, bad anatomy, distorted, blurry, nsfw"
95
-
96
  if randomize_seed:
97
  seed = random.randint(0, MAX_SEED)
98
  generator = torch.Generator(device).manual_seed(seed)
99
 
100
  start_time = time.time()
101
 
102
- print(f"Generating with Prompt: {prompt}")
103
- print(f"Config: Steps={num_inference_steps}, Size={width}x{height}, Seed={seed}")
104
-
105
  images = pipe_qwen(
106
  prompt=prompt,
107
- negative_prompt=final_negative_prompt,
108
  height=height,
109
  width=width,
110
- guidance_scale=guidance_scale,
111
  num_inference_steps=num_inference_steps,
112
  num_images_per_prompt=num_images,
113
  generator=generator,
@@ -128,22 +118,26 @@ def generate_qwen(
128
 
129
  return image_paths, seed, f"{duration:.2f}", zip_path
130
 
131
- # Wrapper function for UI
132
- def generate_ui(
133
- prompt,
134
- negative_prompt, # Kept in signature but overwritten internally
135
- use_negative_prompt, # Kept for UI compatibility
136
- seed,
137
- width,
138
- height,
139
- guidance_scale,
140
- randomize_seed,
141
- num_inference_steps,
142
- num_images,
143
- zip_images,
 
 
144
  ):
 
145
  return generate_qwen(
146
  prompt=prompt,
 
147
  seed=seed,
148
  width=width,
149
  height=height,
@@ -152,32 +146,32 @@ def generate_ui(
152
  num_inference_steps=num_inference_steps,
153
  num_images=num_images,
154
  zip_images=zip_images,
 
155
  )
156
 
157
- # --- Examples ---
158
  examples = [
159
  "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",
160
  "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",
161
  "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.",
162
- "A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text 'Introducing Qwen-Image' appears in neat white chalk at the center of the blackboard. Soft natural light filters through windows. Ultra-detailed 32K resolution, DSLR-quality, soft bokeh effect, documentary-style composition",
163
- "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。"
 
164
  ]
165
 
166
  css = '''
167
  .gradio-container {
168
- max-width: 800px !important;
169
  margin: 0 auto !important;
170
  }
171
- #main-title h1 { font-size: 2.3em !important; text-align: center; }
172
  '''
173
 
174
- # --- Gradio UI ---
175
- with gr.Blocks(css=css) as demo:
176
- gr.Markdown("# **Qwen-Image-Diffusion (Turbo)**", elem_id="main-title")
177
- gr.Markdown("Powered by **Qwen-Image-2512** and **Wuli-art Turbo LoRA** (4-steps).")
178
 
179
  result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
180
-
181
  with gr.Row():
182
  prompt = gr.Text(
183
  label="Prompt",
@@ -193,12 +187,21 @@ with gr.Blocks(css=css) as demo:
193
  choices=list(aspect_ratios.keys()),
194
  value="1:1",
195
  )
196
- # LoRA input settings removed
197
-
198
- with gr.Accordion("Additional Options", open=False):
199
- use_negative_prompt = gr.Checkbox(label="Use default negative prompt", value=True, visible=False)
200
- negative_prompt = gr.Text(value="", visible=False)
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  seed = gr.Slider(
203
  label="Seed",
204
  minimum=0,
@@ -207,36 +210,34 @@ with gr.Blocks(css=css) as demo:
207
  value=0,
208
  )
209
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
210
-
211
  with gr.Row():
212
  width = gr.Slider(
213
  label="Width",
214
  minimum=512,
215
  maximum=2048,
216
  step=64,
217
- value=1328,
218
  )
219
  height = gr.Slider(
220
  label="Height",
221
  minimum=512,
222
  maximum=2048,
223
  step=64,
224
- value=1328,
225
  )
226
-
227
  guidance_scale = gr.Slider(
228
  label="Guidance Scale",
229
  minimum=0.0,
230
- maximum=5.0,
231
  step=0.1,
232
- value=1.0, # Default for Turbo
233
  )
234
  num_inference_steps = gr.Slider(
235
  label="Number of inference steps",
236
  minimum=1,
237
- maximum=20,
238
  step=1,
239
- value=4, # Fixed for Turbo
240
  )
241
  num_images = gr.Slider(
242
  label="Number of images",
@@ -263,10 +264,17 @@ with gr.Blocks(css=css) as demo:
263
  outputs=[width, height]
264
  )
265
 
266
- # Run Event
 
 
 
 
 
 
 
267
  gr.on(
268
  triggers=[prompt.submit, run_button.click],
269
- fn=generate_ui,
270
  inputs=[
271
  prompt,
272
  negative_prompt,
@@ -289,18 +297,13 @@ with gr.Blocks(css=css) as demo:
289
  examples=examples,
290
  inputs=prompt,
291
  outputs=[result, seed_display, generation_time, zip_file],
292
- fn=generate_ui,
293
  cache_examples=False,
294
  )
295
 
296
  if __name__ == "__main__":
297
- demo.queue(max_size=50).launch(
298
- mcp_server=True,
299
- ssr_mode=False,
300
- show_error=True,
301
- theme=gr.themes.Soft(
302
  primary_hue="blue",
303
  secondary_hue="indigo",
304
  neutral_hue="slate",
305
- )
306
- )
 
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-2512 pipeline
34
  dtype = torch.bfloat16
35
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
 
37
  # --- Model Loading ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  print("Loading Qwen-Image-2512...")
39
+ pipe_qwen = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image-2512", torch_dtype=dtype).to(device)
40
+
41
+ # --- LoRA Configuration ---
42
+ ADAPTER_SPECS = {
43
+ "Qwen-Image-2512-Turbo-LoRA": {
44
+ "repo": "Wuli-art/Qwen-Image-2512-Turbo-LoRA",
45
+ "weights": "Wuli-Qwen-Image-2512-Turbo-LoRA-4steps-V1.0-bf16.safetensors",
46
+ "adapter_name": "turbo-fast"
47
+ },
48
+ }
49
 
50
+ # Load the Turbo LoRA by default
51
+ spec = ADAPTER_SPECS["Qwen-Image-2512-Turbo-LoRA"]
52
+ print(f"Loading Adapter: {spec['repo']}")
53
  try:
54
  pipe_qwen.load_lora_weights(
55
+ spec["repo"],
56
+ weight_name=spec["weights"],
57
+ adapter_name=spec["adapter_name"]
58
  )
59
+ pipe_qwen.fuse_lora(adapter_names=[spec["adapter_name"]], lora_scale=1.0)
60
+ print("Turbo LoRA loaded and fused successfully.")
61
  except Exception as e:
62
  print(f"Error loading LoRA: {e}")
63
 
 
70
  "3:4": (1140, 1472)
71
  }
72
 
73
+ # Generation function for Qwen/Qwen-Image-2512
 
 
 
 
 
74
  @spaces.GPU
75
  def generate_qwen(
76
  prompt: str,
 
78
  seed: int = 0,
79
  width: int = 1024,
80
  height: int = 1024,
81
+ guidance_scale: float = 4.0,
82
  randomize_seed: bool = False,
83
  num_inference_steps: int = 4,
84
  num_images: int = 1,
85
  zip_images: bool = False,
86
  progress=gr.Progress(track_tqdm=True),
87
  ):
 
 
 
88
  if randomize_seed:
89
  seed = random.randint(0, MAX_SEED)
90
  generator = torch.Generator(device).manual_seed(seed)
91
 
92
  start_time = time.time()
93
 
94
+ # Generate images
 
 
95
  images = pipe_qwen(
96
  prompt=prompt,
97
+ negative_prompt=negative_prompt if negative_prompt else "",
98
  height=height,
99
  width=width,
100
+ guidance_scale=guidance_scale,
101
  num_inference_steps=num_inference_steps,
102
  num_images_per_prompt=num_images,
103
  generator=generator,
 
118
 
119
  return image_paths, seed, f"{duration:.2f}", zip_path
120
 
121
+ # Wrapper function to handle UI logic
122
+ @spaces.GPU
123
+ def generate(
124
+ prompt: str,
125
+ negative_prompt: str,
126
+ use_negative_prompt: bool,
127
+ seed: int,
128
+ width: int,
129
+ height: int,
130
+ guidance_scale: float,
131
+ randomize_seed: bool,
132
+ num_inference_steps: int,
133
+ num_images: int,
134
+ zip_images: bool,
135
+ progress=gr.Progress(track_tqdm=True),
136
  ):
137
+ final_negative_prompt = negative_prompt if use_negative_prompt else ""
138
  return generate_qwen(
139
  prompt=prompt,
140
+ negative_prompt=final_negative_prompt,
141
  seed=seed,
142
  width=width,
143
  height=height,
 
146
  num_inference_steps=num_inference_steps,
147
  num_images=num_images,
148
  zip_images=zip_images,
149
+ progress=progress,
150
  )
151
 
152
+ # Examples
153
  examples = [
154
  "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",
155
  "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",
156
  "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.",
157
+ "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。",
158
+ "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",
159
+ "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。"
160
  ]
161
 
162
  css = '''
163
  .gradio-container {
164
+ max-width: 590px !important;
165
  margin: 0 auto !important;
166
  }
167
+ #main-title h1 { font-size: 2.3em !important; }
168
  '''
169
 
170
+ with gr.Blocks() as demo:
171
+ gr.Markdown("# **Qwen-Image-2512 Turbo**", elem_id="main-title")
172
+ gr.Markdown("Powered by **Wuli-art/Qwen-Image-2512-Turbo-LoRA** (4-Steps)")
 
173
 
174
  result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
 
175
  with gr.Row():
176
  prompt = gr.Text(
177
  label="Prompt",
 
187
  choices=list(aspect_ratios.keys()),
188
  value="1:1",
189
  )
190
+ # LoRA input removed
 
 
 
 
191
 
192
+ with gr.Accordion("Additional Options", open=False):
193
+ use_negative_prompt = gr.Checkbox(
194
+ label="Use negative prompt",
195
+ value=True,
196
+ visible=True
197
+ )
198
+ negative_prompt = gr.Text(
199
+ label="Negative prompt",
200
+ max_lines=1,
201
+ placeholder="Enter a negative prompt",
202
+ value="text, watermark, copyright, blurry, low resolution",
203
+ visible=True,
204
+ )
205
  seed = gr.Slider(
206
  label="Seed",
207
  minimum=0,
 
210
  value=0,
211
  )
212
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
213
  with gr.Row():
214
  width = gr.Slider(
215
  label="Width",
216
  minimum=512,
217
  maximum=2048,
218
  step=64,
219
+ value=1024,
220
  )
221
  height = gr.Slider(
222
  label="Height",
223
  minimum=512,
224
  maximum=2048,
225
  step=64,
226
+ value=1024,
227
  )
 
228
  guidance_scale = gr.Slider(
229
  label="Guidance Scale",
230
  minimum=0.0,
231
+ maximum=20.0,
232
  step=0.1,
233
+ value=4.0,
234
  )
235
  num_inference_steps = gr.Slider(
236
  label="Number of inference steps",
237
  minimum=1,
238
+ maximum=100,
239
  step=1,
240
+ value=4, # Default set to 4 for Turbo LoRA
241
  )
242
  num_images = gr.Slider(
243
  label="Number of images",
 
264
  outputs=[width, height]
265
  )
266
 
267
+ # Negative prompt visibility
268
+ use_negative_prompt.change(
269
+ fn=lambda x: gr.update(visible=x),
270
+ inputs=use_negative_prompt,
271
+ outputs=negative_prompt
272
+ )
273
+
274
+ # Run button and prompt submit
275
  gr.on(
276
  triggers=[prompt.submit, run_button.click],
277
+ fn=generate,
278
  inputs=[
279
  prompt,
280
  negative_prompt,
 
297
  examples=examples,
298
  inputs=prompt,
299
  outputs=[result, seed_display, generation_time, zip_file],
300
+ fn=generate,
301
  cache_examples=False,
302
  )
303
 
304
  if __name__ == "__main__":
305
+ demo.queue(max_size=50).launch(css=css, theme=gr.themes.Soft(
 
 
 
 
306
  primary_hue="blue",
307
  secondary_hue="indigo",
308
  neutral_hue="slate",
309
+ ), mcp_server=True, ssr_mode=False, show_error=True)