Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesFiles changed (2)
- detect.py+74-6
- requirements.txt+1
1234567891011121342 unmodified lines56575859606162636455 unmodified lines120121122123124125126127128129130131132133"""Core PDF field detection logic.Handles three cases:1. AcroForm PDF β extract native widgets2. Flat vector PDF β extract from drawings layer (rectangles, lines)3. Image/scanned PDF β return 'needs_ml' signal for FFDNet fallback"""import fitzfrom typing import LiteralFieldType = Literal['checkbox', 'text', 'signature']42 unmodified lines})return {'source': 'acroform', 'boxes': boxes}# ββ Case 3: Image/scanned β no vector data to mine ββββββββββββββββββββif not drawings:return {'source': 'needs_ml', 'boxes': []}# ββ Case 2: Flat vector PDF ββββββββββββββββββββββββββββββββββββββββββββtext_spans = []55 unmodified linesreturn {'source': 'vector', 'boxes': boxes}def detect_pdf(pdf_bytes: bytes) -> list[dict]:doc = fitz.open(stream=pdf_bytes, filetype='pdf')pages = []for page_num, page in enumerate(doc):result = detect_page(page)result['page'] = page_numresult['width'] = page.rect.widthresult['height'] = page.rect.heightpages.append(result)doc.close()return pages1234567891011121314151617181920212223242542 unmodified lines68697071727374757655 unmodified lines132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""Core PDF field detection logic.1. AcroForm PDF β extract native widgets2. Flat vector PDF β extract from drawings layer (rectangles, lines)3. Image/scanned PDF β run FFDNet (commonforms) for checkbox/text detection"""import fitzimport tempfile, osfrom typing import Literal# FFDNet via commonforms β loaded lazily on first use_ffdnet_ready = Falsedef _ensure_ffdnet():global _ffdnet_readyif not _ffdnet_ready:try:import commonforms as _cf # triggers model download on first import_ffdnet_ready = Trueexcept Exception as e:print(f"commonforms not available: {e}")return _ffdnet_readyFieldType = Literal['checkbox', 'text', 'signature']42 unmodified lines})return {'source': 'acroform', 'boxes': boxes}# ββ Case 3: Image/scanned β run FFDNet βββββββββββββββββββββββββββββββif not drawings:return {'source': 'needs_ml', 'boxes': []} # resolved in detect_pdf# ββ Case 2: Flat vector PDF ββββββββββββββββββββββββββββββββββββββββββββtext_spans = []55 unmodified linesreturn {'source': 'vector', 'boxes': boxes}def _run_ffdnet(pdf_bytes: bytes, page_nums: list[int]) -> dict[int, list[dict]]:"""Run commonforms FFDNet on specific pages, return boxes per page index."""if not _ensure_ffdnet():return {}from commonforms import prepare_formwith tempfile.TemporaryDirectory() as tmp:in_path = os.path.join(tmp, 'in.pdf')out_path = os.path.join(tmp, 'out.pdf')with open(in_path, 'wb') as f:f.write(pdf_bytes)try:prepare_form(in_path, out_path, confidence=0.25)except Exception as e:print(f"FFDNet error: {e}")return {}out_doc = fitz.open(out_path)results: dict[int, list[dict]] = {}for page_num in page_nums:if page_num >= len(out_doc):continuepage = out_doc[page_num]pw, ph = page.rect.width, page.rect.heightboxes = []for w in page.widgets():r = w.rectftype = 'checkbox' if w.field_type in (fitz.PDF_WIDGET_TYPE_CHECKBOX,fitz.PDF_WIDGET_TYPE_RADIOBUTTON,) else 'text'boxes.append({'type': ftype,'x': r.x0 / pw, 'y': r.y0 / ph,'w': r.width / pw, 'h': r.height / ph,'label': w.field_name or '','source': 'ffdnet',})results[page_num] = boxesout_doc.close()return resultsdef detect_pdf(pdf_bytes: bytes) -> list[dict]:doc = fitz.open(stream=pdf_bytes, filetype='pdf')pages = []for page_num, page in enumerate(doc):result = detect_page(page)result['page'] = page_numresult['width'] = page.rect.widthresult['height'] = page.rect.heightpages.append(result)doc.close()# Run FFDNet on any image pages in one pass (model loaded once)ml_pages = [p['page'] for p in pages if p['source'] == 'needs_ml']if ml_pages:ffdnet_results = _run_ffdnet(pdf_bytes, ml_pages)for p in pages:if p['source'] == 'needs_ml':p['source'] = 'ffdnet'p['boxes'] = ffdnet_results.get(p['page'], [])return pages
1 unmodified line2341 unmodified lineuvicorn==0.30.6python-multipart==0.0.9pymupdf==1.24.101 unmodified line23451 unmodified lineuvicorn==0.30.6python-multipart==0.0.9pymupdf==1.24.10commonforms
detect.py+74-6
requirements.txt+1