Add per-row source position capture for the review screen's highlighting

R.1 (backend half) of the staged review-screen plan (Phase 2). Every
transaction now carries source_page/source_bbox - purely additive, so
the frontend's upcoming pdf.js viewer can box the exact printed row a
flagged transaction came from.

Traced extraction_service.py first: the canonical transactions list for
a normal text PDF always comes from pdfplumber (table_extract.py);
Docling's own extract_transactions() only feeds the cross-check
confidence signal, never the returned data. So this only needed to
touch table_extract.py and raw_ocr_extract.py (the OCR pixel-position
fallback), zero changes to engine-selection/cross-check logic.

One shared helper, table_extract._line_bbox(), used by both files
(mirrors how raw_ocr_extract.py already reuses _classify_money/_REF_RE
rather than re-implementing them) instead of two separate
implementations that could drift apart. A new _union_bbox() grows a
transaction's box as narrative lines merge into it, both the trailing
direction (HSBC) and leading direction (RBC).

Docling's own OCR-table-structure path doesn't get a real bbox (a
synthetic row-index, not a pixel position) - those transactions get
source_bbox: null, a graceful no-highlight rather than an error.

Verified: measure.py run before/after, byte-identical pass rate and
field accuracy on all three fixtures. A real /api/process call against
both HSBC and RBC fixtures confirmed every existing field unchanged.
Then the check measure.py can't make at all: rendered both fixtures'
pages for real and drew the reported source_bbox on the actual page
image - every box landed on exactly the right printed row, including
HSBC's trailing-narrative merge correctly widening the box.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-10-13 11:18:10 -04:00
parent 9c2dbdf591
commit f65dd3fde0
3 changed files with 141 additions and 9 deletions

View File

@ -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 + 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 |
| 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 **in progress, staged R.1-R.5** (see "Review screen" under Key decisions & lessons) — R.1's backend half (per-row source-position capture) shipped 2026-10-13; the pdf.js highlighting viewer, R.2's plain-language flags, and R.3's suggested-fix engine are not started yet |
| 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 |
@ -218,7 +218,13 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
margin that flags genuinely ambiguous gaps (`ambiguous_indices`) rather than guessing
silently. Also captures opening/closing balance values straight from in-table summary
rows when the statement prints them (RBC-style), as a fallback under the user's own
typed values.
typed values. As of the review-screen R.1 work (2026-10-13), also emits each
transaction's own `source_page`/`source_bbox` - a shared `_line_bbox()` helper
(reused by `raw_ocr_extract.py` too) and a `_union_bbox()` that grows a transaction's
box as narrative lines merge into it; purely additive, read by nothing in this
module's own classification logic, `None` for a row with no real position data (see
"Review screen" under Key decisions & lessons for the full record and the real
visual verification this got).
- `backend/services/extraction_service.py` — runs Docling and pdfplumber on every page in
parallel (not a pipeline — pdfplumber re-reads the PDF's own text layer independently)
and cross-checks them: agreement → high confidence; Docling missed a table but pdfplumber
@ -1282,6 +1288,76 @@ touched). **Not machine-verified:** whether the hover fix actually feels right i
real browser, and the sidebar hierarchy's own click-through (expand/collapse, opening a
document, deleting one) - Claude-in-Chrome still did not connect this session.
**Review screen (Phase 2), staged R.1-R.5 - plan approved 2026-10-13; R.1's backend half
shipped same day.** Competitor analysis (DocuClipper reviews) surfaced "occasional
wrong data" - date confusion, reversed signs, missing balances, discovered by the user
rather than surfaced by the tool - as the loudest non-billing complaint. That's exactly
`docs/bankstatement.md` section 4/5's review screen: plain-language flags, one-click
suggested fixes with evidence, structural row edits, an accept/acknowledge workflow,
and a logged edit history. Confirmed as the next build, ahead of a categorizer feature
(grouping/summing transactions into accounting categories for manual journal entries -
the user's own placed reference material now lives at `docs/bank_statement_categorizer/`,
the actual source of the separate `eib-processor` tool CLAUDE.md's own "What this is"
section already named) - that's a real scope expansion beyond this product's documented
boundary ("does not decide how a transaction should be categorized") and gets its own
plan once the review screen ships, not designed yet.
Staged like the earlier PocketBase B.1-B.3 work, five independently-shippable pieces:
R.1 source-position capture + a highlighting source viewer, R.2 plain-language flags +
navigation, R.3 a suggested-fix engine, R.4 structural row edits, R.5 accept/acknowledge
+ edit log. Full plan at the time of writing: `/Users/jason/.claude/plans/
witty-inventing-walrus.md` (not guaranteed to persist - see the same caveat the original
Phase 1 plan note already makes about this).
**R.1 decision, confirmed via `AskUserQuestion`:** include per-row highlighting on the
source document (not just today's side-by-side panels) - on the explicit condition that
it can't disrupt the existing extraction pipeline's own coordinate/classification logic,
already proven correct against the HSBC/RBC fixture corpus. **Traced the real code
before designing anything:** `extraction_service.py::run()`'s canonical `transactions`
list already always comes from pdfplumber (`table_extract.py`) for a normal text PDF -
Docling's own `extract_transactions()` only feeds the cross-check confidence signal,
never the returned data - so bbox capture needed to touch exactly two files, zero
changes to engine-selection/cross-check logic at all.
**One real design correction during plan review**: the first draft would have
duplicated the same min/max bbox computation in both `table_extract.py` and
`raw_ocr_extract.py`. The user asked directly whether the position-gathering approach
already built for the image/OCR path could be reused for the PDF path too - correct
instinct, and `raw_ocr_extract.py` already demonstrates the right pattern (it imports
`table_extract._classify_money`/`_REF_RE` rather than re-implementing them). Fixed by
factoring one shared `table_extract._line_bbox(line_words)` helper, called from both
`extract_page()`'s row-append sites and `raw_ocr_extract.py`'s own three - one
definition of "a row's own bounding box," not two that could quietly diverge.
**Shipped (R.1 backend half):** `table_extract.py` - new `_line_bbox()` (shared,
described above) and `_union_bbox()` (grows a transaction's own bbox as narrative lines
merge into it, both the "trailing" direction HSBC uses and the "leading" direction RBC
uses - both merge sites in `rows_to_transactions()` updated). Every transaction now
carries `source_page`/`source_bbox`, `null` for a row sourced from Docling's own
OCR-table-structure path (a synthetic row-index, not a real position - graceful
no-highlight, not an error) - everything else about every transaction is completely
unchanged. `raw_ocr_extract.py` calls the same shared helper at its own three
row-append sites.
**Verified, not assumed:** `measure.py` run before and after - byte-identical untouched
pass rate and field accuracy (1.0/1.0, same transaction counts, same statuses) on all
three fixtures, proving zero behavioral change to the five fields already being
measured. A real `/api/process` call against both the HSBC and RBC fixtures through the
rebuilt container confirmed every existing field intact and the two new fields
populated. **Then the one check `measure.py` structurally cannot make, since it never
looks at position data at all**: rendered both fixtures' first page for real
(`pdftoppm`) and drew the reported `source_bbox` as a literal box on the actual page
image for several transactions on each - every box landed exactly on its correct
printed row (including HSBC's own trailing-Narrative-line merge correctly widening the
box to cover both lines, and RBC's tighter, differently-laid-out rows), not just "a
bbox exists" but "it's the right one." This is the real reason the fixture-rendering
discipline this project already uses for ground truth exists - a wrong but non-null
bbox would have passed every other check here.
**Not yet built:** the frontend pdf.js-based viewer (R.1's other half) that will
actually consume these fields to draw the highlight - this backend data has no
consumer yet.
**Governing rule: never silently correct or exclude data.** This shows up in several
concrete places, not just as an abstract principle:
- A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is

View File

@ -153,15 +153,17 @@ def _build_rows(words, lines, zones, header_top, page_no):
"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,
"top": top, "page_no": page_no, "bbox": table_extract._line_bbox(line_words),
})
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})
"explicit_label": True, "top": top, "page_no": page_no,
"bbox": table_extract._line_bbox(line_words)})
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})
rows.append({"type": "narrative", "text": text_all, "explicit_label": False, "top": top, "page_no": page_no,
"bbox": table_extract._line_bbox(line_words)})
return rows

View File

@ -229,6 +229,24 @@ def _classify_money(text, x1, zones):
return None
def _line_bbox(line_words):
"""A line's own bounding box - the union of its words' positions, in
whatever coordinate space those words already carry (PDF points for a
native text layer, already pixel-mapped OCR coordinates for a
scanned/photographed page - see raw_ocr_extract.py, which calls this
same function rather than re-deriving its own). Purely additive
bookkeeping for the review screen's row-highlighting feature - never
read by any classification/geometry decision in this module, so it
carries zero risk of changing what extract_page()/rows_to_transactions()
already decide."""
return {
"x0": min(w["x0"] for w in line_words),
"x1": max(w["x1"] for w in line_words),
"top": min(w["top"] for w in line_words),
"bottom": max(w["bottom"] for w in line_words),
}
def extract_page(page, carry_zones=None, page_no=1):
"""
Returns (rows, zones_used). `rows` is a list of {"type": "txn", "date",
@ -380,7 +398,7 @@ def extract_page(page, carry_zones=None, page_no=1):
"debit": money.get("debit"),
"amount": money.get("amount"),
"balance": money.get("balance"),
"top": top, "page_no": page_no,
"top": top, "page_no": page_no, "bbox": _line_bbox(line_words),
})
elif leftmost["text"].lower() in layout_rules.NARRATIVE_LABEL_WORDS:
# An explicit continuation-text label - usually an otherwise-
@ -391,7 +409,7 @@ def extract_page(page, carry_zones=None, page_no=1):
# closed (see rows_to_transactions).
rows.append({
"type": "narrative", "text": " ".join(w["text"] for w in line_words[1:]),
"explicit_label": True, "top": top, "page_no": page_no,
"explicit_label": True, "top": top, "page_no": page_no, "bbox": _line_bbox(line_words),
})
elif _REF_RE.match(leftmost["text"]):
# A reference-numbered row with no money on it at all - page
@ -401,7 +419,7 @@ def extract_page(page, carry_zones=None, page_no=1):
else:
rows.append({
"type": "narrative", "text": text_all,
"explicit_label": False, "top": top, "page_no": page_no,
"explicit_label": False, "top": top, "page_no": page_no, "bbox": _line_bbox(line_words),
})
return rows, zones
@ -485,6 +503,21 @@ def _decide_gap(buffer, saw_label, preceding_y, following_y):
return "leading", dist_preceding >= dist_following * _GEOMETRY_CONFIDENCE_MARGIN
def _union_bbox(a, b):
"""The smallest box containing both a and b - either may be None (no
position data for that line, e.g. a Docling-OCR-sourced row - see
rows_to_transactions), in which case the other is returned unchanged.
Grows a transaction's own bbox as narrative lines merge into it."""
if a is None:
return b
if b is None:
return a
return {
"x0": min(a["x0"], b["x0"]), "x1": max(a["x1"], b["x1"]),
"top": min(a["top"], b["top"]), "bottom": max(a["bottom"], b["bottom"]),
}
def rows_to_transactions(rows):
"""
Group a page's (or a whole statement's concatenated) rows into
@ -519,16 +552,21 @@ def rows_to_transactions(rows):
if row["type"] == "txn":
row_y = _row_y(row)
leading_texts = []
leading_bboxes = []
leading_ambiguous = False
if buffer or saw_label:
direction, confident = _decide_gap(buffer, saw_label, pending_y, row_y)
texts = [b["text"] for b in buffer]
bboxes = [b.get("bbox") for b in buffer]
if direction == "trailing" and pending is not None:
pending["narr"].extend(texts)
for bx in bboxes:
pending["bbox"] = _union_bbox(pending["bbox"], bx)
if not confident:
pending["_ambiguous"] = True
else:
leading_texts = texts
leading_bboxes = bboxes
leading_ambiguous = not confident
if pending is not None:
transactions.append(pending)
@ -541,9 +579,17 @@ def rows_to_transactions(rows):
amount = row["credit"] if row["credit"] is not None else row["debit"]
inline_desc = row.get("inline_description", "").strip()
narr = leading_texts + ([inline_desc] if inline_desc else [])
# The transaction's own bbox starts as this txn row's own
# position, widened by any leading narrative lines that lead
# into it (trailing ones widen it later, above and below) -
# purely additive bookkeeping, see _line_bbox's own docstring.
row_bbox = row.get("bbox")
for bx in leading_bboxes:
row_bbox = _union_bbox(row_bbox, bx)
pending = {
"date": row["date"], "status": row["status"], "amount": amount,
"balance": row["balance"], "narr": narr,
"page_no": row.get("page_no"), "bbox": row_bbox,
}
if leading_texts and leading_ambiguous:
pending["_ambiguous"] = True
@ -559,7 +605,7 @@ def rows_to_transactions(rows):
saw_label = True
text = row["text"].strip()
if text:
buffer.append({"text": text, "y": _row_y(row)})
buffer.append({"text": text, "y": _row_y(row), "bbox": row.get("bbox")})
# else: "opening_balance"/"closing_balance" rows carry a fact, not
# transaction/narrative content - see extract_statement_facts().
@ -568,6 +614,8 @@ def rows_to_transactions(rows):
# following anchor at all in _decide_gap.
if buffer and pending is not None:
pending["narr"].extend(b["text"] for b in buffer)
for b in buffer:
pending["bbox"] = _union_bbox(pending["bbox"], b.get("bbox"))
if pending is not None:
transactions.append(pending)
@ -580,6 +628,12 @@ def rows_to_transactions(rows):
"description": " ".join(t["narr"]),
"amount": round(t["amount"], 2) if t["amount"] is not None else None,
"balance": round(t["balance"], 2) if t["balance"] is not None else None,
# Purely additive - see _line_bbox's own docstring. None for a
# row sourced from a path with no real position data (today,
# Docling's own OCR-table-structure path); the frontend treats
# that as "no highlight available," not an error.
"source_page": t.get("page_no"),
"source_bbox": t.get("bbox"),
}
for t in transactions
]