Update app.py

#1
by naykun - opened
Files changed (1) hide show
  1. app.py +126 -132
app.py CHANGED
@@ -1,181 +1,175 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
- import spaces
5
- import torch
6
- from diffusers import QwenImagePipeline
7
 
8
- dtype = torch.bfloat16
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
 
11
- pipe = QwenImagePipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=dtype).to(device)
 
 
 
 
 
12
 
13
  MAX_SEED = np.iinfo(np.int32).max
14
- MAX_IMAGE_SIZE = 1536
15
-
16
- @spaces.GPU()
17
- def infer(prompt, negative_prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, true_cfg_scale=4.0, distilled_cfg_scale=1.0, progress=gr.Progress(track_tqdm=True)):
18
- """
19
- Generates an image based on a user's prompt using the Qwen-Image pipeline.
20
-
21
- This function takes textual prompts and various generation parameters,
22
- handles seed randomization, and runs the diffusion model to produce an image.
23
-
24
- Args:
25
- prompt (str): The positive text prompt to guide image generation.
26
- negative_prompt (str): The negative text prompt to guide the model
27
- on what to avoid in the generated image.
28
- seed (int, optional): The seed for the random number generator to ensure
29
- reproducible results. Defaults to 42.
30
- randomize_seed (bool, optional): If True, a random seed is generated,
31
- overriding the `seed` parameter. Defaults to False.
32
- width (int, optional): The width of the generated image in pixels.
33
- Defaults to 1024.
34
- height (int, optional): The height of the generated image in pixels.
35
- Defaults to 1024.
36
- num_inference_steps (int, optional): The number of denoising steps.
37
- More steps can lead to higher quality but take longer. Defaults to 4.
38
- true_cfg_scale (float, optional): The Classifier-Free Guidance scale.
39
- Controls how strictly the model follows the prompt. Defaults to 4.0.
40
- progress (gr.Progress, optional): A Gradio Progress object to track
41
- the inference progress in the UI.
42
-
43
- Returns:
44
- tuple: A tuple containing:
45
- - PIL.Image.Image: The generated image.
46
- - int: The seed used for the generation, which is useful for
47
- reproducibility, especially when `randomize_seed` is True.
48
- """
49
  if randomize_seed:
50
  seed = random.randint(0, MAX_SEED)
51
-
52
- generator = torch.Generator().manual_seed(seed)
53
-
54
- image = pipe(
55
- prompt=prompt,
56
- negative_prompt=negative_prompt,
57
- width=width,
58
- height=height,
59
- num_inference_steps=num_inference_steps,
60
- generator=generator,
61
- true_cfg_scale=true_cfg_scale,
62
- guidance_scale=distilled_cfg_scale
63
- ).images[0]
64
-
 
 
 
 
 
 
 
 
 
 
65
  return image, seed
66
-
67
  examples = [
68
- ["a tiny dragon hatching from a crystal egg on Mars"],
69
- ["a red panda holding a sign that says 'I love bamboo'"],
70
- ["a photo of a capybara riding a tricycle in Paris. It is wearing a beret and a striped shirt."],
71
- ["an anime illustration of a delicious ramen bowl"],
72
- ["A logo for a bookstore called 'The Whispering Page'. The logo should feature an open book with a tree growing out of it."],
 
 
 
 
73
  ]
74
 
75
- css="""
76
  #col-container {
77
  margin: 0 auto;
78
- max-width: 580px;
79
  }
80
  """
81
 
82
- # Build the Gradio UI.
 
83
  with gr.Blocks(css=css) as demo:
84
-
85
  with gr.Column(elem_id="col-container"):
86
- # Title and description for the demo.
87
- gr.Markdown(f"""# Qwen-Image
88
- Gradio demo for [Qwen-Image](https://huggingface.co/Qwen/Qwen-Image), a powerful text-to-image model from the Qwen team at Alibaba.
89
- """)
90
-
91
  with gr.Row():
92
- # Main prompt input.
93
  prompt = gr.Text(
94
  label="Prompt",
95
  show_label=False,
96
- max_lines=1,
97
  placeholder="Enter your prompt",
98
  container=False,
 
99
  )
100
- # The "Run" button.
101
- run_button = gr.Button("Run", scale=0)
102
-
103
-
104
  result = gr.Image(label="Result", show_label=False)
105
-
106
- negative_prompt = gr.Text(
107
- label="Negative Prompt",
108
- max_lines=1,
109
- placeholder="Enter a negative prompt",
110
- value="text, watermark, copyright, blurry, low resolution",
111
- )
112
- # Accordion for advanced settings.
113
  with gr.Accordion("Advanced Settings", open=False):
114
-
 
 
 
 
 
 
 
 
 
 
 
 
115
  seed = gr.Slider(
116
  label="Seed",
117
  minimum=0,
118
  maximum=MAX_SEED,
119
  step=1,
120
- value=42,
121
  )
122
-
123
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
124
-
125
  with gr.Row():
126
- width = gr.Slider(
127
- label="Width",
128
- minimum=256,
129
- maximum=MAX_IMAGE_SIZE,
130
- step=32,
131
- value=1024,
132
- )
133
- height = gr.Slider(
134
- label="Height",
135
- minimum=256,
136
- maximum=MAX_IMAGE_SIZE,
137
- step=32,
138
- value=1024,
139
  )
140
-
141
  with gr.Row():
 
 
 
 
 
 
 
 
142
  num_inference_steps = gr.Slider(
143
- label="Inference Steps",
144
  minimum=1,
145
  maximum=50,
146
  step=1,
147
- value=28,
148
- )
149
- true_cfg_scale = gr.Slider(
150
- label="CFG Scale",
151
- info="Controls how much the model follows the prompt. Higher values mean stricter adherence.",
152
- minimum=1.0,
153
- maximum=10.0,
154
- step=0.1,
155
- value=4.0
156
- )
157
- distilled_cfg_scale = gr.Slider(
158
- label="Distilled Guidance",
159
- minimum=0.0,
160
- maximum=20.0,
161
- step=0.1,
162
- value=1.0
163
  )
164
-
165
- gr.Examples(
166
- examples=examples,
167
- fn=infer,
168
- inputs=[prompt, negative_prompt],
169
- outputs=[result, seed],
170
- cache_examples=True,
171
- cache_mode='lazy'
172
- )
173
 
 
174
  gr.on(
175
- triggers=[run_button.click, prompt.submit, negative_prompt.submit],
176
  fn=infer,
177
- inputs=[prompt, negative_prompt, seed, randomize_seed, width, height, num_inference_steps, true_cfg_scale, distilled_cfg_scale],
178
- outputs=[result, seed]
 
 
 
 
 
 
 
 
179
  )
180
 
181
- demo.launch(mcp_server=True)
 
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
 
 
4
 
5
+ from PIL import Image
 
6
 
7
+ from http import HTTPStatus
8
+ from urllib.parse import urlparse, unquote
9
+ from pathlib import PurePosixPath
10
+ import requests
11
+ from dashscope import ImageSynthesis
12
+ import os
13
 
14
  MAX_SEED = np.iinfo(np.int32).max
15
+ MAX_IMAGE_SIZE = 1440
16
+
17
+
18
+ # (1664, 928), (1472, 1140), (1328, 1328)
19
+ def get_image_size(aspect_ratio):
20
+ if aspect_ratio == "1:1":
21
+ return 1328, 1328
22
+ elif aspect_ratio == "16:9":
23
+ return 1664, 928
24
+ elif aspect_ratio == "9:16":
25
+ return 928, 1664
26
+ elif aspect_ratio == "4:3":
27
+ return 1472, 1140
28
+ elif aspect_ratio == "3:4":
29
+ return 1140, 1472
30
+ else:
31
+ return 1328, 1328
32
+
33
+
34
+ def infer(
35
+ prompt,
36
+ negative_prompt=" ",
37
+ seed=42,
38
+ randomize_seed=False,
39
+ aspect_ratio="16:9",
40
+ guidance_scale=4,
41
+ num_inference_steps=50,
42
+ progress=gr.Progress(track_tqdm=True),
43
+ ):
 
 
 
 
 
 
44
  if randomize_seed:
45
  seed = random.randint(0, MAX_SEED)
46
+ width, height = get_image_size(aspect_ratio)
47
+
48
+ rsp = ImageSynthesis.call(api_key=os.environ.get("DASH_API_KEY"),
49
+ model="qwen-image",
50
+ prompt=prompt,
51
+ negative_prompt=negative_prompt,
52
+ n=1,
53
+ seed=seed,
54
+ guidance_scale=guidance_scale,
55
+ steps=num_inference_steps,
56
+ size=f'{width}*{height}'
57
+ ) # support 1664*928, 1472*1140, 1328*1328, 1140*1472, 928*1664
58
+ print('response: %s' % rsp)
59
+ if rsp.status_code == HTTPStatus.OK:
60
+ # 在当前目录下保存图片
61
+ for result in rsp.output.results:
62
+ file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
63
+ with open('./%s' % file_name, 'wb+') as f:
64
+ f.write(requests.get(result.url).content)
65
+ print(f'save image to {file_name}')
66
+ else:
67
+ print('sync_call Failed, status_code: %s, code: %s, message: %s' %
68
+ (rsp.status_code, rsp.code, rsp.message))
69
+ image = Image.open(file_name)
70
  return image, seed
71
+
72
  examples = [
73
+ "A capybara wearing a suit holding a sign that reads Hello World",
74
+ "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。",
75
+ "一位身着淡雅水粉色交领襦裙的年轻女子背对镜头而坐,俯身专注地手持毛笔在素白宣纸上书写“通義千問”四个遒劲汉字。古色古香的室内陈设典雅考究,案头错落摆放着青瓷茶盏与鎏金香炉,一缕熏香轻盈升腾;柔和光线洒落肩头,勾勒出她衣裙的柔美质感与专注神情,仿佛凝固了一段宁静温润的旧时光。",
76
+ " 一个可抽取式的纸巾盒子,上面写着'Face, CLEAN & SOFT TISSUE'下面写着'亲肤可湿水',左上角是品牌名'洁柔',整体是白色和浅黄色的色调",
77
+ "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。",
78
+ '一个会议室,墙上写着"3.14159265-358979-32384626-4338327950",一个小陀螺在桌上转动',
79
+ '一个咖啡点门口有一个黑板,上面写着通义千问咖啡,2美元一杯,旁边有个霓虹灯,写着阿里巴巴,旁边有个海报,海报上面是一个中国美女,海报下方写着qwen newbee',
80
+ """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""",
81
+ "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."
82
  ]
83
 
84
+ css = """
85
  #col-container {
86
  margin: 0 auto;
87
+ max-width: 1024px;
88
  }
89
  """
90
 
91
+
92
+
93
  with gr.Blocks(css=css) as demo:
 
94
  with gr.Column(elem_id="col-container"):
95
+ # 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>')
96
+ 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;">')
97
+ 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.")
 
 
98
  with gr.Row():
 
99
  prompt = gr.Text(
100
  label="Prompt",
101
  show_label=False,
 
102
  placeholder="Enter your prompt",
103
  container=False,
104
+
105
  )
106
+ run_button = gr.Button("Run", scale=0, variant="primary")
107
+
 
 
108
  result = gr.Image(label="Result", show_label=False)
109
+
 
 
 
 
 
 
 
110
  with gr.Accordion("Advanced Settings", open=False):
111
+ negative_prompt = gr.Text(
112
+ label="Negative prompt",
113
+ max_lines=1,
114
+ placeholder="Enter a negative prompt",
115
+ visible=False,
116
+ )
117
+ negative_prompt = gr.Text(
118
+ label="Negative prompt",
119
+ max_lines=1,
120
+ placeholder="Enter a negative prompt",
121
+ visible=False,
122
+ )
123
+
124
  seed = gr.Slider(
125
  label="Seed",
126
  minimum=0,
127
  maximum=MAX_SEED,
128
  step=1,
129
+ value=0,
130
  )
131
+
132
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
133
+
134
  with gr.Row():
135
+ aspect_ratio = gr.Radio(
136
+ label="Aspect ratio(width:height)",
137
+ choices=["1:1", "16:9", "9:16", "4:3", "3:4"],
138
+ value="16:9",
 
 
 
 
 
 
 
 
 
139
  )
140
+
141
  with gr.Row():
142
+ guidance_scale = gr.Slider(
143
+ label="Guidance scale",
144
+ minimum=0.0,
145
+ maximum=7.5,
146
+ step=0.1,
147
+ value=4.0,
148
+ )
149
+
150
  num_inference_steps = gr.Slider(
151
+ label="Number of inference steps",
152
  minimum=1,
153
  maximum=50,
154
  step=1,
155
+ value=50,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  )
 
 
 
 
 
 
 
 
 
157
 
158
+ gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=True, cache_mode="lazy")
159
  gr.on(
160
+ triggers=[run_button.click, prompt.submit],
161
  fn=infer,
162
+ inputs=[
163
+ prompt,
164
+ negative_prompt,
165
+ seed,
166
+ randomize_seed,
167
+ aspect_ratio,
168
+ guidance_scale,
169
+ num_inference_steps,
170
+ ],
171
+ outputs=[result, seed],
172
  )
173
 
174
+ if __name__ == "__main__":
175
+ demo.launch()