Fix: Update handler to return PIL Image directly
Browse files- handler.py +22 -15
handler.py
CHANGED
|
@@ -43,24 +43,31 @@ class EndpointHandler:
|
|
| 43 |
<text x="50%" y="50%" font-family="Arial" font-size="20" text-anchor="middle">{prompt}</text>
|
| 44 |
</svg>"""
|
| 45 |
|
| 46 |
-
# Convert SVG to base64
|
| 47 |
-
svg_bytes = svg_content.encode("utf-8")
|
| 48 |
-
svg_base64 = base64.b64encode(svg_bytes).decode("utf-8")
|
| 49 |
-
|
| 50 |
# Convert SVG to PNG using cairosvg
|
| 51 |
try:
|
| 52 |
-
png_data = cairosvg.svg2png(bytestring=
|
| 53 |
-
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
print(f"Error converting SVG to PNG: {e}")
|
| 56 |
-
#
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
# Return the
|
| 60 |
-
return
|
| 61 |
-
"svg": svg_content,
|
| 62 |
-
"svg_base64": svg_base64,
|
| 63 |
-
"png_base64": png_base64
|
| 64 |
-
}
|
| 65 |
except Exception as e:
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
<text x="50%" y="50%" font-family="Arial" font-size="20" text-anchor="middle">{prompt}</text>
|
| 44 |
</svg>"""
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
# Convert SVG to PNG using cairosvg
|
| 47 |
try:
|
| 48 |
+
png_data = cairosvg.svg2png(bytestring=svg_content.encode("utf-8"))
|
| 49 |
+
# Create a PIL Image from the PNG data
|
| 50 |
+
image = Image.open(io.BytesIO(png_data))
|
| 51 |
except Exception as e:
|
| 52 |
print(f"Error converting SVG to PNG: {e}")
|
| 53 |
+
# Create a simple placeholder image
|
| 54 |
+
image = Image.new("RGB", (width, height), color="#f0f0f0")
|
| 55 |
+
# Add text to the image
|
| 56 |
+
from PIL import ImageDraw, ImageFont
|
| 57 |
+
draw = ImageDraw.Draw(image)
|
| 58 |
+
try:
|
| 59 |
+
font = ImageFont.truetype("Arial", 20)
|
| 60 |
+
except:
|
| 61 |
+
font = ImageFont.load_default()
|
| 62 |
+
draw.text((width/2, height/2), prompt, fill="black", font=font, anchor="mm")
|
| 63 |
|
| 64 |
+
# Return the PIL Image directly
|
| 65 |
+
return image
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
except Exception as e:
|
| 67 |
+
print(f"Error in handler: {e}")
|
| 68 |
+
# Return a simple error image
|
| 69 |
+
image = Image.new("RGB", (512, 512), color="#ff0000")
|
| 70 |
+
from PIL import ImageDraw
|
| 71 |
+
draw = ImageDraw.Draw(image)
|
| 72 |
+
draw.text((256, 256), f"Error: {str(e)}", fill="white", anchor="mm")
|
| 73 |
+
return image
|