ak / app.py
AkashKumarave's picture
Update app.py
c956e8d verified
raw
history blame
2.17 kB
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from PIL import Image
import io
import vtracer
import os
app = Flask(__name__)
CORS(app, resources={r"/vectorize": {"origins": "*"}})
def convert_to_vector(
image,
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
):
input_path = "temp_input.jpg"
output_path = "temp_output.svg"
image.save(input_path)
vtracer.convert_image_to_svg_py(
input_path,
output_path,
colormode=colormode,
hierarchical=hierarchical,
mode=mode,
filter_speckle=int(filter_speckle),
color_precision=int(color_precision),
layer_difference=int(layer_difference),
corner_threshold=int(corner_threshold),
length_threshold=float(length_threshold),
max_iterations=int(max_iterations),
splice_threshold=int(splice_threshold),
path_precision=int(path_precision)
)
with open(output_path, "rb") as f:
svg_content = f.read()
os.remove(input_path)
os.remove(output_path)
return svg_content
@app.route('/vectorize', methods=['POST'])
def vectorize_endpoint():
try:
if request.data:
image = Image.open(io.BytesIO(request.data)).convert('RGB')
elif 'image' in request.files:
file = request.files['image']
image = Image.open(file).convert('RGB')
else:
return jsonify({'error': 'No image data provided'}), 400
svg_content = convert_to_vector(image)
return send_file(
io.BytesIO(svg_content),
mimetype='image/svg+xml',
as_attachment=True,
download_name='vectorized.svg'
)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/')
def index():
return jsonify({'status': 'Image Vectorization API is running'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)