MySafeCode commited on
Commit
8367943
·
verified ·
1 Parent(s): b01fe58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -315
app.py CHANGED
@@ -2,59 +2,32 @@ import spaces
2
  import gradio as gr
3
  import torch
4
  from diffusers import ZImagePipeline
 
5
  import os
6
  from pathlib import Path
7
 
8
  # Load the model directly at startup
9
  print("Loading Z-Image Turbo model...")
10
- print("This may take a few minutes on first run while the model downloads...")
11
-
12
-
13
- # Load the pipeline with optimal settings
14
  pipe = ZImagePipeline.from_pretrained(
15
  "Tongyi-MAI/Z-Image-Turbo",
16
  torch_dtype=torch.bfloat16,
17
  low_cpu_mem_usage=False,
18
  )
19
-
20
- # Move to GPU if available
21
  device = "cuda" if torch.cuda.is_available() else "cpu"
22
  pipe.to(device)
23
  print(f"Model loaded on {device}")
24
-
25
- print("Model loaded successfully!")
26
 
27
  @spaces.GPU()
28
- def generate_image(
29
- prompt,
30
- progress=gr.Progress(track_tqdm=True)
31
- ):
32
- """
33
- Generate an image using Z-Image Turbo model.
34
-
35
- Args:
36
- prompt: Text description of the desired image
37
-
38
- Returns:
39
- Generated PIL Image
40
- """
41
- global pipe
42
-
43
  if pipe is None:
44
  raise gr.Error("Model failed to load on startup. Please restart the application.")
45
-
46
  if not prompt.strip():
47
  raise gr.Error("Please enter a prompt to generate an image.")
48
 
49
- # Determine device
50
  device = "cuda" if torch.cuda.is_available() else "cpu"
51
-
52
- # Set random seed for reproducibility
53
  generator = torch.Generator(device).manual_seed(42)
54
-
55
- # Generate the image with optimal settings
56
  progress(0.1, desc="Generating image...")
57
-
58
  try:
59
  result = pipe(
60
  prompt=prompt,
@@ -65,296 +38,28 @@ def generate_image(
65
  guidance_scale=0.0,
66
  generator=generator,
67
  )
68
-
69
  image = result.images[0]
 
 
 
 
 
70
  progress(1.0, desc="Complete!")
71
-
72
- return image
73
-
74
  except Exception as e:
75
  raise gr.Error(f"Generation failed: {str(e)}")
76
 
77
- # Apple-style CSS
78
- apple_css = """
79
- /* Global Styles */
80
- .gradio-container {
81
- max-width: 980px !important;
82
- margin: 0 auto !important;
83
- padding: 48px 20px !important;
84
- font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', 'Roboto', sans-serif !important;
85
- }
86
-
87
- /* Header */
88
- .header-container {
89
- text-align: center;
90
- margin-bottom: 48px;
91
- }
92
-
93
- .main-title {
94
- font-size: 56px !important;
95
- font-weight: 600 !important;
96
- letter-spacing: -0.02em !important;
97
- line-height: 1.07 !important;
98
- color: #1d1d1f !important;
99
- margin: 0 0 12px 0 !important;
100
- }
101
-
102
- .subtitle {
103
- font-size: 21px !important;
104
- font-weight: 400 !important;
105
- line-height: 1.38 !important;
106
- color: #6e6e73 !important;
107
- margin: 0 0 24px 0 !important;
108
- }
109
-
110
- .attribution-link {
111
- display: inline-block;
112
- font-size: 14px !important;
113
- color: #0071e3 !important;
114
- text-decoration: none !important;
115
- font-weight: 400 !important;
116
- transition: color 0.2s ease !important;
117
- }
118
-
119
- .attribution-link:hover {
120
- color: #0077ed !important;
121
- text-decoration: underline !important;
122
- }
123
-
124
- /* Input Section */
125
- .input-section {
126
- background: #ffffff;
127
- border-radius: 18px;
128
- padding: 32px;
129
- margin-bottom: 24px;
130
- box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
131
- }
132
-
133
- /* Textbox */
134
- textarea {
135
- font-size: 17px !important;
136
- line-height: 1.47 !important;
137
- border-radius: 12px !important;
138
- border: 1px solid #d2d2d7 !important;
139
- padding: 12px 16px !important;
140
- transition: all 0.2s ease !important;
141
- background: #ffffff !important;
142
- font-family: -apple-system, BlinkMacSystemFont, 'Inter', sans-serif !important;
143
- }
144
-
145
- textarea:focus {
146
- border-color: #0071e3 !important;
147
- box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.15) !important;
148
- outline: none !important;
149
- }
150
-
151
- textarea::placeholder {
152
- color: #86868b !important;
153
- }
154
-
155
- /* Button */
156
- button.primary {
157
- font-size: 17px !important;
158
- font-weight: 400 !important;
159
- padding: 12px 32px !important;
160
- border-radius: 980px !important;
161
- background: #0071e3 !important;
162
- border: none !important;
163
- color: #ffffff !important;
164
- min-height: 44px !important;
165
- transition: all 0.2s ease !important;
166
- letter-spacing: -0.01em !important;
167
- cursor: pointer !important;
168
- }
169
-
170
- button.primary:hover {
171
- background: #0077ed !important;
172
- transform: scale(1.02) !important;
173
- }
174
 
175
- button.primary:active {
176
- transform: scale(0.98) !important;
177
- }
178
-
179
- /* Output Section */
180
- .output-section {
181
- background: #ffffff;
182
- border-radius: 18px;
183
- padding: 32px;
184
- box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
185
- overflow: hidden;
186
- }
187
-
188
- .output-section img {
189
- border-radius: 12px !important;
190
- width: 100% !important;
191
- height: auto !important;
192
- }
193
-
194
- /* Footer */
195
- .footer-text {
196
- text-align: center;
197
- margin-top: 48px;
198
- font-size: 14px !important;
199
- color: #86868b !important;
200
- line-height: 1.43 !important;
201
- }
202
-
203
- /* Progress */
204
- .progress-bar {
205
- background: #0071e3 !important;
206
- border-radius: 4px !important;
207
- }
208
-
209
- /* Dark Mode */
210
- .dark .main-title {
211
- color: #f5f5f7 !important;
212
- }
213
-
214
- .dark .subtitle {
215
- color: #a1a1a6 !important;
216
- }
217
-
218
- .dark .input-section,
219
- .dark .output-section {
220
- background: #1d1d1f;
221
- box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);
222
- }
223
-
224
- .dark textarea {
225
- background: #1d1d1f !important;
226
- border-color: #424245 !important;
227
- color: #f5f5f7 !important;
228
- }
229
-
230
- .dark textarea::placeholder {
231
- color: #86868b !important;
232
- }
233
-
234
- /* Responsive */
235
- @media (max-width: 734px) {
236
- .main-title {
237
- font-size: 40px !important;
238
- }
239
-
240
- .subtitle {
241
- font-size: 19px !important;
242
- }
243
-
244
- .gradio-container {
245
- padding: 32px 16px !important;
246
- }
247
-
248
- .input-section,
249
- .output-section {
250
- padding: 24px !important;
251
- }
252
- }
253
-
254
- /* Remove default Gradio styling */
255
- .contain {
256
- padding: 0 !important;
257
- }
258
- """
259
-
260
- # Create the interface
261
- with gr.Blocks(
262
- title="Z-Image Turbo",
263
- fill_height=False,
264
- ) as demo:
265
-
266
- # Header
267
- gr.HTML("""
268
- <div class="header-container">
269
- <h1 class="main-title">Z-Image Turbo</h1>
270
- <p class="subtitle">Transform your ideas into stunning visuals with AI</p>
271
- <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="attribution-link">
272
- Built with anycoder
273
- </a>
274
- </div>
275
- """)
276
-
277
- # Input Section
278
- with gr.Column(elem_classes="input-section"):
279
- prompt = gr.Textbox(
280
- placeholder="Describe the image you want to create...",
281
- lines=3,
282
- max_lines=6,
283
- label="",
284
- show_label=False,
285
- container=False,
286
- )
287
-
288
- generate_btn = gr.Button(
289
- "Generate",
290
- variant="primary",
291
- size="lg",
292
- elem_classes="primary"
293
- )
294
-
295
- # Output Section
296
- with gr.Column(elem_classes="output-section"):
297
- output_image = gr.Image(
298
- type="pil",
299
- label="",
300
- show_label=False,
301
- container=False,
302
- buttons=["download"],
303
- )
304
-
305
- # Footer
306
- gr.HTML("""
307
- <div class="footer-text">
308
- <p>Powered by Z-Image Turbo from Tongyi-MAI</p>
309
- </div>
310
- """)
311
-
312
- # Event handlers
313
- generate_btn.click(
314
- fn=generate_image,
315
- inputs=prompt,
316
- outputs=output_image,
317
- api_visibility="public"
318
- )
319
-
320
- prompt.submit(
321
- fn=generate_image,
322
- inputs=prompt,
323
- outputs=output_image,
324
- api_visibility="public"
325
- )
326
 
327
  if __name__ == "__main__":
328
- demo.launch(
329
- share=False,
330
- show_error=True,
331
- theme=gr.themes.Soft(
332
- primary_hue=gr.themes.colors.blue,
333
- secondary_hue=gr.themes.colors.slate,
334
- neutral_hue=gr.themes.colors.gray,
335
- spacing_size=gr.themes.sizes.spacing_lg,
336
- radius_size=gr.themes.sizes.radius_lg,
337
- text_size=gr.themes.sizes.text_md,
338
- font=[gr.themes.GoogleFont("Inter"), "SF Pro Display", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
339
- font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "SF Mono", "ui-monospace", "monospace"],
340
- ).set(
341
- body_background_fill='#f5f5f7',
342
- body_background_fill_dark='#000000',
343
- button_primary_background_fill='#0071e3',
344
- button_primary_background_fill_hover='#0077ed',
345
- button_primary_text_color='#ffffff',
346
- block_background_fill='#ffffff',
347
- block_background_fill_dark='#1d1d1f',
348
- block_border_width='0px',
349
- block_shadow='0 2px 12px rgba(0, 0, 0, 0.08)',
350
- block_shadow_dark='0 2px 12px rgba(0, 0, 0, 0.4)',
351
- input_background_fill='#ffffff',
352
- input_background_fill_dark='#1d1d1f',
353
- input_border_width='1px',
354
- input_border_color='#d2d2d7',
355
- input_border_color_dark='#424245',
356
- input_shadow='none',
357
- input_shadow_focus='0 0 0 4px rgba(0, 113, 227, 0.15)',
358
- ),
359
- css=apple_css,
360
- )
 
2
  import gradio as gr
3
  import torch
4
  from diffusers import ZImagePipeline
5
+ from io import BytesIO
6
  import os
7
  from pathlib import Path
8
 
9
  # Load the model directly at startup
10
  print("Loading Z-Image Turbo model...")
 
 
 
 
11
  pipe = ZImagePipeline.from_pretrained(
12
  "Tongyi-MAI/Z-Image-Turbo",
13
  torch_dtype=torch.bfloat16,
14
  low_cpu_mem_usage=False,
15
  )
 
 
16
  device = "cuda" if torch.cuda.is_available() else "cpu"
17
  pipe.to(device)
18
  print(f"Model loaded on {device}")
 
 
19
 
20
  @spaces.GPU()
21
+ def generate_image(prompt, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  if pipe is None:
23
  raise gr.Error("Model failed to load on startup. Please restart the application.")
 
24
  if not prompt.strip():
25
  raise gr.Error("Please enter a prompt to generate an image.")
26
 
 
27
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
28
  generator = torch.Generator(device).manual_seed(42)
 
 
29
  progress(0.1, desc="Generating image...")
30
+
31
  try:
32
  result = pipe(
33
  prompt=prompt,
 
38
  guidance_scale=0.0,
39
  generator=generator,
40
  )
 
41
  image = result.images[0]
42
+
43
+ # Convert to PNG in memory
44
+ buffer = BytesIO()
45
+ image.save(buffer, format="PNG")
46
+ buffer.seek(0)
47
  progress(1.0, desc="Complete!")
48
+ return buffer # Return PNG bytes
49
+
 
50
  except Exception as e:
51
  raise gr.Error(f"Generation failed: {str(e)}")
52
 
53
+ # Gradio interface (simplified)
54
+ with gr.Blocks(title="Z-Image Turbo", fill_height=False) as demo:
55
+ gr.HTML("<h1>Z-Image Turbo</h1><p>Generate PNG images from prompts</p>")
56
+ prompt_input = gr.Textbox(placeholder="Describe the image...", lines=3)
57
+ generate_btn = gr.Button("Generate PNG")
58
+ output_image = gr.Image(type="file", label="Generated Image", show_label=False, container=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ generate_btn.click(fn=generate_image, inputs=prompt_input, outputs=output_image)
61
+ prompt_input.submit(fn=generate_image, inputs=prompt_input, outputs=output_image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
+ demo.launch(share=True)
65
+