Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from pixels2svg import pixels2svg
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def vectorize_png_to_svg(input_path: str) -> str:
|
| 8 |
+
"""
|
| 9 |
+
Take a PNG filepath, vectorize it, and return SVG text.
|
| 10 |
+
"""
|
| 11 |
+
# Ensure image is PNG and load to normalize
|
| 12 |
+
with Image.open(input_path) as im:
|
| 13 |
+
im = im.convert("RGBA") # normalize
|
| 14 |
+
tmp_png = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 15 |
+
im.save(tmp_png.name, "PNG")
|
| 16 |
+
|
| 17 |
+
drawing = pixels2svg(tmp_png.name)
|
| 18 |
+
svg_text = drawing.tostring() # svg_text is already a str
|
| 19 |
+
return svg_text # <- just return the string
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
import pathlib
|
| 24 |
+
import tempfile
|
| 25 |
+
|
| 26 |
+
def gradio_vectorize(image_path):
|
| 27 |
+
if image_path is None:
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
svg_text = vectorize_png_to_svg(image_path)
|
| 31 |
+
|
| 32 |
+
tmp_svg = tempfile.NamedTemporaryFile(delete=False, suffix=".svg")
|
| 33 |
+
with open(tmp_svg.name, "w", encoding="utf-8") as f:
|
| 34 |
+
f.write(svg_text)
|
| 35 |
+
|
| 36 |
+
return tmp_svg.name
|
| 37 |
+
|
| 38 |
+
with gr.Blocks() as demo:
|
| 39 |
+
gr.Markdown("⥏⥑ 𓍴 -Vectorizer- 𓍴 ⥏⥑")
|
| 40 |
+
gr.Markdown("PNG📷 ➲ SVG💾.")
|
| 41 |
+
|
| 42 |
+
with gr.Row():
|
| 43 |
+
in_img = gr.Image(type="filepath", label="📷PNG input📷")
|
| 44 |
+
out_file = gr.File(label="💾SVG output💾")
|
| 45 |
+
|
| 46 |
+
run_btn = gr.Button("♻️ Vectorize ♻️")
|
| 47 |
+
run_btn.click(fn=gradio_vectorize, inputs=in_img, outputs=out_file)
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
demo.launch(debug=True)
|