Route scanned/photographed statements through Docling OCR
The pipeline previously had no OCR path at all - pdfplumber has zero OCR
capability (confirmed by building an image-only PDF from a real statement
page and watching extract_text() return nothing), and the only guard
against that case raised a misleading error ("could not recognize this
statement's column layout") written for a different problem entirely.
reconcile._needs_ocr() now distinguishes "no text layer at all" (a scan
or phone photo - routes to _run_ocr_only(), Docling's OCR as the sole
canonical source) from "has text, but this extractor doesn't recognize
the bank's layout" (unchanged, same error as before). docling_client's
new ocr_table_to_rows()/ocr_extract_pdf() reshape Docling's OCR'd table
into the identical row format table_extract.extract_page() produces, so
rows_to_transactions/extract_statement_facts run completely unchanged on
OCR'd data rather than duplicating that logic for a second engine.
Column-role resolution (_resolve_columns, shared with the existing
cross-check path) is now collision-aware instead of first-match-wins:
excludes a field when a header cell's text genuinely contains vocabulary
from two different fields at once (caught a real Docling mis-segmentation
bug this way, on an RBC page), while still correctly resolving two
separately-clean columns that both legitimately match the same field
(HSBC has two real date columns) and not confusing "amount" nested inside
"credit amount" for contamination. Took two iterations against the real
fixture corpus to get both cases right at once.
An OCR-sourced extraction can never reach "Verified" (checks.py's new
check_ocr_source, always needs_review) - there's no second engine to
cross-check Docling's OCR against, so the safety property every other
check rests on doesn't hold here.
The upload UI now accepts .jpg/.png in addition to .pdf.
Real-world reliability is honestly unresolved, not assumed solved - see
CLAUDE.md's new "OCR / scanned statements" section for four real test
renders this session and exactly what did and didn't work. The routing
and reshaping logic itself is verified correct (confirmed through the
real running app, both a text-PDF upload and a raw-image upload); whether
a given scan or photo actually extracts anything depends on Docling's
own, inconsistent table-structure recognition on that specific image.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
84302e28b3
commit
e4e43618b7
|
|
@ -2,6 +2,7 @@ __pycache__/
|
|||
*.pyc
|
||||
.DS_Store
|
||||
.venv*/
|
||||
.claude/
|
||||
uploads/*
|
||||
!uploads/.gitkeep
|
||||
outputs/*
|
||||
|
|
|
|||
76
CLAUDE.md
76
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 | Not started |
|
||||
| 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 |
|
||||
| 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 |
|
||||
|
|
@ -113,7 +113,27 @@ docker compose down # stop and remove both containers
|
|||
|
||||
- `app/main.py` — minimal Flask app factory.
|
||||
- `app/docling_client.py` — wraps the self-hosted Docling container (`to_formats=[md,json]`)
|
||||
to get structured table output per page, not just flat markdown.
|
||||
to get structured table output per page, not just flat markdown. `convert()` guesses the
|
||||
upload's content-type from its own extension (not hardcoded to `application/pdf`) so a
|
||||
raw image upload reaches Docling's OCR correctly — confirmed for real that Docling
|
||||
accepts and OCRs a raw PNG directly when sent with its correct `image/png` content-type.
|
||||
`_resolve_columns()` is the column-role resolver shared by both `extract_transactions()`
|
||||
(the cross-check-only path) and `ocr_table_to_rows()` (the OCR-canonical path below) —
|
||||
it's collision-aware, not first-match-wins: a header cell whose text matches vocabulary
|
||||
from two genuinely different fields at once (confirmed for real on an RBC page where
|
||||
Docling's own table-structure model mis-segmented a wrapped header, scrambling
|
||||
"Debits"/"Deposits" text across the wrong cells) is excluded rather than silently
|
||||
guessed at — but a losing match that's merely a *substring* of the winning one (e.g.
|
||||
"amount" inside "credit amount") isn't treated as contamination, and two separately
|
||||
clean columns that both legitimately match the same field (confirmed for real on HSBC,
|
||||
which has two genuine date columns — "Value date" and "Post date") resolve via whichever
|
||||
matched the longer, more specific phrase rather than being excluded outright. See its own
|
||||
docstring for the full reasoning — this took two iterations to get right, each broke a
|
||||
real fixture, and is exactly the kind of logic worth reading before touching again.
|
||||
`ocr_table_to_rows()`/`ocr_extract_pdf()` reshape a Docling-OCR'd table into the identical
|
||||
row format `table_extract.extract_page()` produces, so `table_extract.rows_to_transactions`/
|
||||
`extract_statement_facts` run unchanged on OCR'd data too — see "OCR / scanned statements"
|
||||
under Key decisions & lessons for what this does and doesn't currently handle well.
|
||||
- `app/table_extract.py` — the generalized pdfplumber extractor. Bank-agnostic: derives
|
||||
each column's role (date/description/debit/credit/balance) from the header row's own
|
||||
word positions and a shared keyword dictionary (`app/layout_rules.py`), rather than
|
||||
|
|
@ -131,7 +151,11 @@ docker compose down # stop and remove both containers
|
|||
pipeline — pdfplumber re-reads the PDF's own text layer independently) and cross-checks
|
||||
them: agreement → high confidence; Docling missed a table but pdfplumber found one →
|
||||
use pdfplumber's result, flagged informationally; disagreement → flagged for review,
|
||||
never silently resolved.
|
||||
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"
|
||||
below.
|
||||
- `app/pipeline.py` — orchestrates extract → reconcile → normalize → run checks.
|
||||
- `app/checks.py` — the six checks (statement balance, running-balance continuity, totals,
|
||||
date sanity, structure sanity, page coverage) plus a 7th, `check_narrative_direction`,
|
||||
|
|
@ -195,6 +219,47 @@ entirely." The correct scope was much narrower (fixed-width columns via `<colgro
|
|||
structure was never meant to change. When a UI request could be read either as a small,
|
||||
scoped fix or a larger structural change, confirm before assuming the larger one.
|
||||
|
||||
**OCR / scanned statements (added 2026-10-11, routing built; real-world reliability
|
||||
unresolved).** pdfplumber has zero OCR capability — confirmed by building an image-only
|
||||
PDF (no text layer, same as a real scan) from a real statement page and watching
|
||||
`extract_text()` return nothing. Before this work, the pipeline's own guard clause
|
||||
(`if not any(pages_rows.values())`) caught that and raised a *misleading* error — "could
|
||||
not recognize this statement's column layout," which is the message written for a
|
||||
different problem (a text PDF whose bank layout isn't supported yet), not "no text layer
|
||||
at all." `reconcile._needs_ocr()` now distinguishes the two: a raw image upload or a
|
||||
scanned/photographed PDF routes to `_run_ocr_only()` (Docling's OCR as the sole canonical
|
||||
source, correctly worded error if even OCR fails), while a text PDF this extractor just
|
||||
doesn't recognize still gets the original, differently-worded error.
|
||||
|
||||
An OCR-sourced extraction can never reach "Verified" — `checks.check_ocr_source()` always
|
||||
reports `needs_review`, by design: there is no second engine to cross-check Docling's OCR
|
||||
against, so the core safety property every other check result rests on (two independent
|
||||
engines, never trust one alone) doesn't hold here. This is enforced by construction (the
|
||||
check's own outcome), not a bolted-on status override.
|
||||
|
||||
**The honest limitation this surfaced, confirmed empirically, not assumed:** Docling's own
|
||||
table-structure recognition is meaningfully less reliable on rasterized/OCR'd input than
|
||||
on a native PDF's text layer — this was already known from the original Docling spike (see
|
||||
above) on the *clean* text-PDF path; this work reconfirmed it's worse again once OCR is
|
||||
also in the loop. Four real test renders this session, same real HSBC statement, different
|
||||
pages/settings: page 1 alone → Docling merged the account-summary preamble block in
|
||||
*above* the real header row into one table (fixed here — `ocr_table_to_rows` now searches
|
||||
for the header row via the same pattern `table_extract._find_header_row` already uses for
|
||||
pdfplumber, rather than assuming row 0); that same render *also* merged "Credit amount" and
|
||||
"Debit amount" into a single cell, which can't be safely split back into two columns after
|
||||
the fact (the column-collision detector correctly refuses to guess, leaving `debit`
|
||||
unresolved) — not fixed, and not safely fixable by reshaping alone. Page 2 alone, at both
|
||||
200 and 300 DPI, wasn't recognized as a table at all (flat OCR text instead, same failure
|
||||
mode the original spike documented on page 4 of the clean PDF). So: the routing and
|
||||
row-reshaping infrastructure is built and unit-verified correct (confirmed end-to-end
|
||||
through the real running app for both a text-PDF upload and a raw-image upload), but
|
||||
whether a *given* real scan or photo actually extracts anything still depends on Docling's
|
||||
own, inconsistent table-structure call on that specific image — not something this session
|
||||
resolved, and not something straightforward to fix from this repo's side (it's the
|
||||
external model's own behavior, not a parsing bug in this codebase). Test images from this
|
||||
session are kept at `docs/scanned_statement.pdf` and `docs/scan_test_page-1.png` for
|
||||
whoever picks this up next.
|
||||
|
||||
## Frontend / UI state (as of 2026-10-11)
|
||||
|
||||
**Theme is enterprise-light, not the Bettersight brand default.** `UI_DESIGN_THEME.md`
|
||||
|
|
@ -211,6 +276,11 @@ the `:root` block or hardcoding colors inline.
|
|||
|
||||
Key current UI behaviors, each the result of an explicit, specific user request (don't
|
||||
"simplify" these away without asking first):
|
||||
- The upload zone (`#fileInput`) accepts `.pdf`, `.jpg`/`.jpeg`, and `.png` (added
|
||||
2026-10-11 for OCR support — see "OCR / scanned statements" above) — the client-side
|
||||
extension check and the preview `<iframe>` both widened accordingly; an image file in
|
||||
that same iframe just renders as an image (the PDF-viewer hash params are harmlessly
|
||||
ignored), so no separate `<img>` element or branching was needed for this.
|
||||
- PDF ("Source Document") and Transactions sit side-by-side with a draggable resizer
|
||||
(`.resizer`, styled as a vertical grip-knob), both wrapped in `.review-grid` which is
|
||||
what's `position:sticky` (not the PDF column alone) so they scroll as one unit.
|
||||
|
|
|
|||
|
|
@ -243,6 +243,24 @@ def check_engine_agreement(page_reports):
|
|||
}
|
||||
|
||||
|
||||
def check_ocr_source():
|
||||
"""Not one of the spec's six named checks - the OCR-path analog of
|
||||
engine_agreement, which specifically means something about TWO
|
||||
engines agreeing and so can't run at all when only one engine (Docling,
|
||||
via OCR) produced any result (see reconcile.py's routing). Always
|
||||
needs_review and never pass: this is the product's own acknowledgment
|
||||
that OCR has no second engine checking it, which is also what keeps
|
||||
the overall status in run_all() from ever reaching "Verified" for an
|
||||
OCR-sourced statement, the same way a genuine fail/needs_review
|
||||
outcome from any other check would."""
|
||||
return {
|
||||
"name": "ocr_source", "outcome": "needs_review",
|
||||
"detail": "This statement was read via OCR - no embedded text layer was found, so "
|
||||
"Docling extracted it alone with no second engine to cross-check against. "
|
||||
"Review the extracted rows against the original image or PDF before relying on them.",
|
||||
}
|
||||
|
||||
|
||||
def check_narrative_direction(narrative_direction):
|
||||
"""
|
||||
Not one of the spec's six named checks, but the natural output of
|
||||
|
|
@ -275,15 +293,25 @@ def check_narrative_direction(narrative_direction):
|
|||
|
||||
|
||||
def run_all(transactions, page_reports, opening_balance=None, closing_balance=None,
|
||||
period_start=None, period_end=None, narrative_direction=None):
|
||||
period_start=None, period_end=None, narrative_direction=None, ocr_only=False):
|
||||
"""
|
||||
Runs every check and derives the overall status:
|
||||
- "Failed": the statement balance check explicitly failed, or the
|
||||
running-balance chain broke, or the two engines actively disagree.
|
||||
- "Needs review": anything else non-passing (missing balance figures,
|
||||
date/structure issues, a page Docling couldn't confirm, a possible
|
||||
mixed narrative-wrapping convention).
|
||||
- "Verified": everything passed.
|
||||
mixed narrative-wrapping convention, or an OCR-sourced statement -
|
||||
see check_ocr_source).
|
||||
- "Verified": everything passed. Not reachable when ocr_only=True -
|
||||
check_ocr_source always reports needs_review, by design (see its
|
||||
own docstring): OCR has no second engine to earn "Verified" against.
|
||||
|
||||
`ocr_only` swaps check_engine_agreement (meaningless with only one
|
||||
engine's result to look at) for check_ocr_source; check_page_coverage
|
||||
still runs unchanged - page_reports' "pdfplumber_count" field holds
|
||||
Docling's own per-page count in this case (see reconcile._run_ocr_only),
|
||||
and an empty page is just as worth flagging regardless of which engine
|
||||
produced the (lack of) rows.
|
||||
"""
|
||||
results = [
|
||||
check_statement_balance(transactions, opening_balance, closing_balance),
|
||||
|
|
@ -291,7 +319,7 @@ def run_all(transactions, page_reports, opening_balance=None, closing_balance=No
|
|||
check_date_sanity(transactions, period_start, period_end),
|
||||
check_structure_sanity(transactions),
|
||||
check_page_coverage(page_reports),
|
||||
check_engine_agreement(page_reports),
|
||||
check_ocr_source() if ocr_only else check_engine_agreement(page_reports),
|
||||
check_narrative_direction(narrative_direction),
|
||||
]
|
||||
outcomes = {r["outcome"] for r in results}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import json
|
||||
import mimetypes
|
||||
import re
|
||||
import requests
|
||||
import layout_rules
|
||||
|
|
@ -9,19 +11,25 @@ _MONEY_FIELDS = ("debit", "credit", "amount", "balance")
|
|||
|
||||
def convert(pdf_path, docling_url):
|
||||
"""
|
||||
POST a PDF to Docling's /v1/convert/file, requesting both Markdown and
|
||||
POST a file to Docling's /v1/convert/file, requesting both Markdown and
|
||||
structured JSON. do_table_structure is left at Docling's own default
|
||||
(true) - confirmed via its /openapi.json schema.
|
||||
(true) - confirmed via its /openapi.json schema. The content-type is
|
||||
guessed from the file's own extension rather than hardcoded to
|
||||
"application/pdf" - this function also handles raw image uploads (a
|
||||
scanned/photographed statement with no PDF container at all) via
|
||||
Docling's own OCR, confirmed for real to work when sent with its
|
||||
correct image/* content-type.
|
||||
|
||||
Returns the raw response dict: {"document": {"md_content", "json_content",
|
||||
...}, "status", "errors", "confidence", ...}. Raises on a non-2xx
|
||||
response or network/timeout error - callers decide how to surface that
|
||||
(this module doesn't know about Flask error responses).
|
||||
"""
|
||||
content_type = mimetypes.guess_type(pdf_path)[0] or "application/octet-stream"
|
||||
with open(pdf_path, "rb") as f:
|
||||
response = requests.post(
|
||||
f"{docling_url}/v1/convert/file",
|
||||
files={"files": (pdf_path.split("/")[-1], f, "application/pdf")},
|
||||
files={"files": (pdf_path.split("/")[-1], f, content_type)},
|
||||
data={"to_formats": ["md", "json"]},
|
||||
timeout=CONVERT_TIMEOUT,
|
||||
)
|
||||
|
|
@ -70,6 +78,100 @@ def num_pages(json_content):
|
|||
return len(json_content.get("pages", {}))
|
||||
|
||||
|
||||
def _all_field_matches(text):
|
||||
"""Every (field, phrase) hit for one header cell's text, across ALL
|
||||
fields - unlike layout_rules.match_field (which returns only the
|
||||
single overall-best match, the right tool for table_extract.py's own
|
||||
sliding-word-window header detection), this is what lets
|
||||
_resolve_columns tell apart two genuinely different situations that
|
||||
both look like "a field has multiple candidate columns" (see its own
|
||||
docstring): a single cell's text containing vocabulary from more than
|
||||
one semantic field at once (corruption) versus two separately-clean
|
||||
cells that each legitimately match the same field on their own."""
|
||||
text = text.lower()
|
||||
hits = []
|
||||
for field, phrases in layout_rules.COLUMN_FIELD_KEYWORDS.items():
|
||||
for phrase in phrases:
|
||||
if phrase in text:
|
||||
hits.append((field, phrase))
|
||||
break # phrases are longest-first per field - first hit is that field's own best
|
||||
return hits
|
||||
|
||||
|
||||
def _resolve_columns(cells, num_cols, header_row=0):
|
||||
"""{field: col} for one row of a table, treated as the header - each
|
||||
column's semantic role via the same keyword vocabulary table_extract.py
|
||||
uses (layout_rules.py). `header_row` defaults to 0 (true for every
|
||||
cross-check table seen so far - see extract_transactions) but
|
||||
ocr_table_to_rows searches multiple candidate rows with this same
|
||||
function (see its own docstring on why row 0 isn't a safe assumption
|
||||
for an OCR'd page).
|
||||
|
||||
A plain first-match-wins scan over match_field's own single-best
|
||||
result per cell isn't safe here - confirmed necessary for real, two
|
||||
different ways:
|
||||
|
||||
1. SELF-CONTAMINATED cell: on an RBC statement, Docling's own table-
|
||||
structure model mis-segmented a wrapped two-line header ("Cheques
|
||||
& Debits ($)" / "Deposits & Credits ($)") into a phantom extra
|
||||
column, scrambling "Debits"/"Deposits" text across the wrong
|
||||
cells - the resulting cell text ("&Debits ($) Deposits") contains
|
||||
vocabulary from BOTH "debit" and "credit" at once. A column whose
|
||||
text matches more than one distinct field this way is excluded
|
||||
outright - trustworthy for neither - rather than letting whichever
|
||||
field match_field's own internal tie-break happened to rank
|
||||
highest silently claim it (confirmed to pick the WRONG one here:
|
||||
"deposits", 8 characters, outranks "credit", 6, even though the
|
||||
clean credit column is the OTHER cell).
|
||||
|
||||
2. LEGITIMATE duplicate coverage: on an HSBC statement, two entirely
|
||||
separate, individually-CLEAN columns - "Value date" and "Post
|
||||
date" - both genuinely and correctly match the "date" field, with
|
||||
neither cell's text containing any other field's vocabulary at
|
||||
all. Excluding "date" entirely here (as a blanket "any collision
|
||||
means ambiguous" rule would) broke a previously-working column
|
||||
resolution for real - confirmed by running the fixture corpus
|
||||
after that version shipped. The fix: among only the non-
|
||||
contaminated candidates for a field, prefer the one matched by the
|
||||
longer, more specific phrase ("value date" beats the bare "date"
|
||||
fallback keyword); only leave the field genuinely unresolved if
|
||||
that's still a tie.
|
||||
"""
|
||||
col_fields = {}
|
||||
for col in range(num_cols):
|
||||
label = cells.get((header_row, col), "") or ""
|
||||
best = layout_rules.match_field(label)
|
||||
if best is None:
|
||||
continue
|
||||
best_field, best_phrase = best
|
||||
# A losing field's own matched phrase that's simply a SUBSTRING
|
||||
# of the winning phrase isn't a second concept, just a smaller
|
||||
# piece of the same one match_field already picked (confirmed
|
||||
# necessary for real: "Credit amount" matches both "credit" field
|
||||
# via "credit amount" AND "amount" field via the bare "amount"
|
||||
# keyword it happens to contain - "amount" is literally inside
|
||||
# "credit amount", not a separate concept, so this must NOT count
|
||||
# as contamination the way "&Debits ($) Deposits" matching both
|
||||
# "debit" via "debit" and "credit" via "deposits" - two completely
|
||||
# disjoint fragments of text - genuinely does).
|
||||
contaminated = any(
|
||||
phrase not in best_phrase for field, phrase in _all_field_matches(label) if field != best_field
|
||||
)
|
||||
if not contaminated:
|
||||
col_fields[col] = (best_field, best_phrase)
|
||||
|
||||
by_field = {}
|
||||
for col, (field, phrase) in col_fields.items():
|
||||
by_field.setdefault(field, []).append((col, phrase))
|
||||
|
||||
resolved = {}
|
||||
for field, candidates in by_field.items():
|
||||
candidates.sort(key=lambda c: (-len(c[1]), c[0]))
|
||||
if len(candidates) == 1 or len(candidates[0][1]) > len(candidates[1][1]):
|
||||
resolved[field] = candidates[0][0]
|
||||
return resolved
|
||||
|
||||
|
||||
def extract_transactions(table):
|
||||
"""
|
||||
Best-effort transaction list from a Docling-recognized table:
|
||||
|
|
@ -92,18 +194,9 @@ def extract_transactions(table):
|
|||
data = table.get("data", {})
|
||||
num_cols = data.get("num_cols", 0)
|
||||
num_rows = data.get("num_rows", 0)
|
||||
cells = {}
|
||||
for cell in data.get("table_cells", []):
|
||||
key = (cell.get("start_row_offset_idx"), cell.get("start_col_offset_idx"))
|
||||
cells[key] = cell.get("text", "")
|
||||
|
||||
col_for_field = {}
|
||||
for col in range(num_cols):
|
||||
label = cells.get((0, col), "") or ""
|
||||
m = layout_rules.match_field(label)
|
||||
if m:
|
||||
col_for_field.setdefault(m[0], col)
|
||||
cells = table_rows(table)
|
||||
|
||||
col_for_field = _resolve_columns(cells, num_cols)
|
||||
if not layout_rules.has_required_shape(col_for_field.keys()):
|
||||
return []
|
||||
|
||||
|
|
@ -162,3 +255,163 @@ def extract_transactions(table):
|
|||
"balance": money.get("balance"),
|
||||
})
|
||||
return transactions
|
||||
|
||||
|
||||
def ocr_table_to_rows(table, page_no):
|
||||
"""
|
||||
One Docling-recognized page's table reshaped into EXACTLY the row
|
||||
format table_extract.extract_page() produces for a pdfplumber page -
|
||||
{"type": "txn"/"narrative"/"opening_balance"/"closing_balance", ...} -
|
||||
so table_extract.rows_to_transactions() and extract_statement_facts()
|
||||
(already proven correct for the dual-engine path) can run unchanged
|
||||
on OCR'd data too, instead of duplicating that row-grouping/narrative-
|
||||
attachment logic a second time for Docling's shape. Used only when
|
||||
there's no text layer to read at all (see reconcile.py's routing) -
|
||||
here Docling's own result IS the canonical source, not just a
|
||||
cross-check signal, unlike extract_transactions() above.
|
||||
|
||||
A data row is a "txn" if it has any money value, same general-purpose
|
||||
signal table_extract.py uses, with the date forward-filled onto rows
|
||||
that leave it blank (confirmed necessary for real on RBC, which only
|
||||
prints a day's first row with its own date - true of Docling's own
|
||||
row-grouping too).
|
||||
|
||||
Docling's own table-structure model already MERGES most wrapped
|
||||
descriptions into their owning row's single cell (confirmed for real
|
||||
on RBC's own two-line "Regular transaction fee..." row - Docling
|
||||
returned it as one cell, unlike pdfplumber which sees two separate
|
||||
physical text lines) - so the genuinely-separate-row narrative case
|
||||
pdfplumber's _decide_gap exists for is rarer here. HSBC's explicit
|
||||
"Narrative" label convention is still a genuinely separate row though
|
||||
(confirmed for real), detected the same way as pdfplumber - by
|
||||
checking the row's own leftmost non-empty cell against
|
||||
layout_rules.NARRATIVE_LABEL_WORDS - rather than via a resolved
|
||||
"description" column, since HSBC's own header has no such column at
|
||||
all (its narrative always arrives via this separate labeled row, per
|
||||
the same evidence). A non-label row with no money and no resolved
|
||||
description-column content is left unrecognized rather than guessed
|
||||
at by sweeping in unrelated columns (HSBC's own txn rows carry real,
|
||||
unrelated reference numbers in columns that never got a semantic
|
||||
field resolved - treating those as narrative text would misattribute
|
||||
real data, not just miss some).
|
||||
|
||||
The header row is SEARCHED FOR (first row whose own text resolves a
|
||||
usable shape), not assumed to be row 0 - confirmed necessary for
|
||||
real: OCR'ing a rasterized page 1 (with its account-summary preamble
|
||||
above the real transaction table) produced a single Docling table
|
||||
that merged the preamble's own rows in ABOVE the real header row,
|
||||
unlike the clean text-PDF path where Docling always kept them as
|
||||
separate tables. Same search pattern table_extract._find_header_row
|
||||
uses for pdfplumber's own per-line scan, for the same reason.
|
||||
"""
|
||||
data = table.get("data", {})
|
||||
num_cols = data.get("num_cols", 0)
|
||||
num_rows = data.get("num_rows", 0)
|
||||
cells = table_rows(table)
|
||||
|
||||
col_for_field, header_row = {}, None
|
||||
for candidate in range(num_rows):
|
||||
resolved = _resolve_columns(cells, num_cols, header_row=candidate)
|
||||
if layout_rules.has_required_shape(resolved.keys()):
|
||||
col_for_field, header_row = resolved, candidate
|
||||
break
|
||||
if header_row is None:
|
||||
return []
|
||||
|
||||
desc_col = col_for_field.get("description")
|
||||
|
||||
def text_at(row, field):
|
||||
col = col_for_field.get(field)
|
||||
return (cells.get((row, col), "") or "").strip() if col is not None else ""
|
||||
|
||||
def money_at(row, field):
|
||||
col = col_for_field.get(field)
|
||||
if col is None:
|
||||
return None
|
||||
m = _MONEY_RE.search(cells.get((row, col), "") or "")
|
||||
return float(m.group().replace(",", "")) if m else None
|
||||
|
||||
def leftmost_text(row):
|
||||
for col in range(num_cols):
|
||||
text = (cells.get((row, col), "") or "").strip()
|
||||
if text:
|
||||
return col, text
|
||||
return None, ""
|
||||
|
||||
# Same bank-specific sign ambiguity extract_transactions() resolves -
|
||||
# see its own comment for why this is detected rather than assumed.
|
||||
debit_col = col_for_field.get("debit")
|
||||
debit_self_signed = False
|
||||
if debit_col is not None:
|
||||
for row in range(header_row + 1, num_rows):
|
||||
text = cells.get((row, debit_col), "") or ""
|
||||
if _MONEY_RE.search(text) and text.strip().startswith("-"):
|
||||
debit_self_signed = True
|
||||
break
|
||||
|
||||
rows = []
|
||||
last_date = ""
|
||||
for row in range(header_row + 1, num_rows):
|
||||
money = {f: money_at(row, f) for f in _MONEY_FIELDS if f in col_for_field}
|
||||
if money.get("debit") is not None and not debit_self_signed:
|
||||
money["debit"] = -abs(money["debit"])
|
||||
present = {k for k, v in money.items() if v is not None}
|
||||
|
||||
row_date = text_at(row, "date")
|
||||
if row_date:
|
||||
last_date = row_date
|
||||
desc_text = text_at(row, "description")
|
||||
|
||||
if present == {"balance"} and desc_text.lower() in layout_rules.OPENING_BALANCE_PHRASES:
|
||||
rows.append({"type": "opening_balance", "balance": money["balance"]})
|
||||
continue
|
||||
if present == {"balance"} and desc_text.lower() in layout_rules.CLOSING_BALANCE_PHRASES:
|
||||
rows.append({"type": "closing_balance", "balance": money["balance"]})
|
||||
continue
|
||||
|
||||
if present:
|
||||
rows.append({
|
||||
"type": "txn", "date": row_date or last_date, "status": text_at(row, "status"),
|
||||
"inline_description": desc_text,
|
||||
"credit": money.get("credit"), "debit": money.get("debit"),
|
||||
"amount": money.get("amount"), "balance": money.get("balance"),
|
||||
"top": row, "page_no": page_no,
|
||||
})
|
||||
continue
|
||||
|
||||
label_col, label_text = leftmost_text(row)
|
||||
if label_text.lower() in layout_rules.NARRATIVE_LABEL_WORDS:
|
||||
rest = " ".join(
|
||||
t for c in range(label_col + 1, num_cols)
|
||||
if (t := (cells.get((row, c), "") or "").strip())
|
||||
)
|
||||
rows.append({"type": "narrative", "text": rest, "explicit_label": True, "top": row, "page_no": page_no})
|
||||
elif desc_col is not None and desc_text:
|
||||
rows.append({"type": "narrative", "text": desc_text, "explicit_label": False, "top": row, "page_no": page_no})
|
||||
# else: no money, no label, no resolved description column with
|
||||
# content - nothing usable on this row (page furniture, or a
|
||||
# layout this still doesn't generalize to - same honest gap
|
||||
# table_extract.py documents for its own pdfplumber path).
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
def ocr_extract_pdf(pdf_path, docling_url):
|
||||
"""
|
||||
{page_no: [rows...]} for every page of a statement with no text layer
|
||||
at all (a scan, or a phone photo) - Docling's OCR is the PRIMARY (only)
|
||||
extraction source here, unlike its cross-check-only role for a normal
|
||||
text PDF (see reconcile.py's routing). A page Docling didn't structure
|
||||
as a table at all contributes an empty list, same per-page shape as
|
||||
table_extract.extract_pdf's own return value, so callers (table_extract.
|
||||
rows_to_transactions, extract_statement_facts) don't need to know which
|
||||
engine produced the rows they're grouping.
|
||||
"""
|
||||
result = convert(pdf_path, docling_url)
|
||||
json_content = result["document"]["json_content"]
|
||||
if isinstance(json_content, str):
|
||||
json_content = json.loads(json_content)
|
||||
tables = tables_by_page(json_content)
|
||||
total_pages = num_pages(json_content)
|
||||
pages = range(1, total_pages + 1) if total_pages else sorted(tables.keys())
|
||||
return {p: (ocr_table_to_rows(tables[p], p) if p in tables else []) for p in pages}
|
||||
|
|
|
|||
|
|
@ -39,16 +39,27 @@ def _extract_header_info(full_text):
|
|||
def run(pdf_path, docling_url, opening_balance=None, closing_balance=None):
|
||||
"""
|
||||
The full section-3 pipeline for one statement: run both extraction
|
||||
engines and cross-check them (reconcile.py), locate statement-level
|
||||
facts, run the six checks (+ the engine-agreement flag), and return
|
||||
engines and cross-check them (reconcile.py) - or, for an upload with
|
||||
no text layer at all, route through Docling's OCR alone (see
|
||||
reconcile.run/_needs_ocr) - locate statement-level facts, run the
|
||||
checks (+ the engine-agreement or ocr-source flag), and return
|
||||
everything the UI/export need.
|
||||
"""
|
||||
recon = reconcile.run(pdf_path, docling_url)
|
||||
transactions = recon["transactions"]
|
||||
ocr_only = recon.get("extraction_method") == "ocr"
|
||||
|
||||
with pdfplumber.open(pdf_path) as pdf:
|
||||
full_text = "\n".join(p.extract_text(x_tolerance=table_extract.X_TOLERANCE) or "" for p in pdf.pages)
|
||||
header_info = _extract_header_info(full_text)
|
||||
# _extract_header_info's regexes (period range, brought-forward
|
||||
# balance) need pdfplumber's own text layer - genuinely nothing to
|
||||
# read here for an OCR-sourced upload (that's the whole premise), so
|
||||
# header_info just stays empty rather than calling pdfplumber.open()
|
||||
# on a file it may not even be able to parse as a PDF at all (a raw
|
||||
# JPG/PNG upload raises PDFSyntaxError, not an empty result).
|
||||
header_info = {}
|
||||
if not ocr_only:
|
||||
with pdfplumber.open(pdf_path) as pdf:
|
||||
full_text = "\n".join(p.extract_text(x_tolerance=table_extract.X_TOLERANCE) or "" for p in pdf.pages)
|
||||
header_info = _extract_header_info(full_text)
|
||||
|
||||
# A figure the user explicitly supplied always wins; otherwise fall
|
||||
# back to whatever extract_statement_facts found printed inside the
|
||||
|
|
@ -70,6 +81,7 @@ def run(pdf_path, docling_url, opening_balance=None, closing_balance=None):
|
|||
opening_balance=opening_balance, closing_balance=closing_balance,
|
||||
period_start=period_start, period_end=period_end,
|
||||
narrative_direction=recon["narrative_direction"],
|
||||
ocr_only=ocr_only,
|
||||
)
|
||||
|
||||
period_text = None
|
||||
|
|
@ -85,6 +97,7 @@ def run(pdf_path, docling_url, opening_balance=None, closing_balance=None):
|
|||
"opening_balance": opening_balance,
|
||||
"closing_balance": closing_balance,
|
||||
"narrative_direction": recon["narrative_direction"],
|
||||
"extraction_method": recon.get("extraction_method", "dual_engine"),
|
||||
**check_results,
|
||||
}
|
||||
|
||||
|
|
@ -95,7 +108,7 @@ _PERIOD_TEXT_RE = re.compile(r"(.+) to (.+)")
|
|||
def recheck(transactions, page_reports, period_text=None, opening_balance=None, closing_balance=None,
|
||||
narrative_direction=None):
|
||||
"""
|
||||
Re-runs the six checks against a transaction list the user may have
|
||||
Re-runs the checks against a transaction list the user may have
|
||||
edited in the UI (see the web app's inline-editable cells) - without
|
||||
re-running either extraction engine. `page_reports` and
|
||||
`narrative_direction` are passed through unchanged: neither which
|
||||
|
|
@ -105,6 +118,13 @@ def recheck(transactions, page_reports, period_text=None, opening_balance=None,
|
|||
results, so the UI can live-update after an edit and the Excel
|
||||
export can reflect the edited values instead of going stale the
|
||||
moment someone fixes a mistake.
|
||||
|
||||
Whether the original extraction was OCR-sourced is inferred from
|
||||
`page_reports` itself (reconcile._run_ocr_only marks every entry
|
||||
"status": "ocr_only") rather than needing a new field threaded
|
||||
through the UI's save/export round trip - the caller already has to
|
||||
pass page_reports through unchanged for other reasons, so this adds
|
||||
no new surface for the frontend to keep in sync.
|
||||
"""
|
||||
period_start = period_end = None
|
||||
if period_text:
|
||||
|
|
@ -113,9 +133,12 @@ def recheck(transactions, page_reports, period_text=None, opening_balance=None,
|
|||
period_start = checks._parse_date(m.group(1))
|
||||
period_end = checks._parse_date(m.group(2))
|
||||
|
||||
ocr_only = any(pr.get("status") == "ocr_only" for pr in page_reports)
|
||||
|
||||
return checks.run_all(
|
||||
transactions, page_reports,
|
||||
opening_balance=opening_balance, closing_balance=closing_balance,
|
||||
period_start=period_start, period_end=period_end,
|
||||
narrative_direction=narrative_direction,
|
||||
ocr_only=ocr_only,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import pdfplumber
|
||||
|
||||
import table_extract
|
||||
import docling_client
|
||||
|
||||
|
|
@ -9,10 +11,37 @@ def _pdfplumber_page_counts(pages_rows):
|
|||
grouping) is enough here: joining narrative text never changes how
|
||||
many "txn"-type rows a page has, so this is directly comparable to
|
||||
Docling's own per-page transaction count without needing cross-page
|
||||
grouping at all."""
|
||||
grouping at all. Also reused for the OCR-only path's own page
|
||||
counts (see _run_ocr_only) - counting "txn" rows is engine-agnostic."""
|
||||
return {p: sum(1 for r in rows if r["type"] == "txn") for p, rows in pages_rows.items()}
|
||||
|
||||
|
||||
def _needs_ocr(path):
|
||||
"""True if this upload has no usable embedded text to read at all -
|
||||
either because it isn't a PDF container (a raw JPG/PNG phone photo)
|
||||
or because it's a PDF wrapping a scanned/photographed page with no
|
||||
text layer (confirmed for real: pdfplumber.open() raises
|
||||
PDFSyntaxError on a raw image file; a scanned-but-PDF-wrapped page
|
||||
opens fine but extract_text() returns nothing on every page). Both
|
||||
cases need Docling's OCR as the PRIMARY source (there's no
|
||||
pdfplumber pass possible either way) - not just the secondary
|
||||
cross-check role it plays for a normal text PDF.
|
||||
|
||||
Deliberately a narrower, cheaper check than table_extract.extract_pdf
|
||||
itself (which also tries to resolve a recognizable column layout) -
|
||||
conflating "no text at all" with "has text, but this extractor
|
||||
doesn't recognize this particular bank's column layout" would wrongly
|
||||
route the second, different problem through OCR instead of today's
|
||||
actual (and correctly scoped) "only supports HSBC/RBC-shaped layouts"
|
||||
error.
|
||||
"""
|
||||
try:
|
||||
with pdfplumber.open(path) as pdf:
|
||||
return not any((page.extract_text() or "").strip() for page in pdf.pages)
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
def _docling_amount(d):
|
||||
"""A Docling row's credit/debit/amount collapsed into one signed
|
||||
amount, the same shape as the pdfplumber canonical transaction's own
|
||||
|
|
@ -39,9 +68,57 @@ def _compare_amounts(pdf_txns, docling_txns):
|
|||
return mismatches
|
||||
|
||||
|
||||
def _run_ocr_only(pdf_path, docling_url):
|
||||
"""
|
||||
Docling-OCR-primary path for an upload with no embedded text layer at
|
||||
all (see _needs_ocr) - a scan, or a phone photo. There is no
|
||||
pdfplumber pass possible here, so there's no second engine to cross-
|
||||
check against either - Docling's own OCR'd table structure IS the
|
||||
canonical source, reshaped (docling_client.ocr_extract_pdf) into the
|
||||
exact same row format table_extract.extract_page() produces, so
|
||||
rows_to_transactions/extract_statement_facts - already proven correct
|
||||
for the dual-engine path - run completely unchanged rather than
|
||||
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.
|
||||
"""
|
||||
pages_rows = docling_client.ocr_extract_pdf(pdf_path, docling_url)
|
||||
if not any(pages_rows.values()):
|
||||
raise ValueError(
|
||||
"Could not read this statement via OCR - no table structure was recognized in the "
|
||||
"scanned or photographed image. Try a clearer photo, or a text-based PDF export "
|
||||
"if one is available."
|
||||
)
|
||||
all_rows = [r for p in sorted(pages_rows.keys()) for r in pages_rows[p]]
|
||||
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
|
||||
statement_facts = table_extract.extract_statement_facts(all_rows)
|
||||
counts = _pdfplumber_page_counts(pages_rows)
|
||||
page_reports = [
|
||||
{"page": p, "pdfplumber_count": counts.get(p, 0), "docling_count": None,
|
||||
"status": "ocr_only", "mismatches": []}
|
||||
for p in sorted(pages_rows.keys())
|
||||
]
|
||||
return {
|
||||
"transactions": transactions, "page_reports": page_reports, "docling_error": None,
|
||||
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
|
||||
"extraction_method": "ocr",
|
||||
}
|
||||
|
||||
|
||||
def run(pdf_path, docling_url):
|
||||
"""
|
||||
Runs both engines on the same PDF and cross-checks them per page.
|
||||
Runs both engines on the same PDF and cross-checks them per page - or,
|
||||
for an upload with no text layer at all (a scan or phone photo),
|
||||
routes to _run_ocr_only instead, where Docling's OCR is the sole
|
||||
source (see _needs_ocr).
|
||||
|
||||
Returns {"transactions": [...] (the canonical list, from pdfplumber -
|
||||
see table_extract.py and docling_client.py's own docstrings for why),
|
||||
|
|
@ -52,7 +129,7 @@ def run(pdf_path, docling_url):
|
|||
itself - None for a layout like HSBC's that doesn't print these there),
|
||||
"narrative_direction": table_extract.rows_to_transactions's own
|
||||
direction_info - see checks.check_narrative_direction for how it's
|
||||
surfaced}.
|
||||
surfaced, "extraction_method": "dual_engine" or "ocr"}.
|
||||
|
||||
`status` per page is one of:
|
||||
- "ok": both engines found the same transaction count (and, where
|
||||
|
|
@ -62,7 +139,11 @@ def run(pdf_path, docling_url):
|
|||
pdfplumber's result is used with no second opinion.
|
||||
- "mismatch": both engines found a table, but disagree on count or
|
||||
on specific amounts - surfaced for review, never silently resolved.
|
||||
- "ocr_only": no text layer existed at all - see _run_ocr_only.
|
||||
"""
|
||||
if _needs_ocr(pdf_path):
|
||||
return _run_ocr_only(pdf_path, docling_url)
|
||||
|
||||
pages_rows = table_extract.extract_pdf(pdf_path)
|
||||
if not any(pages_rows.values()):
|
||||
# Every page came back completely empty - not "a valid statement
|
||||
|
|
@ -133,4 +214,5 @@ def run(pdf_path, docling_url):
|
|||
return {
|
||||
"transactions": transactions, "page_reports": page_reports, "docling_error": docling_error,
|
||||
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
|
||||
"extraction_method": "dual_engine",
|
||||
}
|
||||
|
|
|
|||
|
|
@ -267,14 +267,14 @@ tr.editing td{ background:rgba(37,99,235,.03); }
|
|||
<main>
|
||||
<div class="eyebrow">Extraction & verification</div>
|
||||
<h1>Bank Statement Extractor</h1>
|
||||
<div class="sub">Upload a bank statement PDF. It structures the transactions, proves the arithmetic against two independent extraction passes, and lets you export it.</div>
|
||||
<div class="sub">Upload a bank statement PDF or photo. A text PDF structures the transactions and proves the arithmetic against two independent extraction passes; a scanned or photographed statement is read via OCR instead, with no second pass to cross-check it against.</div>
|
||||
|
||||
<div class="card upload-card">
|
||||
<h2>Statement PDF</h2>
|
||||
<h2>Statement</h2>
|
||||
<div class="file-zone" id="fileZone">
|
||||
<input type="file" id="fileInput" accept=".pdf,application/pdf">
|
||||
<div class="file-zone-label"><strong>Drop a statement PDF here</strong> or browse</div>
|
||||
<div class="file-zone-sub" id="fileZoneSub">.pdf files only</div>
|
||||
<input type="file" id="fileInput" accept=".pdf,application/pdf,.jpg,.jpeg,.png,image/jpeg,image/png">
|
||||
<div class="file-zone-label"><strong>Drop a statement PDF or photo here</strong> or browse</div>
|
||||
<div class="file-zone-sub" id="fileZoneSub">.pdf, .jpg, or .png files</div>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary" id="processBtn" disabled>Extract</button>
|
||||
|
|
@ -445,8 +445,8 @@ function tryRestore(key) {
|
|||
|
||||
function setFile(file) {
|
||||
if (!file) return;
|
||||
if (!/\.pdf$/i.test(file.name)) {
|
||||
$('errorNote').textContent = 'Please choose a .pdf file.';
|
||||
if (!/\.(pdf|jpe?g|png)$/i.test(file.name)) {
|
||||
$('errorNote').textContent = 'Please choose a .pdf, .jpg, or .png file.';
|
||||
$('errorNote').classList.add('visible');
|
||||
return;
|
||||
}
|
||||
|
|
@ -461,6 +461,10 @@ function setFile(file) {
|
|||
// #toolbar=1 forces the browser's native PDF viewer toolbar (page
|
||||
// nav + zoom controls) on; navpanes=0 skips the thumbnails/bookmarks
|
||||
// sidebar so the toolbar isn't competing for space in a narrow column.
|
||||
// Harmless no-op for an image file in this same iframe - the browser's
|
||||
// native image view ignores an unrecognized hash fragment and just
|
||||
// displays the image, so a scanned/photographed upload still previews
|
||||
// correctly without a separate <img> element or any branching here.
|
||||
$('pdfPreview').src = currentPdfUrl + '#toolbar=1&navpanes=0&view=FitH';
|
||||
|
||||
const key = docKeyFor(file);
|
||||
|
|
|
|||
Loading…
Reference in New Issue