rohith083 commited on
Commit
e618e9c
·
verified ·
1 Parent(s): 55d19d5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ from fastapi import FastAPI, File, UploadFile, HTTPException
4
+ from fastapi.responses import JSONResponse
5
+
6
+ app = FastAPI(title="Scholarform Docling Service")
7
+
8
+ try:
9
+ from docling.document_converter import DocumentConverter
10
+ _converter = DocumentConverter()
11
+ DOCLING_OK = True
12
+ except Exception as e:
13
+ _converter = None
14
+ DOCLING_OK = False
15
+ DOCLING_ERR = str(e)
16
+
17
+ @app.get("/")
18
+ def root():
19
+ return {"ok": True, "service": "docling", "docling_available": DOCLING_OK}
20
+
21
+ @app.get("/health")
22
+ def health():
23
+ payload = {"ok": True, "service": "docling", "docling_available": DOCLING_OK}
24
+ if not DOCLING_OK:
25
+ payload["error"] = DOCLING_ERR
26
+ return payload
27
+
28
+ @app.post("/analyze")
29
+ async def analyze(file: UploadFile = File(...)):
30
+ if not DOCLING_OK:
31
+ raise HTTPException(status_code=503, detail=f"Docling unavailable: {DOCLING_ERR}")
32
+ if not file.filename.lower().endswith(".pdf"):
33
+ raise HTTPException(status_code=400, detail="Only PDF is supported")
34
+
35
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
36
+ tmp.write(await file.read())
37
+ path = tmp.name
38
+
39
+ try:
40
+ doc = _converter.convert(path).document
41
+ elements = []
42
+
43
+ for item in getattr(doc, "texts", []):
44
+ text = getattr(item, "text", "") or ""
45
+ label = getattr(item, "label", "text")
46
+ bbox = None
47
+ prov = getattr(item, "prov", None)
48
+ if prov and len(prov) > 0 and getattr(prov[0], "bbox", None):
49
+ b = prov[0].bbox
50
+ bbox = {"x0": b.l, "y0": b.t, "x1": b.r, "y1": b.b, "page": getattr(prov[0], "page_no", 0)}
51
+ elements.append({"type": str(label), "text": text, "bbox": bbox})
52
+
53
+ pages = getattr(doc, "num_pages", 0)
54
+ if callable(pages):
55
+ pages = pages()
56
+
57
+ return {"ok": True, "pages": pages, "elements": elements[:1000]}
58
+ except Exception as e:
59
+ raise HTTPException(status_code=500, detail=f"Docling analyze failed: {e}")
60
+ finally:
61
+ try:
62
+ os.remove(path)
63
+ except Exception:
64
+ pass