Spaces:
Paused
Paused
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, send_file, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
import fitz # PyMuPDF
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
CORS(app)
|
| 9 |
+
|
| 10 |
+
def compress_pdf(input_path, output_path, target_size_kb):
|
| 11 |
+
doc = fitz.open(input_path)
|
| 12 |
+
doc.save(output_path, garbage=4, deflate=True)
|
| 13 |
+
doc.close()
|
| 14 |
+
|
| 15 |
+
current_size_kb = os.path.getsize(output_path) / 1024
|
| 16 |
+
# Optionally, reprocess or notify if size is still too big
|
| 17 |
+
return current_size_kb <= target_size_kb + 50 # allow a little leeway
|
| 18 |
+
|
| 19 |
+
@app.route("/compress", methods=["POST"])
|
| 20 |
+
def compress():
|
| 21 |
+
if 'pdf' not in request.files:
|
| 22 |
+
return jsonify({"error": "No PDF uploaded"}), 400
|
| 23 |
+
|
| 24 |
+
target_size = request.form.get("target_size")
|
| 25 |
+
if not target_size:
|
| 26 |
+
return jsonify({"error": "Target size not specified"}), 400
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
target_kb = float(target_size)
|
| 30 |
+
except ValueError:
|
| 31 |
+
return jsonify({"error": "Invalid target size"}), 400
|
| 32 |
+
|
| 33 |
+
pdf = request.files['pdf']
|
| 34 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as input_file:
|
| 35 |
+
pdf.save(input_file.name)
|
| 36 |
+
|
| 37 |
+
output_path = input_file.name.replace(".pdf", "_compressed.pdf")
|
| 38 |
+
success = compress_pdf(input_file.name, output_path, target_kb)
|
| 39 |
+
|
| 40 |
+
if not success:
|
| 41 |
+
return jsonify({"error": "Unable to meet target size"}), 500
|
| 42 |
+
|
| 43 |
+
return send_file(output_path, as_attachment=True, download_name="compressed.pdf")
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
app.run(host="0.0.0.0", port=7860)
|