AkashKumarave commited on
Commit
4c9a049
·
verified ·
1 Parent(s): d7cc918

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -35
app.py CHANGED
@@ -1,11 +1,16 @@
1
  import gradio as gr
2
  import vtracer
3
  import os
4
- from fastapi import FastAPI, File, UploadFile, Form
5
  from fastapi.responses import JSONResponse
6
  from fastapi.middleware.cors import CORSMiddleware
7
  from PIL import Image
8
  import io
 
 
 
 
 
9
 
10
  # Initialize FastAPI app
11
  app = FastAPI()
@@ -13,7 +18,7 @@ app = FastAPI()
13
  # Configure CORS to allow requests from Figma plugin
14
  app.add_middleware(
15
  CORSMiddleware,
16
- allow_origins=["https://www.figma.com"], # Restrict to Figma's domain
17
  allow_credentials=True,
18
  allow_methods=["*"],
19
  allow_headers=["*"],
@@ -37,35 +42,43 @@ def convert_to_vector(
37
  input_path = "temp_input.jpg"
38
  output_path = "svg_output.svg"
39
 
40
- # Save the input image to a temporary file
41
- image.save(input_path)
42
-
43
- # Convert the image to SVG using VTracer
44
- vtracer.convert_image_to_svg_py(
45
- input_path,
46
- output_path,
47
- colormode=colormode,
48
- hierarchical=hierarchical,
49
- mode=mode,
50
- filter_speckle=int(filter_speckle),
51
- color_precision=int(color_precision),
52
- layer_difference=int(layer_difference),
53
- corner_threshold=int(corner_threshold),
54
- length_threshold=float(length_threshold),
55
- max_iterations=int(max_iterations),
56
- splice_threshold=int(splice_threshold),
57
- path_precision=int(path_precision)
58
- )
59
 
60
- # Read the SVG output
61
- with open(output_path, "r") as f:
62
- svg_content = f.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Clean up temporary files
65
- os.remove(input_path)
66
- os.remove(output_path)
67
 
68
- return svg_content
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  # FastAPI endpoint for vector conversion
71
  @app.post("/convert")
@@ -106,14 +119,147 @@ async def convert_image(
106
 
107
  return JSONResponse(content={"svg": svg_content})
108
  except Exception as e:
 
109
  return JSONResponse(content={"error": str(e)}, status_code=500)
110
 
111
- # Existing Gradio interface (unchanged)
112
- with gr.Blocks(css=...) as gradio_app:
113
- # Your existing Gradio code here (omitted for brevity)
114
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
- # Mount Gradio app to FastAPI
117
- app.mount("/", gradio_app)
 
118
 
119
- # Note: app.launch() is not needed for Hugging Face Spaces; it will be handled by the platform
 
 
 
 
1
  import gradio as gr
2
  import vtracer
3
  import os
4
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException
5
  from fastapi.responses import JSONResponse
6
  from fastapi.middleware.cors import CORSMiddleware
7
  from PIL import Image
8
  import io
9
+ import logging
10
+
11
+ # Set up logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
 
15
  # Initialize FastAPI app
16
  app = FastAPI()
 
18
  # Configure CORS to allow requests from Figma plugin
19
  app.add_middleware(
20
  CORSMiddleware,
21
+ allow_origins=["https://www.figma.com"],
22
  allow_credentials=True,
23
  allow_methods=["*"],
24
  allow_headers=["*"],
 
42
  input_path = "temp_input.jpg"
43
  output_path = "svg_output.svg"
44
 
45
+ try:
46
+ # Save the input image to a temporary file
47
+ image.save(input_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Convert the image to SVG using VTracer
50
+ vtracer.convert_image_to_svg_py(
51
+ input_path,
52
+ output_path,
53
+ colormode=colormode,
54
+ hierarchical=hierarchical,
55
+ mode=mode,
56
+ filter_speckle=int(filter_speckle),
57
+ color_precision=int(color_precision),
58
+ layer_difference=int(layer_difference),
59
+ corner_threshold=int(corner_threshold),
60
+ length_threshold=float(length_threshold),
61
+ max_iterations=int(max_iterations),
62
+ splice_threshold=int(splice_threshold),
63
+ path_precision=int(path_precision)
64
+ )
65
 
66
+ # Read the SVG output
67
+ with open(output_path, "r") as f:
68
+ svg_content = f.read()
69
 
70
+ return svg_content
71
+ # except Exception as e:
72
+ # logger.error(f"Error in convert_to_vector: {str(e)}")
73
+ # raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
74
+ finally:
75
+ # Clean up temporary files
76
+ for path in [input_path, output_path]:
77
+ if os.path.exists(path):
78
+ try:
79
+ os.remove(path)
80
+ except Exception as e:
81
+ logger.warning(f"Failed to remove {path}: {str(e)}")
82
 
83
  # FastAPI endpoint for vector conversion
84
  @app.post("/convert")
 
119
 
120
  return JSONResponse(content={"svg": svg_content})
121
  except Exception as e:
122
+ logger.error(f"Error in convert_image: {str(e)}")
123
  return JSONResponse(content={"error": str(e)}, status_code=500)
124
 
125
+ # Gradio interface
126
+ def handle_color_mode(value):
127
+ return value
128
+
129
+ examples = [
130
+ "examples/11.jpg",
131
+ "examples/02.jpg",
132
+ "examples/03.jpg",
133
+ ]
134
+
135
+ css = """
136
+ #col-container {
137
+ margin: 0 auto;
138
+ max-width: 960px;
139
+ }
140
+ .generate-btn {
141
+ background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%) !important;
142
+ border: none !important;
143
+ color: white !important;
144
+ }
145
+ .generate-btn:hover {
146
+ transform: translateY(-2px);
147
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2);
148
+ }
149
+ """
150
+
151
+ # Define the Gradio interface
152
+ with gr.Blocks(css=css) as gradio_app:
153
+ with gr.Column(elem_id="col-container"):
154
+ gr.HTML("""
155
+ <div style="text-align: center;">
156
+ <h2>Image to Vector Converter ⚡</h2>
157
+ <p>Converts raster images (JPG, PNG, WEBP) to vector graphics (SVG).</p>
158
+ </div>
159
+ """)
160
+ with gr.Row():
161
+ with gr.Column():
162
+ image_input = gr.Image(type="pil", label="Upload Image")
163
+ with gr.Accordion("Advanced Settings", open=False):
164
+ with gr.Accordion("Clustering", open=False):
165
+ colormode = gr.Radio([("COLOR","color"),("B/W", "binary")], value="color", label="Color Mode", show_label=False)
166
+ filter_speckle = gr.Slider(0, 128, value=4, step=1, label="Filter Speckle", info="Cleaner")
167
+ color_precision = gr.Slider(1, 8, value=6, step=1, label="Color Precision", info="More accurate")
168
+ layer_difference = gr.Slider(0, 128, value=16, step=1, label="Gradient Step", info="Less layers")
169
+ hierarchical = gr.Radio([("STACKED","stacked"), ("CUTOUT","cutout")], value="stacked", label="Hierarchical Mode",show_label=False)
170
+ with gr.Accordion("Curve Fitting", open=False):
171
+ mode = gr.Radio([("SPLINE","spline"),("POLYGON", "polygon"), ("PIXEL","none")], value="spline", label="Mode", show_label=False)
172
+ corner_threshold = gr.Slider(0, 180, value=60, step=1, label="Corner Threshold", info="Smoother")
173
+ length_threshold = gr.Slider(3.5, 10, value=4.0, step=0.1, label="Segment Length", info ="More coarse")
174
+ splice_threshold = gr.Slider(0, 180, value=45, step=1, label="Splice Threshold", info="Less accurate")
175
+ max_iterations = gr.Slider(1, 20, value=10, step=1, label="Max Iterations", visible=False)
176
+ path_precision = gr.Slider(1, 10, value=3, step=1, label="Path Precision", visible=False)
177
+ output_text = gr.Textbox(label="Selected Mode", visible=False)
178
+ with gr.Row():
179
+ clear_button = gr.Button("Clear")
180
+ convert_button = gr.Button("✨ Convert to SVG", variant='primary', elem_classes=["generate-btn"])
181
+
182
+ with gr.Column():
183
+ html = gr.HTML(label="SVG Output")
184
+ svg_output = gr.File(label="Download SVG")
185
+
186
+ gr.Examples(
187
+ examples=examples,
188
+ fn=convert_to_vector,
189
+ inputs=[image_input],
190
+ outputs=[html, svg_output],
191
+ cache_examples=False,
192
+ run_on_click=True
193
+ )
194
+
195
+ colormode.change(handle_color_mode, inputs=colormode, outputs=output_text)
196
+ hierarchical.change(handle_color_mode, inputs=hierarchical, outputs=output_text)
197
+ mode.change(handle_color_mode, inputs=mode, outputs=output_text)
198
+ default_values = {
199
+ "color_precision": 6,
200
+ "layer_difference": 16
201
+ }
202
+
203
+ def clear_inputs():
204
+ return (
205
+ gr.Image(value=None), gr.Radio(value="color"), gr.Radio(value="stacked"),
206
+ gr.Radio(value="spline"), gr.Slider(value=4), gr.Slider(value=6),
207
+ gr.Slider(value=16), gr.Slider(value=60), gr.Slider(value=4.0),
208
+ gr.Slider(value=10), gr.Slider(value=45), gr.Slider(value=3)
209
+ )
210
+
211
+ def update_interactivity_and_visibility(colormode, color_precision_value, layer_difference_value):
212
+ is_color_mode = colormode == "color"
213
+ return (
214
+ gr.update(interactive=is_color_mode),
215
+ gr.update(interactive=is_color_mode),
216
+ gr.update(visible=is_color_mode)
217
+ )
218
+
219
+ colormode.change(
220
+ update_interactivity_and_visibility,
221
+ inputs=[colormode, color_precision, layer_difference],
222
+ outputs=[color_precision, layer_difference, hierarchical]
223
+ )
224
+
225
+ def update_interactivity_and_visibility_for_mode(mode):
226
+ is_spline_mode = mode == "spline"
227
+ return (
228
+ gr.update(interactive=is_spline_mode),
229
+ gr.update(interactive=is_spline_mode),
230
+ gr.update(interactive=is_spline_mode)
231
+ )
232
+
233
+ mode.change(
234
+ update_interactivity_and_visibility_for_mode,
235
+ inputs=[mode],
236
+ outputs=[corner_threshold, length_threshold, splice_threshold]
237
+ )
238
+
239
+ clear_button.click(
240
+ clear_inputs,
241
+ outputs=[
242
+ image_input, colormode, hierarchical, mode, filter_speckle,
243
+ color_precision, layer_difference, corner_threshold, length_threshold,
244
+ max_iterations, splice_threshold, path_precision
245
+ ]
246
+ )
247
+
248
+ convert_button.click(
249
+ convert_to_vector,
250
+ inputs=[
251
+ image_input, colormode, hierarchical, mode, filter_speckle,
252
+ color_precision, layer_difference, corner_threshold, length_threshold,
253
+ max_iterations, splice_threshold, path_precision
254
+ ],
255
+ outputs=[html, svg_output]
256
+ )
257
 
258
+ # Mount Gradio app to FastAPI at a subpath
259
+ from gradio import mount_gradio_app
260
+ app = mount_gradio_app(app, gradio_app, path="/gradio")
261
 
262
+ # Health check endpoint
263
+ @app.get("/")
264
+ async def health_check():
265
+ return {"status": "healthy"}