GGPENG commited on
Commit
46b37c8
·
verified ·
1 Parent(s): afcab82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +242 -125
app.py CHANGED
@@ -1,154 +1,271 @@
 
 
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
  from diffusers import DiffusionPipeline
7
- import torch
8
 
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
 
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
 
 
 
 
 
 
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
 
 
 
 
 
23
 
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
 
39
- generator = torch.Generator().manual_seed(seed)
 
 
 
 
40
 
 
 
 
 
 
 
 
41
  image = pipe(
42
  prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
  generator=generator,
49
  ).images[0]
50
-
51
  return image, seed
52
 
53
-
54
  examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
 
 
58
  ]
59
 
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
-
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
 
 
 
 
70
 
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
  )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
  num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
  minimum=1,
131
- maximum=50,
 
132
  step=1,
133
- value=2, # Replace with defaults that work for your model
 
134
  )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  )
152
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import spaces
3
  import gradio as gr
 
 
 
 
4
  from diffusers import DiffusionPipeline
 
5
 
6
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
7
 
8
+ dtype = torch.float16 if device == "cuda" else torch.float32
 
 
 
9
 
10
+ # Load the pipeline once at startup
11
+ print("Loading Z-Image-Turbo pipeline...")
12
+ pipe = DiffusionPipeline.from_pretrained(
13
+ "Tongyi-MAI/Z-Image-Turbo",
14
+ torch_dtype=torch.bfloat16,
15
+ low_cpu_mem_usage=False,
16
+ )
17
+ pipe.to("cuda")
18
 
 
 
19
 
20
+ pipe.unet.load_attn_procs(
21
+ ".",
22
+ weight_name="pytorch_custom_diffusion_weights.bin"
23
+ )
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # ======== AoTI compilation + FA3 ========
27
+ # pipe.transformer.layers._repeated_blocks = ["ZImageTransformerBlock"]
28
+ # spaces.aoti_blocks_load(pipe.transformer.layers, "zerogpu-aoti/Z-Image", variant="fa3")
29
+
30
+ print("Pipeline loaded!")
31
 
32
+ @spaces.GPU
33
+ def generate_image(prompt, height, width, num_inference_steps, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
34
+ """Generate an image from the given prompt."""
35
+ if randomize_seed:
36
+ seed = torch.randint(0, 2**32 - 1, (1,)).item()
37
+
38
+ generator = torch.Generator("cuda").manual_seed(int(seed))
39
  image = pipe(
40
  prompt=prompt,
41
+ height=int(height),
42
+ width=int(width),
43
+ num_inference_steps=int(num_inference_steps),
44
+ guidance_scale=0.0,
 
45
  generator=generator,
46
  ).images[0]
47
+
48
  return image, seed
49
 
50
+ # Example prompts
51
  examples = [
52
+ ["Young Chinese woman in red Hanfu, intricate embroidery. Impeccable makeup, red floral forehead pattern. Elaborate high bun, golden phoenix headdress, red flowers, beads. Holds round folding fan with lady, trees, bird. Neon lightning-bolt lamp, bright yellow glow, above extended left palm. Soft-lit outdoor night background, silhouetted tiered pagoda, blurred colorful distant lights."],
53
+ ["A majestic dragon soaring through clouds at sunset, scales shimmering with iridescent colors, detailed fantasy art style"],
54
+ ["Cozy coffee shop interior, warm lighting, rain on windows, plants on shelves, vintage aesthetic, photorealistic"],
55
+ ["Astronaut riding a horse on Mars, cinematic lighting, sci-fi concept art, highly detailed"],
56
+ ["Portrait of a wise old wizard with a long white beard, holding a glowing crystal staff, magical forest background"],
57
  ]
58
 
59
+ # Custom theme with modern aesthetics (Gradio 6)
60
+ custom_theme = gr.themes.Soft(
61
+ primary_hue="yellow",
62
+ secondary_hue="amber",
63
+ neutral_hue="slate",
64
+ font=gr.themes.GoogleFont("Inter"),
65
+ text_size="lg",
66
+ spacing_size="md",
67
+ radius_size="lg"
68
+ ).set(
69
+ button_primary_background_fill="*primary_500",
70
+ button_primary_background_fill_hover="*primary_600",
71
+ block_title_text_weight="600",
72
+ )
73
 
74
+ # Build the Gradio interface
75
+ with gr.Blocks(fill_height=True) as demo:
76
+ # Header
77
+ gr.Markdown(
78
+ """
79
+ # ���� Z-Image-Turbo
80
+ **Ultra-fast AI image generation** • Generate stunning images in just 8 steps
81
+ """,
82
+ elem_classes="header-text"
83
+ )
84
+
85
+ with gr.Row(equal_height=False):
86
+ # Left column - Input controls
87
+ with gr.Column(scale=1, min_width=320):
88
+ prompt = gr.Textbox(
89
+ label=" Your Prompt",
90
+ placeholder="Describe the image you want to create...",
91
+ lines=5,
92
+ max_lines=10,
93
+ autofocus=True,
 
 
 
 
 
 
 
94
  )
95
+
96
+ with gr.Accordion("⚙️ Advanced Settings", open=False):
97
+ with gr.Row():
98
+ height = gr.Slider(
99
+ minimum=512,
100
+ maximum=2048,
101
+ value=1024,
102
+ step=64,
103
+ label="Height",
104
+ info="Image height in pixels"
105
+ )
106
+ width = gr.Slider(
107
+ minimum=512,
108
+ maximum=2048,
109
+ value=1024,
110
+ step=64,
111
+ label="Width",
112
+ info="Image width in pixels"
113
+ )
114
+
 
 
 
 
 
 
 
 
 
115
  num_inference_steps = gr.Slider(
 
116
  minimum=1,
117
+ maximum=20,
118
+ value=9,
119
  step=1,
120
+ label="Inference Steps",
121
+ info="9 steps = 8 DiT forwards (recommended)"
122
  )
123
+
124
+ with gr.Row():
125
+ randomize_seed = gr.Checkbox(
126
+ label="🎲 Random Seed",
127
+ value=True,
128
+ )
129
+ seed = gr.Number(
130
+ label="Seed",
131
+ value=42,
132
+ precision=0,
133
+ visible=False,
134
+ )
135
+
136
+ def toggle_seed(randomize):
137
+ return gr.Number(visible=not randomize)
138
+
139
+ randomize_seed.change(
140
+ toggle_seed,
141
+ inputs=[randomize_seed],
142
+ outputs=[seed]
143
+ )
144
+
145
+ generate_btn = gr.Button(
146
+ "🚀 Generate Image",
147
+ variant="primary",
148
+ size="lg",
149
+ scale=1
150
+ )
151
+
152
+ # Example prompts
153
+ gr.Examples(
154
+ examples=examples,
155
+ inputs=[prompt],
156
+ label="💡 Try these prompts",
157
+ examples_per_page=5,
158
+ )
159
+
160
+ # Right column - Output
161
+ with gr.Column(scale=1, min_width=320):
162
+ output_image = gr.Image(
163
+ label="Generated Image",
164
+ type="pil",
165
+ format="png",
166
+ show_label=False,
167
+ height=600,
168
+ buttons=["download", "share"],
169
+ )
170
+
171
+ used_seed = gr.Number(
172
+ label="🎲 Seed Used",
173
+ interactive=False,
174
+ container=True,
175
+ )
176
+
177
+ # Footer credits
178
+ gr.Markdown(
179
+ """
180
+ ---
181
+ <div style="text-align: center; opacity: 0.7; font-size: 0.9em; margin-top: 1rem;">
182
+ <strong>Model:</strong> <a href="https://huggingface.co/Tongyi-MAI/Z-Image-Turbo" target="_blank">Tongyi-MAI/Z-Image-Turbo</a> (Apache 2.0 License) •
183
+ <strong>Demo by:</strong> <a href="https://x.com/realmrfakename" target="_blank">@mrfakename</a> •
184
+ <strong>Redesign by:</strong> AnyCoder •
185
+ <strong>Optimizations:</strong> <a href="https://huggingface.co/multimodalart" target="_blank">@multimodalart</a> (FA3 + AoTI)
186
+ </div>
187
+ """,
188
+ elem_classes="footer-text"
189
+ )
190
+
191
+ # Connect the generate button
192
+ generate_btn.click(
193
+ fn=generate_image,
194
+ inputs=[prompt, height, width, num_inference_steps, seed, randomize_seed],
195
+ outputs=[output_image, used_seed],
196
+ )
197
+
198
+ # Also allow generating by pressing Enter in the prompt box
199
+ prompt.submit(
200
+ fn=generate_image,
201
+ inputs=[prompt, height, width, num_inference_steps, seed, randomize_seed],
202
+ outputs=[output_image, used_seed],
203
  )
204
 
205
  if __name__ == "__main__":
206
+ demo.launch(
207
+ theme=custom_theme,
208
+ css="""
209
+ .header-text h1 {
210
+ font-size: 2.5rem !important;
211
+ font-weight: 700 !important;
212
+ margin-bottom: 0.5rem !important;
213
+ background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
214
+ -webkit-background-clip: text;
215
+ -webkit-text-fill-color: transparent;
216
+ background-clip: text;
217
+ }
218
+
219
+ .header-text p {
220
+ font-size: 1.1rem !important;
221
+ color: #64748b !important;
222
+ margin-top: 0 !important;
223
+ }
224
+
225
+ .footer-text {
226
+ padding: 1rem 0;
227
+ }
228
+
229
+ .footer-text a {
230
+ color: #f59e0b !important;
231
+ text-decoration: none !important;
232
+ font-weight: 500;
233
+ }
234
+
235
+ .footer-text a:hover {
236
+ text-decoration: underline !important;
237
+ }
238
+
239
+ /* Mobile optimizations */
240
+ @media (max-width: 768px) {
241
+ .header-text h1 {
242
+ font-size: 1.8rem !important;
243
+ }
244
+
245
+ .header-text p {
246
+ font-size: 1rem !important;
247
+ }
248
+ }
249
+
250
+ /* Smooth transitions */
251
+ button, .gr-button {
252
+ transition: all 0.2s ease !important;
253
+ }
254
+
255
+ button:hover, .gr-button:hover {
256
+ transform: translateY(-1px);
257
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
258
+ }
259
+
260
+ /* Better spacing */
261
+ .gradio-container {
262
+ max-width: 1400px !important;
263
+ margin: 0 auto !important;
264
+ }
265
+ """,
266
+ footer_links=[
267
+ "api",
268
+ "gradio"
269
+ ],
270
+ mcp_server=True
271
+ )