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

1285 lines
63 KiB
Python

# Bank-agnostic pdfplumber table extractor - derives column roles and row grouping from word geometry.
import re
import unicodedata
from services.extraction import layout_rules
from services.extraction import layout_quirks
X_TOLERANCE = 1.5
# Points each forced_zones range (extract_pdf's own layout-mapper
# argument) is padded outward by before use - see extract_pdf's own
# docstring for the real bug this fixes (a word's reported x1 landing a
# fraction of a point past an unpadded zone boundary, silently excluding
# it) and why a user's own hand-drawn region needs this margin too.
_FORCED_ZONE_PADDING = 3
# The BODY shape only (sign/parens already stripped off by _parse_money
# before this is ever checked, see below) - optional leading "$"
# confirmed necessary for real on an Equals Money USD statement, which
# prints every amount as "$33.62" rather than the bare "33.62"/
# "1,280.25" HSBC/RBC both use. This is deliberately the ONLY currency
# format hardcoded here - every OTHER real currency-wrapping shape (a
# 2-letter country prefix like "CA$386.01", any non-"$" symbol) is
# handled generically by _money_value()'s own fallback below, not by
# growing this regex a branch at a time every time a new one shows up.
_MONEY_RE = re.compile(r"^\$?[\d,]+\.\d{2}$")
# _money_value()'s fallback core - the bare numeral alone, no currency
# marker of any kind (that's stripped and validated separately, see
# _money_value) - but anchored with a negative lookahead against a
# trailing digit so a 4-decimal exchange-rate ratio like "1.0000" (which
# shows up right next to a real amount in this exact statement's own
# footnote lines - "1 CAD = 1.0000 CAD") can't be mistaken for a 2-decimal
# amount by matching only its own first two decimal digits.
_MONEY_FALLBACK_CORE_RE = re.compile(r"[\d,]+\.\d{2}(?!\d)")
_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, value_patterns=None):
"""
{"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
# A value-pattern mapping's own learned cleanup rules (see
# CLAUDE.md's "Value-pattern mapping" entry) - DISCOVERY breadth
# (every distinct pattern, field identity not known yet) for both
# calls below; _classify_money applies the tighter, per-field
# CLASSIFICATION breadth later, once a word's own field is known.
discovery_patterns = _distinct_patterns(value_patterns)
# Computed BEFORE zones exist (it only needs the raw page words) and
# used throughout the rest of this function and by _classify_money
# later (stashed into zones["_native_marker"] below) - see
# _dominant_money_marker's own docstring for the real phantom-
# transaction bug this prevents.
native_marker = _dominant_money_marker(page_words, discovery_patterns)
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_value(w["text"], native_marker, discovery_patterns) is not None 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)
# Only set when this page actually found a marker - leaving the key
# absent (rather than set to None) lets extract_page's own carry_zones
# merge (a plain dict.setdefault) correctly fall back to an EARLIER
# page's marker for a continuation page with no money words of its
# own, instead of a present-but-None value blocking that fallback.
if native_marker is not None:
zones["_native_marker"] = native_marker
# Carried alongside the other _-prefixed bookkeeping keys so
# _classify_money (called later, per-word, from extract_page's own
# row loop) can look up each field's own CLASSIFICATION-breadth
# pattern without needing a separate parameter threaded all the way
# through - a no-op (absent key) when no value-pattern mapping was
# ever supplied.
if value_patterns:
zones["_value_patterns"] = value_patterns
# 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_value(w["text"], native_marker, discovery_patterns) is not None 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 _is_currency_symbol(ch):
"""True for any real Unicode currency symbol - $, £, €, ¥, ₦, ₹, ₩,
₫, ₪, ₴, ₺, and effectively every other currency symbol in real use,
via Unicode's own "Sc" (Symbol, Currency) category rather than a
hand-maintained finite list. This is what lets _parse_money's own
fallback recognize a currency this codebase has never been tested
against without a developer having to add it by name first."""
return unicodedata.category(ch) == "Sc"
def _split_sign(text):
"""
(negative, body) - pulls a leading "-" or a full parenthesized wrap
("(25.00)", the standard accounting convention for a negative
amount - confirmed necessary for real: a single signed "Amount"
column statement using this instead of a minus sign produced a
fully blank extraction, since nothing recognized "(25.00)" as money
at all) off `text`, leaving the sign-free body either way. Shared by
_parse_money and _parse_money_with_patterns so both recognize
exactly the same negative forms, rather than two copies of this
logic that could quietly drift apart - a value-pattern mapping's own
stripPrefix/stripSuffix has to be matched against the SIGN-FREE body
too, the same reasoning _parse_money_with_patterns' own docstring
already gives for "-".
"""
if text.startswith("-"):
return True, text[1:]
if text.startswith("(") and text.endswith(")") and len(text) > 2:
return True, text[1:-1]
return False, text
def _parse_money(text):
"""
(value, marker) if `text` is money-shaped at all, else None. `marker`
is the non-numeric wrapper around the amount - "" for a bare
"386.01", "$" for "$33.62", "CA$" for "CA$386.01" - see
_dominant_money_marker/_money_value for why this is returned
separately from the value rather than just the value alone.
The sign (see _split_sign) comes off FIRST, leaving the sign-free
body everything below actually operates on - a parenthesized
currency-wrapped value like "(CA$386.01)" is handled for free this
way, not as a separate case.
Tries the exact, already-confirmed-real _MONEY_RE format first (fast,
zero ambiguity - a bare amount or one with a plain "$" in front). If
that fails, falls back to a deliberately more permissive check: find
the one clean [digits].[2 digits] amount in the word (via
_MONEY_FALLBACK_CORE_RE), then require every OTHER character in the
word to be either an uppercase letter or a real Unicode currency
symbol, with AT LEAST ONE actual symbol present - i.e. "some
currency marker(s) wrapped around one clean amount, nothing else."
This fallback is the general fail-safe for a currency-wrapping
format this extractor has never specifically been taught - confirmed
necessary for real on an Equals Money CAD statement printing
"CA$386.01" (where the USD version of the same product just prints
"$33.62"). Deliberately requires a REAL currency symbol, not letters
alone - "REF123.45" (a plain reference code, all letters, no symbol)
must still fail this, exactly as it fails _MONEY_RE today - still
true with the sign/parens handling factored out above, since
"REF123.45" has neither and `body` is just `text` unchanged for it.
And the core regex's own trailing-digit lookahead keeps a 4-decimal
currency-exchange ratio printed right next to a real amount on this
exact statement ("1 CAD = 1.0000 CAD") from being misread as a
2-decimal amount by matching only its first two decimal digits.
"""
negative, body = _split_sign(text)
if _MONEY_RE.match(body):
marker = "$" if "$" in body else ""
value = float(body.replace(",", "").replace("$", ""))
else:
match = _MONEY_FALLBACK_CORE_RE.search(body)
if not match:
return None
remainder = body[:match.start()] + body[match.end():]
if not remainder or not any(_is_currency_symbol(ch) for ch in remainder):
return None
if not all(ch.isupper() or _is_currency_symbol(ch) for ch in remainder):
return None
marker = remainder
value = float(match.group().replace(",", ""))
return (-value if negative else value), marker
def _distinct_patterns(value_patterns):
"""Every distinct {stripPrefix, stripSuffix} pair across a
value-pattern mapping's own per-field rules, de-duplicated - the
DISCOVERY-breadth list _find_zones' own clustering step and
_dominant_money_marker need (see _money_value's own docstring for
why discovery and classification use different breadths). `None`
(no value-pattern mapping at all) or an empty dict both return []."""
if not value_patterns:
return []
seen = []
for pattern in value_patterns.values():
if pattern and pattern not in seen:
seen.append(pattern)
return seen
def _dominant_money_marker(page_words, patterns=None):
"""
The single marker (see _parse_money) that appears on the MOST
money-shaped words on this page - treated as this statement's own
ledger currency. Needed because x-position zone membership alone
isn't enough to rule out a false positive: a real statement's own
narrative continuation lines can span the FULL page width (confirmed
on this exact Equals Money layout), so a word that's merely MENTIONED
in passing - not a real column value - can still land inside a
resolved money zone purely by coincidence of where it happens to
print. Concretely, the same USD statement whose "CA$"-style fallback
this function supports ALSO prints one-off currency-conversion
annotations next to its own exchange-rate footnotes ("1 USD = 0.7104
GBP • £964.58") - a real, correctly-formatted £ amount, but not this
ledger's own money; trusting it as one corrupted the running balance
(confirmed for real - it introduced a phantom 37th transaction with
a broken balance chain where there should have been 36). A
statement's real transaction amounts use the SAME marker dozens of
times over; a one-off foreign marker like this is what marks an
annotation, not the statement's own currency - so _money_value only
ever accepts the dominant one.
`patterns` (see _money_value's own docstring) is passed straight
through at DISCOVERY breadth - a value-pattern mapping's own learned
cleanup rules need to count toward this tally too, or a statement
whose every amount needs stripping would never resolve a dominant
marker at all (nothing would parse as money in the first place).
Known, accepted limitation: on a page with a genuine tie (equally
few money-shaped words of each marker), this picks whichever marker
was encountered first, not necessarily the right one - not fixed,
since a real statement's own transaction amounts are reliably the
large majority on any page that has more than a couple of rows.
"""
counts = {}
for w in page_words:
parsed = _parse_money_with_patterns(w["text"], patterns)
if parsed is not None:
counts[parsed[1]] = counts.get(parsed[1], 0) + 1
return max(counts, key=counts.get) if counts else None
def _strip_pattern(body, pattern):
"""Removes `pattern`'s own stripPrefix/stripSuffix from `body` if (and
only if) `body` literally starts/ends with them - a safe no-op
otherwise, never a crash, never a partial/fuzzy match. `pattern` may
be None (no-op) or missing either key (treated as "" - nothing to
strip on that side). Takes the already sign-stripped BODY, not the
raw word text - see _parse_money_with_patterns, the only caller, for
why a leading "-" has to come off first."""
if not pattern:
return body
prefix = pattern.get("stripPrefix") or ""
suffix = pattern.get("stripSuffix") or ""
if prefix and not body.startswith(prefix):
return body
if suffix and not body.endswith(suffix):
return body
start = len(prefix)
end = len(body) - len(suffix) if suffix else len(body)
return body[start:end]
def _parse_money_with_patterns(text, patterns):
"""
_parse_money(text), or - if that fails and `patterns` is given - the
first pattern (see _money_value's own docstring for the discovery-
vs-classification breadth distinction) that parses once stripped.
The sign (see _split_sign) is pulled off BEFORE stripping and put
back on the candidate afterward, the same way _parse_money's own
strict path already handles it - a real bug, caught before this
ever reached a real statement: a first version stripped the pattern
against the raw text as-is, so a negative value like "-CAD50.00"
never matched a learned `stripPrefix: "CAD"` pattern at all (the
string literally starts with "-", not "CAD") - every negative
amount on the one real test statement that exercised this silently
failed to parse, even though the exact same pattern worked fine on
every positive one.
"""
parsed = _parse_money(text)
if parsed is not None or not patterns:
return parsed
negative, body = _split_sign(text)
for pattern in patterns:
stripped = _strip_pattern(body, pattern)
candidate = ("-" + stripped) if negative else stripped
parsed = _parse_money(candidate)
if parsed is not None:
return parsed
return None
def _money_value(text, native_marker=None, patterns=None):
"""
The parsed float value of `text` if it's money-shaped AND (whenever
`native_marker` is given) its own marker matches this statement's
established native one - see _dominant_money_marker for why that
check matters. `native_marker=None` (the default) skips that check
entirely - used by the zone-discovery clustering step and the
debit-self-signed check in _find_zones, which both need to compute
the dominant marker from EVERY money-shaped word in the first place,
before any marker could be known to gate against.
`patterns` (a value-pattern mapping's own learned cleanup rules - see
CLAUDE.md's "Value-pattern mapping" entry) is an optional LIST of
`{stripPrefix, stripSuffix}` dicts tried, in order, only after the
plain parse above has already failed - each is stripped from `text`
and re-parsed; the first pattern that produces a real value wins.
Callers pass different BREADTHS of this list depending on what they
already know: _find_zones' own clustering step and
_dominant_money_marker (neither of which has resolved which FIELD a
word belongs to yet - that's decided only after clustering) pass
every distinct pattern across every field, so a cluster can form at
all; _classify_money (which already knows the field, from the word's
own x1 against an already-resolved zone) passes just that one
field's own pattern, so one field's cleanup rule can never misfire on
a different, differently-formatted column.
"""
parsed = _parse_money_with_patterns(text, patterns)
if parsed is None:
return None
value, marker = parsed
if native_marker is not None and marker != native_marker:
return None
return value
def _classify_money(text, x1, zones):
"""
Resolves which field `x1` falls into FIRST, then parses `text` for
that field specifically - the reverse of the order this function
used before value-pattern mappings existed (parse first, THEN find
the field), because a value-pattern's own cleanup rule is looked up
BY field - CLASSIFICATION breadth, see _money_value's own docstring -
so the field has to be known before the right pattern can even be
selected. The field-resolution step itself is unchanged: still a
plain x1-against-zone-bounds check, same as before.
"""
value_patterns = zones.get("_value_patterns")
native_marker = zones.get("_native_marker")
for field in _MONEY_FIELDS:
z = zones.get(field)
if not (z and z[0] <= x1 <= z[1]):
continue
pattern = value_patterns.get(field) if value_patterns else None
value = _money_value(text, native_marker, [pattern] if pattern else None)
if value is not None:
return field, value
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", header_bottom=None, value_patterns=None):
"""
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`/`header_bottom`/`value_patterns`
are only ever non-default when a layout mapping supplies them (see
extract_pdf's own docstring) - all are no-ops for every statement
that auto-detects its own header, which never passes these through
at all. `value_patterns` differs from the others in one way worth
noting: it's the one layout-mapping field that still makes real
sense to combine with auto-detection (no `forced_zones` at all) -
see CLAUDE.md's "Value-pattern mapping" entry for why - so unlike
`header_bottom`, it's passed into `_find_zones` below even when this
page resolves its OWN header fresh, not just carried forward.
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, value_patterns)
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
# The forced-mapping equivalent of the check above -
# found_zones is NEVER set under a forced mapping (that's the
# whole reason one exists at all), so the real header row text
# on the mapped page would otherwise have nothing to exclude it
# and gets swept into the first transaction's own description -
# confirmed for real: a synthetic 2-page test statement's own
# unrecognized header line ("Wen Detz Owt Inn Bal") merged
# straight into row 1 ("Coffee Shop") until this was added.
# header_bottom is only ever non-None on the page a forced
# mapping's own regions were actually drawn on (see
# extract_pdf's own docstring) - never on a carried-forward
# continuation page, which has no header line of its own either.
# The same small margin as _FORCED_ZONE_PADDING, subtracted
# here rather than added - header_bottom is the TOP of the
# user's own first drawn region, meant to mark "the real data
# starts here," so the raw value sits right at (or a hair
# below) the real first row's own top; using it unmodified as
# an inclusive `<=` boundary would risk excluding that exact
# row, not just the header above it.
if header_bottom is not None and top <= header_bottom - _FORCED_ZONE_PADDING:
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"])
# Date values are never clustered (the date zone comes straight
# from the header LABEL's own position, see _find_zones) - so,
# unlike the money fields, there's no discovery-breadth problem
# here at all; the date value-pattern (if any) is applied
# directly against the already-joined text, right before the
# existing normalize_date() call - a prefix/suffix can span a
# word boundary, so this strips the JOINED string, not each
# word in date_parts individually.
date_text = " ".join(date_parts)
date_pattern = zones.get("_value_patterns", {}).get("date") if zones.get("_value_patterns") else None
if date_pattern:
date_text = _strip_pattern(date_text, date_pattern)
row_date = normalize_date(date_text, 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, header_bottom=None, value_patterns=None):
"""
{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.
Each `forced_zones` range is padded outward by
`_FORCED_ZONE_PADDING` points before use - confirmed necessary for
real: a word's own reported x1 can sit a fraction of a point past a
zone's raw, unpadded upper bound (floating-point precision in how
pdfplumber reports word positions, confirmed directly - a value that
LOOKS like 416.1 at a glance is actually 416.14), silently excluding
it from money classification with no error at all - exactly the
"never silently exclude data" governing rule this whole app is built
around, and the realistic case this guards (a user's own hand-drawn
region in the manual mapping screen, L.6, rarely lands exactly on a
glyph's true edge either) is far more consequential than the literal
float-rounding example that first surfaced it. The auto-detected
path already pads its own zones generously for an analogous reason
(`-80`/`+5` on money zones, `-5`/`+15` on text zones in `_find_zones`
above) - this is the same discipline, just a smaller margin, since
this only needs to absorb imprecision, not "where does the real data
sit relative to a header label" uncertainty.
`header_bottom` exists because `start_page` alone only ever skips
WHOLE pages before the real table - it does nothing about the real
header ROW TEXT that still sits at the top of the start page itself
(unlike the auto-detected path, which always has a real `header_top`
of its own to filter that exact line out). Confirmed necessary for
real: a synthetic test statement's own unrecognized header line
("Wen Detz Owt Inn Bal") merged straight into the first transaction's
description under a forced mapping with no `header_bottom` set - the
manual mapping screen (L.6) supplies this as the topmost y-position
of whatever regions the user actually drew on the start page, so
"anything above the columns I just mapped" is excluded the same way
"anything above the header row I just detected" already is for the
auto-detected case. Only ever applied to the start page itself (a
continuation page has no header line of its own to exclude either).
`value_patterns` (see CLAUDE.md's "Value-pattern mapping" entry) is
the one layout-mapping field that's genuinely useful WITHOUT
`forced_zones` too - it only cleans a word's raw text before the
normal classification logic runs, it doesn't replace that logic, so
a statement whose columns the auto-detector already finds fine but
whose VALUES it can't parse (a currency wrapper, a stray character)
only ever needs this one field, letting auto-detection do the rest.
Passed to every page's own extract_page() call unconditionally
(unlike `header_bottom`, which only ever applies to the start page) -
see extract_page's own docstring for why.
"""
import pdfplumber
result = {}
zones = None
if forced_zones:
zones = {field: (x0 - _FORCED_ZONE_PADDING, x1 + _FORCED_ZONE_PADDING) for field, (x0, x1) in forced_zones.items()}
if zones is not None and forced_sign_convention is not None:
zones.setdefault("_debit_self_signed", forced_sign_convention.get("debitSelfSigned", True))
# Stashed here too (not just inside _find_zones, see that function's
# own docstring) so _classify_money can look value_patterns up the
# same way regardless of whether this call is using forced_zones (a
# full manual mapping) or auto-detection - value_patterns is meant
# to compose with either, per extract_pdf's own docstring.
if zones is not None and value_patterns:
zones.setdefault("_value_patterns", value_patterns)
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,
header_bottom=header_bottom if i == start_page else None,
value_patterns=value_patterns,
)
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 many lines below the header this function will scan looking for
# one with a date-shaped token in the date column before giving up and
# just using the first non-empty line instead - generous enough for any
# real preamble/blank-line noise, cheap enough to never matter.
_CANDIDATE_LINE_LOOKAHEAD = 30
_PREVIEW_FIELD_ORDER = ("date", "description", "status", "debit", "credit", "amount", "balance")
def value_recognition_preview(pdf_path):
"""
(words, lines_by_top, page_width, page_height, candidate_row,
field_order) for the one representative transaction-shaped line
this extractor can show a user to correct, when the auto-detector
found a usable header but couldn't turn any of its values into real
money - the SAME shape `header_candidate_geometry()`'s own return
value has (plus the two new fields), deliberately, so
extraction_service.py can chain it into
`layout_fingerprint.compute_fingerprint(*preview[:4])` exactly the
way it already does for `header_candidate_geometry()` - this module
has no reason to depend on layout_fingerprint.py itself, and isn't
given one here.
Returns `None` if no header resolves on any page at all, or no
plausible candidate line exists even with this function's own rough
fallback anchoring - the caller then falls through to the existing
"could not recognize this layout" path instead (full manual
mapping), since there's nothing concrete to show a user yet.
Built on top of `header_candidate_geometry()` (reused, not
duplicated). For whichever money field never resolved a real,
CLUSTERED zone at all (the exact CA$-shaped failure this function
exists for), falls back to a rough zone anchored directly off that
field's own header LABEL position - the same generous padding shape
the date/status/description zones already use. This rough zone is
used ONLY to build this one preview - it is never passed into real
extraction, which stays exactly as strict as it already is; a
label-anchored zone's own position is often a poor guess at where a
right-aligned numeric column's real values actually print, which is
exactly why a human confirms it rather than this code trusting it.
"""
geometry = header_candidate_geometry(pdf_path)
if geometry is None:
return None
words, lines_by_top, page_width, page_height = geometry
zones, header_top, lines_by_top = _find_zones(words, lines_by_top)
if zones is None:
return None
_, _, resolved = _find_header_row(lines_by_top)
field_order = [f for f in _PREVIEW_FIELD_ORDER if f in resolved]
if not field_order:
return None
# Only ever reached for a money field (debit/credit/amount/balance) -
# date/status/description are always anchored by _find_zones itself
# regardless of whether any value parsed, so they're never missing
# here. Mirrors the SAME generous-left/minimal-right asymmetry the
# real clustered zones use (-80/+5 there) for the same reason: a
# right-aligned numeric column's real data starts well left of its
# own header label, essentially never further right than it - a
# first version of this used the opposite asymmetry (-5/+60) and
# bled into the very next column's own values on a real test;
# caught before this ever reached a real statement.
preview_zones = dict(zones)
for field in field_order:
if field not in preview_zones:
anchor = resolved[field]
preview_zones[field] = (anchor[0] - 60, anchor[1] + 5)
date_zone = preview_zones.get("date")
candidate_line, fallback_line = None, None
body_tops = sorted(t for t in lines_by_top.keys() if t > header_top)
for i, top in enumerate(body_tops):
line = sorted(lines_by_top[top], key=lambda w: w["x0"])
if not line:
continue
if fallback_line is None:
fallback_line = line
if date_zone and any(date_zone[0] <= w["x0"] <= date_zone[1] for w in line):
candidate_line = line
break
if i >= _CANDIDATE_LINE_LOOKAHEAD:
break
candidate_line = candidate_line or fallback_line
if candidate_line is None:
return None
candidate_row = {}
for field in field_order:
zone = preview_zones.get(field)
words_in_zone = [w["text"] for w in candidate_line if zone and zone[0] <= w["x0"] <= zone[1]]
candidate_row[field] = " ".join(words_in_zone) if words_in_zone else None
return words, lines_by_top, page_width, page_height, candidate_row, field_order
# 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