Spaces:
Sleeping
Sleeping
File size: 1,765 Bytes
e84c544 444e666 e84c544 444e666 e84c544 444e666 e84c544 444e666 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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
@app.route("/")
def home():
return render_template("index.html")
@app.route("/convert", methods=["POST"])
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"
)
@app.route("/health")
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) |