prithivMLmods commited on
Commit
4f8d4c0
·
verified ·
1 Parent(s): 73bfc18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -189
app.py CHANGED
@@ -2,10 +2,9 @@ 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
@@ -14,32 +13,74 @@ import requests
14
  from urllib.parse import urlparse
15
  import tempfile
16
  import shutil
 
17
 
18
- # Description for the app
19
  DESCRIPTION = """## Qwen Image Hpc/."""
20
 
21
- # Helper functions
 
 
22
  def save_image(img):
 
23
  unique_name = str(uuid.uuid4()) + ".png"
24
  img.save(unique_name)
25
  return unique_name
26
 
27
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
 
28
  if randomize_seed:
29
  seed = random.randint(0, MAX_SEED)
30
  return seed
31
 
32
- MAX_SEED = np.iinfo(np.int32).max
33
- MAX_IMAGE_SIZE = 2048
34
-
35
- # Load Qwen/Qwen-Image pipeline
36
  dtype = torch.bfloat16
37
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
38
 
39
- # --- Model Loading ---
40
- pipe_qwen = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=dtype).to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Aspect ratios
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  aspect_ratios = {
44
  "1:1": (1328, 1328),
45
  "16:9": (1664, 928),
@@ -49,29 +90,25 @@ aspect_ratios = {
49
  }
50
 
51
  def load_lora_opt(pipe, lora_input):
 
52
  lora_input = lora_input.strip()
53
  if not lora_input:
54
  return
55
 
56
- # If it's just an ID like "author/model"
57
  if "/" in lora_input and not lora_input.startswith("http"):
58
  pipe.load_lora_weights(lora_input, adapter_name="default")
59
  return
60
 
61
  if lora_input.startswith("http"):
62
  url = lora_input
63
-
64
- # Repo page (no blob/resolve)
65
  if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
66
  repo_id = urlparse(url).path.strip("/")
67
  pipe.load_lora_weights(repo_id, adapter_name="default")
68
  return
69
 
70
- # Blob link → convert to resolve link
71
  if "/blob/" in url:
72
  url = url.replace("/blob/", "/resolve/")
73
 
74
- # Download direct file
75
  tmp_dir = tempfile.mkdtemp()
76
  local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
77
 
@@ -87,7 +124,6 @@ def load_lora_opt(pipe, lora_input):
87
  finally:
88
  shutil.rmtree(tmp_dir, ignore_errors=True)
89
 
90
- # Generation function for Qwen/Qwen-Image
91
  @spaces.GPU(duration=120)
92
  def generate_qwen(
93
  prompt: str,
@@ -104,56 +140,51 @@ def generate_qwen(
104
  lora_scale: float = 1.0,
105
  progress=gr.Progress(track_tqdm=True),
106
  ):
107
- if randomize_seed:
108
- seed = random.randint(0, MAX_SEED)
109
  generator = torch.Generator(device).manual_seed(seed)
110
-
111
  start_time = time.time()
112
 
113
- current_adapters = pipe_qwen.get_list_adapters()
114
  for adapter in current_adapters:
115
- pipe_qwen.delete_adapters(adapter)
116
- pipe_qwen.disable_lora()
117
 
118
- use_lora = False
119
  if lora_input and lora_input.strip() != "":
120
- load_lora_opt(pipe_qwen, lora_input)
121
- pipe_qwen.set_adapters(["default"], adapter_weights=[lora_scale])
122
- use_lora = True
123
-
124
- images = pipe_qwen(
125
  prompt=prompt,
126
- negative_prompt=negative_prompt if negative_prompt else "",
127
  height=height,
128
  width=width,
129
  guidance_scale=guidance_scale,
130
  num_inference_steps=num_inference_steps,
131
  num_images_per_prompt=num_images,
132
  generator=generator,
133
- output_type="pil",
134
  ).images
135
-
136
  end_time = time.time()
137
  duration = end_time - start_time
138
-
139
  image_paths = [save_image(img) for img in images]
140
  zip_path = None
141
- if zip_images:
142
  zip_name = str(uuid.uuid4()) + ".zip"
143
  with zipfile.ZipFile(zip_name, 'w') as zipf:
144
  for i, img_path in enumerate(image_paths):
145
  zipf.write(img_path, arcname=f"Img_{i}.png")
146
  zip_path = zip_name
147
 
148
- # Clean up adapters
149
- current_adapters = pipe_qwen.get_list_adapters()
150
  for adapter in current_adapters:
151
- pipe_qwen.delete_adapters(adapter)
152
- pipe_qwen.disable_lora()
153
-
154
  return image_paths, seed, f"{duration:.2f}", zip_path
155
 
156
- # Wrapper function to handle UI logic
157
  @spaces.GPU(duration=120)
158
  def generate(
159
  prompt: str,
@@ -171,6 +202,7 @@ def generate(
171
  lora_scale: float,
172
  progress=gr.Progress(track_tqdm=True),
173
  ):
 
174
  final_negative_prompt = negative_prompt if use_negative_prompt else ""
175
  return generate_qwen(
176
  prompt=prompt,
@@ -188,19 +220,48 @@ def generate(
188
  progress=progress,
189
  )
190
 
191
- # Examples
192
- examples = [
193
- "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",
194
- "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",
195
- "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.",
196
- "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。",
197
- "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",
198
- "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。"
199
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  css = '''
202
  .gradio-container {
203
- max-width: 590px !important;
204
  margin: 0 auto !important;
205
  }
206
  h1 {
@@ -211,148 +272,123 @@ footer {
211
  }
212
  '''
213
 
214
- # Gradio interface
215
  with gr.Blocks(css=css, theme="bethecloud/storj_theme", delete_cache=(240, 240)) as demo:
216
  gr.Markdown(DESCRIPTION)
217
- with gr.Row():
218
- prompt = gr.Text(
219
- label="Prompt",
220
- show_label=False,
221
- max_lines=1,
222
- placeholder="✦︎ Enter your prompt",
223
- container=False,
224
- )
225
- run_button = gr.Button("Run", scale=0, variant="primary")
226
- result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
227
-
228
- with gr.Row():
229
- aspect_ratio = gr.Dropdown(
230
- label="Aspect Ratio",
231
- choices=list(aspect_ratios.keys()),
232
- value="1:1",
233
- )
234
- lora = gr.Textbox(label="qwen image lora (optional)", placeholder="enter the path...")
235
- with gr.Accordion("Additional Options", open=False):
236
- use_negative_prompt = gr.Checkbox(
237
- label="Use negative prompt",
238
- value=True,
239
- visible=True
240
- )
241
- negative_prompt = gr.Text(
242
- label="Negative prompt",
243
- max_lines=1,
244
- placeholder="Enter a negative prompt",
245
- value="text, watermark, copyright, blurry, low resolution",
246
- visible=True,
247
- )
248
- seed = gr.Slider(
249
- label="Seed",
250
- minimum=0,
251
- maximum=MAX_SEED,
252
- step=1,
253
- value=0,
254
- )
255
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
256
- with gr.Row():
257
- width = gr.Slider(
258
- label="Width",
259
- minimum=512,
260
- maximum=2048,
261
- step=64,
262
- value=1024,
263
- )
264
- height = gr.Slider(
265
- label="Height",
266
- minimum=512,
267
- maximum=2048,
268
- step=64,
269
- value=1024,
270
- )
271
- guidance_scale = gr.Slider(
272
- label="Guidance Scale",
273
- minimum=0.0,
274
- maximum=20.0,
275
- step=0.1,
276
- value=4.0,
277
- )
278
- num_inference_steps = gr.Slider(
279
- label="Number of inference steps",
280
- minimum=1,
281
- maximum=100,
282
- step=1,
283
- value=50,
284
- )
285
- num_images = gr.Slider(
286
- label="Number of images",
287
- minimum=1,
288
- maximum=5,
289
- step=1,
290
- value=1,
291
- )
292
- zip_images = gr.Checkbox(label="Zip generated images", value=False)
293
- with gr.Row():
294
- lora_scale = gr.Slider(
295
- label="LoRA Scale",
296
- minimum=0,
297
- maximum=2,
298
- step=0.01,
299
- value=1,
300
- )
301
-
302
- gr.Markdown("### Output Information")
303
- seed_display = gr.Textbox(label="Seed used", interactive=False)
304
- generation_time = gr.Textbox(label="Generation time (seconds)", interactive=False)
305
- zip_file = gr.File(label="Download ZIP")
306
-
307
- # Update aspect ratio
308
- def set_dimensions(ar):
309
- w, h = aspect_ratios[ar]
310
- return gr.update(value=w), gr.update(value=h)
311
-
312
- aspect_ratio.change(
313
- fn=set_dimensions,
314
- inputs=aspect_ratio,
315
- outputs=[width, height]
316
- )
317
 
318
- # Negative prompt visibility
319
- use_negative_prompt.change(
320
- fn=lambda x: gr.update(visible=x),
321
- inputs=use_negative_prompt,
322
- outputs=negative_prompt
323
- )
 
 
 
 
 
 
 
324
 
325
- # Run button and prompt submit
326
- gr.on(
327
- triggers=[prompt.submit, run_button.click],
328
- fn=generate,
329
- inputs=[
330
- prompt,
331
- negative_prompt,
332
- use_negative_prompt,
333
- seed,
334
- width,
335
- height,
336
- guidance_scale,
337
- randomize_seed,
338
- num_inference_steps,
339
- num_images,
340
- zip_images,
341
- lora,
342
- lora_scale,
343
- ],
344
- outputs=[result, seed_display, generation_time, zip_file],
345
- api_name="run",
346
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
 
348
- # Examples
349
- gr.Examples(
350
- examples=examples,
351
- inputs=prompt,
352
- outputs=[result, seed_display, generation_time, zip_file],
353
- fn=generate,
354
- cache_examples=False,
355
- )
356
 
357
  if __name__ == "__main__":
358
- demo.queue(max_size=50).launch(share=False, mcp_server=True, ssr_mode=False, debug=True, show_error=True)
 
2
  import gradio as gr
3
  import torch
4
  from PIL import Image
5
+ from diffusers import DiffusionPipeline, QwenImageEditPipeline, FlowMatchEulerDiscreteScheduler
6
  import random
7
  import uuid
 
8
  import numpy as np
9
  import time
10
  import zipfile
 
13
  from urllib.parse import urlparse
14
  import tempfile
15
  import shutil
16
+ import math
17
 
18
+ # --- App Description ---
19
  DESCRIPTION = """## Qwen Image Hpc/."""
20
 
21
+ # --- Helper Functions for Both Tabs ---
22
+ MAX_SEED = np.iinfo(np.int32).max
23
+
24
  def save_image(img):
25
+ """Saves a PIL image to a temporary file with a unique name."""
26
  unique_name = str(uuid.uuid4()) + ".png"
27
  img.save(unique_name)
28
  return unique_name
29
 
30
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
31
+ """Returns a random seed if randomize_seed is True, otherwise returns the original seed."""
32
  if randomize_seed:
33
  seed = random.randint(0, MAX_SEED)
34
  return seed
35
 
36
+ # --- Model Loading ---
 
 
 
37
  dtype = torch.bfloat16
38
+ device = "cuda" if torch.cuda.is_available() else "cpu"
39
 
40
+ # --- Qwen-Image-Gen Model ---
41
+ pipe_qwen_gen = DiffusionPipeline.from_pretrained(
42
+ "Qwen/Qwen-Image",
43
+ torch_dtype=dtype
44
+ ).to(device)
45
+
46
+ # --- Qwen-Image-Edit Model with Lightning LoRA ---
47
+ scheduler_config = {
48
+ "base_image_seq_len": 256,
49
+ "base_shift": math.log(3),
50
+ "invert_sigmas": False,
51
+ "max_image_seq_len": 8192,
52
+ "max_shift": math.log(3),
53
+ "num_train_timesteps": 1000,
54
+ "shift": 1.0,
55
+ "shift_terminal": None,
56
+ "stochastic_sampling": False,
57
+ "time_shift_type": "exponential",
58
+ "use_beta_sigmas": False,
59
+ "use_dynamic_shifting": True,
60
+ "use_exponential_sigmas": False,
61
+ "use_karras_sigmas": False,
62
+ }
63
+ scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
64
 
65
+ pipe_qwen_edit = QwenImageEditPipeline.from_pretrained(
66
+ "Qwen/Qwen-Image-Edit",
67
+ scheduler=scheduler,
68
+ torch_dtype=dtype
69
+ ).to(device)
70
+
71
+ try:
72
+ pipe_qwen_edit.load_lora_weights(
73
+ "lightx2v/Qwen-Image-Lightning",
74
+ weight_name="Qwen-Image-Lightning-8steps-V1.1.safetensors"
75
+ )
76
+ pipe_qwen_edit.fuse_lora()
77
+ print("Successfully loaded Lightning LoRA weights for Qwen-Image-Edit")
78
+ except Exception as e:
79
+ print(f"Warning: Could not load Lightning LoRA weights for Qwen-Image-Edit: {e}")
80
+ print("Continuing with the base Qwen-Image-Edit model...")
81
+
82
+
83
+ # --- Qwen-Image-Gen Functions ---
84
  aspect_ratios = {
85
  "1:1": (1328, 1328),
86
  "16:9": (1664, 928),
 
90
  }
91
 
92
  def load_lora_opt(pipe, lora_input):
93
+ """Loads a LoRA from a local path, Hugging Face repo, or URL."""
94
  lora_input = lora_input.strip()
95
  if not lora_input:
96
  return
97
 
 
98
  if "/" in lora_input and not lora_input.startswith("http"):
99
  pipe.load_lora_weights(lora_input, adapter_name="default")
100
  return
101
 
102
  if lora_input.startswith("http"):
103
  url = lora_input
 
 
104
  if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:
105
  repo_id = urlparse(url).path.strip("/")
106
  pipe.load_lora_weights(repo_id, adapter_name="default")
107
  return
108
 
 
109
  if "/blob/" in url:
110
  url = url.replace("/blob/", "/resolve/")
111
 
 
112
  tmp_dir = tempfile.mkdtemp()
113
  local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))
114
 
 
124
  finally:
125
  shutil.rmtree(tmp_dir, ignore_errors=True)
126
 
 
127
  @spaces.GPU(duration=120)
128
  def generate_qwen(
129
  prompt: str,
 
140
  lora_scale: float = 1.0,
141
  progress=gr.Progress(track_tqdm=True),
142
  ):
143
+ """Main generation function for Qwen-Image-Gen."""
144
+ seed = randomize_seed_fn(seed, randomize_seed)
145
  generator = torch.Generator(device).manual_seed(seed)
146
+
147
  start_time = time.time()
148
 
149
+ current_adapters = pipe_qwen_gen.get_list_adapters()
150
  for adapter in current_adapters:
151
+ pipe_qwen_gen.delete_adapters(adapter)
152
+ pipe_qwen_gen.disable_lora()
153
 
 
154
  if lora_input and lora_input.strip() != "":
155
+ load_lora_opt(pipe_qwen_gen, lora_input)
156
+ pipe_qwen_gen.set_adapters(["default"], adapter_weights=[lora_scale])
157
+
158
+ images = pipe_qwen_gen(
 
159
  prompt=prompt,
160
+ negative_prompt=negative_prompt if negative_prompt else " ",
161
  height=height,
162
  width=width,
163
  guidance_scale=guidance_scale,
164
  num_inference_steps=num_inference_steps,
165
  num_images_per_prompt=num_images,
166
  generator=generator,
 
167
  ).images
168
+
169
  end_time = time.time()
170
  duration = end_time - start_time
171
+
172
  image_paths = [save_image(img) for img in images]
173
  zip_path = None
174
+ if zip_images and len(image_paths) > 0:
175
  zip_name = str(uuid.uuid4()) + ".zip"
176
  with zipfile.ZipFile(zip_name, 'w') as zipf:
177
  for i, img_path in enumerate(image_paths):
178
  zipf.write(img_path, arcname=f"Img_{i}.png")
179
  zip_path = zip_name
180
 
181
+ current_adapters = pipe_qwen_gen.get_list_adapters()
 
182
  for adapter in current_adapters:
183
+ pipe_qwen_gen.delete_adapters(adapter)
184
+ pipe_qwen_gen.disable_lora()
185
+
186
  return image_paths, seed, f"{duration:.2f}", zip_path
187
 
 
188
  @spaces.GPU(duration=120)
189
  def generate(
190
  prompt: str,
 
202
  lora_scale: float,
203
  progress=gr.Progress(track_tqdm=True),
204
  ):
205
+ """UI wrapper for the Qwen-Image-Gen generation function."""
206
  final_negative_prompt = negative_prompt if use_negative_prompt else ""
207
  return generate_qwen(
208
  prompt=prompt,
 
220
  progress=progress,
221
  )
222
 
223
+ # --- Qwen-Image-Edit Functions ---
224
+ @spaces.GPU(duration=60)
225
+ def infer_edit(
226
+ image,
227
+ prompt,
228
+ seed=42,
229
+ randomize_seed=False,
230
+ true_guidance_scale=1.0,
231
+ num_inference_steps=8,
232
+ progress=gr.Progress(track_tqdm=True),
233
+ ):
234
+ """Main inference function for Qwen-Image-Edit."""
235
+ if image is None:
236
+ raise gr.Error("Please upload an image to edit.")
237
+
238
+ negative_prompt = " "
239
+ seed = randomize_seed_fn(seed, randomize_seed)
240
+ generator = torch.Generator(device=device).manual_seed(seed)
241
+
242
+ print(f"Original prompt: '{prompt}'")
243
+ print(f"Negative Prompt: '{negative_prompt}'")
244
+ print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}")
245
 
246
+ try:
247
+ images = pipe_qwen_edit(
248
+ image,
249
+ prompt=prompt,
250
+ negative_prompt=negative_prompt,
251
+ num_inference_steps=num_inference_steps,
252
+ generator=generator,
253
+ true_cfg_scale=true_guidance_scale,
254
+ num_images_per_prompt=1
255
+ ).images
256
+ return images[0], seed
257
+ except Exception as e:
258
+ print(f"Error during inference: {e}")
259
+ raise gr.Error(f"An error occurred during image editing: {e}")
260
+
261
+ # --- Gradio UI ---
262
  css = '''
263
  .gradio-container {
264
+ max-width: 800px !important;
265
  margin: 0 auto !important;
266
  }
267
  h1 {
 
272
  }
273
  '''
274
 
 
275
  with gr.Blocks(css=css, theme="bethecloud/storj_theme", delete_cache=(240, 240)) as demo:
276
  gr.Markdown(DESCRIPTION)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
+ with gr.Tabs():
279
+ with gr.TabItem("Qwen-Image-Gen"):
280
+ with gr.Column():
281
+ with gr.Row():
282
+ prompt_gen = gr.Text(
283
+ label="Prompt",
284
+ show_label=False,
285
+ max_lines=1,
286
+ placeholder="✦︎ Enter your prompt for generation",
287
+ container=False,
288
+ )
289
+ run_button_gen = gr.Button("Generate", scale=0, variant="primary")
290
+ result_gen = gr.Gallery(label="Result", columns=2, show_label=False, preview=True, height="auto")
291
 
292
+ with gr.Row():
293
+ aspect_ratio_gen = gr.Dropdown(
294
+ label="Aspect Ratio",
295
+ choices=list(aspect_ratios.keys()),
296
+ value="1:1",
297
+ )
298
+ lora_gen = gr.Textbox(label="Optional LoRA", placeholder="Enter Hugging Face repo ID or URL...")
299
+
300
+ with gr.Accordion("Additional Options", open=False):
301
+ use_negative_prompt_gen = gr.Checkbox(label="Use negative prompt", value=True)
302
+ negative_prompt_gen = gr.Text(
303
+ label="Negative prompt",
304
+ max_lines=1,
305
+ placeholder="Enter a negative prompt",
306
+ value="text, watermark, copyright, blurry, low resolution",
307
+ )
308
+ seed_gen = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
309
+ randomize_seed_gen = gr.Checkbox(label="Randomize seed", value=True)
310
+ with gr.Row():
311
+ width_gen = gr.Slider(label="Width", minimum=512, maximum=2048, step=64, value=1328)
312
+ height_gen = gr.Slider(label="Height", minimum=512, maximum=2048, step=64, value=1328)
313
+ guidance_scale_gen = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=20.0, step=0.1, value=4.0)
314
+ num_inference_steps_gen = gr.Slider("Number of inference steps", 1, 100, 50, step=1)
315
+ num_images_gen = gr.Slider("Number of images", 1, 5, 1, step=1)
316
+ zip_images_gen = gr.Checkbox(label="Zip generated images", value=False)
317
+ with gr.Row():
318
+ lora_scale_gen = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1)
319
+
320
+ gr.Markdown("### Output Information")
321
+ seed_display_gen = gr.Textbox(label="Seed used", interactive=False)
322
+ generation_time_gen = gr.Textbox(label="Generation time (seconds)", interactive=False)
323
+ zip_file_gen = gr.File(label="Download ZIP")
324
+
325
+ # --- Gen Tab Logic ---
326
+ def set_dimensions(ar):
327
+ w, h = aspect_ratios[ar]
328
+ return gr.update(value=w), gr.update(value=h)
329
+
330
+ aspect_ratio_gen.change(fn=set_dimensions, inputs=aspect_ratio_gen, outputs=[width_gen, height_gen])
331
+ use_negative_prompt_gen.change(fn=lambda x: gr.update(visible=x), inputs=use_negative_prompt_gen, outputs=negative_prompt_gen)
332
+
333
+ gen_inputs = [
334
+ prompt_gen, negative_prompt_gen, use_negative_prompt_gen, seed_gen, width_gen, height_gen,
335
+ guidance_scale_gen, randomize_seed_gen, num_inference_steps_gen, num_images_gen,
336
+ zip_images_gen, lora_gen, lora_scale_gen
337
+ ]
338
+ gen_outputs = [result_gen, seed_display_gen, generation_time_gen, zip_file_gen]
339
+
340
+ gr.on(triggers=[prompt_gen.submit, run_button_gen.click], fn=generate, inputs=gen_inputs, outputs=gen_outputs)
341
+
342
+ gen_examples = [
343
+ "A decadent slice of layered chocolate cake on a ceramic plate with a drizzle of chocolate syrup and powdered sugar dusted on top.",
344
+ "A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text 'Introducing Qwen-Image' appears in neat white chalk.",
345
+ "一幅精致细腻的工笔画,画面中心是一株��勃生长的红色牡丹,花朵繁茂。",
346
+ "Realistic still life photography style: A single, fresh apple, resting on a clean, soft-textured surface.",
347
+ ]
348
+ gr.Examples(examples=gen_examples, inputs=prompt_gen, outputs=gen_outputs, fn=generate, cache_examples=False)
349
+
350
+ with gr.TabItem("Qwen-Image-Edit"):
351
+ with gr.Column():
352
+ with gr.Row():
353
+ input_image_edit = gr.Image(label="Input Image", type="pil", height=400)
354
+ result_edit = gr.Image(label="Result", type="pil", height=400)
355
+
356
+ with gr.Row():
357
+ prompt_edit = gr.Text(
358
+ label="Edit Instruction",
359
+ show_label=False,
360
+ placeholder="Describe the edit you want to make",
361
+ container=False,
362
+ )
363
+ run_button_edit = gr.Button("Edit", variant="primary")
364
+
365
+ with gr.Accordion("Advanced Settings", open=False):
366
+ seed_edit = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
367
+ randomize_seed_edit = gr.Checkbox(label="Randomize seed", value=True)
368
+ with gr.Row():
369
+ true_guidance_scale_edit = gr.Slider(
370
+ label="True guidance scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0
371
+ )
372
+ num_inference_steps_edit = gr.Slider(
373
+ label="Inference steps (Lightning LoRA)", minimum=4, maximum=28, step=1, value=8
374
+ )
375
+
376
+ # --- Edit Tab Logic ---
377
+ edit_inputs = [
378
+ input_image_edit, prompt_edit, seed_edit, randomize_seed_edit,
379
+ true_guidance_scale_edit, num_inference_steps_edit
380
+ ]
381
+ edit_outputs = [result_edit, seed_edit]
382
+
383
+ gr.on(triggers=[prompt_edit.submit, run_button_edit.click], fn=infer_edit, inputs=edit_inputs, outputs=edit_outputs)
384
+
385
+ edit_examples = [
386
+ ["image-edit/cat.png", "make the cat wear sunglasses"],
387
+ ["image-edit/girl.png", "change her hair to blonde"],
388
+ ]
389
+
390
+ gr.Examples(examples=edit_examples, inputs=[input_image_edit, prompt_edit], outputs=edit_outputs, fn=infer_edit, cache_examples=True)
391
 
 
 
 
 
 
 
 
 
392
 
393
  if __name__ == "__main__":
394
+ demo.queue(max_size=50).launch(share=False, debug=True)