bettersight-statement-extra.../backend/services/extraction/layout_rules.py

194 lines
8.6 KiB
Python

# Shared bank-statement column/balance keyword vocabulary used by every extraction engine.
"""
Shared bank-statement column/balance vocabulary - the keyword-dictionary
auto-detector: most banks describe their own columns (and their opening/
closing balance) using a small, predictable set of English phrases, so
this is tried FIRST, before any AI suggestion or manual mapping (per the
"rules first, AI last" principle the rest of this pipeline follows - see
checks_service.py/pipeline_service.py's own docstrings). Shared between
table_extract.py (pdfplumber), docling_parser.py (Docling's table JSON),
and raw_ocr_extract.py (raw OCR word boxes) so every extraction engine
agrees on what a given header label means, rather than each keeping its
own separate hardcoded dictionary (which is how this started - see the
HSBC-only _TEXT_COLUMN_LABELS/_COLUMN_KEYWORDS this replaced).
This resolves COLUMN ROLES only (which column is the date, which is the
balance, etc). It does NOT resolve a bank's own ROW-GROUPING convention -
e.g. whether a transaction's description sits on a separate row following
the amount (HSBC) or wraps onto a line preceding it (RBC) - that is a
structurally different axis of variation, still handled per-bank in
table_extract.py's row-grouping logic, and a real gap on the way to
"universal" (see table_extract.py's own notes on this).
"""
# Column-header vocabulary, by semantic field. "debit"/"credit" are for
# statements with two separate columns; "amount" is for the alternative
# single-signed-amount-column shape - a layout should resolve EITHER
# (debit AND credit) OR (amount), not an arbitrary mix of the two shapes.
# Each field's phrase list is ordered longest/most-specific first.
COLUMN_FIELD_KEYWORDS = {
"date": [
"transaction date", "posting date", "value date", "trans date", "date",
],
"description": [
"transaction details", "particulars", "narrative", "description", "details", "memo",
],
"debit": [
"cheques & debits", "cheques and debits", "debit amount", "withdrawals",
"withdrawal", "payments out", "money out", "debit",
],
"credit": [
"deposits & credits", "deposits and credits", "credit amount", "deposits",
"deposit", "payments in", "money in", "credit",
],
"amount": [
"transaction amount", "amount",
],
"balance": [
"running balance", "balance",
],
"status": [
"trn status", "transaction status", "status",
],
}
# Statement-level (not column-header) text for the opening/closing balance
# figures, usually printed as a standalone summary line rather than a
# table column.
# Words that explicitly introduce a transaction's continuation/narrative
# text on its own line (HSBC's own convention uses "Narrative" - usually
# as an otherwise-empty label line, the real text sitting just above it).
# A layout that uses one of these words reliably means that continuation
# text TRAILS the transaction that already closed; a layout with no such
# label at all falls back to geometric proximity instead (see
# table_extract.rows_to_transactions) - confirmed necessary for real
# since a different bank's own line spacing doesn't reliably make
# "closer" the right signal when a label is present (checked, on HSBC's
# own statement, before falling back to geometry).
NARRATIVE_LABEL_WORDS = {"narrative", "details", "memo", "remarks"}
OPENING_BALANCE_PHRASES = [
"opening balance", "balance brought forward", "opening ledger balance",
"previous balance", "balance b/f",
]
CLOSING_BALANCE_PHRASES = [
"closing balance", "balance carried forward", "closing ledger balance",
"new balance", "balance c/f",
]
# A layout is auto-resolved only if these are all found; "amount" OR
# ("debit" and "credit") covers the two column shapes a statement can use
# for transaction values. "description" is deliberately not required here
# - plenty of real layouts (HSBC) put it on separate rows rather than a
# header-bearing column, so it's resolved by row-grouping, not this check.
REQUIRED_FIELDS = ("date", "balance")
# How many consecutive words a single header label can span - a label can
# be one word ("Balance") or several ("Deposits & Credits ($)").
MAX_LABEL_WINDOW = 4
def match_field(text):
"""
Finds the best (field, phrase) match for one candidate label's text.
Data flow:
text (str) - a candidate header cell/word's own text
returns (tuple) - (field, phrase) for the longest matching phrase
across ALL fields, or None if nothing matches
Steps:
1. Lowercase the input text for case-insensitive matching
2. Scan every field's phrase list (already longest-first per field)
3. Track the single longest phrase match found across all fields -
longest wins across ALL fields, not just within one, so a window
like "Debit Amount" matches the "debit" field's "debit amount"
phrase rather than some other field's shorter, coincidentally-
present substring
"""
text = text.lower()
best = None
for field, phrases in COLUMN_FIELD_KEYWORDS.items():
for phrase in phrases:
if phrase in text:
if best is None or len(phrase) > len(best[1]):
best = (field, phrase)
break # phrases are ordered longest-first per field - first hit is that field's best
return best
def has_required_shape(resolved_fields):
"""
Whether a candidate header row resolves a usable column shape.
Data flow:
resolved_fields (iterable) - field names found on a candidate header row
returns (bool) - True if every REQUIRED_FIELDS entry is
present AND at least one amount-column
shape (debit+credit, or a single amount) is present
"""
if not all(f in resolved_fields for f in REQUIRED_FIELDS):
return False
return "amount" in resolved_fields or ("debit" in resolved_fields and "credit" in resolved_fields)
def match_line_fields(line_words):
"""
Every (field, phrase_len, x0, x1, start_idx, end_idx) candidate match
from sliding 1..MAX_LABEL_WINDOW-word windows across this line against
the shared keyword dictionary - words aren't pre-grouped into cells the
way Docling's table structure is, so every contiguous window is a
candidate. Sorted longest-phrase-first so the greedy resolver below
(resolve_header_matches) prefers the most specific match available.
Relocated from table_extract.py (as _line_field_matches) so
layout_quirks.py can reuse this same line-to-fields resolution without
creating a circular import - table_extract.py calls into
layout_quirks.py, which only ever needs to depend on this module.
"""
candidates = []
n = len(line_words)
for start in range(n):
for length in range(1, MAX_LABEL_WINDOW + 1):
end = start + length
if end > n:
break
window = line_words[start:end]
text = " ".join(w["text"] for w in window)
m = match_field(text)
if m:
field, phrase = m
candidates.append({
"field": field, "phrase_len": len(phrase),
"x0": window[0]["x0"], "x1": window[-1]["x1"],
"start": start, "end": end,
})
# Longest matched phrase wins first; among ties (a wider window can
# still match the same keyword length if it merely contains extra,
# unrelated words alongside it - confirmed for real: "Description
# Cheques & Debits" still contains "cheques & debits" and tied with
# the correct, narrower "Cheques & Debits" window, and being
# generated first, won and swallowed the Description column's own
# word entirely), prefer the NARROWEST window - the tightest match
# for a given phrase length is the correct one.
candidates.sort(key=lambda c: (-c["phrase_len"], c["end"] - c["start"]))
return candidates
def resolve_header_matches(candidates):
"""Greedy non-overlapping assignment: longest-phrase matches win first;
each word claimed by at most one field, each field assigned at most
once. Returns {field: (x0, x1)}. Relocated from table_extract.py (as
_resolve_header_matches) - see match_line_fields's own docstring."""
claimed = set()
resolved = {}
for c in candidates:
if c["field"] in resolved:
continue
word_range = set(range(c["start"], c["end"]))
if word_range & claimed:
continue
resolved[c["field"]] = (c["x0"], c["x1"])
claimed |= word_range
return resolved