Abhi1907 commited on
Commit
64f477a
·
verified ·
1 Parent(s): 6900fe1

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +222 -111
app.py CHANGED
@@ -1,153 +1,264 @@
1
  import gradio as gr
2
- import torch
 
 
3
  import random
4
- from utils import load_pipeline
5
 
6
- # Configuration
7
- # NOTE: If "Z-Image Turbo" is a specific custom model, replace the ID below.
8
- # Common fast models: "stabilityai/sdxl-turbo", "stabilityai/sd-turbo"
9
- MODEL_ID = "stabilityai/sdxl-turbo"
10
 
11
- # Load the pipeline once at startup to save memory and time
12
- print(f"Loading model: {MODEL_ID}...")
13
- pipe = load_pipeline(MODEL_ID)
14
- print("Model loaded successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  def generate_image(
17
  prompt: str,
18
- negative_prompt: str,
19
- seed: int,
20
- num_inference_steps: int
 
 
21
  ):
22
  """
23
- Generates an image based on the text prompt using the loaded pipeline.
24
  """
 
 
 
25
  if not prompt:
26
  raise gr.Error("Please enter a text prompt.")
 
 
27
 
28
- # Set seed for reproducibility
29
- generator = torch.Generator(device=pipe.device).manual_seed(seed)
 
 
 
 
 
 
30
 
 
31
  try:
32
- # SDXL Turbo works best with 1-4 steps and guidance_scale=0.0
33
- # Adjust these if using a different model
34
- result = pipe(
35
- prompt=prompt,
36
- negative_prompt=negative_prompt,
37
- num_inference_steps=num_inference_steps,
38
- generator=generator,
39
- guidance_scale=0.0
40
- )
41
-
42
- # Return the first image
43
- return result.images[0]
44
-
45
  except Exception as e:
46
- raise gr.Error(f"Error during generation: {str(e)}")
 
 
47
 
48
- def set_random_seed():
49
- """Helper to generate a random seed for the UI."""
50
- return random.randint(0, 2147483647)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- # Gradio 6 Application
53
- with gr.Blocks() as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- # Header Section
56
  gr.HTML("""
57
- <div style="text-align: center; margin-bottom: 20px;">
58
- <h1>🖼️ Z-Image Turbo Generator</h1>
59
- <p style="color: #666;">Generate high-quality images from text in seconds using fast diffusion models.</p>
60
- <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="text-decoration: none; color: #007bff; font-weight: bold;">
61
- Built with anycoder
 
62
  </a>
63
  </div>
64
  """)
65
 
 
 
66
  with gr.Row():
67
- # Input Column (Controls)
68
  with gr.Column(scale=1):
69
- gr.Markdown("### ⚙️ Settings")
70
-
71
- prompt_input = gr.Textbox(
72
- label="Prompt",
73
- placeholder="Describe the image you want to generate...",
74
- lines=3,
75
- interactive=True
76
- )
77
-
78
- negative_prompt_input = gr.Textbox(
79
- label="Negative Prompt",
80
- placeholder="Things to avoid in the image...",
81
- lines=2,
82
- value="blurry, bad quality, distorted",
83
- interactive=True
84
- )
85
-
86
- with gr.Accordion("Advanced Options", open=False):
87
- seed_input = gr.Number(
88
- label="Seed",
89
- value=42,
90
- precision=0,
91
- info="Set to -1 for random seed"
92
  )
93
 
94
- random_seed_btn = gr.Button("🎲 Randomize Seed", size="sm")
 
 
 
 
 
 
95
 
96
- steps_input = gr.Slider(
97
- label="Inference Steps",
98
- minimum=1,
99
- maximum=10,
100
- step=1,
101
- value=2,
102
- info="Lower is faster (Turbo models work best with 1-4)"
 
 
103
  )
104
-
105
- generate_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
106
-
107
- gr.Examples(
108
- examples=[
109
- ["A futuristic cyberpunk city with neon lights, highly detailed, 8k", "", 12345, 2],
110
- ["A cute robot painting a canvas in a garden, soft lighting", "", 999, 2],
111
- ["An astronaut riding a horse on Mars, photorealistic", "", 42, 2],
112
- ],
113
- inputs=[prompt_input, negative_prompt_input, seed_input, steps_input],
114
- )
 
 
 
 
 
 
 
 
 
115
 
116
- # Output Column (Result)
117
- with gr.Column(scale=1):
118
- gr.Markdown("### 🖼️ Result")
119
- image_output = gr.Image(
120
- label="Generated Image",
121
- type="pil",
122
- show_download_button=True,
123
- show_share_button=True
124
  )
125
 
126
- # Event Listeners
127
- random_seed_btn.click(
128
- fn=set_random_seed,
129
- outputs=seed_input
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  )
131
 
 
 
 
 
 
 
 
132
  generate_btn.click(
133
  fn=generate_image,
134
- inputs=[prompt_input, negative_prompt_input, seed_input, steps_input],
135
- outputs=image_output,
 
 
 
 
 
 
 
136
  api_visibility="public"
137
  )
138
 
139
- # Gradio 6 Launch - All app parameters go here!
 
 
 
 
 
 
 
140
  demo.launch(
141
- theme=gr.themes.Soft(
142
- primary_hue="indigo",
143
- secondary_hue="purple",
144
- neutral_hue="slate",
145
- font=gr.themes.GoogleFont("Inter"),
146
- text_size="lg",
147
- spacing_size="lg",
148
- radius_size="md"
149
- ),
150
- footer_links=[
151
- {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
152
- ]
153
  )
 
1
  import gradio as gr
2
+ import requests
3
+ from PIL import Image
4
+ from io import BytesIO
5
  import random
 
6
 
7
+ # --- Configuration ---
8
+ # Using SDXL Turbo as the engine for high-speed generation
9
+ MODEL_API_URL = "https://api-inference.huggingface.co/models/stabilityai/sdxl-turbo"
 
10
 
11
+ # --- Helper Functions ---
12
+
13
+ def query_huggingface_api(payload, token):
14
+ """
15
+ Sends a request to the Hugging Face Inference API.
16
+ """
17
+ headers = {"Authorization": f"Bearer {token}"}
18
+ response = requests.post(MODEL_API_URL, headers=headers, json=payload)
19
+
20
+ if response.status_code != 200:
21
+ error_data = {}
22
+ try:
23
+ error_data = response.json()
24
+ except:
25
+ pass
26
+
27
+ if response.status_code == 503:
28
+ raise gr.Error("Model is warming up. Please try again in a moment.")
29
+ elif response.status_code == 401:
30
+ raise gr.Error("Invalid Access Token. Please check your credentials.")
31
+ elif response.status_code == 429:
32
+ raise gr.Error("Rate limit exceeded. Please wait a moment.")
33
+ else:
34
+ error_msg = error_data.get("error", f"Error {response.status_code}")
35
+ raise gr.Error(f"API Error: {error_msg}")
36
+
37
+ return response.content
38
 
39
  def generate_image(
40
  prompt: str,
41
+ token: str,
42
+ negative_prompt: str = "",
43
+ steps: int = 2,
44
+ guidance_scale: float = 0.0,
45
+ progress=gr.Progress()
46
  ):
47
  """
48
+ Main generation function.
49
  """
50
+ if not token or not token.startswith("hf_"):
51
+ raise gr.Error("Please enter a valid Hugging Face Access Token (starts with 'hf_').")
52
+
53
  if not prompt:
54
  raise gr.Error("Please enter a text prompt.")
55
+
56
+ progress(0.1, desc="Initializing...")
57
 
58
+ payload = {
59
+ "inputs": prompt,
60
+ "parameters": {
61
+ "negative_prompt": negative_prompt,
62
+ "num_inference_steps": int(steps),
63
+ "guidance_scale": float(guidance_scale)
64
+ }
65
+ }
66
 
67
+ progress(0.5, desc="Generating...")
68
  try:
69
+ image_bytes = query_huggingface_api(payload, token)
70
+ image = Image.open(BytesIO(image_bytes))
71
+ progress(1.0, desc="Done!")
72
+ return image
 
 
 
 
 
 
 
 
 
73
  except Exception as e:
74
+ if isinstance(e, gr.Error):
75
+ raise e
76
+ raise gr.Error(f"An unexpected error occurred: {str(e)}")
77
 
78
+ def get_random_prompt():
79
+ """Returns a random creative prompt."""
80
+ prompts = [
81
+ "A cinematic shot of a futuristic astronaut standing on Mars, golden hour lighting, hyperrealistic, 8k",
82
+ "A cute robot painting a canvas in a garden, watercolor style, soft colors, highly detailed",
83
+ "Cyberpunk street food vendor in Tokyo, neon rain reflections, volumetric lighting",
84
+ "A majestic lion made of clouds in a blue sky, fantasy art, dreamlike atmosphere",
85
+ "Portrait of a warrior with intricate golden armor, digital painting, dramatic lighting",
86
+ "A cozy library inside a giant tree, magical atmosphere, fireflies, warm lighting",
87
+ "Futuristic sports car concept, sleek design, neon trim, motion blur, dark city background"
88
+ ]
89
+ return random.choice(prompts)
90
+
91
+ # --- Gradio 6 Application ---
92
+
93
+ # Custom CSS to mimic the dark/tech vibe of the original HTML
94
+ custom_css = """
95
+ body {
96
+ background-color: #0f172a;
97
+ color: #f8fafc;
98
+ }
99
+ .gradio-container {
100
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
101
+ max-width: 1400px !important;
102
+ }
103
+ #header-text {
104
+ font-family: 'Courier New', monospace;
105
+ font-weight: bold;
106
+ color: #6366f1;
107
+ text-transform: uppercase;
108
+ letter-spacing: 2px;
109
+ }
110
+ """
111
 
112
+ # Define the Theme
113
+ custom_theme = gr.themes.Soft(
114
+ primary_hue="indigo",
115
+ secondary_hue="pink",
116
+ neutral_hue="slate",
117
+ font=gr.themes.GoogleFont("Outfit"),
118
+ text_size="lg",
119
+ spacing_size="lg",
120
+ radius_size="md"
121
+ ).set(
122
+ button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #ec4899 100%)",
123
+ button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #db2777 100%)",
124
+ button_primary_text_color="white",
125
+ block_background_fill="*neutral_950",
126
+ block_border_color="*neutral_800",
127
+ block_shadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
128
+ block_title_text_weight="600",
129
+ block_title_text_color="*primary_300",
130
+ )
131
+
132
+ with gr.Blocks(theme=custom_theme, css=custom_css) as demo:
133
 
134
+ # Header
135
  gr.HTML("""
136
+ <div style="display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid rgba(255,255,255,0.1);">
137
+ <div id="header-text" style="font-size: 1.5rem;">
138
+ <i class="fa-solid fa-bolt"></i> Z-Image Turbo
139
+ </div>
140
+ <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #94a3b8; text-decoration: none; font-size: 0.9rem; border: 1px solid rgba(255,255,255,0.1); padding: 8px 16px; border-radius: 20px; transition: all 0.3s;">
141
+ Built with anycoder <i class="fa-solid fa-arrow-up-right-from-square" style="font-size: 0.7em;"></i>
142
  </a>
143
  </div>
144
  """)
145
 
146
+ gr.Markdown("Generate high-quality images in seconds using the SDXL Turbo engine.", elem_classes="text-center")
147
+
148
  with gr.Row():
149
+ # --- Left Column: Controls ---
150
  with gr.Column(scale=1):
151
+ with gr.Group():
152
+ gr.Markdown("### 🛠️ Configuration")
153
+
154
+ # Authentication
155
+ token_input = gr.Textbox(
156
+ label="Hugging Face Access Token",
157
+ placeholder="hf_...",
158
+ type="password",
159
+ info="Your token is required to access the API. It is not stored on the server.",
160
+ scale=9
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  )
162
 
163
+ # Prompts
164
+ prompt_input = gr.Textbox(
165
+ label="Prompt",
166
+ placeholder="Describe the image you want to generate...",
167
+ lines=3,
168
+ info="Be descriptive for better results."
169
+ )
170
 
171
+ with gr.Row():
172
+ random_btn = gr.Button("🎲 Surprise Me", size="sm", scale=1)
173
+ clear_btn = gr.Button("🗑️ Clear", size="sm", scale=1)
174
+
175
+ negative_prompt_input = gr.Textbox(
176
+ label="Negative Prompt",
177
+ placeholder="blur, low quality, distortion...",
178
+ lines=1,
179
+ info="Elements to avoid in the image."
180
  )
181
+
182
+ # Parameters
183
+ with gr.Accordion("Advanced Settings", open=False):
184
+ steps_slider = gr.Slider(
185
+ minimum=1,
186
+ maximum=4,
187
+ step=1,
188
+ value=2,
189
+ label="Inference Steps",
190
+ info="Turbo models work best with 1-4 steps."
191
+ )
192
+
193
+ guidance_slider = gr.Slider(
194
+ minimum=0.0,
195
+ maximum=2.0,
196
+ step=0.1,
197
+ value=0.0,
198
+ label="Guidance Scale",
199
+ info="Lower values (0.0-1.0) often work best for Turbo."
200
+ )
201
 
202
+ generate_btn = gr.Button(
203
+ "✨ Generate Image",
204
+ variant="primary",
205
+ size="lg"
 
 
 
 
206
  )
207
 
208
+ # --- Right Column: Output ---
209
+ with gr.Column(scale=2):
210
+ with gr.Group():
211
+ gr.Markdown("### 🖼️ Result")
212
+
213
+ output_image = gr.Image(
214
+ label="Generated Image",
215
+ type="pil",
216
+ height=600,
217
+ show_label=False,
218
+ show_download_button=True,
219
+ interactive=False
220
+ )
221
+
222
+ # Status/Info
223
+ status_text = gr.Markdown("", visible=False)
224
+
225
+ # --- Event Listeners ---
226
+
227
+ # Random Prompt Logic
228
+ random_btn.click(
229
+ fn=get_random_prompt,
230
+ outputs=prompt_input
231
  )
232
 
233
+ # Clear Logic
234
+ clear_btn.click(
235
+ fn=lambda: ("", "", None),
236
+ outputs=[prompt_input, negative_prompt_input, output_image]
237
+ )
238
+
239
+ # Generate Logic
240
  generate_btn.click(
241
  fn=generate_image,
242
+ inputs=[
243
+ prompt_input,
244
+ token_input,
245
+ negative_prompt_input,
246
+ steps_slider,
247
+ guidance_slider
248
+ ],
249
+ outputs=output_image,
250
+ api_name="generate",
251
  api_visibility="public"
252
  )
253
 
254
+ # --- Footer Links ---
255
+ footer_links = [
256
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
257
+ {"label": "Gradio", "url": "https://gradio.app"},
258
+ {"label": "Hugging Face", "url": "https://huggingface.co"}
259
+ ]
260
+
261
+ # --- Launch ---
262
  demo.launch(
263
+ footer_links=footer_links
 
 
 
 
 
 
 
 
 
 
 
264
  )