anki-csv2ankicards/server.py

47 lines
1.4 KiB
Python

from flask import Flask, request, send_from_directory, jsonify
from werkzeug.utils import secure_filename
import os
import tempfile
import shutil
from pipeline import pipeline
app = Flask(__name__)
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:
return jsonify({'error': 'No image part'}), 400
images = request.files.getlist(IMAGE_KEY)
if not images or not any(img.filename != '' for img in images):
return jsonify({'error': 'No selected file'}), 400
save_uploaded_images(images, TEMP_DIR)
try:
pipeline(TEMP_DIR)
return send_from_directory('.', OUTPUT_FILE, as_attachment=True)
except Exception as e: # Consider catching more specific exceptions
return jsonify({'error': str(e)}), 500
finally:
shutil.rmtree(TEMP_DIR)
if __name__ == '__main__':
app.run(debug=True)