import os import tempfile import shutil import logging from flask import Flask, request, send_from_directory, jsonify from werkzeug.utils import secure_filename from ankiai import images_to_package from constants import IMAGE_KEY, APKG_FILE, NO_IMAGE_PART_ERROR, NO_SELECTED_FILE_ERROR, INVALID_FILENAME_ERROR from logging_config import setup_logging setup_logging() app = Flask(__name__) def save_uploaded_images(images, directory): for img in images: safe_filename = secure_filename(img.filename) if not safe_filename: raise ValueError(INVALID_FILENAME_ERROR) 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_ERROR}), 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_ERROR}), 400 temp_dir = tempfile.mkdtemp() save_uploaded_images(images, temp_dir) try: 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) except Exception as e: logging.error("Exception occurred: "+str(e), exc_info=True) return jsonify({'error': str(e)}), 500 finally: shutil.rmtree(temp_dir) if __name__ == '__main__': app.run(debug=True)