prithivMLmods commited on
Commit
ee5186b
·
verified ·
1 Parent(s): 68a17c4
Files changed (1) hide show
  1. app.py +358 -0
app.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 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),
46
+ "9:16": (928, 1664),
47
+ "4:3": (1472, 1140),
48
+ "3:4": (1140, 1472)
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
+
78
+ try:
79
+ print(f"Downloading LoRA from {url}...")
80
+ resp = requests.get(url, stream=True)
81
+ resp.raise_for_status()
82
+ with open(local_path, "wb") as f:
83
+ for chunk in resp.iter_content(chunk_size=8192):
84
+ f.write(chunk)
85
+ print(f"Saved LoRA to {local_path}")
86
+ pipe.load_lora_weights(local_path, adapter_name="default")
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,
94
+ negative_prompt: str = "",
95
+ seed: int = 0,
96
+ width: int = 1024,
97
+ height: int = 1024,
98
+ guidance_scale: float = 4.0,
99
+ randomize_seed: bool = False,
100
+ num_inference_steps: int = 50,
101
+ num_images: int = 1,
102
+ zip_images: bool = False,
103
+ lora_input: str = "",
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,
160
+ negative_prompt: str,
161
+ use_negative_prompt: bool,
162
+ seed: int,
163
+ width: int,
164
+ height: int,
165
+ guidance_scale: float,
166
+ randomize_seed: bool,
167
+ num_inference_steps: int,
168
+ num_images: int,
169
+ zip_images: bool,
170
+ lora_input: str,
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,
177
+ negative_prompt=final_negative_prompt,
178
+ seed=seed,
179
+ width=width,
180
+ height=height,
181
+ guidance_scale=guidance_scale,
182
+ randomize_seed=randomize_seed,
183
+ num_inference_steps=num_inference_steps,
184
+ num_images=num_images,
185
+ zip_images=zip_images,
186
+ lora_input=lora_input,
187
+ lora_scale=lora_scale,
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 {
207
+ text-align: center;
208
+ }
209
+ footer {
210
+ visibility: hidden;
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)