From 054e2a1b60abcdce47bb98cb43994fc4f4529bef Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Sun, 11 Oct 2026 17:22:34 -0400 Subject: [PATCH] Add raw-OCR-word-box fallback for Docling table-structure failures Docling's own OCR engine swaps (tesseract, rapidocr) and table_mode (fast vs accurate) were all benchmarked against the same problem page and made no difference - confirmed the table-structure model itself (TableFormer), not the OCR engine, is the bottleneck (see CLAUDE.md). app/raw_ocr_extract.py sidesteps TableFormer entirely: runs OCR directly (tesserocr) for raw per-word text+position, then reuses table_extract.py's own column-geometry logic (_find_zones/_classify_ money/etc) to derive columns from word positions, the same way it already does for native PDFs. Two real adaptations: pixel-to-point scaling (exact for a scanned PDF via its own known point dimensions, heuristic for a bare photo), and cross-page zone sharing (a page with one-sided data, e.g. zero debits, can't reliably resolve its own columns alone - confirmed for real on HSBC page 1 - so zones resolve from whichever page is most complete and apply across the whole document, deterministically fixing the sign-assignment bug a single page alone can't). Wired into reconcile._run_ocr_only as a PER-PAGE fallback, not document-level - confirmed necessary for real: Docling succeeded on one page and silently missed another's table in the same conversion call, which a document-level "did any page work" check would have missed entirely (10 real transactions, including debits, would have vanished with no error). Verified end-to-end through the real running app on a genuine 2-page scanned test file (docs/scanned_statement_2page.pdf, built from real HSBC pages 1+2): 17/17 transactions, correct signs and balances, date_sanity correctly flagged the one real OCR misread. measure.py confirms zero regression on the existing text-PDF corpus. New dependencies: tesserocr, pypdfium2, pillow (Python) plus tesseract-ocr/libtesseract-dev/libleptonica-dev (OS, Dockerfile). TESSDATA_PREFIX must be set explicitly - tesserocr doesn't reliably auto-discover Debian's tessdata path on its own. Known limitation, documented not hidden: the one-sided-data edge case is only reliably fixed with a second page to borrow zones from - a true single-page photo upload has no such fallback and stays a close geometric call. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 74 +++++++++++++- Dockerfile | 9 ++ app/raw_ocr_extract.py | 223 +++++++++++++++++++++++++++++++++++++++++ app/reconcile.py | 68 +++++++++++-- requirements.txt | 3 + 5 files changed, 366 insertions(+), 11 deletions(-) create mode 100644 app/raw_ocr_extract.py diff --git a/CLAUDE.md b/CLAUDE.md index 58493c0..36c7f23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ to rough effort: | Phase | Contains | Status here | |---|---|---| | **1** | Extraction + 6 checks + Excel export, dual-engine, measurement harness | **In progress — see gaps below** | -| 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | OCR routing built 2026-10-11, real-world reliability unresolved (see "OCR / scanned statements" below) — review screen and suggested-fix patterns not started | +| 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | OCR routing + working Docling-fallback (`raw_ocr_extract.py`) built and verified against a real multi-page scan 2026-10-11 — one known single-page edge case remains unreliable, see "OCR / scanned statements" below — review screen and suggested-fix patterns not started | | 3 | Layout mapper (fingerprinting, versioning, drift detection) | Not started | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 5 | Free front door, public accuracy page | Not started | @@ -154,7 +154,9 @@ docker compose down # stop and remove both containers never silently resolved. `_needs_ocr()` routes an upload with no embedded text layer at all (a raw image, or a PDF wrapping a scan/photo) to `_run_ocr_only()` instead — Docling's OCR becomes the sole canonical source there (no pdfplumber pass is even possible), not - just the cross-check role it plays for a normal text PDF. See "OCR / scanned statements" + just the cross-check role it plays for a normal text PDF. `_run_ocr_only()` additionally + falls back to `raw_ocr_extract.py` on a PER-PAGE basis when Docling's own table-structure + recognition fails for a given page (zero transaction rows) — see "OCR / scanned statements" below. - `app/pipeline.py` — orchestrates extract → reconcile → normalize → run checks. - `app/checks.py` — the six checks (statement balance, running-balance continuity, totals, @@ -165,6 +167,13 @@ docker compose down # stop and remove both containers is "not available." Running-balance and date-ordering checks try both directions and pick whichever has fewer violations, rather than assuming one. - `app/excel_export.py` — Transactions + Summary sheet export. +- `app/raw_ocr_extract.py` — the per-page fallback for `reconcile._run_ocr_only` when + Docling's table-structure recognition fails on a scanned/photographed page. Runs OCR + directly (`tesserocr`) for raw word text + pixel position, bypassing any table-structure + model's row/column grouping entirely, then reuses `table_extract.py`'s own column- + geometry logic unchanged. See "OCR / scanned statements" below for the full reasoning, + the two real adaptations this needed (pixel-to-point scaling, cross-page zone sharing), + and the one known edge case that isn't reliably fixed. - `app/measure.py` — the measurement harness. Auto-discovers its corpus from `fixtures/*.pdf` with a matching `*_ground_truth.xlsx` sibling (each ground-truth file is a `Transactions` sheet of date/status/description/amount/balance rows in the same @@ -273,6 +282,67 @@ with no recoverable cell anywhere — one field short of usable, 0 transactions One data point against one hard image, not a broad verdict, but enough to not pursue it further here — the adapter code was removed rather than kept unused. +**`app/raw_ocr_extract.py` — a working fallback for Docling's OCR-structure failures, +shipped 2026-10-11.** Also benchmarked: Docling's own alternate OCR engines (`tesseract`, +`rapidocr`) and `table_mode: fast` against the same problem image — all produced the +identical grid (same merges, same failure) or worse; neither the OCR engine nor the table +mode was ever the actual bottleneck. The real fix came from a different idea: don't trust +ANY table-structure model's row/column grouping at all. Run OCR directly (`tesserocr`) to +get raw per-word text + pixel position, then reuse `table_extract.py`'s own column- +geometry logic (`_find_zones`/`_classify_money`/etc. — the same code already proven +correct for HSBC and RBC's real pdfplumber path) to derive columns from word geometry +itself, same as it already does for a native PDF. + +Two adaptations beyond the pdfplumber path, both confirmed necessary by testing against +real rendered pages, not assumed: +1. **Pixel-to-point scaling.** `_assign_money_columns`'s `max_distance=60` is tuned for PDF + points (72/inch), meaningless for raw pixel coordinates. For a scanned PDF the exact + scale is knowable (pdfplumber reports a page's real point-dimensions even with no text + layer) and used directly. For a bare photo with no PDF page to anchor against, there's + no way to know true scale, so the image's own pixel width is treated as if it were a + standard portrait US Letter page (612pt) — a real, documented assumption, not a fact; + wrong for a landscape photo or non-Letter paper. +2. **Cross-page zone sharing.** A single page with one-sided data (e.g. zero debit + transactions, confirmed for real on HSBC's own page 1) makes its own column-clustering + genuinely ambiguous — its lone value cluster can get assigned to the wrong field purely + by which header word sits pixel-closer, a geometric coin-flip with no data on that page + able to correct it (confirmed for real: this exact case resolved correctly in one test + run and would plausibly resolve wrong in another — it is NOT reliably fixed when only + one page exists, see below). `table_extract.py`'s own `carry_zones` only carries + FORWARD; this instead resolves zones on every page first, keeps whichever page resolved + the MOST complete shape (both credit and debit present), and applies that single zone + definition across every page. Confirmed fixing a real case: HSBC page 1 (all credits) + alone always mis-signed every amount as a negative debit; processed together with page 2 + (which has real debits, resolves cleanly on its own), page 1's 7 transactions came back + with correct positive amounts, deterministically, every time — verified through the + actual running app, not just the extraction function in isolation. + +**Wired into `reconcile._run_ocr_only` as a per-page fallback, not document-level** — +confirmed necessary for real: on an actual 2-page scan, Docling succeeded on page 1 but +missed page 2's table entirely in the SAME conversion call; a document-level "did ANY page +get rows" check would have silently kept page 2 empty (10 real transactions, including +both debits, would have vanished with no error) since page 1 alone made the overall result +non-empty. The fallback runs the whole document through `raw_ocr_extract` whenever any +page comes back empty from Docling (so its cross-page zone-sharing can still use a good +page), then only replaces the specific pages Docling actually failed — a page Docling got +right is never second-guessed. `page_reports[].status` is `"ocr_only"` or `"ocr_raw_words"` +per page so it's visible which engine produced which page. Verified end-to-end through the +real running app on a genuine 2-page scanned test file +(`docs/scanned_statement_2page.pdf`, built from real HSBC pages 1+2): 17/17 transactions, +correct signs, correct balances; `date_sanity` correctly flagged the one real OCR date +misread rather than hiding it. `measure.py` confirms zero regression on the existing +text-PDF corpus. + +**Known, honest limitation, not glossed over:** the one-sided-data edge case above is only +reliably fixed when a SECOND page with both debits and credits exists to borrow zones from. +A genuine single-page photo upload with only one-sided data on it has no second page to +borrow from — the geometric assignment stays a close call, and which way it resolves isn't +guaranteed. New dependencies: `tesserocr`, `pypdfium2`, `pillow`, plus `tesseract-ocr`/ +`libtesseract-dev`/`libleptonica-dev` at the OS level (Dockerfile) — `TESSDATA_PREFIX` must +be set explicitly (`/usr/share/tesseract-ocr/5/tessdata`); tesserocr does not reliably +auto-discover Debian's tessdata location on its own (confirmed for real: failed with +"invalid tessdata path: ./" without it). + ## Frontend / UI state (as of 2026-10-11) **Theme is enterprise-light, not the Bettersight brand default.** `UI_DESIGN_THEME.md` diff --git a/Dockerfile b/Dockerfile index 29ed779..d8211a0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,8 +4,17 @@ WORKDIR /app RUN apt-get update && apt-get install -y \ curl \ + tesseract-ocr \ + libtesseract-dev \ + libleptonica-dev \ + pkg-config \ && rm -rf /var/lib/apt/lists/* +# tesserocr doesn't reliably auto-discover Debian's tessdata location - +# confirmed for real: "Failed to init API, possibly an invalid tessdata +# path: ./" without this set explicitly. +ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/5/tessdata + COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt diff --git a/app/raw_ocr_extract.py b/app/raw_ocr_extract.py new file mode 100644 index 0000000..9382173 --- /dev/null +++ b/app/raw_ocr_extract.py @@ -0,0 +1,223 @@ +""" +Raw-OCR-word-box extraction - the fallback for reconcile._run_ocr_only +when Docling's own table-structure recognition (TableFormer) fails to +produce usable rows on a scanned/photographed statement. Confirmed for +real: TableFormer can merge unrelated page content into one table, or +merge two real columns into one cell, on a page it structures correctly +as a native PDF - see CLAUDE.md's "OCR / scanned statements" section. + +Instead of trusting ANY external table-structure model's row/column +grouping, this runs OCR directly (tesserocr) for raw per-word text + +pixel position, then reuses table_extract.py's EXISTING column-clustering +logic (_find_zones/_classify_money/etc - the same code already proven +correct for two real bank formats on the pdfplumber path) to derive +column zones from word geometry itself, the same way it already does for +a native PDF's own word positions. + +Two adaptations beyond the pdfplumber path, both confirmed necessary by +testing against real statement pages: + +1. Pixel-to-point scaling. table_extract.py's distance thresholds + (_assign_money_columns's max_distance=60) are tuned for PDF POINTS + (72/inch) - meaningless for raw pixel coordinates, which vary with + image resolution. For a PDF-sourced scan, the exact scale is knowable + (pdfplumber reports a scanned page's own point dimensions even with no + text layer) and used directly - no guessing. For a bare photo upload + with no PDF page to anchor against, there's no way to know the true + scale, so the image's own width is treated as if it were a standard + portrait US Letter page (612pt) - a real assumption, not a fact, and + wrong for a landscape photo or non-Letter paper. + +2. Cross-page zone sharing. A single page can have degenerate data (e.g. + zero debit transactions) that makes its OWN column-clustering + ambiguous - confirmed for real: HSBC's page 1 (all credits) had its + lone money-value cluster misassigned to "debit" purely by pixel + proximity to that header word, nothing on the page itself able to + correct it. table_extract.py's own carry_zones only carries FORWARD + (an earlier page's zones fill a later page's gaps) - this instead + resolves zones on EVERY page first, keeps whichever page resolved the + MOST complete shape (ideally both credit and debit present), and + applies that single zone definition to every page's row-building - + fixing page 1 using page 2's cleaner data, which a forward-only carry + can't do. If no page ever resolves a complete shape, this honestly + returns nothing rather than extracting with an unresolved or guessed + field. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(__file__)) +import table_extract +import layout_rules + +_REFERENCE_PAGE_WIDTH_PT = 612.0 # US Letter portrait - the photo-upload fallback assumption + + +def _extract_words(image, page_no): + """[{"text","x0","x1","top","bottom","page_no"}] for every word + tesserocr finds on one PIL Image, in raw pixel coordinates (scaled to + points by the caller - see _scale_to_points).""" + import tesserocr + words = [] + with tesserocr.PyTessBaseAPI() as api: + api.SetImage(image) + api.Recognize() + ri = api.GetIterator() + level = tesserocr.RIL.WORD + for r in tesserocr.iterate_level(ri, level): + text = r.GetUTF8Text(level) + if text and text.strip(): + bbox = r.BoundingBox(level) + words.append({ + "text": text.strip(), "x0": bbox[0], "x1": bbox[2], + "top": bbox[1], "bottom": bbox[3], "page_no": page_no, + }) + return words + + +def _scale_to_points(words, scale): + for w in words: + w["x0"] *= scale + w["x1"] *= scale + w["top"] *= scale + w["bottom"] *= scale + + +def _lines_by_top(words): + lines = {} + for w in words: + lines.setdefault(round(w["top"]), []).append(w) + return lines + + +def _zone_completeness(zones): + """How many usable fields this zone set resolved - the signal used to + pick which page's zones to trust across the whole document (see this + module's own docstring on cross-page zone sharing).""" + if not zones: + return -1 + return len(set(zones.keys()) - {"_debit_self_signed"}) + + +def _build_rows(words, lines, zones, header_top, page_no): + """Per-line row classification identical to table_extract.extract_page's + own loop, adapted for a plain OCR word list instead of a pdfplumber + Page object - produces the exact same row shape (see extract_page's + docstring for the full contract), so table_extract.rows_to_transactions/ + extract_statement_facts run unchanged on this too.""" + rows = [] + last_date = "" + for top in sorted(lines.keys()): + if header_top is not None and top <= header_top: + continue + line_words = sorted(lines[top], key=lambda w: w["x0"]) + leftmost = line_words[0] + text_all = " ".join(w["text"] for w in line_words) + if table_extract._PAGE_FOOTER_RE.search(text_all) or table_extract._BARE_PAGE_FOOTER_RE.match(text_all.strip()): + continue + if leftmost["text"] == "Bank": + continue + if text_all in table_extract._HEADER_BOILERPLATE: + continue + + date_parts, status_parts, desc_parts = [], [], [] + money = {} + for w in line_words: + amount = table_extract._classify_money(w["text"], w["x1"], zones) + if amount: + field, value = amount + money[field] = value + continue + dz, sz, descz = zones.get("date"), zones.get("status"), zones.get("description") + if dz and dz[0] <= w["x0"] <= dz[1]: + date_parts.append(w["text"]) + elif sz and sz[0] <= w["x0"] <= sz[1]: + status_parts.append(w["text"]) + elif descz and descz[0] <= w["x0"] <= descz[1]: + desc_parts.append(w["text"]) + + row_date = " ".join(date_parts) + if row_date: + last_date = row_date + if money.get("debit") is not None and not zones.get("_debit_self_signed", True): + money["debit"] = -abs(money["debit"]) + + row_text_lower = (" ".join(desc_parts) or text_all).strip().lower() + if set(money.keys()) == {"balance"} and row_text_lower in layout_rules.OPENING_BALANCE_PHRASES: + rows.append({"type": "opening_balance", "balance": money["balance"]}) + continue + if set(money.keys()) == {"balance"} and row_text_lower in layout_rules.CLOSING_BALANCE_PHRASES: + rows.append({"type": "closing_balance", "balance": money["balance"]}) + continue + + if money: + rows.append({ + "type": "txn", "date": row_date or last_date, "status": " ".join(status_parts), + "inline_description": " ".join(desc_parts), "credit": money.get("credit"), + "debit": money.get("debit"), "amount": money.get("amount"), "balance": money.get("balance"), + "top": top, "page_no": page_no, + }) + elif leftmost["text"].lower() in layout_rules.NARRATIVE_LABEL_WORDS: + rows.append({"type": "narrative", "text": " ".join(w["text"] for w in line_words[1:]), + "explicit_label": True, "top": top, "page_no": page_no}) + elif table_extract._REF_RE.match(leftmost["text"]): + continue + else: + rows.append({"type": "narrative", "text": text_all, "explicit_label": False, "top": top, "page_no": page_no}) + return rows + + +def _extract_from_images(images_with_scale): + """images_with_scale: [(PIL.Image, points_per_pixel_scale), ...], one + per page in order. Returns {page_no: [rows...]}, same per-page shape + table_extract.extract_pdf/docling_client.ocr_extract_pdf return.""" + page_data = [] + best_zones, best_score = None, -1 + for page_no, (image, scale) in enumerate(images_with_scale, start=1): + words = _extract_words(image, page_no) + if not words: + page_data.append((page_no, words, {}, None)) + continue + _scale_to_points(words, scale) + lines = _lines_by_top(words) + zones, header_top = table_extract._find_zones(words, lines) + page_data.append((page_no, words, lines, header_top)) + score = _zone_completeness(zones) + if zones and score > best_score: + best_zones, best_score = zones, score + + if not best_zones or not layout_rules.has_required_shape(set(best_zones.keys()) - {"_debit_self_signed"}): + return {p: [] for p, _, _, _ in page_data} + + return { + page_no: (_build_rows(words, lines, best_zones, header_top, page_no) if words else []) + for page_no, words, lines, header_top in page_data + } + + +def extract_pdf(pdf_path, resolution=200): + """{page_no: [rows...]} for a PDF with no text layer (a scanned PDF) - + each page is rendered to an image via pdfplumber's own pypdfium2 + backend, scaled using the PAGE'S OWN KNOWN point dimensions (exact, + not guessed - a scanned PDF still reports real page geometry even + with nothing in its text layer).""" + import pdfplumber + images_with_scale = [] + with pdfplumber.open(pdf_path) as pdf: + for page in pdf.pages: + img = page.to_image(resolution=resolution).original + scale = page.width / img.width + images_with_scale.append((img, scale)) + return _extract_from_images(images_with_scale) + + +def extract_image(image_path): + """{1: [rows...]} for a single raw image upload (a phone photo, no PDF + container) - true physical scale is unknowable here, so the image's + own pixel width is treated as if it were a standard portrait US + Letter page (612pt). A real assumption - see this module's own + docstring - not a measurement.""" + from PIL import Image + image = Image.open(image_path) + scale = _REFERENCE_PAGE_WIDTH_PT / image.width + return _extract_from_images([(image, scale)]) diff --git a/app/reconcile.py b/app/reconcile.py index bbd57cd..4251937 100644 --- a/app/reconcile.py +++ b/app/reconcile.py @@ -2,6 +2,7 @@ import pdfplumber import table_extract import docling_client +import raw_ocr_extract AMOUNT_TOLERANCE = 0.01 @@ -81,16 +82,49 @@ def _run_ocr_only(pdf_path, docling_url): duplicating that logic for this engine. "page_reports" entries carry "pdfplumber_count" populated with - Docling's own per-page count (not literally from pdfplumber - there - is none here) so checks.check_page_coverage can run unmodified; there - is no "docling_count" to compare it against, so "status" is always - "ocr_only" rather than "ok"/"fallback_only"/"mismatch" - those values - specifically mean something about engine AGREEMENT, which doesn't - apply when only one engine ran. See pipeline.py/checks.py for how - "extraction_method": "ocr" is used to keep this path from ever - reaching "Verified" - there's no second opinion to earn that on. + whichever engine actually ran's own per-page count (not literally + from pdfplumber - there is none here) so checks.check_page_coverage + can run unmodified; there is no "docling_count" to compare it + against, so "status" is "ocr_only" or "ocr_raw_words" (never + "ok"/"fallback_only"/"mismatch" - those values specifically mean + something about engine AGREEMENT, which doesn't apply when only one + engine ran). See pipeline.py/checks.py for how "extraction_method": + "ocr" is used to keep this path from ever reaching "Verified" - + there's no second opinion to earn that on. + + Docling's table-structure recognition (TableFormer) is tried first - + it's usually fine - but confirmed for real to sometimes merge + unrelated page content into a table, or merge two real columns into + one cell, or miss a page's table entirely, on a page it would + structure correctly as a native PDF (see CLAUDE.md's "OCR / scanned + statements" section). The fallback is PER-PAGE, not document-level - + confirmed necessary for real: on a genuine multi-page scan, Docling + succeeded on one page and completely missed another in the SAME + conversion call, and a document-level "any page got rows at all" + check would have silently kept the failed page empty instead of + retrying it, exactly the silent-data-loss this product exists to + avoid. raw_ocr_extract is run across the WHOLE document whenever ANY + page is empty (not just the empty ones) so its own cross-page zone- + sharing (see its docstring) can still use a good page to fix a + degenerate one - then only the pages Docling actually failed are + replaced with its result; a page Docling got right is never + second-guessed. Still genuinely possible for a page to fail in both + engines (nothing OCR-detectable on it at all) - that page just stays + empty, same as it would with no fallback. """ pages_rows = docling_client.ocr_extract_pdf(pdf_path, docling_url) + engine_by_page = {p: "ocr_only" for p in pages_rows} + + empty_pages = [p for p, rows in pages_rows.items() if not any(r["type"] == "txn" for r in rows)] + if empty_pages: + fallback_rows = _try_raw_ocr_fallback(pdf_path) + if fallback_rows: + for p in empty_pages: + fb_rows = fallback_rows.get(p, []) + if any(r["type"] == "txn" for r in fb_rows): + pages_rows[p] = fb_rows + engine_by_page[p] = "ocr_raw_words" + if not any(pages_rows.values()): raise ValueError( "Could not read this statement via OCR - no table structure was recognized in the " @@ -103,7 +137,7 @@ def _run_ocr_only(pdf_path, docling_url): counts = _pdfplumber_page_counts(pages_rows) page_reports = [ {"page": p, "pdfplumber_count": counts.get(p, 0), "docling_count": None, - "status": "ocr_only", "mismatches": []} + "status": engine_by_page.get(p, "ocr_only"), "mismatches": []} for p in sorted(pages_rows.keys()) ] return { @@ -113,6 +147,22 @@ def _run_ocr_only(pdf_path, docling_url): } +def _try_raw_ocr_fallback(pdf_path): + """None if the fallback itself errors (e.g. a genuinely corrupt file) - + distinct from an empty-but-successful result, so the caller can tell + "fallback ran and found nothing" from "fallback couldn't run at all" + without either one masking a real exception.""" + try: + with pdfplumber.open(pdf_path): + return raw_ocr_extract.extract_pdf(pdf_path) + except Exception: + pass + try: + return raw_ocr_extract.extract_image(pdf_path) + except Exception: + return None + + def run(pdf_path, docling_url): """ Runs both engines on the same PDF and cross-checks them per page - or, diff --git a/requirements.txt b/requirements.txt index 70722a3..cf25c54 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,6 @@ flask==3.0.3 requests==2.32.3 openpyxl==3.1.5 pdfplumber==0.11.4 +tesserocr==2.7.1 +pillow==10.4.0 +pypdfium2==4.30.1