-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Expand file tree
/
Copy pathapp.py
More file actions
46 lines (35 loc) · 1.18 KB
/
app.py
File metadata and controls
46 lines (35 loc) · 1.18 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
import os
import tempfile
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.responses import JSONResponse, PlainTextResponse
from markitdown import MarkItDown
app = FastAPI(title="markitdown-api")
md = MarkItDown(enable_plugins=False)
@app.get("/health")
async def health():
return {"status": "ok"}
@app.post("/convert", response_class=PlainTextResponse)
async def convert(file: UploadFile = File(...)):
filename = file.filename or "upload.bin"
suffix = os.path.splitext(filename)[1]
data = await file.read()
if not data:
raise HTTPException(status_code=400, detail="Empty file")
tmp_path = None
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(data)
tmp_path = tmp.name
result = md.convert(tmp_path)
return result.text_content
except Exception as e:
return JSONResponse(
status_code=500,
content={"error": str(e), "filename": filename},
)
finally:
if tmp_path and os.path.exists(tmp_path):
try:
os.remove(tmp_path)
except OSError:
pass