From 326b43ba11c4494cacb839bd91345fea0df92d29 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Wed, 14 Oct 2026 08:09:34 -0400 Subject: [PATCH] Add layout-mapper backend contract: fingerprinting + forced-mapping extraction (L.2) Lays the backend groundwork for the layout mapper (no UI/PocketBase yet): when both the keyword detector and the layout_quirks fallback fail on every page, extraction_service.run() now raises LayoutMappingRequired with a computed fingerprint instead of a dead-end error; routes/extraction.py returns this as a 422 with {needs_mapping, fingerprint, fingerprintHash}. run()/pipeline_service.run() gained a forced_mapping parameter that extracts directly from given column positions, bypassing auto-detection entirely - the entry point a future manual mapping screen will use. Two real gaps surfaced by testing against the actual problem statement, not assumed: header_candidate_geometry() scans every page for the best candidate rather than just page 1 (this statement's own page 1 is a pure cover page); a forced mapping had no page-boundary concept, so a cover page's own letterhead merged into the first real transaction - fixed with a new start_page field. Verified: a synthetic unrecognizable PDF correctly triggers the 422 contract through the real running container; the real problem statement, forced through a hand-built mapping, now extracts 36/36 transactions with every check passing, matching the auto-detected L.1 result exactly; measure.py byte-identical on HSBC/RBC throughout. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 106 ++++++++++++- backend/routes/extraction.py | 19 ++- backend/schemas/extraction_schema.py | 18 ++- .../services/extraction/layout_fingerprint.py | 94 +++++++++++ backend/services/extraction/table_extract.py | 149 +++++++++++++++++- backend/services/extraction_service.py | 79 ++++++++-- backend/services/pipeline_service.py | 6 +- 7 files changed, 441 insertions(+), 30 deletions(-) create mode 100644 backend/services/extraction/layout_fingerprint.py diff --git a/CLAUDE.md b/CLAUDE.md index 9040400..67842f4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ to rough effort: |---|---|---| | **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 (R.1-R.5) complete as of 2026-10-13** (see "Review screen"/"R.2"/"R.3"/"R.4"/"R.5" under Key decisions & lessons) — R.1 (source-position capture + the pdf.js highlighting viewer), R.2 (plain-language flags + jump-to-flagged navigation), R.3 (the suggested-fix engine - debit/credit swap, transposed digits, OCR digit misread), R.4 (structural row edits - flip sign, insert, split, merge, delete, behind a "more actions" menu), and R.5 (edit log + acknowledge/accept workflow + an optional Excel "Edits" sheet) all shipped; "date format swapped" and a separate "bulk column fix" both investigated and found not to apply to this pipeline's own data shape (see R.3/R.4's own entries) | -| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2-L.8 (fingerprinting, PocketBase schema, the manual mapping screen, the Layouts page, drift detection, the superuser review screen) not started yet | +| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3-L.8 (PocketBase schema, the manual mapping screen, the Layouts page, drift detection, the superuser review screen) not started yet | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 5 | Free front door, public accuracy page | Not started | | 6 | Append mode, credit cards, multi-account statements | Not started | @@ -144,11 +144,20 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co extraction.py — Blueprint: POST /api/process, /recheck, /export — request in, call a service, response out, no business logic. GET /api/download/ removed 2026-10-13 - (was dead — nothing ever called it, see below) + (was dead — nothing ever called it, see below). As of + the layout-mapper work's L.2 stage (2026-10-14), + /api/process also catches LayoutMappingRequired ahead + of the generic ValueError handler, returning HTTP 422 + with {needs_mapping, fingerprint, fingerprintHash} — + see "Layout mapper" under Key decisions & lessons health.py — GET /health — pings Docling via docling_repository /services extraction_service.py — text-PDF-vs-OCR routing + the dual-engine cross-check - (was reconcile.py) + (was reconcile.py). As of L.2, also owns + LayoutMappingRequired (raised once tiers 1+2 both fail + on every page) and run()'s own forced_mapping=None + parameter, which bypasses auto-detection/layout_quirks + entirely when a layout mapping is supplied checks_service.py — the checks (was checks.py, near-direct relocate) pipeline_service.py — composes extraction_service + checks_service (was pipeline.py); as of 2026-10-13 also calls @@ -173,15 +182,42 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co 2026-10-13 — /api/export now streams straight from an in-memory buffer, see below) /extraction — pure parsing/domain logic, no I/O: - table_extract.py — the pdfplumber extractor (unchanged) - layout_rules.py — shared column/balance keyword vocabulary (unchanged) + table_extract.py — the pdfplumber extractor. As of the layout-mapper + work's L.1/L.2 stages (2026-10-14): calls + layout_quirks.normalize() as a fallback when the + plain single-line header detector finds nothing; + _MONEY_RE accepts an optional leading "$"; + normalize_date()/header_candidate_geometry() are + new; extract_pdf()/extract_page() gained + forced_zones/forced_sign_convention/ + ignored_row_rules/date_format/start_page params, + all no-ops when omitted — see "Layout mapper" + under Key decisions & lessons + layout_rules.py — shared column/balance keyword vocabulary. As of + L.1, also owns the public match_line_fields/ + resolve_header_matches (relocated from + table_extract.py's own private versions, so + layout_quirks.py can depend on this module alone) + layout_quirks.py — NEW 2026-10-14 — modular, independently-addable + fixes for mechanical layout oddities the keyword/ + geometry detector can't see on its own; tried only + after that detector has already failed, so it's a + guaranteed no-op for every statement that already + works + layout_fingerprint.py — NEW 2026-10-14 — compute_fingerprint()/ + fingerprint_hash(), only ever called once tier 1 + AND tier 2 (layout_quirks) have both failed on + every page (see extraction_service.py's own + LayoutMappingRequired) docling_parser.py — the PARSING half of the old docling_client.py (tables_by_page, _resolve_columns, extract_transactions, ocr_table_to_rows, ocr_extract_pdf) — the HTTP call itself moved to docling_repository - raw_ocr_extract.py — the per-page OCR fallback (unchanged logic, import - paths updated) + raw_ocr_extract.py — the per-page OCR fallback. As of L.1, also + shares table_extract.py's own layout_quirks + fallback and normalize_date() via the same + _find_zones() call both engines already use /repositories — the only two real data-access boundaries this app has (no DB — see the restructure note above for why local library calls like pdfplumber/tesserocr/openpyxl are @@ -1999,6 +2035,62 @@ no transaction table - also expected. The real OCR fallback path ground-truth workbook exists yet for the Equals Money PDF - a reasonable follow-up, not a blocker for this stage. +**L.2 shipped same day: fingerprinting + the forced-mapping backend contract (no UI, +no PocketBase schema yet - that's L.3+).** `backend/services/extraction/ +layout_fingerprint.py` (NEW) - `compute_fingerprint()`/`fingerprint_hash()`, only +ever called once tier 1 (keyword detector) AND tier 2 (layout_quirks) have both +failed on every page. A new `LayoutMappingRequired` (in `extraction_service.py`, a +`ValueError` subclass so it's still caught by any not-yet-updated generic handler, +just with a worse message) carries the computed fingerprint; `routes/extraction.py +::process()` catches it ahead of the generic `ValueError` handler and returns HTTP +422 with `{needs_mapping: true, fingerprint, fingerprintHash}`. `extraction_service +.run()`/`pipeline_service.run()` both gained `forced_mapping=None` - when supplied, +`table_extract.extract_pdf()` extracts directly from the given column positions +(`forced_zones`/`forced_sign_convention`/`ignored_row_rules`/`date_format`/ +`start_page`), bypassing auto-detection and `layout_quirks` entirely. New +`table_extract.normalize_date(raw_text, date_format)` - always tries the already- +unambiguous textual/ISO path first (zero change for every statement that already +works), only falling back to a `dmy`/`mdy`/`ymd` hint - which only an explicit +mapping can ever supply, never auto-detection - when that finds nothing and a +numeric date token is present. + +**Two real deviations from the original plan, both found by actually running this +against the real Equals Money PDF, not assumed from reading the code:** +- `table_extract.header_candidate_geometry()` was planned as "page 1 only," but the + real statement that prompted this whole feature has a pure cover/summary page as + its own page 1 - fingerprinting literally page 1 would have produced an empty, + useless fingerprint for the exact case this exists to handle. Fixed by scanning + every page and keeping whichever one matches the most distinct keyword-vocabulary + fields across its own lines - the same "keep the most complete candidate" pattern + `raw_ocr_extract.py`'s own cross-page zone sharing already uses, not a new one. +- A forced mapping has no per-page `header_top` of its own to anchor the existing + "skip anything above the header" preamble filter against. Confirmed for real: the + FIRST attempt at forcing the real Equals Money PDF's column zones produced a + phantom extra "transaction" - page 1's own letterhead/address/legal narrative text + had nothing to anchor a boundary against and got merged forward into the first + real money-bearing row the forced zones happened to match. A one-off + `ignoredRowRules` entry couldn't fix this generally (page 1 has many distinct + narrative lines, not one line worth matching). Fixed by adding `start_page` + (1-based, default 1) to the forced-mapping contract - `extract_pdf()` now skips + every page before it entirely, never classifying it as narrative or transaction + data at all. The layout mapper's own manual screen (L.6, not built yet) will need + to let the user set this, or infer it from which page they're looking at when they + map. + +**Verified, all real:** a hand-built, genuinely-unrecognizable one-page PDF +confirmed `LayoutMappingRequired` raises correctly with a valid (empty) fingerprint, +both calling `extraction_service.run()` directly and through a real `/api/process` +call against the rebuilt container (HTTP 422, a real fingerprint + hash in the +body). The real Equals Money PDF, forced through a hand-built mapping via curl: +the first attempt (no `startPage`) reproduced the phantom-transaction bug above, +confirming it was real; after adding `start_page` and setting `startPage: 2`, the +SAME statement produced 36/36 correct transactions with `statement_balance`/ +`running_balance`/`date_sanity`/`structure_sanity`/`narrative_direction` all +**pass** - matching L.1's own auto-detected result exactly, proving the +forced-mapping contract is functionally equivalent once given the right inputs, not +just "doesn't crash." `backend/measure.py` re-run byte-identical on HSBC/RBC both +before and after the `start_page` addition. + **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 diff --git a/backend/routes/extraction.py b/backend/routes/extraction.py index a09ad82..2b35023 100644 --- a/backend/routes/extraction.py +++ b/backend/routes/extraction.py @@ -8,6 +8,7 @@ from schemas import extraction_schema from schemas.extraction_schema import ValidationError from services import pipeline_service from services import excel_service +from services.extraction_service import LayoutMappingRequired from repositories import file_repository extraction_bp = Blueprint("extraction", __name__, url_prefix="/api") @@ -19,7 +20,8 @@ def process(): Extracts and verifies a freshly-uploaded statement. Data flow: - request (multipart form: statement_file, opening_balance?, closing_balance?) + request (multipart form: statement_file, opening_balance?, closing_balance?, + forced_mapping? - layout mapper work, see extraction_schema) -> extraction_schema.parse_process_request (validate) -> file_repository.save_upload (write to disk) -> pipeline_service.run (extract + check) @@ -33,13 +35,24 @@ def process(): Excel/All - see that route below. """ try: - file_storage, opening_balance, closing_balance = extraction_schema.parse_process_request(request) + file_storage, opening_balance, closing_balance, forced_mapping = extraction_schema.parse_process_request(request) except ValidationError as e: return jsonify({"error": str(e)}), 400 path = file_repository.save_upload(file_storage, dependencies.UPLOAD_FOLDER) try: - result = pipeline_service.run(path, dependencies.DOCLING_URL, opening_balance, closing_balance) + result = pipeline_service.run(path, dependencies.DOCLING_URL, opening_balance, closing_balance, forced_mapping) + except LayoutMappingRequired as e: + # Caught ahead of the generic ValueError handler below (this IS + # a ValueError subclass) - the layout mapper's own entry point: + # tier 1 (keyword detector) and tier 2 (layout_quirks) both + # failed on every page, so the frontend needs the fingerprint to + # look up a stored mapping or open the manual mapping screen, + # not just a dead-end error message. + return jsonify({ + "error": str(e), "needs_mapping": True, + "fingerprint": e.fingerprint, "fingerprintHash": e.fingerprint_hash, + }), 422 except ValueError as e: return jsonify({"error": str(e)}), 400 except Exception as e: diff --git a/backend/schemas/extraction_schema.py b/backend/schemas/extraction_schema.py index 646490c..e6a1cb3 100644 --- a/backend/schemas/extraction_schema.py +++ b/backend/schemas/extraction_schema.py @@ -1,4 +1,5 @@ # Validates and shapes incoming request data for the extraction routes - no business logic beyond that. +import json class ValidationError(Exception): @@ -22,11 +23,15 @@ def parse_process_request(request): Data flow: request (flask.Request) - the incoming POST request - returns (tuple) - (file_storage, opening_balance, closing_balance) + returns (tuple) - (file_storage, opening_balance, closing_balance, forced_mapping) Steps: 1. Require a non-empty "statement_file" field 2. Parse optional opening_balance/closing_balance form fields + 3. Parse optional forced_mapping form field (layout mapper work - + a JSON-stringified {"columnMap", "signConvention"?, + "ignoredRowRules"?, "dateFormat"?}, passed through to + pipeline_service.run unchanged; absent on every normal upload) """ file_storage = request.files.get("statement_file") if not file_storage or not file_storage.filename: @@ -34,7 +39,16 @@ def parse_process_request(request): opening_balance = _opt_float(request.form.get("opening_balance", "").strip() or None) closing_balance = _opt_float(request.form.get("closing_balance", "").strip() or None) - return file_storage, opening_balance, closing_balance + + forced_mapping = None + raw_forced_mapping = request.form.get("forced_mapping", "").strip() + if raw_forced_mapping: + try: + forced_mapping = json.loads(raw_forced_mapping) + except ValueError: + raise ValidationError("forced_mapping must be valid JSON") + + return file_storage, opening_balance, closing_balance, forced_mapping def parse_recheck_request(json_body): diff --git a/backend/services/extraction/layout_fingerprint.py b/backend/services/extraction/layout_fingerprint.py new file mode 100644 index 0000000..edd9d5a --- /dev/null +++ b/backend/services/extraction/layout_fingerprint.py @@ -0,0 +1,94 @@ +""" +Computes a fingerprint for a statement layout the keyword/geometry +detector (and the layout_quirks module) couldn't resolve on their own - +used by the layout mapper (not built yet - this is the backend +contract only) to recognize "this is the same layout as a mapping +someone already created" without a human re-mapping it every time. + +Only ever called on the failure path - extraction_service.py computes +this right before raising LayoutMappingRequired. A statement that +resolves normally (tier 1 or tier 2) never reaches this module at all. +""" +import hashlib +import json + +from services.extraction import layout_rules + +# field_positions are bucketed to this fraction of the page's own width - +# absorbs ordinary pixel/margin jitter between two statements of the same +# template (e.g. a slightly different margin on a continuation page) +# while still distinguishing a genuinely different column layout. +_POSITION_BUCKET = 0.02 +# page dimensions bucketed to the nearest this many points - absorbs +# minor PDF-generator rounding without conflating Letter and A4. +_PAGE_SIZE_BUCKET = 6 + +_MONEY_FIELDS_ORDERED = ("date", "description", "debit", "credit", "amount", "balance", "status") + + +def compute_fingerprint(words, lines_by_top, page_width, page_height): + """ + {header_labels, field_order, field_positions, page_width_bucket, + page_height_bucket, header_line_count, has_status_column, + has_single_amount_column} - see this module's own docstring for how + it's used. Built by resolving EVERY line on the candidate page + against the shared keyword vocabulary and unioning the matches, + since on a failing statement no single line resolves the full + required shape (that's the whole reason a fingerprint is being + computed at all). + """ + resolved_by_x0 = {} + header_labels = [] + header_line_count = 0 + for top in sorted(lines_by_top.keys()): + line_sorted = sorted(lines_by_top[top], key=lambda w: w["x0"]) + resolved = layout_rules.resolve_header_matches(layout_rules.match_line_fields(line_sorted)) + if not resolved: + continue + header_line_count += 1 + for field, (x0, x1) in resolved.items(): + # Earlier (higher on the page) and leftmost wins if the same + # field is somehow matched on more than one line - keeps the + # fingerprint stable rather than picking whichever happened + # to be last in dict-iteration order. + resolved_by_x0.setdefault(field, (x0, x1)) + header_labels.append(" ".join(w["text"] for w in line_sorted)) + + field_order = [f for f in _MONEY_FIELDS_ORDERED if f in resolved_by_x0] + field_positions = {} + for field, (x0, x1) in resolved_by_x0.items(): + center = (x0 + x1) / 2 + bucket = round((center / page_width) / _POSITION_BUCKET) * _POSITION_BUCKET + field_positions[field] = round(bucket, 4) + + return { + "header_labels": sorted(set(label.strip().lower() for label in header_labels if label.strip())), + "field_order": field_order, + "field_positions": field_positions, + "page_width_bucket": round(page_width / _PAGE_SIZE_BUCKET) * _PAGE_SIZE_BUCKET, + "page_height_bucket": round(page_height / _PAGE_SIZE_BUCKET) * _PAGE_SIZE_BUCKET, + "header_line_count": header_line_count, + "has_status_column": "status" in resolved_by_x0, + "has_single_amount_column": "amount" in resolved_by_x0, + } + + +def fingerprint_hash(fingerprint): + """ + SHA-256 hex of the canonical JSON of the fields that define "this is + the SAME layout" for exact-match lookups - deliberately excludes + page_width_bucket/page_height_bucket/header_line_count (these can + vary innocuously, e.g. a slightly taller continuation page, without + the layout itself having changed) while keeping them in the stored + fingerprint object for the separate, looser near-match comparison + (frontend-only, see the layout mapper's own plan). + """ + hashed_fields = { + "header_labels": fingerprint["header_labels"], + "field_order": fingerprint["field_order"], + "field_positions": fingerprint["field_positions"], + "has_status_column": fingerprint["has_status_column"], + "has_single_amount_column": fingerprint["has_single_amount_column"], + } + canonical = json.dumps(hashed_fields, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() diff --git a/backend/services/extraction/table_extract.py b/backend/services/extraction/table_extract.py index 13509c5..24f9b42 100644 --- a/backend/services/extraction/table_extract.py +++ b/backend/services/extraction/table_extract.py @@ -228,6 +228,57 @@ def _normalize_date_text(text): return f"{day:02d} {_MONTH_ABBR[month - 1]} {year}" +# A looser numeric date shape than _NUMERIC_DATE_RE - any of the 3 groups +# could be the year, so this is only ever read with an explicit +# date_format hint from a layout mapping (never auto-detected), since a +# bare "03/04/26" genuinely IS ambiguous (day-first vs month-first) - +# exactly the human decision the manual mapping screen exists to make. +_GENERIC_NUMERIC_DATE_RE = re.compile(r"^(\d{1,4})[/-](\d{1,2})[/-](\d{1,4})$") + + +def normalize_date(raw_text, date_format="textual"): + """ + Converts raw date text to the canonical "DD Mon YYYY" shape every + downstream consumer (checks_service, suggested_fixes_service) already + expects - called from extract_page()'s own row loop in place of a + bare _normalize_date_text() call so a layout mapping (review screen/ + layout-mapper work) can supply a date_format hint for a statement + whose dates are NOT already unambiguous. + + date_format: + "textual" (default) - today's behavior exactly: try the always-safe + _normalize_date_text() (unambiguous YYYY/MM/DD or YYYY-MM-DD, + 4-digit year required) and otherwise pass the text through + unchanged (HSBC/RBC's own "DD Mon[ YYYY]" text, already fine). + "dmy"/"mdy"/"ymd" - only ever set by an explicit layout mapping + (not auto-detected) for a statement whose dates are genuinely + ambiguous without a human's say - tried only after the always- + safe path above finds nothing to do, using the hint to decide + which of three numeric groups is the day/month/year. + """ + normalized = _normalize_date_text(raw_text) + if normalized != raw_text or date_format == "textual": + return normalized + + m = _GENERIC_NUMERIC_DATE_RE.match(raw_text) + if not m: + return raw_text + a, b, c = int(m.group(1)), int(m.group(2)), int(m.group(3)) + if date_format == "dmy": + day, month, year = a, b, c + elif date_format == "mdy": + month, day, year = a, b, c + elif date_format == "ymd": + year, month, day = a, b, c + else: + return raw_text + if year < 100: + year += 2000 + if not (1 <= month <= 12): + return raw_text + return f"{day:02d} {_MONTH_ABBR[month - 1]} {year}" + + 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 @@ -246,7 +297,7 @@ def _line_bbox(line_words): } -def extract_page(page, carry_zones=None, page_no=1): +def extract_page(page, carry_zones=None, page_no=1, ignored_row_rules=None, date_format="textual"): """ Returns (rows, zones_used). `rows` is a list of {"type": "txn", "date", "status", "credit", "debit", "amount", "balance"} or {"type": @@ -254,6 +305,11 @@ def extract_page(page, carry_zones=None, page_no=1): page's own derived zones, or `carry_zones` if this page had no resolvable header of its own - None if no zones are available at all. + `ignored_row_rules`/`date_format` are only ever non-default when a + layout mapping supplies them (see extract_pdf's own docstring) - both + are no-ops for every statement that auto-detects its own header, + which never passes these through at all. + A row is a transaction ("txn") if it has a value in ANY money field (debit, credit, amount, or balance) - not a bank-specific reference- number pattern (the HSBC-only version this replaced required a @@ -346,6 +402,12 @@ def extract_page(page, carry_zones=None, page_no=1): continue if text_all in _HEADER_BOILERPLATE: continue + # A layout mapping can name specific lines to skip outright (a + # footer/disclaimer the auto-detector has no generic rule for) - + # never engaged by auto-detection, so this is a no-op whenever + # ignored_row_rules isn't explicitly supplied. + if ignored_row_rules and any(rule in text_all for rule in ignored_row_rules): + continue date_parts, status_parts, desc_parts = [], [], [] money = {} @@ -363,7 +425,7 @@ def extract_page(page, carry_zones=None, page_no=1): elif descz and descz[0] <= w["x0"] <= descz[1]: desc_parts.append(w["text"]) - row_date = _normalize_date_text(" ".join(date_parts)) + row_date = normalize_date(" ".join(date_parts), date_format) if row_date: last_date = row_date @@ -424,22 +486,99 @@ def extract_page(page, carry_zones=None, page_no=1): return rows, zones -def extract_pdf(pdf_path): +def extract_pdf(pdf_path, forced_zones=None, forced_sign_convention=None, ignored_row_rules=None, + date_format="textual", start_page=1): """ {page_no (1-based): [rows...]} for every page of the PDF, using extract_page() with zones carried forward across pages that lack a resolvable header of their own. + + `forced_zones`/`forced_sign_convention`/`ignored_row_rules`/ + `date_format`/`start_page` are all layout-mapper concerns (review + screen/layout mapper work) - every argument defaults to "do nothing + extra," so a normal call with none of them behaves exactly as + before. When `forced_zones` is given (the keyword/geometry + auto-detector already failed on every page, that's why a mapping + exists at all), it seeds the carried-forward zones BEFORE page 1 + instead of starting from `None` - the existing + `found_zones.setdefault(field, zone)` gap-fill logic in + extract_page() is untouched, so a page that DOES still resolve + something of its own (a continuation page's own clean header, say) + keeps taking priority over the forced mapping for whatever it finds, + exactly like carrying zones forward already works between ordinary + pages today. + + `start_page` (1-based, default 1) exists because a forced mapping + has no per-page `header_top` of its own to anchor extract_page's + existing "skip anything above the header" preamble filter against - + confirmed necessary for real: a cover/summary page (an Equals Money + statement's own page 1, with no table at all) produced a phantom + extra "transaction" under a forced mapping, because its own + letterhead/address/legal narrative text had nothing to anchor a + boundary against and got merged forward into the first real + money-bearing row the forced zones happened to match. Pages before + `start_page` are skipped entirely - never classified as narrative OR + transaction data, the same as "above this page's own header row" + already is for the auto-detected case. """ import pdfplumber result = {} - zones = None + zones = dict(forced_zones) if forced_zones else None + if zones is not None and forced_sign_convention is not None: + zones.setdefault("_debit_self_signed", forced_sign_convention.get("debitSelfSigned", True)) with pdfplumber.open(pdf_path) as pdf: for i, page in enumerate(pdf.pages, start=1): - rows, zones = extract_page(page, carry_zones=zones, page_no=i) + if i < start_page: + result[i] = [] + continue + rows, zones = extract_page( + page, carry_zones=zones, page_no=i, + ignored_row_rules=ignored_row_rules, date_format=date_format, + ) result[i] = rows return result +def header_candidate_geometry(pdf_path): + """ + (words, lines_by_top, page_width, page_height) for whichever page of + this PDF looks MOST header-like - deliberately not just page 1: + confirmed for real (an Equals Money account statement) that a real + statement can open with a pure cover/summary page that has no table + at all, before the real header ever appears. Scores each page by how + many distinct keyword-vocabulary fields its own lines collectively + match (unioned across every line on that page, since this is only + ever called once the normal single-line detector has already failed + everywhere - see layout_fingerprint.py, the only caller), keeping + whichever page scores highest. Same "keep the most complete + candidate" shape raw_ocr_extract.py's own cross-page zone-sharing + already uses, not a new pattern. Returns None if no page has any + extractable words at all (shouldn't happen here - a page with no + text at all would have already routed through OCR instead). + """ + import pdfplumber + best = None + best_score = -1 + with pdfplumber.open(pdf_path) as pdf: + for page in pdf.pages: + page = page.dedupe_chars() + words = page.extract_words(x_tolerance=X_TOLERANCE) + if not words: + continue + lines = {} + for w in words: + lines.setdefault(round(w["top"]), []).append(w) + matched_fields = set() + for line in lines.values(): + line_sorted = sorted(line, key=lambda w: w["x0"]) + resolved = layout_rules.resolve_header_matches(layout_rules.match_line_fields(line_sorted)) + matched_fields |= set(resolved.keys()) + if len(matched_fields) > best_score: + best = (words, lines, page.width, page.height) + best_score = len(matched_fields) + return best + + # How much smaller the winning side's gap has to be, relative to the # losing side's, to call a geometric decision confident rather than a # close call worth flagging (e.g. 1.3 means the far side must be at diff --git a/backend/services/extraction_service.py b/backend/services/extraction_service.py index 4c7548f..c2c0a90 100644 --- a/backend/services/extraction_service.py +++ b/backend/services/extraction_service.py @@ -4,11 +4,33 @@ import pdfplumber from services.extraction import table_extract from services.extraction import docling_parser from services.extraction import raw_ocr_extract +from services.extraction import layout_fingerprint from repositories import docling_repository AMOUNT_TOLERANCE = 0.01 +class LayoutMappingRequired(ValueError): + """ + Raised instead of the plain "could not recognize this layout" error + when BOTH the keyword/geometry auto-detector AND the layout_quirks + fallback have failed on every page - the layout mapper's own entry + point (not built yet; this is the backend contract it depends on, + see CLAUDE.md's "Layout mapper" entry). Carries the computed + fingerprint so the frontend can look up (or later save) a mapping + without re-deriving it. A ValueError subclass so existing + `except ValueError` handlers that haven't been updated yet still + catch it (as the old generic error, with a worse message) rather + than crashing with an unhandled exception - routes/extraction.py + adds a more specific handler ahead of that fallback. + """ + + def __init__(self, fingerprint, fingerprint_hash): + super().__init__("Could not recognize this statement's column layout.") + self.fingerprint = fingerprint + self.fingerprint_hash = fingerprint_hash + + def _pdfplumber_page_counts(pages_rows): """{page_no: txn-row count} - counting raw rows (before narrative grouping) is enough here: joining narrative text never changes how @@ -165,13 +187,21 @@ def _try_raw_ocr_fallback(file_path): return None -def run(file_path, docling_url): +def run(file_path, docling_url, forced_mapping=None): """ 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). + `forced_mapping` ({"columnMap", "signConvention"?, "ignoredRowRules"?, + "dateFormat"?} or None) - supplied by the layout mapper (not built + yet; this is the backend contract) when a statement's layout needed + a human (or a previously-saved mapping) to resolve, bypassing the + keyword/geometry auto-detector and layout_quirks fallback entirely + and extracting directly from the given column positions instead. A + normal call with no forced_mapping behaves exactly as before. + Returns {"transactions": [...] (the canonical list, from pdfplumber - see table_extract.py and docling_parser.py's own docstrings for why), "page_reports": [{"page", "pdfplumber_count", "docling_count", @@ -197,16 +227,43 @@ def run(file_path, docling_url): if _needs_ocr(file_path): return _run_ocr_only(file_path, docling_url) - pages_rows = table_extract.extract_pdf(file_path) - if not any(pages_rows.values()): - # Every page came back completely empty - not "a valid statement - # with no transactions this period" (that still produces page - # furniture/narrative rows, since table_extract only returns [] - # for a page where it never found a recognizable header at all). - # Confirmed for real: uploading an RBC statement - a different - # column layout this extractor doesn't know about yet - silently - # produced zero transactions instead of telling the user why. - raise ValueError("Could not recognize this statement's column layout.") + if forced_mapping: + pages_rows = table_extract.extract_pdf( + file_path, + forced_zones=forced_mapping.get("columnMap"), + forced_sign_convention=forced_mapping.get("signConvention"), + ignored_row_rules=forced_mapping.get("ignoredRowRules"), + date_format=forced_mapping.get("dateFormat", "textual"), + start_page=forced_mapping.get("startPage", 1), + ) + if not any(pages_rows.values()): + # The mapping itself didn't produce anything - a bad column + # selection, not "this layout needs mapping" (we already have + # one). Distinct message, and deliberately NOT + # LayoutMappingRequired again - raising that here would loop + # the mapper back on itself instead of surfacing the real + # problem (the mapping the user just built/picked is wrong). + raise ValueError("This mapping produced no transaction rows - check the column selections.") + else: + pages_rows = table_extract.extract_pdf(file_path) + if not any(pages_rows.values()): + # Every page came back completely empty - not "a valid statement + # with no transactions this period" (that still produces page + # furniture/narrative rows, since table_extract only returns [] + # for a page where it never found a recognizable header at all). + # Confirmed for real: uploading an RBC statement - a different + # column layout this extractor doesn't know about yet - silently + # produced zero transactions instead of telling the user why. + # As of the layout-mapper work, this is the signal that tier + # 1 (keyword detector) AND tier 2 (layout_quirks) have both + # failed - compute a fingerprint so tier 3/4 (a stored + # mapping, or the manual mapping screen) have something to + # key off of, rather than a bare, unrecoverable error. + geometry = table_extract.header_candidate_geometry(file_path) + if geometry is None: + raise ValueError("Could not recognize this statement's column layout.") + fingerprint = layout_fingerprint.compute_fingerprint(*geometry) + raise LayoutMappingRequired(fingerprint, layout_fingerprint.fingerprint_hash(fingerprint)) 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) diff --git a/backend/services/pipeline_service.py b/backend/services/pipeline_service.py index 67ac656..3762f13 100644 --- a/backend/services/pipeline_service.py +++ b/backend/services/pipeline_service.py @@ -39,7 +39,7 @@ def _extract_header_info(full_text): return result -def run(file_path, docling_url, opening_balance=None, closing_balance=None): +def run(file_path, docling_url, opening_balance=None, closing_balance=None, forced_mapping=None): """ The full section-3 pipeline for one statement: run both extraction engines and cross-check them (extraction_service.py) - or, for an @@ -53,10 +53,12 @@ def run(file_path, docling_url, opening_balance=None, closing_balance=None): docling_url (str) - base URL of the self-hosted Docling container opening_balance (float or None) - user-supplied, wins over anything auto-detected closing_balance (float or None) - user-supplied, wins over anything auto-detected + forced_mapping (dict or None) - a layout mapping to extract with directly, + bypassing auto-detection - see extraction_service.run returns (dict) - transactions, page_reports, checks, status, period, balances, extraction_method """ - recon = extraction_service.run(file_path, docling_url) + recon = extraction_service.run(file_path, docling_url, forced_mapping=forced_mapping) transactions = recon["transactions"] ocr_only = recon.get("extraction_method") == "ocr"