ginipick commited on
Commit
76a0dbd
Β·
verified Β·
1 Parent(s): 975601a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -135
app.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  import random
3
  import os
4
  import uuid
@@ -9,37 +8,47 @@ import spaces
9
  import torch
10
  from diffusers import DiffusionPipeline
11
  from PIL import Image
12
- import huggingface_hub
13
- import requests
14
- from tqdm.auto import tqdm
15
- import time
16
-
17
- # νƒ€μž„μ•„μ›ƒ κ°’ 증가 μ„€μ •
18
- huggingface_hub.constants.DEFAULT_ETAG_TIMEOUT = 30
19
- huggingface_hub.constants.DEFAULT_DOWNLOAD_TIMEOUT = 120
20
 
21
- # Temporary fix to patch the gradio_client.utils module
22
  import gradio_client.utils
23
- original_get_type = gradio_client.utils.get_type
 
 
 
24
 
25
- def patched_get_type(schema):
26
- if not isinstance(schema, dict):
27
- return "any" # Default to "any" type for non-dict schemas
28
- return original_get_type(schema)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- gradio_client.utils.get_type = patched_get_type
 
31
 
32
  # Create permanent storage directory
33
  SAVE_DIR = "saved_images" # Gradio will handle the persistence
34
  if not os.path.exists(SAVE_DIR):
35
  os.makedirs(SAVE_DIR, exist_ok=True)
36
 
37
- # λͺ¨λΈ λ‘œλ”© ν•¨μˆ˜ - μž¬μ‹œλ„ 둜직 μΆ”κ°€
 
 
 
 
38
  def load_model_with_retry(max_retries=5):
39
- device = "cuda" if torch.cuda.is_available() else "cpu"
40
- repo_id = "black-forest-labs/FLUX.1-dev"
41
- adapter_id = "openfree/flux-chatgpt-ghibli-lora"
42
-
43
  for attempt in range(max_retries):
44
  try:
45
  print(f"Loading model attempt {attempt+1}/{max_retries}...")
@@ -53,18 +62,18 @@ def load_model_with_retry(max_retries=5):
53
  pipeline.load_lora_weights(adapter_id)
54
  pipeline = pipeline.to(device)
55
  print("Pipeline ready!")
56
- return pipeline, device
57
- except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError) as e:
58
  if attempt < max_retries - 1:
59
- wait_time = 10 * (attempt + 1) # μ μ§„μ μœΌλ‘œ λŒ€κΈ° μ‹œκ°„ 증가
60
- print(f"Download timed out or connection error: {e}. Retrying in {wait_time} seconds...")
 
61
  time.sleep(wait_time)
62
  else:
63
- raise Exception(f"Failed to download model after {max_retries} attempts: {e}")
64
 
65
- # λͺ¨λΈ λ‘œλ“œ μ‹œμž‘
66
- print("Starting model loading process...")
67
- pipeline, device = load_model_with_retry()
68
 
69
  MAX_SEED = np.iinfo(np.int32).max
70
  MAX_IMAGE_SIZE = 1024
@@ -97,10 +106,6 @@ def load_generated_images():
97
  image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
98
  return image_files
99
 
100
- def load_predefined_images():
101
- # Return empty list since we're not using predefined images
102
- return []
103
-
104
  @spaces.GPU(duration=120)
105
  def inference(
106
  prompt: str,
@@ -117,21 +122,28 @@ def inference(
117
  seed = random.randint(0, MAX_SEED)
118
  generator = torch.Generator(device=device).manual_seed(seed)
119
 
120
- image = pipeline(
121
- prompt=prompt,
122
- guidance_scale=guidance_scale,
123
- num_inference_steps=num_inference_steps,
124
- width=width,
125
- height=height,
126
- generator=generator,
127
- joint_attention_kwargs={"scale": lora_scale},
128
- ).images[0]
129
-
130
- # Save the generated image
131
- filepath = save_generated_image(image, prompt)
132
-
133
- # Return the image, seed, and updated gallery
134
- return image, seed, load_generated_images()
 
 
 
 
 
 
 
135
 
136
  examples = [
137
  "Ghibli style futuristic stormtrooper with glossy white armor and a sleek helmet, standing heroically on a lush alien planet, vibrant flowers blooming around, soft sunlight illuminating the scene, a gentle breeze rustling the leaves. The armor reflects the pink and purple hues of the alien sunset, creating an ethereal glow around the figure. [trigger]",
@@ -153,105 +165,122 @@ footer {
153
  }
154
  """
155
 
156
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, analytics_enabled=False) as demo:
 
157
  gr.HTML('<div class="title"> FLUX Ghibli LoRA</div>')
158
- gr.HTML('<div class="title">πŸ˜„Community: <a href="https://discord.gg/openfreeai" target="_blank">https://discord.gg/openfreeai</a></div>')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- with gr.Tabs() as tabs:
161
- with gr.Tab("Generation"):
162
- with gr.Column(elem_id="col-container"):
163
  with gr.Row():
164
- prompt = gr.Text(
165
- label="Prompt",
166
- show_label=False,
167
- max_lines=1,
168
- placeholder="Enter your prompt",
169
- container=False,
 
 
 
 
 
 
 
170
  )
171
- run_button = gr.Button("Run", scale=0)
172
-
173
- result = gr.Image(label="Result", show_label=False)
174
 
175
- with gr.Accordion("Advanced Settings", open=False):
176
- seed = gr.Slider(
177
- label="Seed",
178
- minimum=0,
179
- maximum=MAX_SEED,
 
 
 
 
 
 
 
180
  step=1,
181
- value=42,
182
  )
183
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
184
-
185
- with gr.Row():
186
- width = gr.Slider(
187
- label="Width",
188
- minimum=256,
189
- maximum=MAX_IMAGE_SIZE,
190
- step=32,
191
- value=1024,
192
- )
193
- height = gr.Slider(
194
- label="Height",
195
- minimum=256,
196
- maximum=MAX_IMAGE_SIZE,
197
- step=32,
198
- value=768,
199
- )
200
-
201
- with gr.Row():
202
- guidance_scale = gr.Slider(
203
- label="Guidance scale",
204
- minimum=0.0,
205
- maximum=10.0,
206
- step=0.1,
207
- value=3.5,
208
- )
209
- num_inference_steps = gr.Slider(
210
- label="Number of inference steps",
211
- minimum=1,
212
- maximum=50,
213
- step=1,
214
- value=30,
215
- )
216
- lora_scale = gr.Slider(
217
- label="LoRA scale",
218
- minimum=0.0,
219
- maximum=1.0,
220
- step=0.1,
221
- value=1.0,
222
- )
223
-
224
- gr.Examples(
225
- examples=examples,
226
- inputs=[prompt],
227
- outputs=[result, seed],
228
- )
229
-
230
- with gr.Tab("Gallery"):
231
- gallery_header = gr.Markdown("### Generated Images Gallery")
232
- generated_gallery = gr.Gallery(
233
- label="Generated Images",
234
- columns=6,
235
- show_label=False,
236
- value=load_generated_images(),
237
- elem_id="generated_gallery",
238
- height="auto"
239
  )
240
- refresh_btn = gr.Button("πŸ”„ Refresh Gallery")
241
-
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
  # Event handlers
244
  def refresh_gallery():
245
  return load_generated_images()
246
 
 
 
 
247
  refresh_btn.click(
248
  fn=refresh_gallery,
249
  inputs=None,
250
  outputs=generated_gallery,
251
  )
 
 
 
 
 
 
252
 
253
- gr.on(
254
- triggers=[run_button.click, prompt.submit],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  fn=inference,
256
  inputs=[
257
  prompt,
@@ -263,15 +292,15 @@ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, analytics_enabled=Fa
263
  num_inference_steps,
264
  lora_scale,
265
  ],
266
- outputs=[result, seed, generated_gallery],
267
  )
268
 
269
- # Launch with explicit host and port
270
- demo.queue()
271
  try:
272
- demo.launch(share=False)
 
273
  except Exception as e:
274
  print(f"Error during launch: {e}")
275
- # μ—λŸ¬ λ°œμƒ μ‹œ, κ°„μ†Œν™”λœ λ²„μ „μœΌλ‘œ μž¬μ‹œλ„
276
- print("Retrying with simplified launch...")
277
- demo.launch(share=False, ssl_verify=False)
 
 
1
  import random
2
  import os
3
  import uuid
 
8
  import torch
9
  from diffusers import DiffusionPipeline
10
  from PIL import Image
 
 
 
 
 
 
 
 
11
 
12
+ # Apply more comprehensive patches to Gradio's utility functions
13
  import gradio_client.utils
14
+ import types
15
+
16
+ # Patch 1: Fix the _json_schema_to_python_type function
17
+ original_json_schema = gradio_client.utils._json_schema_to_python_type
18
 
19
+ def patched_json_schema(schema, defs=None):
20
+ # Handle boolean values directly
21
+ if isinstance(schema, bool):
22
+ return "bool"
23
+
24
+ # Handle cases where 'additionalProperties' is a boolean
25
+ try:
26
+ if "additionalProperties" in schema and isinstance(schema["additionalProperties"], bool):
27
+ schema["additionalProperties"] = {"type": "any"}
28
+ except (TypeError, KeyError):
29
+ pass
30
+
31
+ # Call the original function
32
+ try:
33
+ return original_json_schema(schema, defs)
34
+ except Exception as e:
35
+ # Fallback to a safe value when the schema can't be parsed
36
+ return "any"
37
 
38
+ # Replace the original function with our patched version
39
+ gradio_client.utils._json_schema_to_python_type = patched_json_schema
40
 
41
  # Create permanent storage directory
42
  SAVE_DIR = "saved_images" # Gradio will handle the persistence
43
  if not os.path.exists(SAVE_DIR):
44
  os.makedirs(SAVE_DIR, exist_ok=True)
45
 
46
+ # Safe settings for model loading
47
+ device = "cuda" if torch.cuda.is_available() else "cpu"
48
+ repo_id = "black-forest-labs/FLUX.1-dev"
49
+ adapter_id = "openfree/flux-chatgpt-ghibli-lora"
50
+
51
  def load_model_with_retry(max_retries=5):
 
 
 
 
52
  for attempt in range(max_retries):
53
  try:
54
  print(f"Loading model attempt {attempt+1}/{max_retries}...")
 
62
  pipeline.load_lora_weights(adapter_id)
63
  pipeline = pipeline.to(device)
64
  print("Pipeline ready!")
65
+ return pipeline
66
+ except Exception as e:
67
  if attempt < max_retries - 1:
68
+ wait_time = 10 * (attempt + 1)
69
+ print(f"Error loading model: {e}. Retrying in {wait_time} seconds...")
70
+ import time
71
  time.sleep(wait_time)
72
  else:
73
+ raise Exception(f"Failed to load model after {max_retries} attempts: {e}")
74
 
75
+ # Load the model
76
+ pipeline = load_model_with_retry()
 
77
 
78
  MAX_SEED = np.iinfo(np.int32).max
79
  MAX_IMAGE_SIZE = 1024
 
106
  image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
107
  return image_files
108
 
 
 
 
 
109
  @spaces.GPU(duration=120)
110
  def inference(
111
  prompt: str,
 
122
  seed = random.randint(0, MAX_SEED)
123
  generator = torch.Generator(device=device).manual_seed(seed)
124
 
125
+ # Error handling for the inference process
126
+ try:
127
+ image = pipeline(
128
+ prompt=prompt,
129
+ guidance_scale=guidance_scale,
130
+ num_inference_steps=num_inference_steps,
131
+ width=width,
132
+ height=height,
133
+ generator=generator,
134
+ joint_attention_kwargs={"scale": lora_scale},
135
+ ).images[0]
136
+
137
+ # Save the generated image
138
+ filepath = save_generated_image(image, prompt)
139
+
140
+ # Return the image, seed, and updated gallery
141
+ return image, seed, load_generated_images()
142
+ except Exception as e:
143
+ # Log the error and return a simple error image
144
+ print(f"Error during inference: {e}")
145
+ error_img = Image.new('RGB', (width, height), color='red')
146
+ return error_img, seed, load_generated_images()
147
 
148
  examples = [
149
  "Ghibli style futuristic stormtrooper with glossy white armor and a sleek helmet, standing heroically on a lush alien planet, vibrant flowers blooming around, soft sunlight illuminating the scene, a gentle breeze rustling the leaves. The armor reflects the pink and purple hues of the alien sunset, creating an ethereal glow around the figure. [trigger]",
 
165
  }
166
  """
167
 
168
+ # Use a simpler UI configuration that is less likely to cause issues
169
+ with gr.Blocks(css=css, analytics_enabled=False) as demo:
170
  gr.HTML('<div class="title"> FLUX Ghibli LoRA</div>')
171
+ gr.HTML('<div class="title">πŸ˜„Image to Video Explore: <a href="https://huggingface.co/spaces/ginigen/theater" target="_blank">https://huggingface.co/spaces/ginigen/theater</a></div>')
172
+
173
+ with gr.Row():
174
+ with gr.Column(scale=3):
175
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt")
176
+
177
+ with gr.Row():
178
+ run_button = gr.Button("Generate Image")
179
+ clear_button = gr.Button("Clear")
180
+
181
+ with gr.Accordion("Settings", open=False):
182
+ seed = gr.Slider(
183
+ label="Seed",
184
+ minimum=0,
185
+ maximum=MAX_SEED,
186
+ step=1,
187
+ value=42,
188
+ )
189
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
190
 
 
 
 
191
  with gr.Row():
192
+ width = gr.Slider(
193
+ label="Width",
194
+ minimum=256,
195
+ maximum=MAX_IMAGE_SIZE,
196
+ step=32,
197
+ value=1024,
198
+ )
199
+ height = gr.Slider(
200
+ label="Height",
201
+ minimum=256,
202
+ maximum=MAX_IMAGE_SIZE,
203
+ step=32,
204
+ value=768,
205
  )
 
 
 
206
 
207
+ with gr.Row():
208
+ guidance_scale = gr.Slider(
209
+ label="Guidance scale",
210
+ minimum=0.0,
211
+ maximum=10.0,
212
+ step=0.1,
213
+ value=3.5,
214
+ )
215
+ num_inference_steps = gr.Slider(
216
+ label="Steps",
217
+ minimum=1,
218
+ maximum=50,
219
  step=1,
220
+ value=30,
221
  )
222
+ lora_scale = gr.Slider(
223
+ label="LoRA scale",
224
+ minimum=0.0,
225
+ maximum=1.0,
226
+ step=0.1,
227
+ value=1.0,
228
+ )
229
+
230
+ gr.Examples(
231
+ examples=examples,
232
+ inputs=prompt,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  )
234
+
235
+ with gr.Column(scale=4):
236
+ result = gr.Image(label="Generated Image")
237
+ seed_text = gr.Number(label="Used Seed", value=42)
238
+
239
+ with gr.Tab("Gallery"):
240
+ gallery_header = gr.Markdown("### Generated Images Gallery")
241
+ generated_gallery = gr.Gallery(
242
+ label="Generated Images",
243
+ columns=3,
244
+ value=load_generated_images(),
245
+ height="auto"
246
+ )
247
+ refresh_btn = gr.Button("πŸ”„ Refresh Gallery")
248
 
249
  # Event handlers
250
  def refresh_gallery():
251
  return load_generated_images()
252
 
253
+ def clear_output():
254
+ return "", gr.update(value=None), seed
255
+
256
  refresh_btn.click(
257
  fn=refresh_gallery,
258
  inputs=None,
259
  outputs=generated_gallery,
260
  )
261
+
262
+ clear_button.click(
263
+ fn=clear_output,
264
+ inputs=None,
265
+ outputs=[prompt, result, seed_text]
266
+ )
267
 
268
+ run_button.click(
269
+ fn=inference,
270
+ inputs=[
271
+ prompt,
272
+ seed,
273
+ randomize_seed,
274
+ width,
275
+ height,
276
+ guidance_scale,
277
+ num_inference_steps,
278
+ lora_scale,
279
+ ],
280
+ outputs=[result, seed_text, generated_gallery],
281
+ )
282
+
283
+ prompt.submit(
284
  fn=inference,
285
  inputs=[
286
  prompt,
 
292
  num_inference_steps,
293
  lora_scale,
294
  ],
295
+ outputs=[result, seed_text, generated_gallery],
296
  )
297
 
298
+ # Launch with fallback options
 
299
  try:
300
+ demo.queue(concurrency_count=1, max_size=10)
301
+ demo.launch(debug=True, show_api=False)
302
  except Exception as e:
303
  print(f"Error during launch: {e}")
304
+ print("Trying alternative launch configuration...")
305
+ # Skip queue and simplify launch parameters
306
+ demo.launch(debug=True, show_api=False, share=False)