Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, HTTPException
|
2 |
+
from fastapi.responses import FileResponse
|
3 |
+
import subprocess
|
4 |
+
import os
|
5 |
+
import shutil
|
6 |
+
from pathlib import Path
|
7 |
+
import uuid
|
8 |
+
|
9 |
+
app = FastAPI(title="Document Conversion API")
|
10 |
+
|
11 |
+
# Create directories for file handling
|
12 |
+
UPLOAD_DIR = Path("uploads")
|
13 |
+
OUTPUT_DIR = Path("outputs")
|
14 |
+
UPLOAD_DIR.mkdir(exist_ok=True)
|
15 |
+
OUTPUT_DIR.mkdir(exist_ok=True)
|
16 |
+
|
17 |
+
@app.post("/convert/")
|
18 |
+
async def convert_document(
|
19 |
+
file: UploadFile,
|
20 |
+
output_format: str,
|
21 |
+
filter_options: str = None
|
22 |
+
):
|
23 |
+
try:
|
24 |
+
# Generate unique filenames
|
25 |
+
input_filename = f"{uuid.uuid4()}_{file.filename}"
|
26 |
+
output_filename = f"{Path(input_filename).stem}.{output_format}"
|
27 |
+
|
28 |
+
input_path = UPLOAD_DIR / input_filename
|
29 |
+
output_path = OUTPUT_DIR / output_filename
|
30 |
+
|
31 |
+
# Save uploaded file
|
32 |
+
with open(input_path, "wb") as buffer:
|
33 |
+
shutil.copyfileobj(file.file, buffer)
|
34 |
+
|
35 |
+
# Prepare conversion command
|
36 |
+
command = ["unoconvert"]
|
37 |
+
if filter_options:
|
38 |
+
command.extend(["--filter-options", filter_options])
|
39 |
+
command.extend([str(input_path), str(output_path)])
|
40 |
+
|
41 |
+
# Execute conversion
|
42 |
+
process = subprocess.run(
|
43 |
+
command,
|
44 |
+
capture_output=True,
|
45 |
+
text=True
|
46 |
+
)
|
47 |
+
|
48 |
+
if process.returncode != 0:
|
49 |
+
raise HTTPException(
|
50 |
+
status_code=500,
|
51 |
+
detail=f"Conversion failed: {process.stderr}"
|
52 |
+
)
|
53 |
+
|
54 |
+
# Return converted file
|
55 |
+
return FileResponse(
|
56 |
+
path=output_path,
|
57 |
+
filename=output_filename,
|
58 |
+
media_type="application/octet-stream"
|
59 |
+
)
|
60 |
+
|
61 |
+
except Exception as e:
|
62 |
+
raise HTTPException(status_code=500, detail=str(e))
|
63 |
+
|
64 |
+
finally:
|
65 |
+
# Cleanup
|
66 |
+
if input_path.exists():
|
67 |
+
input_path.unlink()
|
68 |
+
if output_path.exists():
|
69 |
+
output_path.unlink()
|
70 |
+
|
71 |
+
@app.get("/health")
|
72 |
+
async def health_check():
|
73 |
+
return {"status": "healthy"}
|