Spaces:
Runtime error
Runtime error
| 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=["*"], | |
| ) | |
| def health(): | |
| from detect import _ensure_ffdnet, _ffdnet_error | |
| return {"ok": True, "ffdnet": _ensure_ffdnet(), "ffdnet_error": _ffdnet_error or None} | |
| 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)} | |
| 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)) | |