AkashKumarave commited on
Commit
b3f1777
·
verified ·
1 Parent(s): 90494c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -52
app.py CHANGED
@@ -1,28 +1,18 @@
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()
17
-
18
- # Configure CORS to allow requests from Figma plugin
19
- app.add_middleware(
20
- CORSMiddleware,
21
- allow_origins=["https://www.figma.com", "*"], # Allow Figma and local testing
22
- allow_credentials=True,
23
- allow_methods=["*"],
24
- allow_headers=["*"],
25
- )
26
 
27
  # VTracer conversion function
28
  def convert_to_vector(
@@ -72,7 +62,7 @@ def convert_to_vector(
72
  return svg_content
73
  except Exception as e:
74
  logger.error(f"Error in convert_to_vector: {str(e)}")
75
- raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
76
  finally:
77
  # Clean up temporary files
78
  for path in [input_path, output_path]:
@@ -83,27 +73,30 @@ def convert_to_vector(
83
  except Exception as e:
84
  logger.warning(f"Failed to remove {path}: {str(e)}")
85
 
86
- # FastAPI endpoint for vector conversion
87
- @app.post("/convert")
88
- async def convert_image(
89
- file: UploadFile = File(...),
90
- colormode: str = Form("color"),
91
- hierarchical: str = Form("stacked"),
92
- mode: str = Form("spline"),
93
- filter_speckle: int = Form(4),
94
- color_precision: int = Form(6),
95
- layer_difference: int = Form(16),
96
- corner_threshold: int = Form(60),
97
- length_threshold: float = Form(4.0),
98
- max_iterations: int = Form(10),
99
- splice_threshold: int = Form(45),
100
- path_precision: int = Form(3)
101
- ):
102
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  logger.info("Received request to /convert")
104
- # Read the uploaded image
105
- image_data = await file.read()
106
- image = Image.open(io.BytesIO(image_data))
107
 
108
  # Convert to SVG
109
  svg_content = convert_to_vector(
@@ -116,27 +109,27 @@ async def convert_image(
116
  layer_difference=layer_difference,
117
  corner_threshold=corner_threshold,
118
  length_threshold=length_threshold,
119
- max_iterations=max_iterations, # Fixed syntax error
120
  splice_threshold=splice_threshold,
121
  path_precision=path_precision
122
  )
123
 
124
- return JSONResponse(content={"svg": svg_content})
 
125
  except Exception as e:
126
  logger.error(f"Error in convert_image: {str(e)}")
127
- return JSONResponse(content={"error": str(e)}, status_code=500)
128
 
129
  # Health check endpoint
130
- @app.get("/")
131
- async def health_check():
132
  logger.info("Health check requested")
133
- return {"status": "healthy"}
134
 
135
- # Gradio interface
136
  def handle_color_mode(value):
137
  return value
138
 
139
- # Check if examples directory exists, else use empty list
140
  examples_dir = "examples"
141
  examples = [
142
  os.path.join(examples_dir, f) for f in ["11.jpg", "02.jpg", "03.jpg"]
@@ -159,7 +152,6 @@ css = """
159
  }
160
  """
161
 
162
- # Define the Gradio interface
163
  with gr.Blocks(css=css) as gradio_app:
164
  with gr.Column(elem_id="col-container"):
165
  gr.HTML("""
@@ -208,11 +200,6 @@ with gr.Blocks(css=css) as gradio_app:
208
  hierarchical.change(handle_color_mode, inputs=hierarchical, outputs=output_text)
209
  mode.change(handle_color_mode, inputs=mode, outputs=output_text)
210
 
211
- default_values = {
212
- "color_precision": 6,
213
- "layer_difference": 16
214
- }
215
-
216
  def clear_inputs():
217
  return (
218
  gr.Image(value=None), gr.Radio(value="color"), gr.Radio(value="stacked"),
@@ -268,10 +255,14 @@ with gr.Blocks(css=css) as gradio_app:
268
  outputs=[html, svg_output]
269
  )
270
 
271
- # Mount Gradio app to FastAPI at /gradio
272
  try:
273
  from gradio import mount_gradio_app
 
274
  app = mount_gradio_app(app, gradio_app, path="/gradio")
275
  logger.info("Gradio app mounted successfully at /gradio")
276
  except Exception as e:
277
- logger.error(f"Failed to mount Gradio app: {str(e)}")
 
 
 
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ from flask_cors import CORS
3
  import vtracer
 
 
 
 
4
  from PIL import Image
5
  import io
6
+ import os
7
  import logging
8
+ import gradio as gr
9
 
10
  # Set up logging
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
+ app = Flask(__name__)
15
+ CORS(app, resources={r"/convert": {"origins": ["https://www.figma.com", "*"]}})
 
 
 
 
 
 
 
 
 
16
 
17
  # VTracer conversion function
18
  def convert_to_vector(
 
62
  return svg_content
63
  except Exception as e:
64
  logger.error(f"Error in convert_to_vector: {str(e)}")
65
+ raise Exception(f"Conversion failed: {str(e)}")
66
  finally:
67
  # Clean up temporary files
68
  for path in [input_path, output_path]:
 
73
  except Exception as e:
74
  logger.warning(f"Failed to remove {path}: {str(e)}")
75
 
76
+ # Flask endpoint for vector conversion
77
+ @app.route('/convert', methods=['POST'])
78
+ def convert_image():
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  try:
80
+ # Handle image upload
81
+ if 'file' not in request.files:
82
+ return jsonify({'error': 'No image file provided'}), 400
83
+ file = request.files['file']
84
+ image = Image.open(file).convert('RGB')
85
+
86
+ # Get parameters (with defaults)
87
+ colormode = request.form.get('colormode', 'color')
88
+ hierarchical = request.form.get('hierarchical', 'stacked')
89
+ mode = request.form.get('mode', 'spline')
90
+ filter_speckle = int(request.form.get('filter_speckle', 4))
91
+ color_precision = int(request.form.get('color_precision', 6))
92
+ layer_difference = int(request.form.get('layer_difference', 16))
93
+ corner_threshold = int(request.form.get('corner_threshold', 60))
94
+ length_threshold = float(request.form.get('length_threshold', 4.0))
95
+ max_iterations = int(request.form.get('max_iterations', 10))
96
+ splice_threshold = int(request.form.get('splice_threshold', 45))
97
+ path_precision = int(request.form.get('path_precision', 3))
98
+
99
  logger.info("Received request to /convert")
 
 
 
100
 
101
  # Convert to SVG
102
  svg_content = convert_to_vector(
 
109
  layer_difference=layer_difference,
110
  corner_threshold=corner_threshold,
111
  length_threshold=length_threshold,
112
+ max_iterations=max_iterations,
113
  splice_threshold=splice_threshold,
114
  path_precision=path_precision
115
  )
116
 
117
+ # Return SVG as JSON
118
+ return jsonify({'svg': svg_content})
119
  except Exception as e:
120
  logger.error(f"Error in convert_image: {str(e)}")
121
+ return jsonify({'error': str(e)}), 500
122
 
123
  # Health check endpoint
124
+ @app.route('/')
125
+ def health_check():
126
  logger.info("Health check requested")
127
+ return jsonify({'status': 'Image to Vector Converter API is running'})
128
 
129
+ # Optional Gradio interface (comment out if not needed)
130
  def handle_color_mode(value):
131
  return value
132
 
 
133
  examples_dir = "examples"
134
  examples = [
135
  os.path.join(examples_dir, f) for f in ["11.jpg", "02.jpg", "03.jpg"]
 
152
  }
153
  """
154
 
 
155
  with gr.Blocks(css=css) as gradio_app:
156
  with gr.Column(elem_id="col-container"):
157
  gr.HTML("""
 
200
  hierarchical.change(handle_color_mode, inputs=hierarchical, outputs=output_text)
201
  mode.change(handle_color_mode, inputs=mode, outputs=output_text)
202
 
 
 
 
 
 
203
  def clear_inputs():
204
  return (
205
  gr.Image(value=None), gr.Radio(value="color"), gr.Radio(value="stacked"),
 
255
  outputs=[html, svg_output]
256
  )
257
 
258
+ # Mount Gradio app at /gradio (optional)
259
  try:
260
  from gradio import mount_gradio_app
261
+ from flask import Flask
262
  app = mount_gradio_app(app, gradio_app, path="/gradio")
263
  logger.info("Gradio app mounted successfully at /gradio")
264
  except Exception as e:
265
+ logger.error(f"Failed to mount Gradio app: {str(e)}")
266
+
267
+ if __name__ == '__main__':
268
+ app.run(host='0.0.0.0', port=7860)