File size: 2,321 Bytes
926601d
 
 
 
 
 
 
b5f85d0
926601d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ae0dfd
 
 
 
 
 
 
 
 
 
 
926601d
 
 
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
from fastapi import FastAPI, UploadFile, HTTPException
from fastapi.responses import FileResponse
import subprocess
import os
import shutil
from pathlib import Path
import uuid
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(title="Document Conversion API")

# Create directories for file handling
UPLOAD_DIR = Path("uploads")
OUTPUT_DIR = Path("outputs")
UPLOAD_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)

@app.post("/convert/")
async def convert_document(
    file: UploadFile,
    output_format: str,
    filter_options: str = None
):
    try:
        # Generate unique filenames
        input_filename = f"{uuid.uuid4()}_{file.filename}"
        output_filename = f"{Path(input_filename).stem}.{output_format}"
        
        input_path = UPLOAD_DIR / input_filename
        output_path = OUTPUT_DIR / output_filename

        # Save uploaded file
        with open(input_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Prepare conversion command
        command = ["unoconvert"]
        if filter_options:
            command.extend(["--filter-options", filter_options])
        command.extend([str(input_path), str(output_path)])

        # Execute conversion
        process = subprocess.run(
            command,
            capture_output=True,
            text=True
        )

        if process.returncode != 0:
            raise HTTPException(
                status_code=500,
                detail=f"Conversion failed: {process.stderr}"
            )

        # Return converted file
        return FileResponse(
            path=output_path,
            filename=output_filename,
            media_type="application/octet-stream"
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

    finally:
        # Cleanup
        if input_path.exists():
            input_path.unlink()
        if output_path.exists():
            output_path.unlink()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

from fastapi.staticfiles import StaticFiles
app.mount("/", StaticFiles(directory="static/ui", html=True), name="index")

@app.get("/health")
async def health_check():
    return {"status": "healthy"}