ak / app.py
AkashKumarave's picture
Update app.py
cff54b7 verified
raw
history blame
3.23 kB
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from PIL import Image
import vtracer
import io
import os
import logging
app = Flask(__name__)
CORS(app, resources={r"/convert-to-vector": {"origins": "*"}})
# Configure logging
logging.basicConfig(level=logging.DEBUG)
def convert_to_vector(image):
input_path = "temp_input.jpg"
output_svg_path = "temp_output.svg"
try:
# Save the input image to a temporary file
app.logger.debug("Saving input image to %s", input_path)
image.save(input_path)
# Convert the image to SVG using VTracer
app.logger.debug("Converting image to SVG")
vtracer.convert_image_to_svg_py(
input_path,
output_svg_path,
colormode="color",
hierarchical="stacked",
mode="spline",
filter_speckle=4,
color_precision=6,
layer_difference=16,
corner_threshold=60,
length_threshold=4.0,
max_iterations=10,
splice_threshold=45,
path_precision=3
)
# Read the SVG output
app.logger.debug("Reading SVG from %s", output_svg_path)
with open(output_svg_path, "r") as f:
svg_content = f.read()
# Validate SVG content
if not svg_content.startswith('<?xml') or '<svg' not in svg_content:
app.logger.error("Invalid SVG content: %s", svg_content[:100])
raise ValueError("Generated SVG is invalid")
return svg_content
finally:
# Clean up temporary files
app.logger.debug("Cleaning up temporary files")
if os.path.exists(input_path):
os.remove(input_path)
if os.path.exists(output_svg_path):
os.remove(output_svg_path)
@app.route('/convert-to-vector', methods=['POST'])
def convert_to_vector_endpoint():
try:
# Handle raw image data in the request body
if request.data:
app.logger.debug("Received raw image data")
image = Image.open(io.BytesIO(request.data)).convert('RGB')
# Fallback for multipart/form-data
elif 'image' in request.files:
app.logger.debug("Received multipart image data")
file = request.files['image']
image = Image.open(file).convert('RGB')
else:
app.logger.error("No image data provided")
return jsonify({'error': 'No image data provided'}), 400
# Process the image
app.logger.debug("Processing image")
svg_content = convert_to_vector(image)
# Return the SVG as a response
app.logger.debug("Sending SVG response")
return send_file(
io.BytesIO(svg_content.encode('utf-8')),
mimetype='image/svg+xml',
as_attachment=True,
download_name='vector_output.svg'
)
except Exception as e:
app.logger.error("Error processing request: %s", str(e))
return jsonify({'error': str(e)}), 500
@app.route('/')
def index():
return jsonify({'status': 'Image to Vector Converter API is running'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)