Run it directly on Spaces

#8
by multimodalart HF Staff - opened
Files changed (1) hide show
  1. app.py +54 -60
app.py CHANGED
@@ -1,23 +1,24 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
 
4
 
5
  from PIL import Image
 
6
 
7
- import spaces
8
- from http import HTTPStatus
9
- from urllib.parse import urlparse, unquote
10
- from pathlib import PurePosixPath
11
- import requests
12
- from dashscope import ImageSynthesis
13
- import os
14
 
15
- MAX_SEED = np.iinfo(np.int32).max
16
- MAX_IMAGE_SIZE = 1440
17
 
 
 
18
 
19
- # (1664, 928), (1472, 1140), (1328, 1328)
20
  def get_image_size(aspect_ratio):
 
21
  if aspect_ratio == "1:1":
22
  return 1328, 1328
23
  elif aspect_ratio == "16:9":
@@ -29,47 +30,54 @@ def get_image_size(aspect_ratio):
29
  elif aspect_ratio == "3:4":
30
  return 1140, 1472
31
  else:
 
32
  return 1328, 1328
33
 
 
34
  @spaces.GPU(duration=120)
35
  def infer(
36
  prompt,
37
- negative_prompt=" ",
38
  seed=42,
39
  randomize_seed=False,
40
  aspect_ratio="16:9",
41
- guidance_scale=4,
42
  num_inference_steps=50,
43
  progress=gr.Progress(track_tqdm=True),
44
  ):
 
 
 
 
 
 
45
  if randomize_seed:
46
  seed = random.randint(0, MAX_SEED)
 
 
47
  width, height = get_image_size(aspect_ratio)
48
- print("calling with prompt: %s" % prompt)
49
- rsp = ImageSynthesis.call(api_key=os.environ.get("DASH_API_KEY"),
50
- model="qwen-image",
51
- prompt=prompt,
52
- negative_prompt=negative_prompt,
53
- n=1,
54
- seed=seed,
55
- guidance_scale=guidance_scale,
56
- steps=num_inference_steps,
57
- size=f'{width}*{height}'
58
- ) # support 1664*928, 1472*1140, 1328*1328, 1140*1472, 928*1664
59
- print('response: %s' % rsp)
60
- if rsp.status_code == HTTPStatus.OK:
61
- # 在当前目录下保存图片
62
- for result in rsp.output.results:
63
- file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
64
- with open('./%s' % file_name, 'wb+') as f:
65
- f.write(requests.get(result.url).content)
66
- print(f'save image to {file_name}')
67
- else:
68
- print('sync_call Failed, status_code: %s, code: %s, message: %s' %
69
- (rsp.status_code, rsp.code, rsp.message))
70
- image = Image.open(file_name)
71
  return image, seed
72
 
 
73
  examples = [
74
  "A capybara wearing a suit holding a sign that reads Hello World",
75
  "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。",
@@ -77,7 +85,7 @@ examples = [
77
  " 一个可抽取式的纸巾盒子,上面写着'Face, CLEAN & SOFT TISSUE'下面写着'亲肤可湿水',左上角是品牌名'洁柔',整体是白色和浅黄色的色调",
78
  "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色��表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。",
79
  '一个会议室,墙上写着"3.14159265-358979-32384626-4338327950",一个小陀螺在桌上转动',
80
- '一个咖啡点门口有一个黑板,上面写着通义千问咖啡,2美元一杯,旁边有个霓虹灯,写着阿里巴巴,旁边有个海报,海报上面是一个中国美女,海报下方写着qwen newbee',
81
  """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""",
82
  "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."
83
  ]
@@ -89,12 +97,9 @@ css = """
89
  }
90
  """
91
 
92
-
93
-
94
  with gr.Blocks(css=css) as demo:
95
  with gr.Column(elem_id="col-container"):
96
- # gr.Markdown('<div style="text-align: center;"><a href="https://huggingface.co/Qwen/Qwen-Image"><img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_logo.png" width="400"/></a></div>')
97
- gr.Markdown('<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_logo.png" alt="your_alt_text" width="400" style="display: block; margin: 0 auto;">')
98
  gr.Markdown("[Learn more](https://github.com/QwenLM/Qwen-Image) about the Qwen-Image series. Try on [Qwen Chat](https://chat.qwen.ai/), or [download model](https://huggingface.co/Qwen/Qwen-Image) to run locally with ComfyUI or diffusers.")
99
  with gr.Row():
100
  prompt = gr.Text(
@@ -102,25 +107,13 @@ with gr.Blocks(css=css) as demo:
102
  show_label=False,
103
  placeholder="Enter your prompt",
104
  container=False,
105
-
106
  )
107
  run_button = gr.Button("Run", scale=0, variant="primary")
108
 
109
- result = gr.Image(label="Result", show_label=False)
110
 
111
  with gr.Accordion("Advanced Settings", open=False):
112
- negative_prompt = gr.Text(
113
- label="Negative prompt",
114
- max_lines=1,
115
- placeholder="Enter a negative prompt",
116
- visible=False,
117
- )
118
- negative_prompt = gr.Text(
119
- label="Negative prompt",
120
- max_lines=1,
121
- placeholder="Enter a negative prompt",
122
- visible=False,
123
- )
124
 
125
  seed = gr.Slider(
126
  label="Seed",
@@ -134,7 +127,7 @@ with gr.Blocks(css=css) as demo:
134
 
135
  with gr.Row():
136
  aspect_ratio = gr.Radio(
137
- label="Aspect ratio(width:height)",
138
  choices=["1:1", "16:9", "9:16", "4:3", "3:4"],
139
  value="16:9",
140
  )
@@ -143,7 +136,7 @@ with gr.Blocks(css=css) as demo:
143
  guidance_scale = gr.Slider(
144
  label="Guidance scale",
145
  minimum=0.0,
146
- maximum=7.5,
147
  step=0.1,
148
  value=4.0,
149
  )
@@ -153,16 +146,17 @@ with gr.Blocks(css=css) as demo:
153
  minimum=1,
154
  maximum=50,
155
  step=1,
156
- value=50,
157
  )
158
 
159
- gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False, cache_mode="lazy")
 
160
  gr.on(
161
  triggers=[run_button.click, prompt.submit],
162
  fn=infer,
163
  inputs=[
164
  prompt,
165
- negative_prompt,
166
  seed,
167
  randomize_seed,
168
  aspect_ratio,
@@ -173,4 +167,4 @@ with gr.Blocks(css=css) as demo:
173
  )
174
 
175
  if __name__ == "__main__":
176
- demo.launch(ssr_mode=False)
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ import torch
5
+ import spaces
6
 
7
  from PIL import Image
8
+ from diffusers import QwenImagePipeline
9
 
10
+ # --- Model Loading ---
11
+ dtype = torch.bfloat16
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
13
 
14
+ # Load the model pipeline
15
+ pipe = QwenImagePipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=dtype).to(device)
16
 
17
+ # --- UI Constants and Helpers ---
18
+ MAX_SEED = np.iinfo(np.int32).max
19
 
 
20
  def get_image_size(aspect_ratio):
21
+ """Converts aspect ratio string to width, height tuple."""
22
  if aspect_ratio == "1:1":
23
  return 1328, 1328
24
  elif aspect_ratio == "16:9":
 
30
  elif aspect_ratio == "3:4":
31
  return 1140, 1472
32
  else:
33
+ # Default to 1:1 if something goes wrong
34
  return 1328, 1328
35
 
36
+ # --- Main Inference Function (with hardcoded negative prompt) ---
37
  @spaces.GPU(duration=120)
38
  def infer(
39
  prompt,
 
40
  seed=42,
41
  randomize_seed=False,
42
  aspect_ratio="16:9",
43
+ guidance_scale=4.0,
44
  num_inference_steps=50,
45
  progress=gr.Progress(track_tqdm=True),
46
  ):
47
+ """
48
+ Generates an image using the local Qwen-Image diffusers pipeline.
49
+ """
50
+ # Hardcode the negative prompt as requested
51
+ negative_prompt = "text, watermark, copyright, blurry, low resolution"
52
+
53
  if randomize_seed:
54
  seed = random.randint(0, MAX_SEED)
55
+
56
+ # Convert aspect ratio to width and height
57
  width, height = get_image_size(aspect_ratio)
58
+
59
+ # Set up the generator for reproducibility
60
+ generator = torch.Generator(device=device).manual_seed(seed)
61
+
62
+ print(f"Calling pipeline with prompt: '{prompt}'")
63
+ print(f"Negative Prompt: '{negative_prompt}'")
64
+ print(f"Seed: {seed}, Size: {width}x{height}, Steps: {num_inference_steps}, Guidance: {guidance_scale}")
65
+
66
+ # Generate the image
67
+ image = pipe(
68
+ prompt=prompt,
69
+ negative_prompt=negative_prompt,
70
+ width=width,
71
+ height=height,
72
+ num_inference_steps=num_inference_steps,
73
+ generator=generator,
74
+ true_cfg_scale=guidance_scale,
75
+ guidance_scale=1.0 # Use a fixed default for distilled guidance
76
+ ).images[0]
77
+
 
 
 
78
  return image, seed
79
 
80
+ # --- Examples and UI Layout ---
81
  examples = [
82
  "A capybara wearing a suit holding a sign that reads Hello World",
83
  "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。",
 
85
  " 一个可抽取式的纸巾盒子,上面写着'Face, CLEAN & SOFT TISSUE'下面写着'亲肤可湿水',左上角是品牌名'洁柔',整体是白色和浅黄色的色调",
86
  "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色��表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。",
87
  '一个会议室,墙上写着"3.14159265-358979-32384626-4338327950",一个小陀螺在桌上转动',
88
+ '一个咖啡店门口有一个黑板,上面写着通义千问咖啡,2美元一杯,旁边有个霓虹灯,写着阿里巴巴,旁边有个海报,海报上面是一个中国美女,海报下方写着qwen newbee',
89
  """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""",
90
  "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."
91
  ]
 
97
  }
98
  """
99
 
 
 
100
  with gr.Blocks(css=css) as demo:
101
  with gr.Column(elem_id="col-container"):
102
+ gr.Markdown('<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_logo.png" alt="Qwen-Image Logo" width="400" style="display: block; margin: 0 auto;">')
 
103
  gr.Markdown("[Learn more](https://github.com/QwenLM/Qwen-Image) about the Qwen-Image series. Try on [Qwen Chat](https://chat.qwen.ai/), or [download model](https://huggingface.co/Qwen/Qwen-Image) to run locally with ComfyUI or diffusers.")
104
  with gr.Row():
105
  prompt = gr.Text(
 
107
  show_label=False,
108
  placeholder="Enter your prompt",
109
  container=False,
 
110
  )
111
  run_button = gr.Button("Run", scale=0, variant="primary")
112
 
113
+ result = gr.Image(label="Result", show_label=False, type="pil")
114
 
115
  with gr.Accordion("Advanced Settings", open=False):
116
+ # Negative prompt UI element is removed here
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  seed = gr.Slider(
119
  label="Seed",
 
127
 
128
  with gr.Row():
129
  aspect_ratio = gr.Radio(
130
+ label="Aspect ratio (width:height)",
131
  choices=["1:1", "16:9", "9:16", "4:3", "3:4"],
132
  value="16:9",
133
  )
 
136
  guidance_scale = gr.Slider(
137
  label="Guidance scale",
138
  minimum=0.0,
139
+ maximum=10.0,
140
  step=0.1,
141
  value=4.0,
142
  )
 
146
  minimum=1,
147
  maximum=50,
148
  step=1,
149
+ value=50,
150
  )
151
 
152
+ gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False)
153
+
154
  gr.on(
155
  triggers=[run_button.click, prompt.submit],
156
  fn=infer,
157
  inputs=[
158
  prompt,
159
+ # negative_prompt is no longer an input from the UI
160
  seed,
161
  randomize_seed,
162
  aspect_ratio,
 
167
  )
168
 
169
  if __name__ == "__main__":
170
+ demo.launch()