Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| from PIL import Image | |
| import vtracer | |
| import io | |
| import os | |
| app = Flask(__name__) | |
| CORS(app, resources={r"/convert-to-vector": {"origins": "*"}}) | |
| def convert_to_vector(image): | |
| input_path = "temp_input.png" | |
| output_path = "svg_output.svg" | |
| # Save input image | |
| image.save(input_path) | |
| # Convert to SVG using VTracer | |
| vtracer.convert_image_to_svg_py( | |
| input_path, | |
| output_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 SVG content | |
| with open(output_path, "r") as f: | |
| svg_content = f.read() | |
| # Clean up | |
| os.remove(input_path) | |
| os.remove(output_path) | |
| return svg_content | |
| def convert_to_vector_endpoint(): | |
| try: | |
| if not request.data: | |
| return jsonify({'error': 'No image data provided'}), 400 | |
| # Open image | |
| image = Image.open(io.BytesIO(request.data)).convert('RGB') | |
| # Convert to SVG | |
| svg_content = convert_to_vector(image) | |
| return svg_content, 200, {'Content-Type': 'text/plain'} | |
| except Exception as e: | |
| return jsonify({'error': str(e)}), 500 | |
| def index(): | |
| return jsonify({'status': 'Image to Vector API is running'}) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) |