greendra commited on
Commit
7abf720
·
verified ·
1 Parent(s): 9d7887d

fix mistake

Browse files
Files changed (1) hide show
  1. app.py +58 -106
app.py CHANGED
@@ -4,22 +4,20 @@ import io
4
  import random
5
  import os
6
  import time
7
- from PIL import Image, UnidentifiedImageError # Added UnidentifiedImageError
8
  from deep_translator import GoogleTranslator
9
  import json
10
  import uuid
11
  from urllib.parse import quote
12
- import traceback # For detailed error logging
13
 
14
  # Project by Nymbo
15
 
16
  # --- Constants ---
17
- API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-3.5-large"
18
  API_TOKEN = os.getenv("HF_READ_TOKEN")
19
  if not API_TOKEN:
20
  print("WARNING: HF_READ_TOKEN environment variable not set. API calls may fail.")
21
- # Optionally, raise an error or exit if the token is essential
22
- # raise ValueError("Missing required environment variable: HF_READ_TOKEN")
23
  headers = {"Authorization": f"Bearer {API_TOKEN}"} if API_TOKEN else {}
24
  timeout = 100 # seconds for API call timeout
25
 
@@ -40,13 +38,10 @@ except OSError as e:
40
  absolute_image_dir = os.path.abspath(IMAGE_DIR)
41
  print(f"Absolute path for allowed_paths: {absolute_image_dir}")
42
 
43
-
44
- # --- Function to query the API and return the generated image and download link ---
45
- def query(prompt, negative_prompt, steps=35, cfg_scale=7, seed=-1, width=1024, height=1024):
46
- # Renamed `strength` input as it wasn't used in the payload for txt2img
47
- # Removed `sampler` input as it wasn't used in payload
48
-
49
- # Basic Input Validation
50
  if not prompt or not prompt.strip():
51
  print("Empty prompt received.")
52
  # Return None for image and an informative message for the HTML component
@@ -57,120 +52,99 @@ def query(prompt, negative_prompt, steps=35, cfg_scale=7, seed=-1, width=1024, h
57
 
58
  # Translation
59
  try:
60
- # Using 'auto' source detection
61
  translated_prompt = GoogleTranslator(source='auto', target='en').translate(prompt)
62
- print(f'Generation {key} translation: {translated_prompt}')
63
  except Exception as e:
64
- print(f"Translation failed: {e}. Using original prompt.")
65
  translated_prompt = prompt # Fallback to original if translation fails
66
 
67
  # Add suffix to prompt
68
  final_prompt = f"{translated_prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
69
- print(f'Generation {key} final prompt: {final_prompt}')
70
 
71
- # Prepare payload for API call
72
  payload = {
73
  "inputs": final_prompt,
74
- "negative_prompt": negative_prompt,
75
  "steps": steps,
76
  "guidance_scale": cfg_scale, # API often uses guidance_scale
77
  "seed": seed if seed != -1 else random.randint(1, 1000000000),
78
- "parameters": { # Nested parameters as per original structure
79
  "width": width,
80
  "height": height,
 
81
  }
82
- # Add other parameters here if needed (e.g., sampler if supported)
 
83
  }
84
 
85
  # API Call Section
86
  try:
87
- print(f"Sending request to API: {API_URL}")
88
  if not headers:
89
  print("WARNING: Authorization header is missing (HF_READ_TOKEN not set?)")
90
- # Handle error appropriately - maybe return an error message
91
  return None, "<p style='color: red; text-align: center;'>Configuration Error: API Token missing.</p>"
92
 
93
  response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
94
- response.raise_for_status() # Raises HTTPError for 4xx/5xx responses
95
 
96
  image_bytes = response.content
97
- # Check for valid image data before proceeding
98
- if not image_bytes or len(image_bytes) < 100: # Basic check for empty/tiny response
99
  print(f"Error: Received empty or very small response content (length: {len(image_bytes)}). Potential API issue.")
100
  return None, "<p style='color: red; text-align: center;'>API returned invalid image data.</p>"
101
 
102
  try:
103
  image = Image.open(io.BytesIO(image_bytes))
104
- print(f"Image received and opened successfully. Format: {image.format}, Size: {image.size}")
105
  except UnidentifiedImageError as img_err:
106
  print(f"Error: Could not identify or open image from API response bytes: {img_err}")
107
- # Optionally save the invalid bytes for debugging
108
- # error_bytes_path = os.path.join(IMAGE_DIR, f"error_{key}_bytes.bin")
109
- # with open(error_bytes_path, "wb") as f: f.write(image_bytes)
110
- # print(f"Saved problematic bytes to {error_bytes_path}")
111
  return None, "<p style='color: red; text-align: center;'>Failed to process image data from API.</p>"
112
 
113
- print(f'Generation {key} API call successful!')
114
-
115
  # --- Save image and create download link ---
116
  filename = f"{int(time.time())}_{uuid.uuid4().hex[:8]}.png"
117
- # save_path is relative to the script's execution directory
118
  save_path = os.path.join(IMAGE_DIR, filename)
119
- absolute_save_path = os.path.abspath(save_path) # Get absolute path for logging
120
 
121
  try:
122
- print(f"Attempting to save image to: {absolute_save_path}")
123
- # Save image explicitly as PNG
124
  image.save(save_path, "PNG")
125
 
126
- # *** Verify file exists after saving ***
127
  if os.path.exists(save_path):
128
  file_size = os.path.getsize(save_path)
129
- print(f"SUCCESS: Image confirmed saved to: {save_path} (Absolute: {absolute_save_path})")
130
- print(f"Saved file size: {file_size} bytes")
131
- if file_size < 100: # Warn if the saved file is suspiciously small
132
  print(f"WARNING: Saved file {save_path} is very small ({file_size} bytes). May indicate an issue.")
133
- # Optionally return a warning message in the UI
134
- # return image, "<p style='color: orange; text-align: center;'>Warning: Saved image file is unexpectedly small.</p>"
135
  else:
136
- # This indicates a serious problem if save() didn't raise an error but the file isn't there
137
  print(f"CRITICAL ERROR: File NOT found at {save_path} (Absolute: {absolute_save_path}) immediately after saving!")
138
  return image, "<p style='color: red; text-align: center;'>Internal Error: Failed to confirm image file save.</p>"
139
 
140
- # Get current space name from the API URL
141
- space_name = "greendra-stable-diffusion-3-5-large-serverless"
142
- print(f"Current space name: {space_name}")
143
-
 
 
 
 
144
  relative_file_url = f"/gradio_api/file={save_path}"
145
- print(f"Generated relative file URL for Gradio API: {relative_file_url}")
146
 
147
  encoded_file_url = quote(relative_file_url)
148
- # Add space_name parameter to the URL
149
  arintelli_url = f"{ARINTELLI_REDIRECT_BASE}?download_url={encoded_file_url}&space_name={space_name}"
150
- print(f"Generated redirect link: {arintelli_url}")
151
 
152
- # Use simpler button style like the Run button
153
  download_html = (
154
- f'<div style="text-align: center;">'
155
  f'<a href="{arintelli_url}" target="_blank" class="gr-button gr-button-lg gr-button-primary">'
156
  f'Download Image'
157
  f'</a>'
158
  f'</div>'
159
  )
160
 
161
- print(f"--- Generation {key} Completed Successfully ---")
162
  return image, download_html
163
 
164
  except (OSError, IOError) as save_err:
165
- # Handle errors during the file save operation
166
  print(f"CRITICAL ERROR: Failed to save image to {save_path} (Absolute: {absolute_save_path}): {save_err}")
167
- traceback.print_exc() # Log detailed traceback
168
  return image, f"<p style='color: red; text-align: center;'>Internal Error: Failed to save image file. Details: {save_err}</p>"
169
  except Exception as e:
170
- # Catch any other unexpected errors during link creation/saving
171
  print(f"Error during link creation or unexpected save issue: {e}")
172
  traceback.print_exc()
173
- # Return the generated image (if available) but indicate link error
174
  return image, "<p style='color: red; text-align: center;'>Internal Error creating download link.</p>"
175
 
176
  # --- Exception Handling for API Call ---
@@ -178,46 +152,41 @@ def query(prompt, negative_prompt, steps=35, cfg_scale=7, seed=-1, width=1024, h
178
  print(f"Error: Request timed out after {timeout} seconds.")
179
  return None, "<p style='color: red; text-align: center;'>Request timed out. The model is taking too long.</p>"
180
  except requests.exceptions.HTTPError as e:
181
- # Handle HTTP errors from the API (4xx, 5xx)
182
  status_code = e.response.status_code
183
- error_text = e.response.text # Default error text
184
  try:
185
- # Try to parse more specific error message from JSON response
186
  error_data = e.response.json()
187
  error_text = error_data.get('error', error_text)
188
  if isinstance(error_text, dict) and 'message' in error_text:
189
- error_text = error_text['message'] # Handle nested messages
190
  except json.JSONDecodeError:
191
- pass # Keep raw text if not JSON
192
 
193
  print(f"Error: Failed API call. Status: {status_code}, Response: {error_text}")
194
 
195
- # Generate user-friendly messages based on status code
196
- if status_code == 503: # Service Unavailable (often model loading)
197
  estimated_time = error_data.get("estimated_time") if 'error_data' in locals() and isinstance(error_data, dict) else None
198
  if estimated_time:
199
  error_message = f"Model is loading (503), please wait. Est. time: {estimated_time:.1f}s. Try again."
200
  else:
201
  error_message = f"Service unavailable (503). Model might be loading or down. Try again later."
202
- elif status_code == 400: # Bad Request (invalid parameters)
203
  error_message = f"Bad Request (400): Check parameters. API Error: {error_text}"
204
- elif status_code == 422: # Unprocessable Entity (validation error)
205
  error_message = f"Validation Error (422): Input invalid. API Error: {error_text}"
206
- elif status_code == 401 or status_code == 403: # Unauthorized / Forbidden
207
  error_message = f"Authorization Error ({status_code}): Check your API Token (HF_READ_TOKEN)."
208
- else: # Generic API error
209
  error_message = f"API Error: {status_code}. Details: {error_text}"
210
 
211
- # Return None for image, and the error message string for the HTML component
212
  return None, f"<p style='color: red; text-align: center;'>{error_message}</p>"
213
  except Exception as e:
214
- # Catch any other unexpected errors during the process
215
  print(f"An unexpected error occurred: {e}")
216
- traceback.print_exc() # Log detailed traceback
217
  return None, f"<p style='color: red; text-align: center;'>An unexpected error occurred: {e}</p>"
218
 
219
 
220
- # --- CSS Styling ---
221
  css = """
222
  #app-container {
223
  max-width: 800px;
@@ -227,48 +196,33 @@ css = """
227
  textarea:focus {
228
  background: #0d1117 !important;
229
  }
230
- #download-link-container p { /* Style the link container */
231
- margin-top: 10px; /* Add some space above the link */
232
- font-size: 0.9em; /* Slightly smaller text for the link message */
233
  }
234
  """
235
 
236
- # --- Build the Gradio UI with Blocks ---
237
  with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
238
- gr.HTML("<center><h1>Stable Diffusion 3.5 Large</h1></center>")
239
 
240
  with gr.Column(elem_id="app-container"):
241
- # --- Input Components ---
242
  with gr.Row():
243
  with gr.Column(elem_id="prompt-container"):
244
  with gr.Row():
245
- text_prompt = gr.Textbox(
246
- label="Prompt",
247
- placeholder="Enter a prompt here",
248
- lines=2,
249
- elem_id="prompt-text-input"
250
- )
251
  with gr.Row():
252
  with gr.Accordion("Advanced Settings", open=False):
253
- negative_prompt = gr.Textbox(
254
- label="Negative Prompt",
255
- placeholder="What should not be in the image",
256
- value="(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos",
257
- lines=3,
258
- elem_id="negative-prompt-text-input"
259
- )
260
  with gr.Row():
261
  width = gr.Slider(label="Width", value=1024, minimum=64, maximum=1216, step=32)
262
  height = gr.Slider(label="Height", value=1024, minimum=64, maximum=1216, step=32)
263
- steps = gr.Slider(label="Sampling steps", value=35, minimum=1, maximum=100, step=1)
264
- cfg = gr.Slider(label="CFG Scale (guidance_scale)", value=7, minimum=1, maximum=20, step=1)
265
- # Removed 'strength' slider as it wasn't used in query payload
266
- # strength = gr.Slider(label="Strength (Primarily for Img2Img)", value=0.7, minimum=0, maximum=1, step=0.001, info="Note: Strength is mainly used in Image-to-Image generation.")
267
  seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1, info="Set to -1 for random seed")
268
- # Removed 'method' radio as it wasn't used in query payload
269
- # method = gr.Radio(label="Sampling method", value="DPM++ 2M Karras", choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"], info="Note: Sampler choice might not be supported by this API.")
270
 
271
- # --- Action Button ---
272
  with gr.Row():
273
  text_button = gr.Button("Run", variant='primary', elem_id="gen-button")
274
 
@@ -279,21 +233,19 @@ with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
279
  # HTML component to display status messages or the download link
280
  download_link_display = gr.HTML(elem_id="download-link-container")
281
 
282
- # --- Event Listener ---
283
- # Bind the button click to the query function
284
  text_button.click(
285
  query,
286
- # Ensure the inputs list matches the parameters of the `query` function definition
287
  inputs=[text_prompt, negative_prompt, steps, cfg, seed, width, height],
288
- # Outputs go to the image component and the HTML component
289
  outputs=[image_output, download_link_display]
290
  )
291
 
292
- # --- Launch the Gradio app ---
293
  print("Starting Gradio app...")
294
- # Use allowed_paths with the pre-calculated absolute path to the image directory
295
  app.launch(
296
  show_api=False,
297
- share=False, # Set to True only if you need a public link for direct testing
298
- allowed_paths=[absolute_image_dir]
299
  )
 
4
  import random
5
  import os
6
  import time
7
+ from PIL import Image, UnidentifiedImageError
8
  from deep_translator import GoogleTranslator
9
  import json
10
  import uuid
11
  from urllib.parse import quote
12
+ import traceback
13
 
14
  # Project by Nymbo
15
 
16
  # --- Constants ---
17
+ API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"
18
  API_TOKEN = os.getenv("HF_READ_TOKEN")
19
  if not API_TOKEN:
20
  print("WARNING: HF_READ_TOKEN environment variable not set. API calls may fail.")
 
 
21
  headers = {"Authorization": f"Bearer {API_TOKEN}"} if API_TOKEN else {}
22
  timeout = 100 # seconds for API call timeout
23
 
 
38
  absolute_image_dir = os.path.abspath(IMAGE_DIR)
39
  print(f"Absolute path for allowed_paths: {absolute_image_dir}")
40
 
41
+ # Function to query the API and return the generated image and download link
42
+ def query(prompt, negative_prompt="", steps=30, cfg_scale=7, seed=-1, width=1024, height=1024):
43
+ # Removed sampler and strength as they are not explicitly used in the payload below
44
+ # Note: If the API endpoint *does* support sampler/strength, add them back to the payload
 
 
 
45
  if not prompt or not prompt.strip():
46
  print("Empty prompt received.")
47
  # Return None for image and an informative message for the HTML component
 
52
 
53
  # Translation
54
  try:
 
55
  translated_prompt = GoogleTranslator(source='auto', target='en').translate(prompt)
 
56
  except Exception as e:
 
57
  translated_prompt = prompt # Fallback to original if translation fails
58
 
59
  # Add suffix to prompt
60
  final_prompt = f"{translated_prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
61
+ print(f'Generation {key} prompt: {final_prompt}')
62
 
63
+ # Prepare the payload for the API call
64
  payload = {
65
  "inputs": final_prompt,
66
+ "negative_prompt": negative_prompt, # Assuming API accepts negative_prompt
67
  "steps": steps,
68
  "guidance_scale": cfg_scale, # API often uses guidance_scale
69
  "seed": seed if seed != -1 else random.randint(1, 1000000000),
70
+ "parameters": {
71
  "width": width,
72
  "height": height,
73
+ # If the API supports other params like 'steps', 'guidance_scale', they might belong here or top-level
74
  }
75
+ # Removed 'is_negative' as negative_prompt is usually passed directly
76
+ # Removed 'strength' and 'sampler' as they weren't in the target API structure
77
  }
78
 
79
  # API Call Section
80
  try:
 
81
  if not headers:
82
  print("WARNING: Authorization header is missing (HF_READ_TOKEN not set?)")
 
83
  return None, "<p style='color: red; text-align: center;'>Configuration Error: API Token missing.</p>"
84
 
85
  response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
86
+ response.raise_for_status()
87
 
88
  image_bytes = response.content
89
+ if not image_bytes or len(image_bytes) < 100:
 
90
  print(f"Error: Received empty or very small response content (length: {len(image_bytes)}). Potential API issue.")
91
  return None, "<p style='color: red; text-align: center;'>API returned invalid image data.</p>"
92
 
93
  try:
94
  image = Image.open(io.BytesIO(image_bytes))
 
95
  except UnidentifiedImageError as img_err:
96
  print(f"Error: Could not identify or open image from API response bytes: {img_err}")
 
 
 
 
97
  return None, "<p style='color: red; text-align: center;'>Failed to process image data from API.</p>"
98
 
 
 
99
  # --- Save image and create download link ---
100
  filename = f"{int(time.time())}_{uuid.uuid4().hex[:8]}.png"
 
101
  save_path = os.path.join(IMAGE_DIR, filename)
102
+ absolute_save_path = os.path.abspath(save_path)
103
 
104
  try:
 
 
105
  image.save(save_path, "PNG")
106
 
 
107
  if os.path.exists(save_path):
108
  file_size = os.path.getsize(save_path)
109
+ if file_size < 100:
 
 
110
  print(f"WARNING: Saved file {save_path} is very small ({file_size} bytes). May indicate an issue.")
 
 
111
  else:
 
112
  print(f"CRITICAL ERROR: File NOT found at {save_path} (Absolute: {absolute_save_path}) immediately after saving!")
113
  return image, "<p style='color: red; text-align: center;'>Internal Error: Failed to confirm image file save.</p>"
114
 
115
+ # Determine space name (adjust logic if API_URL format differs)
116
+ try:
117
+ space_name = "greendra-flux-1-schnell-serverless"
118
+ # A more robust way might involve getting the space ID from env vars if available
119
+ except IndexError:
120
+ print("WARNING: Could not reliably determine space name from API_URL. Using a default.")
121
+ space_name = "unknown-flux-space" # Provide a fallback
122
+
123
  relative_file_url = f"/gradio_api/file={save_path}"
 
124
 
125
  encoded_file_url = quote(relative_file_url)
 
126
  arintelli_url = f"{ARINTELLI_REDIRECT_BASE}?download_url={encoded_file_url}&space_name={space_name}"
127
+ print(f"{arintelli_url}")
128
 
129
+ # Use Gradio's primary button style for the link
130
  download_html = (
131
+ f'<div style="text-align: center; margin-top: 15px;">' # Added margin-top
132
  f'<a href="{arintelli_url}" target="_blank" class="gr-button gr-button-lg gr-button-primary">'
133
  f'Download Image'
134
  f'</a>'
135
  f'</div>'
136
  )
137
 
138
+ print(f"--- Generation {key} Done ---")
139
  return image, download_html
140
 
141
  except (OSError, IOError) as save_err:
 
142
  print(f"CRITICAL ERROR: Failed to save image to {save_path} (Absolute: {absolute_save_path}): {save_err}")
143
+ traceback.print_exc()
144
  return image, f"<p style='color: red; text-align: center;'>Internal Error: Failed to save image file. Details: {save_err}</p>"
145
  except Exception as e:
 
146
  print(f"Error during link creation or unexpected save issue: {e}")
147
  traceback.print_exc()
 
148
  return image, "<p style='color: red; text-align: center;'>Internal Error creating download link.</p>"
149
 
150
  # --- Exception Handling for API Call ---
 
152
  print(f"Error: Request timed out after {timeout} seconds.")
153
  return None, "<p style='color: red; text-align: center;'>Request timed out. The model is taking too long.</p>"
154
  except requests.exceptions.HTTPError as e:
 
155
  status_code = e.response.status_code
156
+ error_text = e.response.text
157
  try:
 
158
  error_data = e.response.json()
159
  error_text = error_data.get('error', error_text)
160
  if isinstance(error_text, dict) and 'message' in error_text:
161
+ error_text = error_text['message']
162
  except json.JSONDecodeError:
163
+ pass
164
 
165
  print(f"Error: Failed API call. Status: {status_code}, Response: {error_text}")
166
 
167
+ if status_code == 503:
 
168
  estimated_time = error_data.get("estimated_time") if 'error_data' in locals() and isinstance(error_data, dict) else None
169
  if estimated_time:
170
  error_message = f"Model is loading (503), please wait. Est. time: {estimated_time:.1f}s. Try again."
171
  else:
172
  error_message = f"Service unavailable (503). Model might be loading or down. Try again later."
173
+ elif status_code == 400:
174
  error_message = f"Bad Request (400): Check parameters. API Error: {error_text}"
175
+ elif status_code == 422:
176
  error_message = f"Validation Error (422): Input invalid. API Error: {error_text}"
177
+ elif status_code == 401 or status_code == 403:
178
  error_message = f"Authorization Error ({status_code}): Check your API Token (HF_READ_TOKEN)."
179
+ else:
180
  error_message = f"API Error: {status_code}. Details: {error_text}"
181
 
 
182
  return None, f"<p style='color: red; text-align: center;'>{error_message}</p>"
183
  except Exception as e:
 
184
  print(f"An unexpected error occurred: {e}")
185
+ traceback.print_exc()
186
  return None, f"<p style='color: red; text-align: center;'>An unexpected error occurred: {e}</p>"
187
 
188
 
189
+ # CSS to style the app
190
  css = """
191
  #app-container {
192
  max-width: 800px;
 
196
  textarea:focus {
197
  background: #0d1117 !important;
198
  }
199
+ #download-link-container p {
200
+ margin-top: 10px;
201
+ font-size: 0.9em;
202
  }
203
  """
204
 
205
+ # Build the Gradio UI with Blocks
206
  with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
207
+ gr.HTML("<center><h1>FLUX.1-Schnell</h1></center>")
208
 
209
  with gr.Column(elem_id="app-container"):
 
210
  with gr.Row():
211
  with gr.Column(elem_id="prompt-container"):
212
  with gr.Row():
213
+ text_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt here", lines=2, elem_id="prompt-text-input")
214
+
 
 
 
 
215
  with gr.Row():
216
  with gr.Accordion("Advanced Settings", open=False):
217
+ negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="What should not be in the image", value="(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos", lines=3, elem_id="negative-prompt-text-input")
 
 
 
 
 
 
218
  with gr.Row():
219
  width = gr.Slider(label="Width", value=1024, minimum=64, maximum=1216, step=32)
220
  height = gr.Slider(label="Height", value=1024, minimum=64, maximum=1216, step=32)
221
+ steps = gr.Slider(label="Sampling steps", value=30, minimum=1, maximum=100, step=1) # Default updated based on query function default
222
+ cfg = gr.Slider(label="CFG Scale (guidance_scale)", value=7, minimum=1, maximum=20, step=1) # Label updated
223
+ # Removed strength and sampler sliders as they are not passed to query
 
224
  seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1, info="Set to -1 for random seed")
 
 
225
 
 
226
  with gr.Row():
227
  text_button = gr.Button("Run", variant='primary', elem_id="gen-button")
228
 
 
233
  # HTML component to display status messages or the download link
234
  download_link_display = gr.HTML(elem_id="download-link-container")
235
 
236
+ # Bind the button to the query function
 
237
  text_button.click(
238
  query,
239
+ # Ensure inputs match the query function definition
240
  inputs=[text_prompt, negative_prompt, steps, cfg, seed, width, height],
241
+ # Outputs go to the image and HTML components
242
  outputs=[image_output, download_link_display]
243
  )
244
 
245
+ # Launch the Gradio app with allowed_paths
246
  print("Starting Gradio app...")
 
247
  app.launch(
248
  show_api=False,
249
+ share=False,
250
+ allowed_paths=[absolute_image_dir] # Added allowed_paths
251
  )