Jensin commited on
Commit
26b8a7f
·
verified ·
1 Parent(s): e740d72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -0
app.py CHANGED
@@ -143,6 +143,38 @@ def decode_and_save_image(image_b64, filename):
143
  image.save(full_path)
144
  return full_path
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  def single_image_generation(prompt, num_steps, style):
148
  """Generate a single image with optional style"""
 
143
  image.save(full_path)
144
  return full_path
145
 
146
+ # app.py – drop this right above single_image_generation (or put in utils.py)
147
+ import base64, binascii, json, os
148
+ from PIL import Image, UnidentifiedImageError
149
+ from io import BytesIO
150
+
151
+ def safe_decode_image(image_b64: str, filename: str) -> str:
152
+ """
153
+ Decode a base-64 PNG/JPEG **only if** the payload is valid.
154
+ Returns the fully-qualified file path or raises ValueError.
155
+ """
156
+ # Bail fast if tool returned JSON / HTML / plain-text
157
+ txt = image_b64.lstrip() # strip leading whitespace
158
+ if txt.startswith("{") or txt.startswith("<") or txt.startswith("Error"):
159
+ raise ValueError(f"Received non-image payload: {txt[:120]}…")
160
+
161
+ # Strict base-64 decode
162
+ try:
163
+ image_bytes = base64.b64decode(txt, validate=True)
164
+ except binascii.Error as e:
165
+ raise ValueError(f"Invalid base-64: {e}") from None
166
+
167
+ # Pillow decode
168
+ try:
169
+ img = Image.open(BytesIO(image_bytes))
170
+ except UnidentifiedImageError:
171
+ raise ValueError("Decoded bytes are not a valid image")
172
+
173
+ # Persist
174
+ os.makedirs("AI-Marketing-Content-Creator/created_image", exist_ok=True)
175
+ full_path = os.path.join("AI-Marketing-Content-Creator/created_image", filename)
176
+ img.save(full_path)
177
+ return full_path
178
 
179
  def single_image_generation(prompt, num_steps, style):
180
  """Generate a single image with optional style"""