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

801 lines
38 KiB
Python

# Bank-agnostic pdfplumber table extractor - derives column roles and row grouping from word geometry.
import re
from services.extraction import layout_rules
from services.extraction import layout_quirks
X_TOLERANCE = 1.5
# Optional leading "$" - confirmed necessary for real on an Equals Money
# statement, which prints every amount as "$33.62" rather than the bare
# "33.62"/"1,280.25" HSBC/RBC both use. No real statement seen so far
# prints the "$" after a leading "-", so that ordering isn't supported.
_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")
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.
`layout_rules.match_line_fields`/`resolve_header_matches` used to live
here as private functions (_line_field_matches/_resolve_header_matches)
- relocated to layout_rules.py so layout_quirks.py can reuse the exact
same line-to-fields resolution without this module needing to import
that one (which would be circular, since this module calls INTO
layout_quirks.py below).
"""
for top, line in lines_by_top.items():
line_sorted = sorted(line, key=lambda w: w["x0"])
resolved = layout_rules.resolve_header_matches(layout_rules.match_line_fields(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, lines_by_top) 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. The third return value is normally just the same
`lines_by_top` passed in, UNLESS the layout_quirks fallback below
actually merged some lines to resolve the header - in that case the
caller (extract_page) needs the merged version too, so its own
row-extraction loop doesn't still iterate over the pre-merge
fragment lines (e.g. a lone "balance" label line left over from a
wrapped header) as if they were ordinary page content.
"""
header_row, header_top, resolved = _find_header_row(lines_by_top)
if header_row is None:
# The plain single-line detector found nothing - try the quirks
# module (layout_quirks.py) before giving up. It's a no-op
# (returns the same dict) for every statement that already
# resolves on its own, so this retry costs nothing there.
normalized = layout_quirks.normalize(lines_by_top)
if normalized is not lines_by_top:
header_row, header_top, resolved = _find_header_row(normalized)
if header_row is not None:
lines_by_top = normalized
if header_row is None:
return None, None, lines_by_top
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, lines_by_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(",", "").replace("$", ""))
return None
_MONTH_ABBR = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# YYYY/MM/DD or YYYY-MM-DD - confirmed necessary for real on an Equals
# Money statement, which prints dates this way instead of HSBC/RBC's own
# "DD Mon[ YYYY]" text. Safe to auto-normalize (not a mapper/human
# decision) because this specific shape is NEVER ambiguous - the 4-digit
# year anchors which part is the year, and ISO ordering (year, then
# month, then day) leaves no day/month confusion the way a bare "03/04"
# would. Converted to the same "DD Mon YYYY" shape every downstream
# consumer (checks_service._parse_date, suggested_fixes_service.py's own
# documented assumption) already expects, so nothing past this point
# needs to know a second date shape ever existed.
_NUMERIC_DATE_RE = re.compile(r"^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$")
def _normalize_date_text(text):
"""Converts a recognized unambiguous numeric date shape to "DD Mon
YYYY"; returns the input UNCHANGED for anything else (including
HSBC/RBC's own already-textual dates) - a guaranteed no-op there."""
m = _NUMERIC_DATE_RE.match(text)
if not m:
return text
year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
if not (1 <= month <= 12):
return 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
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, 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":
"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.
`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
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, lines = _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 = ""
after_closing_balance = False
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
# Anything BELOW the closing-balance line is trailing account
# boilerplate, not transaction data, the same way anything above
# the header row is leading boilerplate. Confirmed for real: RBC
# prints "Account Fees: $48.75" directly under "Closing balance"
# on the statement's last page - no money token this regex
# recognizes (it's "$48.75", not "48.75"), no reference-number
# prefix, so with nothing else to catch it, it fell through to
# plain narrative text and - since it's the very last row on the
# statement, with no following transaction to lead into - landed
# on the LAST real transaction's description via the same
# trailing-leftover-buffer rule a genuine trailing narrative line
# needs (see rows_to_transactions). The closing balance is always
# the true end of a bank's own transaction table (confirmed: it's
# printed once, at the end, same as "4 of 4" already marks the
# end of the page) - once seen, nothing after it on this page is
# worth classifying as either a transaction or narrative text.
if after_closing_balance:
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
# 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 = {}
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 = normalize_date(" ".join(date_parts), date_format)
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"]})
after_closing_balance = True
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, "bbox": _line_bbox(line_words),
})
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, "bbox": _line_bbox(line_words),
})
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, "bbox": _line_bbox(line_words),
})
return rows, zones
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 = 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):
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
# 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 _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
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_service.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_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)
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 [])
# 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
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), "bbox": row.get("bbox")})
# 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)
for b in buffer:
pending["bbox"] = _union_bbox(pending["bbox"], b.get("bbox"))
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,
# 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
]
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