bakyt92 commited on
Commit
e4c0d3f
·
1 Parent(s): 5cafc1f

update app.py - fix of errors

Browse files
Files changed (1) hide show
  1. app.py +45 -20
app.py CHANGED
@@ -35,7 +35,8 @@ def generate_ideogram_image(api_key, prompt, aspect_ratio="ASPECT_1_1"):
35
  image_url = result["data"][0]["url"]
36
  img_response = requests.get(image_url)
37
  image = Image.open(io.BytesIO(img_response.content))
38
- return image, "Image generated successfully!", image
 
39
  else:
40
  return None, "No image data received", None
41
  else:
@@ -61,7 +62,8 @@ def generate_dalle_image(api_key, prompt, size="1024x1024"):
61
  image_url = response.data[0].url
62
  img_response = requests.get(image_url)
63
  image = Image.open(io.BytesIO(img_response.content))
64
- return image, "Image generated successfully with DALL-E 3!", image
 
65
 
66
  except Exception as e:
67
  return None, f"Error generating image: {str(e)}", None
@@ -70,7 +72,12 @@ def process_uploaded_image(image):
70
  """Process uploaded image"""
71
  if image is None:
72
  return None, "No image uploaded", None
73
- return image, "Image uploaded successfully!", image
 
 
 
 
 
74
 
75
  # Text Overlay Functions
76
  def add_text_to_image(img, pattern, line1, line2, line3, font_size, color, add_outline):
@@ -340,11 +347,6 @@ def create_pattern_template(pattern, width=200, height=120):
340
  positions = [(width // 2, int(height * 0.45)), (width // 2, int(height * 0.65)), (width // 2, int(height * 0.85))]
341
 
342
  # Draw white rectangles to represent text boxes
343
- try:
344
- font = ImageFont.load_default()
345
- except:
346
- font = None
347
-
348
  for i, (x, y) in enumerate(positions):
349
  # Draw white rectangle as text placeholder
350
  box_width = 60
@@ -355,18 +357,35 @@ def create_pattern_template(pattern, width=200, height=120):
355
  bottom = y + box_height // 2
356
 
357
  draw.rectangle([left, top, right, bottom], fill='white', outline='white')
358
-
359
- # Add small text label
360
- if font:
361
- try:
362
- label = f"Line {i+1}"
363
- draw.text((x, y), label, fill='black', font=font, anchor="mm")
364
- except TypeError:
365
- # Fallback for older PIL
366
- draw.text((x-15, y-5), f"L{i+1}", fill='black', font=font)
367
 
368
  return img
369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  # Function to convert PIL image to base64 for Gradio
371
  def pil_to_base64(img):
372
  """Convert PIL image to base64 string for Gradio"""
@@ -496,10 +515,10 @@ with gr.Blocks(title="AI Image Generator & Text Overlay") as demo:
496
  )
497
 
498
  with gr.Column(scale=1):
499
- # Template preview image
500
  template_preview = gr.Image(
501
  label="Template Preview",
502
- value=pattern_templates["2-lines-top"],
503
  show_label=True,
504
  interactive=False,
505
  width=200,
@@ -551,7 +570,7 @@ with gr.Blocks(title="AI Image Generator & Text Overlay") as demo:
551
 
552
  # Update template when pattern changes
553
  pattern.change(
554
- update_pattern_template,
555
  inputs=[pattern],
556
  outputs=[template_preview]
557
  )
@@ -574,6 +593,12 @@ with gr.Blocks(title="AI Image Generator & Text Overlay") as demo:
574
  outputs=[text_image, status_message]
575
  )
576
 
 
 
 
 
 
 
577
  # Launch the application
578
  if __name__ == "__main__":
579
  demo.launch(
 
35
  image_url = result["data"][0]["url"]
36
  img_response = requests.get(image_url)
37
  image = Image.open(io.BytesIO(img_response.content))
38
+ safe_copy = safe_image_copy(image)
39
+ return image, "Image generated successfully!", safe_copy
40
  else:
41
  return None, "No image data received", None
42
  else:
 
62
  image_url = response.data[0].url
63
  img_response = requests.get(image_url)
64
  image = Image.open(io.BytesIO(img_response.content))
65
+ safe_copy = safe_image_copy(image)
66
+ return image, "Image generated successfully with DALL-E 3!", safe_copy
67
 
68
  except Exception as e:
69
  return None, f"Error generating image: {str(e)}", None
 
72
  """Process uploaded image"""
73
  if image is None:
74
  return None, "No image uploaded", None
75
+ try:
76
+ safe_copy = safe_image_copy(image)
77
+ return image, "Image uploaded successfully!", safe_copy
78
+ except Exception as e:
79
+ print(f"Error processing uploaded image: {e}")
80
+ return image, f"Image uploaded with warning: {e}", image
81
 
82
  # Text Overlay Functions
83
  def add_text_to_image(img, pattern, line1, line2, line3, font_size, color, add_outline):
 
347
  positions = [(width // 2, int(height * 0.45)), (width // 2, int(height * 0.65)), (width // 2, int(height * 0.85))]
348
 
349
  # Draw white rectangles to represent text boxes
 
 
 
 
 
350
  for i, (x, y) in enumerate(positions):
351
  # Draw white rectangle as text placeholder
352
  box_width = 60
 
357
  bottom = y + box_height // 2
358
 
359
  draw.rectangle([left, top, right, bottom], fill='white', outline='white')
 
 
 
 
 
 
 
 
 
360
 
361
  return img
362
 
363
+ # Create templates
364
+ def get_pattern_template(pattern):
365
+ """Get template for pattern - create on demand to avoid initialization issues"""
366
+ return create_pattern_template(pattern)
367
+
368
+ # Fix the image passing with better error handling
369
+ def safe_image_copy(img):
370
+ """Safely copy an image to avoid corruption issues"""
371
+ if img is None:
372
+ return None
373
+ try:
374
+ # Convert to RGB and create a fresh copy
375
+ if hasattr(img, 'mode'):
376
+ # It's a PIL image
377
+ rgb_img = img.convert('RGB')
378
+ # Create a new image by copying pixel data
379
+ new_img = Image.new('RGB', rgb_img.size)
380
+ new_img.paste(rgb_img)
381
+ return new_img
382
+ else:
383
+ print(f"Warning: Unexpected image type: {type(img)}")
384
+ return img
385
+ except Exception as e:
386
+ print(f"Error copying image: {e}")
387
+ return img
388
+
389
  # Function to convert PIL image to base64 for Gradio
390
  def pil_to_base64(img):
391
  """Convert PIL image to base64 string for Gradio"""
 
515
  )
516
 
517
  with gr.Column(scale=1):
518
+ # Template preview image - initialize with None first
519
  template_preview = gr.Image(
520
  label="Template Preview",
521
+ value=None, # Start with None to avoid initialization issues
522
  show_label=True,
523
  interactive=False,
524
  width=200,
 
570
 
571
  # Update template when pattern changes
572
  pattern.change(
573
+ get_pattern_template,
574
  inputs=[pattern],
575
  outputs=[template_preview]
576
  )
 
593
  outputs=[text_image, status_message]
594
  )
595
 
596
+ # Initialize template preview after the interface is created
597
+ demo.load(
598
+ lambda: get_pattern_template("2-lines-top"),
599
+ outputs=[template_preview]
600
+ )
601
+
602
  # Launch the application
603
  if __name__ == "__main__":
604
  demo.launch(