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

103 lines
5.0 KiB
Python

"""
Modular, narrow fixes for mechanical layout oddities that defeat the
keyword/geometry header detector (table_extract._find_header_row) even
though the required vocabulary is genuinely present on the page - tried
ONLY after that detector has already failed on every line, so this adds
zero risk to any statement that already works (HSBC/RBC never reach this
module at all in practice, since they always resolve on a single line).
This is deliberately NOT the same thing as the layout mapper (stored,
fingerprinted column mappings, a manual mapping screen, a shared
library - see CLAUDE.md's "Layout mapper" entry). A quirk here is a
self-contained, code-based geometric rule a developer can write once a
new mechanical pattern is seen; the mapper is for anything a geometric
rule can't describe at all (a genuinely different column set/order/
terminology). Each quirk is independent and added here as its own
function + a registry entry - never by editing an existing quirk or by
growing table_extract.py's own line-grouping/header logic.
"""
from services.extraction import layout_rules
# Points. The real statement that motivated this (an "Equals Money"
# account PDF) had its "Running"/"balance" header label wrap across two
# extra physical lines straddling the main single-line header, with
# measured gaps of ~6pt between the fragments - real, distinct lines of
# body text elsewhere on the same page measured >=10pt apart. 8pt sits
# cleanly between the two, with margin either side.
MAX_MERGE_GAP = 8
def _wrapped_header_label(lines_by_top):
"""
Detects a header column label wrapped across one or more extra
physical lines that straddle the main single-line header row -
e.g. "Running" printed just above, and "balance" just below, a line
that already carries "Date"/"Credits"/"Debits" etc. Confirmed for
real: pdfplumber's own word positions for this exact case showed
"Running" (top=133.5), the main header line (top=139.5), and
"balance" (top=145.5) as three separate rounded-top buckets, each
only 6pt apart - too close to be genuinely distinct lines, but just
far enough that table_extract.py's own round(w["top"]) grouping (no
tolerance) never merges them on its own.
Returns a NEW lines_by_top dict with the offending lines merged into
one, or None if this page doesn't exhibit the pattern (including the
normal case where some line already resolves the shape on its own -
nothing to fix, so this is a guaranteed no-op there).
"""
tops = sorted(lines_by_top.keys())
# Already works today - never touch a page where the existing
# detector would have succeeded on its own.
for top in tops:
line_sorted = sorted(lines_by_top[top], 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 None
# Try every run of consecutive lines whose pairwise gaps are all
# within MAX_MERGE_GAP, union their words, and see if that resolves
# the shape. Checked shortest-cluster-first (pairs before triples)
# so a 2-line fix is preferred over an unnecessarily wide merge.
n = len(tops)
for cluster_size in range(2, n + 1):
for start in range(n - cluster_size + 1):
cluster_tops = tops[start:start + cluster_size]
if any(cluster_tops[i + 1] - cluster_tops[i] > MAX_MERGE_GAP for i in range(len(cluster_tops) - 1)):
continue
cluster_words = [w for top in cluster_tops for w in lines_by_top[top]]
cluster_words_sorted = sorted(cluster_words, key=lambda w: w["x0"])
resolved = layout_rules.resolve_header_matches(layout_rules.match_line_fields(cluster_words_sorted))
if not layout_rules.has_required_shape(resolved):
continue
# Anchor the merged line at whichever member had the most
# words (ties broken by smallest top) - that's the "main"
# single line in the cluster (e.g. the "Date ... Debits"
# line), not one of its short wrapped-label fragments.
anchor_top = max(cluster_tops, key=lambda t: (len(lines_by_top[t]), -t))
new_lines = {top: words for top, words in lines_by_top.items() if top not in cluster_tops}
new_lines[anchor_top] = cluster_words_sorted
return new_lines
return None
QUIRKS = [_wrapped_header_label]
def normalize(lines_by_top):
"""
Tries each registered quirk in turn against this page's own
lines_by_top; the first one that actually changes something wins
(each quirk targets a narrow, specific geometric pattern - they're
not meant to stack). Returns the input UNCHANGED if nothing matches -
the case for every statement this pipeline already supports, so this
is zero-risk by construction for HSBC/RBC.
"""
for quirk in QUIRKS:
result = quirk(lines_by_top)
if result is not None:
return result
return lines_by_top