anki-csv2ankicards/server.py

55 lines
1.5 KiB
Python
Raw Normal View History

import os
2023-09-11 17:02:17 +00:00
import tempfile
import shutil
import logging
2023-09-11 17:02:17 +00:00
from flask import Flask, request, send_from_directory, jsonify
from werkzeug.utils import secure_filename
from ankiai import images_to_package
2023-09-11 17:35:55 +00:00
from constants import IMAGE_KEY, APKG_FILE, NO_IMAGE_PART_ERROR, NO_SELECTED_FILE_ERROR, INVALID_FILENAME_ERROR
2023-09-11 18:04:51 +00:00
from logging_config import setup_logging
2023-09-11 17:02:17 +00:00
setup_logging()
app = Flask(__name__)
2023-09-08 15:22:57 +00:00
def save_uploaded_images(images, directory):
for img in images:
safe_filename = secure_filename(img.filename)
if not safe_filename:
2023-09-11 17:02:17 +00:00
raise ValueError(INVALID_FILENAME_ERROR)
2023-09-08 15:22:57 +00:00
filename = os.path.join(directory, safe_filename)
img.save(filename)
2023-09-11 17:02:17 +00:00
2023-09-08 15:22:57 +00:00
@app.route('/deck-from-images', methods=['POST'])
def deck_from_images():
if IMAGE_KEY not in request.files:
2023-09-11 17:02:17 +00:00
return jsonify({'error': NO_IMAGE_PART_ERROR}), 400
2023-09-08 15:22:57 +00:00
images = request.files.getlist(IMAGE_KEY)
2023-09-08 15:22:57 +00:00
if not images or not any(img.filename != '' for img in images):
2023-09-11 17:02:17 +00:00
return jsonify({'error': NO_SELECTED_FILE_ERROR}), 400
temp_dir = tempfile.mkdtemp()
2023-09-11 17:02:17 +00:00
save_uploaded_images(images, temp_dir)
try:
2023-09-11 17:35:55 +00:00
images_to_package(temp_dir).write_to_file(APKG_FILE)
logging.info(f"Anki package written to {APKG_FILE}")
return send_from_directory('.', APKG_FILE, as_attachment=True)
2023-09-11 17:02:17 +00:00
except Exception as e:
logging.error("Exception occurred: "+str(e), exc_info=True)
return jsonify({'error': str(e)}), 500
finally:
2023-09-11 17:02:17 +00:00
shutil.rmtree(temp_dir)
if __name__ == '__main__':
app.run(debug=True)