-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
89 lines (70 loc) · 2.23 KB
/
app.py
File metadata and controls
89 lines (70 loc) · 2.23 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from flask import Flask, request, send_file, jsonify
from flask_cors import CORS
import subprocess
import os
import uuid
import shutil
import sys
app = Flask(__name__)
CORS(app)
UPLOAD_FOLDER = "uploads"
OUTPUT_FOLDER = "outputs"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
def get_libreoffice_path():
# macOS
mac_path = "/Applications/LibreOffice.app/Contents/MacOS/soffice"
if os.path.exists(mac_path):
return mac_path
# Linux / Docker
return shutil.which("libreoffice") or shutil.which("soffice")
@app.route("/")
def home():
return "Winzaap Converter API is running"
@app.route("/convert", methods=["POST"])
def convert():
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
libreoffice = get_libreoffice_path()
if not libreoffice:
return jsonify({"error": "LibreOffice not found"}), 500
file = request.files["file"]
unique_id = str(uuid.uuid4())
input_path = os.path.join(
UPLOAD_FOLDER, f"{unique_id}_{file.filename}"
)
file.save(input_path)
try:
subprocess.run(
[
libreoffice,
"--headless",
"--nologo",
"--nofirststartwizard",
"--convert-to", "pdf",
"--outdir", OUTPUT_FOLDER,
input_path,
],
check=True,
timeout=120,
)
pdf_name = os.path.splitext(os.path.basename(input_path))[0] + ".pdf"
pdf_path = os.path.join(OUTPUT_FOLDER, pdf_name)
if not os.path.exists(pdf_path):
return jsonify({"error": "PDF not generated"}), 500
return send_file(pdf_path, as_attachment=True)
except subprocess.TimeoutExpired:
return jsonify({"error": "Conversion timeout"}), 504
except subprocess.CalledProcessError:
return jsonify({"error": "Conversion failed"}), 500
finally:
# Cleanup
try:
if os.path.exists(input_path):
os.remove(input_path)
if os.path.exists(pdf_path):
os.remove(pdf_path)
except Exception:
pass
if __name__ == "__main__":
app.run(port=5000, debug=True)