Spaces:
Sleeping
Sleeping
| from flask import Flask, request, send_file, jsonify, render_template | |
| from flask_cors import CORS | |
| from PIL import Image | |
| import img2pdf | |
| import io | |
| import os | |
| app = Flask(__name__) | |
| CORS(app) | |
| FREE_IMAGE_LIMIT = 15 | |
| def home(): | |
| return render_template("index.html") | |
| def convert(): | |
| files = request.files.getlist("images") | |
| if not files or len(files) == 0: | |
| return jsonify({"error": "No images provided."}), 400 | |
| if len(files) > FREE_IMAGE_LIMIT: | |
| return jsonify({ | |
| "error": "limit_exceeded", | |
| "message": f"Free plan allows up to {FREE_IMAGE_LIMIT} images.", | |
| "count": len(files), | |
| "limit": FREE_IMAGE_LIMIT | |
| }), 403 | |
| image_bytes_list = [] | |
| for f in files: | |
| try: | |
| img = Image.open(f.stream) | |
| if img.mode in ("RGBA", "P", "LA", "PA"): | |
| img = img.convert("RGB") | |
| buf = io.BytesIO() | |
| img.save(buf, format="JPEG", quality=95) | |
| buf.seek(0) | |
| image_bytes_list.append(buf.read()) | |
| except Exception as e: | |
| return jsonify({"error": f"Error in {f.filename}: {str(e)}"}), 400 | |
| try: | |
| pdf_bytes = img2pdf.convert(image_bytes_list) | |
| except Exception as e: | |
| return jsonify({"error": f"PDF conversion failed: {str(e)}"}), 500 | |
| return send_file( | |
| io.BytesIO(pdf_bytes), | |
| mimetype="application/pdf", | |
| as_attachment=True, | |
| download_name="converted.pdf" | |
| ) | |
| def health(): | |
| return jsonify({"status": "ok", "message": "PDF Generator is running"}) | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| app.run(host="0.0.0.0", port=port) |