File size: 4,416 Bytes
b3f1777
 
a8a350d
 
 
b3f1777
4c9a049
 
 
 
 
a8a350d
b3f1777
 
a8a350d
68e3db1
a8a350d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a049
 
 
68e3db1
a8a350d
4c9a049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68e3db1
a8a350d
4c9a049
 
 
a8a350d
4c9a049
68e3db1
 
b3f1777
4c9a049
 
 
 
 
 
68e3db1
4c9a049
 
a8a350d
b3f1777
 
 
a8a350d
b3f1777
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68e3db1
a8a350d
 
 
 
90494c1
 
 
 
 
 
 
 
b3f1777
68e3db1
 
a8a350d
 
b3f1777
 
a8a350d
4c9a049
b3f1777
a8a350d
68e3db1
b3f1777
 
68e3db1
b3f1777
68e3db1
b3f1777
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import vtracer
from PIL import Image
import io
import os
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app, resources={r"/convert": {"origins": ["https://www.figma.com", "*"]}})

# VTracer conversion function
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 = "svg_output.svg"

    try:
        # Save the input image to a temporary file
        image.save(input_path)
        logger.info(f"Saved image to {input_path}")

        # Convert the image to SVG using VTracer
        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)
        )
        logger.info(f"Converted image to SVG at {output_path}")

        # Read the SVG output
        with open(output_path, "r") as f:
            svg_content = f.read()

        return svg_content
    except Exception as e:
        logger.error(f"Error in convert_to_vector: {str(e)}")
        raise Exception(f"Conversion failed: {str(e)}")
    finally:
        # Clean up temporary files
        for path in [input_path, output_path]:
            if os.path.exists(path):
                try:
                    os.remove(path)
                    logger.info(f"Removed {path}")
                except Exception as e:
                    logger.warning(f"Failed to remove {path}: {str(e)}")

# Flask endpoint for vector conversion
@app.route('/convert', methods=['POST'])
def convert_image():
    try:
        # Handle image upload
        if 'file' not in request.files:
            return jsonify({'error': 'No image file provided'}), 400
        file = request.files['file']
        image = Image.open(file).convert('RGB')

        # Get parameters (with defaults)
        colormode = request.form.get('colormode', 'color')
        hierarchical = request.form.get('hierarchical', 'stacked')
        mode = request.form.get('mode', 'spline')
        filter_speckle = int(request.form.get('filter_speckle', 4))
        color_precision = int(request.form.get('color_precision', 6))
        layer_difference = int(request.form.get('layer_difference', 16))
        corner_threshold = int(request.form.get('corner_threshold', 60))
        length_threshold = float(request.form.get('length_threshold', 4.0))
        max_iterations = int(request.form.get('max_iterations', 10))
        splice_threshold = int(request.form.get('splice_threshold', 45))
        path_precision = int(request.form.get('path_precision', 3))

        logger.info("Received request to /convert")

        # Convert to SVG
        svg_content = convert_to_vector(
            image,
            colormode=colormode,
            hierarchical=hierarchical,
            mode=mode,
            filter_speckle=filter_speckle,
            color_precision=color_precision,
            layer_difference=layer_difference,
            corner_threshold=corner_threshold,
            length_threshold=length_threshold,
            max_iterations=max_iterations,
            splice_threshold=splice_threshold,
            path_precision=path_precision
        )

        # Return SVG as JSON
        return jsonify({'svg': svg_content})
    except Exception as e:
        logger.error(f"Error in convert_image: {str(e)}")
        return jsonify({'error': str(e)}), 500

# Health check endpoint
@app.route('/')
def health_check():
    logger.info("Health check requested")
    return jsonify({'status': 'Image to Vector Converter API is running'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)