pabbelt commited on
Commit
16fa907
·
verified ·
1 Parent(s): 4715690

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -0
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ from transformers import AutoModelForCausalLM
4
+ from starvector.data.util import process_and_rasterize_svg
5
+ import torch
6
+
7
+ print("Loading model...")
8
+ model_name = "starvector/starvector-8b-im2svg"
9
+ starvector = AutoModelForCausalLM.from_pretrained(
10
+ model_name,
11
+ torch_dtype=torch.float16,
12
+ trust_remote_code=True
13
+ )
14
+ processor = starvector.model.processor
15
+ tokenizer = starvector.model.svg_transformer.tokenizer
16
+
17
+ # Move to GPU
18
+ device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ starvector.to(device)
20
+ starvector.eval()
21
+ print(f"Model loaded on {device}!")
22
+
23
+ def convert_image_to_svg(image_pil):
24
+ """Convert uploaded image to SVG"""
25
+ try:
26
+ # Process image
27
+ image = processor(image_pil, return_tensors="pt")['pixel_values'].to(device)
28
+ if image.shape[0] != 1:
29
+ image = image.unsqueeze(0)
30
+
31
+ batch = {"image": image}
32
+
33
+ # Generate SVG
34
+ raw_svg = starvector.generate_im2svg(batch, max_length=4000)[0]
35
+ svg, raster_image = process_and_rasterize_svg(raw_svg)
36
+
37
+ # Save SVG to file
38
+ svg_path = "output.svg"
39
+ with open(svg_path, 'w') as f:
40
+ f.write(svg)
41
+
42
+ return svg_path, raster_image
43
+
44
+ except Exception as e:
45
+ return None, f"Error: {str(e)}"
46
+
47
+ # Create Gradio interface
48
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
49
+ gr.Markdown("# 🎨 Image to SVG Converter")
50
+ gr.Markdown("Convert your images to SVG format using StarVector AI")
51
+
52
+ with gr.Row():
53
+ with gr.Column():
54
+ input_image = gr.Image(type="pil", label="Upload Image")
55
+ convert_btn = gr.Button("Convert to SVG", variant="primary")
56
+
57
+ with gr.Column():
58
+ output_file = gr.File(label="Download SVG")
59
+ output_preview = gr.Image(label="Preview")
60
+
61
+ convert_btn.click(
62
+ fn=convert_image_to_svg,
63
+ inputs=input_image,
64
+ outputs=[output_file, output_preview]
65
+ )
66
+
67
+ gr.Markdown("### Example: Upload a PNG/JPG image and get an SVG file!")
68
+
69
+ demo.launch()