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

129 lines
5.8 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")
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)