Spaces:
Runtime error
Runtime error
File size: 2,068 Bytes
968fcad ee70a30 968fcad 34cbeee 5f3cfc2 34cbeee 968fcad | 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 | from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from detect import detect_pdf
app = FastAPI(title="PDF Field Detector")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["POST", "GET"],
allow_headers=["*"],
)
@app.get("/health")
def health():
from detect import _ensure_ffdnet, _ffdnet_error
return {"ok": True, "ffdnet": _ensure_ffdnet(), "ffdnet_error": _ffdnet_error or None}
@app.post("/debug")
async def debug(file: UploadFile = File(...)):
"""Run commonforms and return raw widget count + sample boxes before normalization."""
import tempfile, os, fitz
from commonforms import prepare_form
pdf_bytes = await file.read()
with tempfile.TemporaryDirectory() as tmp:
in_p = os.path.join(tmp, 'in.pdf')
out_p = os.path.join(tmp, 'out.pdf')
with open(in_p, 'wb') as f: f.write(pdf_bytes)
try:
prepare_form(in_p, out_p, confidence=0.1, device='cpu')
except Exception as e:
return {"error": str(e)}
if not os.path.exists(out_p):
return {"error": "no output produced"}
doc = fitz.open(out_p)
result = []
for pi, page in enumerate(doc):
widgets = list(page.widgets())
result.append({
"page": pi,
"widget_count": len(widgets),
"sample": [{"type": w.field_type, "rect": list(w.rect)} for w in widgets[:5]],
})
return {"pages": result, "output_size": os.path.getsize(out_p)}
@app.post("/detect")
async def detect(file: UploadFile = File(...)):
if not file.filename.lower().endswith(".pdf"):
raise HTTPException(400, "Only PDF files accepted")
pdf_bytes = await file.read()
if len(pdf_bytes) > 50 * 1024 * 1024:
raise HTTPException(413, "PDF too large (max 50MB)")
try:
pages = detect_pdf(pdf_bytes)
return {"pages": pages}
except Exception as e:
raise HTTPException(500, str(e))
|