Update app.py
Browse files
app.py
CHANGED
@@ -1,44 +1,45 @@
|
|
1 |
-
import
|
2 |
-
import gradio as gr
|
3 |
from PIL import Image
|
4 |
-
import
|
5 |
-
from io import BytesIO
|
6 |
|
7 |
def show(svg_file):
|
8 |
-
# Check if svg_file is None (no file uploaded)
|
9 |
if svg_file is None:
|
10 |
return None, None
|
11 |
|
12 |
-
#
|
13 |
-
# svg_file is a tempfile._TemporaryFileWrapper or similar object
|
14 |
with open(svg_file.name, 'rb') as f:
|
15 |
svg_content = f.read()
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
#
|
22 |
-
|
23 |
-
return png_image, output_path
|
24 |
-
|
25 |
-
with gr.Blocks() as bl:
|
26 |
-
gr.Markdown("# SVG to PNG Converter")
|
27 |
|
28 |
-
with
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
36 |
|
37 |
-
#
|
38 |
-
|
39 |
-
|
40 |
-
inputs=svg_input,
|
41 |
-
outputs=[png_output, download_btn]
|
42 |
-
)
|
43 |
-
|
44 |
-
bl.launch()
|
|
|
1 |
+
import xml.etree.ElementTree as ET
|
|
|
2 |
from PIL import Image
|
3 |
+
import cairosvg
|
|
|
4 |
|
5 |
def show(svg_file):
|
|
|
6 |
if svg_file is None:
|
7 |
return None, None
|
8 |
|
9 |
+
# Read the SVG content
|
|
|
10 |
with open(svg_file.name, 'rb') as f:
|
11 |
svg_content = f.read()
|
12 |
|
13 |
+
# Parse SVG to extract width and height
|
14 |
+
try:
|
15 |
+
root = ET.fromstring(svg_content)
|
16 |
+
width = root.get('width')
|
17 |
+
height = root.get('height')
|
18 |
+
if width and height:
|
19 |
+
# Remove 'px' units and convert to float
|
20 |
+
width = float(width.replace('px', ''))
|
21 |
+
height = float(height.replace('px', ''))
|
22 |
+
else:
|
23 |
+
width = height = None
|
24 |
+
except ET.ParseError:
|
25 |
+
# Handle invalid SVG
|
26 |
+
width = height = None
|
27 |
|
28 |
+
# Define output path
|
29 |
+
output_path = "./test.png"
|
|
|
|
|
|
|
|
|
30 |
|
31 |
+
# Convert SVG to PNG with explicit size if available
|
32 |
+
if width and height:
|
33 |
+
cairosvg.svg2png(
|
34 |
+
bytestring=svg_content,
|
35 |
+
write_to=output_path,
|
36 |
+
output_width=width,
|
37 |
+
output_height=height
|
38 |
+
)
|
39 |
+
else:
|
40 |
+
# Fallback to default rendering if no size is specified
|
41 |
+
cairosvg.svg2png(bytestring=svg_content, write_to=output_path)
|
42 |
|
43 |
+
# Load the PNG as a PIL image
|
44 |
+
png_image = Image.open(output_path)
|
45 |
+
return png_image, output_path
|
|
|
|
|
|
|
|
|
|