2023-09-08 13:24:34 +00:00
|
|
|
from flask import Flask, request, send_from_directory, jsonify
|
2023-09-08 15:22:57 +00:00
|
|
|
from werkzeug.utils import secure_filename
|
2023-09-08 13:24:34 +00:00
|
|
|
import os
|
2023-09-08 15:22:57 +00:00
|
|
|
import tempfile
|
|
|
|
import shutil
|
2023-09-08 13:24:34 +00:00
|
|
|
|
|
|
|
from pipeline import pipeline
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
2023-09-08 15:22:57 +00:00
|
|
|
IMAGE_KEY = 'image'
|
|
|
|
OUTPUT_FILE = 'cards.apkg'
|
|
|
|
TEMP_DIR = tempfile.mkdtemp()
|
|
|
|
|
|
|
|
def save_uploaded_images(images, directory):
|
|
|
|
for img in images:
|
|
|
|
# Sanitize the filename
|
|
|
|
safe_filename = secure_filename(img.filename)
|
|
|
|
if not safe_filename:
|
|
|
|
# Handle the case where the filename becomes empty after sanitization
|
|
|
|
raise ValueError("Invalid filename")
|
|
|
|
filename = os.path.join(directory, safe_filename)
|
|
|
|
img.save(filename)
|
|
|
|
|
|
|
|
@app.route('/deck-from-images', methods=['POST'])
|
|
|
|
def deck_from_images():
|
|
|
|
if IMAGE_KEY not in request.files:
|
2023-09-08 13:24:34 +00:00
|
|
|
return jsonify({'error': 'No image part'}), 400
|
|
|
|
|
2023-09-08 15:22:57 +00:00
|
|
|
images = request.files.getlist(IMAGE_KEY)
|
2023-09-08 13:24:34 +00:00
|
|
|
|
2023-09-08 15:22:57 +00:00
|
|
|
if not images or not any(img.filename != '' for img in images):
|
2023-09-08 13:24:34 +00:00
|
|
|
return jsonify({'error': 'No selected file'}), 400
|
|
|
|
|
2023-09-08 15:22:57 +00:00
|
|
|
save_uploaded_images(images, TEMP_DIR)
|
2023-09-08 13:24:34 +00:00
|
|
|
|
|
|
|
try:
|
2023-09-08 15:22:57 +00:00
|
|
|
pipeline(TEMP_DIR)
|
|
|
|
return send_from_directory('.', OUTPUT_FILE, as_attachment=True)
|
|
|
|
except Exception as e: # Consider catching more specific exceptions
|
2023-09-08 13:24:34 +00:00
|
|
|
return jsonify({'error': str(e)}), 500
|
|
|
|
finally:
|
2023-09-08 15:22:57 +00:00
|
|
|
shutil.rmtree(TEMP_DIR)
|
2023-09-08 13:24:34 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
app.run(debug=True)
|