bettersight-statement-extra.../app/table_extract.py

587 lines
26 KiB
Python

import re
import layout_rules
X_TOLERANCE = 1.5
_MONEY_RE = re.compile(r"^-?[\d,]+\.\d{2}$")
_REF_RE = re.compile(r"^\d{6,}$")
# Two real page-footer pagination patterns seen so far: "Page N of M"
# (HSBC) and a bare "N of M" with no leading word at all (confirmed on a
# real RBC statement) - the second is only treated as a footer when it's
# the ENTIRE line's content, not a substring, so real narrative text
# that happens to contain "3 of 4" in passing isn't swept up by accident.
_PAGE_FOOTER_RE = re.compile(r"Page \d+ of \d+")
_BARE_PAGE_FOOTER_RE = re.compile(r"^\d+ of \d+$")
_HEADER_BOILERPLATE = {"| Statement details", "Customer", "reference"}
_MONEY_FIELDS = ("debit", "credit", "amount", "balance")
_MAX_LABEL_WINDOW = 4
def _line_field_matches(line_words):
"""
Every (field, phrase_len, x0, x1, start_idx, end_idx) candidate match
from sliding 1..4-word windows across this line against the shared
keyword dictionary (layout_rules.py) - a header label can be one word
("Balance") or several ("Deposits & Credits ($)"), and 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 prefers the most specific match available.
"""
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 = layout_rules.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)}."""
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
def _find_header_row(lines_by_top):
"""
(header_row_words, header_top, resolved_fields) for the first line
whose keyword-dictionary matches satisfy layout_rules.has_required_shape
(a date, a balance, and either debit+credit or a single amount column),
or (None, None, None) if no line on this page resolves that shape.
This is the keyword-dictionary auto-detector - no bank-specific literal
text matching, unlike the HSBC-only version this replaced.
"""
for top, line in lines_by_top.items():
line_sorted = sorted(line, key=lambda w: w["x0"])
resolved = _resolve_header_matches(_line_field_matches(line_sorted))
if layout_rules.has_required_shape(resolved):
return line_sorted, top, resolved
return None, None, None
def _assign_money_columns(labels, clusters, max_distance=60):
"""
labels: [(field, label_x1), ...]; clusters: [(min_x1, max_x1), ...].
Matches each label to at most one cluster, each cluster to at most one
label, preserving left-to-right order on both sides (confirmed on a
real statement that a label's OWN position isn't reliably closest to
its own data's cluster, so each label picking its single nearest
cluster independently can let two different labels claim the same
one - this is a proper order-preserving minimum-cost assignment
instead, with unassigned labels left out rather than forced).
"""
n, m = len(labels), len(clusters)
mids = [((c[0] + c[1]) / 2) for c in clusters]
INF = float("inf")
dp = [[0.0] * (m + 1) for _ in range(n + 1)]
choice = [[None] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(m + 1):
skip_cost = dp[i - 1][j] + max_distance
best, best_choice = skip_cost, "skip"
if j >= 1 and dp[i - 1][j - 1] < INF:
d = abs(mids[j - 1] - labels[i - 1][1])
if d <= max_distance:
cost = dp[i - 1][j - 1] + d
if cost < best:
best, best_choice = cost, j - 1
dp[i][j], choice[i][j] = best, best_choice
assignments = {}
i, j = n, m
while i > 0:
c = choice[i][j]
if c == "skip":
i -= 1
else:
assignments[labels[i - 1][0]] = clusters[c]
i, j = i - 1, c
return assignments
def _cluster_by_gap(values, gap=15):
"""Sorted values split into groups wherever the gap to the previous
value exceeds `gap` - finds each money column's own natural x1
cluster directly from the data (right-aligned numeric columns land in
a tight, consistent x1 band regardless of how many digits a given
value has)."""
if not values:
return []
values = sorted(values)
clusters = [[values[0]]]
for v in values[1:]:
if v - clusters[-1][-1] > gap:
clusters.append([v])
else:
clusters[-1].append(v)
return clusters
def _find_zones(page_words, lines_by_top):
"""
{"date": (x0,x1), "status": ..., "debit"/"credit"/"amount": ...,
"balance": ...} derived fresh from this page via the keyword-
dictionary auto-detector: text-ish fields (date, status) come from
the header label's own position with generous padding; money fields
(whichever of debit/credit/amount/balance the header resolved) come
from clustering the actual money-shaped words' own x1 positions on
this page, then an order-preserving assignment to labels (see
_assign_money_columns) rather than trusting each label's own position
directly.
Returns (None, None) if this page's header doesn't resolve to a
usable shape at all - the caller falls back to carried-forward zones,
or ultimately to the manual mapper if nothing ever resolves.
"""
header_row, header_top, resolved = _find_header_row(lines_by_top)
if header_row is None:
return None, None
zones = {}
for field in ("date", "status", "description"):
anchor = resolved.get(field)
if anchor:
zones[field] = (anchor[0] - 5, anchor[1] + 15)
# Page 1 can carry an account-summary preamble ABOVE the header row
# that repeats balance figures - those are money-shaped too and would
# otherwise form a phantom extra cluster. Anything above the header
# row itself isn't transaction data.
money_x1 = [w["x1"] for w in page_words if _MONEY_RE.match(w["text"]) and w["top"] > header_top]
cluster_ranges = [(min(c), max(c)) for c in _cluster_by_gap(money_x1)]
cluster_ranges.sort(key=lambda r: (r[0] + r[1]) / 2)
money_labels = [(field, resolved[field][1]) for field in _MONEY_FIELDS if field in resolved]
money_labels.sort(key=lambda fl: fl[1])
assigned = _assign_money_columns(money_labels, cluster_ranges)
for field, (cmin, cmax) in assigned.items():
zones[field] = (cmin - 80, cmax + 5)
# Some banks' debit column already prints its own leading minus sign
# (confirmed: HSBC); others print a plain positive magnitude that
# needs explicit negation when combined into one signed amount
# (confirmed: RBC) - this is detected from the real text rather than
# assumed, since forcing one convention onto the other bank either
# double-negates (flips back positive) or leaves a debit positive.
# Only "debit" has this ambiguity - "amount" is already the full
# signed value by definition, and "credit" is never negated.
if "debit" in zones:
zones["_debit_self_signed"] = any(
_MONEY_RE.match(w["text"]) and zones["debit"][0] <= w["x1"] <= zones["debit"][1] and w["text"].startswith("-")
for w in page_words
)
# Description is typically a wide column - widen its zone to span
# from the end of the date/status zone(s) to the start of the
# leftmost money zone, rather than just padding its own (often much
# shorter) header label text. Confirmed necessary for real: a
# layout like RBC's "Description" label is far narrower than the
# actual column of text beneath it.
if "description" in zones:
left_bound = max([zones[f][1] for f in ("date", "status") if f in zones], default=zones["description"][0])
money_starts = [zones[f][0] for f in _MONEY_FIELDS if f in zones]
right_bound = min(money_starts) if money_starts else zones["description"][1]
if right_bound > left_bound:
zones["description"] = (left_bound, right_bound)
return zones, header_top
def _classify_money(text, x1, zones):
if not _MONEY_RE.match(text):
return None
for field in _MONEY_FIELDS:
z = zones.get(field)
if z and z[0] <= x1 <= z[1]:
return field, float(text.replace(",", ""))
return None
def extract_page(page, carry_zones=None, page_no=1):
"""
Returns (rows, zones_used). `rows` is a list of {"type": "txn", "date",
"status", "credit", "debit", "amount", "balance"} or {"type":
"narrative", "text"} in top-to-bottom order. `zones_used` is this
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.
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
leading 6+ digit number, which simply doesn't exist on every bank's
layout). This is a strictly more general signal: every real HSBC
transaction row already has a money value, so this doesn't change
HSBC's own behavior at all, while also recognizing a transaction row
on a layout with no reference-number column. The date is
forward-filled onto money-bearing rows that have no date text of
their own (a no-op for HSBC, where every row has its own date; needed
for a layout like RBC's, which leaves it blank after a day's first
transaction).
What this does NOT yet generalize: a bank's own ROW-GROUPING
convention for multi-line descriptions. Narrative text attaching to
the transaction BEFORE it (via a literal "Narrative" label, as HSBC
does) is still the only pattern handled - a layout that wraps
descriptions onto a line BEFORE the amount (as RBC does) will still
produce no description text for those transactions. That's a
separate, real gap, not solved by column-role detection alone.
"""
page = page.dedupe_chars()
words = page.extract_words(x_tolerance=X_TOLERANCE)
lines = {}
for w in words:
lines.setdefault(round(w["top"]), []).append(w)
found_zones, header_top = _find_zones(words, lines)
if found_zones is not None and carry_zones is not None:
# This page found its OWN header, but a field resolved on an
# earlier page might be missing from it - confirmed for real: a
# continuation page's "Description" header label can print on
# its own separate physical line from the rest of the header
# ("Date ... Balance ($)"), so this page's own header matching
# never resolves a description zone at all even though the real
# description text is right there on every transaction row.
# Only fills gaps - anything this page DID resolve is trusted
# over the carried-forward value, in case a layout genuinely
# shifts page to page (confirmed necessary for RBC, unlike HSBC).
for field, zone in carry_zones.items():
found_zones.setdefault(field, zone)
zones = found_zones or carry_zones
if zones is None:
return [], None
rows = []
last_date = ""
for top in sorted(lines.keys()):
# Anything at or above this page's own header row - an account-
# summary preamble, "Opening/Closing balance" lines, repeated
# totals - isn't transaction data. Confirmed for real: an RBC
# statement's own summary block has dollar figures that land
# inside the real table's zones, and its own header ROW text
# ("Date Description Cheques & Debits...") would otherwise get
# swept up as narrative - both skipped here by position, not by
# bank-specific literal text matching. Only applies when this
# page's header was found fresh (found_zones is not None) - a
# page using carried-forward zones has no header line of its own
# to filter against.
if found_zones is not None and top <= header_top:
continue
line_words = sorted(lines[top], key=lambda w: w["x0"])
leftmost = line_words[0]
text_all = " ".join(w["text"] for w in line_words)
if _PAGE_FOOTER_RE.search(text_all) or _BARE_PAGE_FOOTER_RE.match(text_all.strip()):
continue
if leftmost["text"] == "Bank":
continue
if text_all in _HEADER_BOILERPLATE:
continue
date_parts, status_parts, desc_parts = [], [], []
money = {}
for w in line_words:
amount = _classify_money(w["text"], w["x1"], zones)
if amount:
field, value = amount
money[field] = value
continue
dz, sz, descz = zones.get("date"), zones.get("status"), zones.get("description")
if dz and dz[0] <= w["x0"] <= dz[1]:
date_parts.append(w["text"])
elif sz and sz[0] <= w["x0"] <= sz[1]:
status_parts.append(w["text"])
elif descz and descz[0] <= w["x0"] <= descz[1]:
desc_parts.append(w["text"])
row_date = " ".join(date_parts)
if row_date:
last_date = row_date
if money.get("debit") is not None and not zones.get("_debit_self_signed", True):
money["debit"] = -abs(money["debit"])
# An "Opening balance"/"Closing balance" summary line has a
# balance value and nothing else (no credit/debit/amount) -
# confirmed for real: without this check, a layout like RBC's
# (which prints these as ordinary rows inside the same table,
# unlike HSBC) gets them miscounted as two extra transactions.
# Its value is captured (not just discarded) so the statement
# balance check can use it automatically instead of asking the
# user to type in a figure the statement already printed.
row_text_lower = (" ".join(desc_parts) or text_all).strip().lower()
if set(money.keys()) == {"balance"} and row_text_lower in layout_rules.OPENING_BALANCE_PHRASES:
rows.append({"type": "opening_balance", "balance": money["balance"]})
continue
if set(money.keys()) == {"balance"} and row_text_lower in layout_rules.CLOSING_BALANCE_PHRASES:
rows.append({"type": "closing_balance", "balance": money["balance"]})
continue
if money:
rows.append({
"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,
})
elif leftmost["text"].lower() in layout_rules.NARRATIVE_LABEL_WORDS:
# An explicit continuation-text label - usually an otherwise-
# empty line (the real text sits on the unlabeled line just
# above it), so its own text contributes nothing extra here,
# but its PRESENCE is itself the reliable signal: this
# bank's own convention trails the transaction that already
# 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,
})
elif _REF_RE.match(leftmost["text"]):
# A reference-numbered row with no money on it at all - page
# furniture or a row this layout doesn't expect, not useful
# either as a transaction or as narrative text.
continue
else:
rows.append({
"type": "narrative", "text": text_all,
"explicit_label": False, "top": top, "page_no": page_no,
})
return rows, zones
def extract_pdf(pdf_path):
"""
{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.
"""
import pdfplumber
result = {}
zones = None
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)
result[i] = rows
return result
# 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
# least 30% bigger than the near side).
_GEOMETRY_CONFIDENCE_MARGIN = 1.3
def _row_y(row):
"""A page-spanning vertical position for distance comparisons - page
number dominates so two rows on different pages never compare as
"close" just because their own in-page top values happen to be
near each other."""
return row["page_no"] * 10000 + row["top"]
def _decide_gap(buffer, saw_label, preceding_y, following_y):
"""
Which transaction a block of orphan continuation lines belongs to:
the one that already closed ("trailing", HSBC's convention) or the
one about to open ("leading", RBC's convention) - decided PER GAP,
not once for the whole statement, since nothing rules out a
genuinely mixed statement and a per-gap decision handles that for
free.
An explicit label word (layout_rules.NARRATIVE_LABEL_WORDS) anywhere
in the block is a direct, reliable signal - always trailing,
always confident - confirmed necessary for real: HSBC's own line
spacing isn't a reliable geometric signal (its narrative line sits
physically CLOSER to the next transaction than to its own, by raw
vertical distance), so the label has to win outright when present
rather than just nudging a distance comparison.
With no label at all, fall back to which neighboring transaction
this block sits physically closer to on the page - confirmed for
real against RBC's own wrapped descriptions (e.g. "OysterHR - dMRK"
sits 14pt below its own transaction's row but only 10pt above the
transaction it actually describes).
Returns (direction, confident) - confident is False when the
geometric fallback was a close call (within _GEOMETRY_CONFIDENCE_MARGIN),
worth a human glance rather than trusting a near-coin-flip.
"""
if saw_label:
return "trailing", True
if not buffer:
return "trailing", False
first_y, last_y = buffer[0]["y"], buffer[-1]["y"]
dist_preceding = (first_y - preceding_y) if preceding_y is not None else None
dist_following = (following_y - last_y) if following_y is not None else None
if dist_preceding is None and dist_following is None:
return "trailing", False
if dist_preceding is None:
return "leading", True
if dist_following is None:
return "trailing", True
if dist_preceding <= dist_following:
return "trailing", dist_following >= dist_preceding * _GEOMETRY_CONFIDENCE_MARGIN
return "leading", dist_preceding >= dist_following * _GEOMETRY_CONFIDENCE_MARGIN
def rows_to_transactions(rows):
"""
Group a page's (or a whole statement's concatenated) rows into
transactions: {"date", "status", "description", "amount", "balance"},
amount signed (credit positive, debit negative; a single "amount"
field's own sign is used as-is for the single-column shape).
A bank's own row-grouping convention for multi-line descriptions can
go either direction - HSBC's own continuation text TRAILS the
transaction that already closed; RBC's own wrapped descriptions LEAD
INTO the transaction about to open - and each orphan continuation
block is decided independently (see _decide_gap), not assumed for
the whole statement, so a genuinely mixed statement needs no special
handling: every gap resolves on its own evidence regardless of what
any other gap in the same statement needed.
A "Cancelled" (or any non-"Posted") status row is KEPT, not dropped -
see checks.py for why (the spec's "never silently correct" rule) and
how the running-balance check surfaces it instead.
Returns (transactions, direction_info) where direction_info =
{"ambiguous_indices": [...]} - transactions whose attachment
direction was a close geometric call with no label to settle it.
"""
transactions = []
pending = None
pending_y = None
buffer = []
saw_label = False
for row in rows:
if row["type"] == "txn":
row_y = _row_y(row)
leading_texts = []
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]
if direction == "trailing" and pending is not None:
pending["narr"].extend(texts)
if not confident:
pending["_ambiguous"] = True
else:
leading_texts = texts
leading_ambiguous = not confident
if pending is not None:
transactions.append(pending)
buffer = []
saw_label = False
if row.get("amount") is not None:
amount = row["amount"]
else:
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 [])
pending = {
"date": row["date"], "status": row["status"], "amount": amount,
"balance": row["balance"], "narr": narr,
}
if leading_texts and leading_ambiguous:
pending["_ambiguous"] = True
pending_y = row_y
elif row["type"] == "narrative":
# A label's PRESENCE is the signal even when (as is usual for
# HSBC's own "Narrative" line) it carries no text of its own -
# tracked separately from `buffer`, which only holds lines
# with actual content, so an empty labeled line's signal
# isn't silently lost just because there's nothing to add to
# the buffer for it.
if row.get("explicit_label"):
saw_label = True
text = row["text"].strip()
if text:
buffer.append({"text": text, "y": _row_y(row)})
# else: "opening_balance"/"closing_balance" rows carry a fact, not
# transaction/narrative content - see extract_statement_facts().
# Trailing leftover buffer at the very end of the statement has
# nothing to lead into - it must trail, same as not finding a
# following anchor at all in _decide_gap.
if buffer and pending is not None:
pending["narr"].extend(b["text"] for b in buffer)
if pending is not None:
transactions.append(pending)
ambiguous_indices = [i for i, t in enumerate(transactions) if t.get("_ambiguous")]
result = [
{
"date": t["date"],
"status": t["status"],
"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,
}
for t in transactions
]
return result, {"ambiguous_indices": ambiguous_indices}
def extract_statement_facts(rows):
"""
{"opening_balance": float or None, "closing_balance": float or None} -
from the "opening_balance"/"closing_balance" row types extract_page
captures when it recognizes one of those summary lines INSIDE the
transaction table (confirmed for real on RBC, which prints them as
ordinary table rows - "Opening balance 90,569.13" - rather than in
a page header/preamble the way HSBC does, which is why HSBC's own
opening/closing balance isn't picked up here at all: that text lives
above the table header and is already excluded from every row by
position, per extract_page's own preamble filter. Last value wins if
a statement somehow prints either more than once).
"""
facts = {"opening_balance": None, "closing_balance": None}
for row in rows:
if row["type"] == "opening_balance":
facts["opening_balance"] = row["balance"]
elif row["type"] == "closing_balance":
facts["closing_balance"] = row["balance"]
return facts