Generalize money-format detection into a standing fail-safe, gated by dominant currency marker
Replaces the one-off "CA$" regex fix with a general mechanism: _parse_money()/_money_value() recognize any currency-wrapped amount (a currency-code prefix, or any real Unicode currency symbol via category "Sc") rather than needing a new _MONEY_RE branch hardcoded every time an unseen format shows up. Letters alone (no symbol) still correctly fail, so a reference code like "REF123.45" is never misread as money. This alone reintroduced a real phantom-transaction bug, caught before shipping by re-testing the already-fixed Equals Money USD fixture: its own currency-exchange footnotes print a converted foreign-currency amount (e.g. "£964.58") that's genuinely money-shaped but isn't this ledger's own currency - and because this bank's narrative continuation lines span the full page width, that token's x-position coincidentally fell inside the money column's zone, promoting the whole line into a phantom 37th transaction with a broken balance chain. Fixed with a dominant-marker gate: _dominant_money_marker() tallies every money-shaped word's own currency marker on a page, and the fallback only accepts whichever marker is most common - a real statement's own amounts use the same marker dozens of times; a one-off foreign marker marks itself as an annotation, not the ledger's money. Verified: 19 direct assertions on _money_value (including the false- positive guards), the regression reproduced then fixed against the real USD fixture (37→36 transactions, balance checks restored), the original CAD case re-verified via a reconstructed synthetic PDF (its real file's PocketBase record was since deleted), and the full HSBC/RBC fixture corpus byte-identical to baseline throughout. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
17a8ef1acf
commit
53ff90a8f7
174
CLAUDE.md
174
CLAUDE.md
|
|
@ -188,7 +188,20 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
|
||||||
the plain single-line header detector finds
|
the plain single-line header detector finds
|
||||||
nothing; _MONEY_RE accepts an optional leading
|
nothing; _MONEY_RE accepts an optional leading
|
||||||
"$"; normalize_date()/header_candidate_geometry()
|
"$"; normalize_date()/header_candidate_geometry()
|
||||||
are new; extract_pdf()/extract_page() gained
|
are new. As of 2026-10-30, money-shape detection
|
||||||
|
is a standing fail-safe, not just _MONEY_RE's own
|
||||||
|
exact format: _parse_money()/_money_value() fall
|
||||||
|
back to recognizing ANY currency-wrapped amount
|
||||||
|
(a currency-code prefix, any real Unicode currency
|
||||||
|
symbol) via _MONEY_FALLBACK_CORE_RE + Unicode's
|
||||||
|
"Sc" category, gated by _dominant_money_marker()
|
||||||
|
(stashed as zones["_native_marker"]) so a one-off
|
||||||
|
foreign-currency annotation elsewhere on the page
|
||||||
|
can't be mistaken for this ledger's own money - see
|
||||||
|
"A real new-statement bug..." under Key decisions &
|
||||||
|
lessons for the real phantom-transaction regression
|
||||||
|
this needed to guard against. extract_pdf()/
|
||||||
|
extract_page() gained
|
||||||
forced_zones/forced_sign_convention/
|
forced_zones/forced_sign_convention/
|
||||||
ignored_row_rules/date_format/start_page/
|
ignored_row_rules/date_format/start_page/
|
||||||
header_bottom params, all no-ops when omitted;
|
header_bottom params, all no-ops when omitted;
|
||||||
|
|
@ -2614,64 +2627,113 @@ library two independent users' matching mappings promote into automatically, or
|
||||||
a real PocketBase superuser can push there directly after reviewing it against
|
a real PocketBase superuser can push there directly after reviewing it against
|
||||||
the actual source document.
|
the actual source document.
|
||||||
|
|
||||||
**A real new-statement bug, reported via the UI ("No opening and/or closing
|
**A real new-statement bug ("No opening and/or closing balance available"),
|
||||||
balance available") and traced through to a money-format gap `_MONEY_RE` didn't
|
traced to a money-format gap, then generalized into a standing fail-safe for
|
||||||
cover, fixed 2026-10-30.** A user-uploaded `EQUALS - CAD.pdf` (a CAD-denominated
|
ANY currency-wrapping format after a design discussion with the user -
|
||||||
Equals Money account - the same product L.1's USD fixture already generalized
|
2026-10-30, three stages in one day.**
|
||||||
for) extracted ZERO transactions - `page_reports` showed `pdfplumber_count: 0`
|
|
||||||
AND `docling_count: 0`, `status: "ok"` (both engines "agreeing" on nothing, which
|
|
||||||
is why this returned a plain 200 with `status: "Needs review"` rather than
|
|
||||||
erroring - every check downstream of "no transactions" degrades gracefully
|
|
||||||
rather than crashing, which is also exactly why the user's own report of
|
|
||||||
"it failed" initially looked like nothing more than the ordinary, already-
|
|
||||||
documented "no printed balance" banner, not a hard error).
|
|
||||||
|
|
||||||
**Root cause, confirmed by retrieving the user's actual uploaded file from
|
**Stage 1 - the immediate bug.** A user-uploaded `EQUALS - CAD.pdf` (a
|
||||||
PocketBase/R2 (via the superuser's own file API, the same access pattern L.8's
|
CAD-denominated Equals Money account - the same product L.1's USD fixture
|
||||||
review screen already uses) and running the real `table_extract.extract_pdf()`
|
already generalized for) extracted ZERO transactions - `page_reports` showed
|
||||||
against it directly, not guessed from the symptom:** this statement prints every
|
`pdfplumber_count: 0` AND `docling_count: 0`, `status: "ok"` (both engines
|
||||||
money amount as `"CA$386.01"` - a 2-letter CURRENCY-CODE prefix immediately
|
"agreeing" on nothing, which is why this returned a plain 200 with
|
||||||
before the `$`, not just a bare `$` the way the already-fixed Equals Money USD
|
`status: "Needs review"` rather than erroring, and why the user's own "it
|
||||||
statement does (`"$33.62"`, no prefix at all). `_MONEY_RE` only tolerated an
|
failed" report initially looked like nothing more than the ordinary, already-
|
||||||
optional bare `$`, so every single amount on the page failed money
|
documented "no printed balance" banner). Root cause, confirmed by retrieving
|
||||||
classification and fell through to plain narrative text - every row in the
|
the user's actual uploaded file from PocketBase/R2 (via the superuser's own
|
||||||
table became indistinguishable from the "Card (...) • 1 CAD = ..." footnote
|
file API, the same access pattern L.8's review screen already uses) and
|
||||||
lines underneath it.
|
running `table_extract.extract_pdf()` against it directly, not guessed from
|
||||||
|
the symptom: this statement prints every amount as `"CA$386.01"` - a 2-letter
|
||||||
|
currency-code prefix immediately before the `$` - which `_MONEY_RE` (bare `$`
|
||||||
|
only) didn't recognize at all, so every amount fell through to plain
|
||||||
|
narrative text. First fix: widened `_MONEY_RE` itself to
|
||||||
|
`^-?(?:[A-Z]{1,3}\$|\$)?[\d,]+\.\d{2}$` - letters accepted only when a literal
|
||||||
|
`$` immediately follows (a broader letters-with-no-required-`$` draft was
|
||||||
|
tried and rejected first, since it would also match a plain reference code
|
||||||
|
like `"REF123.45"` as money).
|
||||||
|
|
||||||
Fixed by widening `_MONEY_RE` to `^-?(?:[A-Z]{1,3}\$|\$)?[\d,]+\.\d{2}$` - an
|
**Stage 2 - a design conversation, not an immediate build.** The user asked
|
||||||
optional 1-3 letter prefix is accepted, but ONLY when a literal `$` immediately
|
whether this class of bug (new statement, new money format, silent failure
|
||||||
follows it. **A broader first draft (`[A-Z]{0,3}\$?...`, letters alone with no
|
needing a developer to notice and patch) could be caught automatically on the
|
||||||
required `$`) was tried and rejected before it ever shipped**: that shape would
|
FIRST run - initially framed as an AI-assisted idea ("use Claude to see what
|
||||||
also match a plain reference code like `"REF123.45"` as money, a real false-
|
the engine expects and extract just that"). Talked through why handing this to
|
||||||
positive this extractor's own governing "never silently misclassify" discipline
|
an LLM is the wrong fit for THIS specific codebase: it would introduce
|
||||||
exists to catch - confirmed by directly testing the regex against that exact
|
non-determinism into a pipeline whose own `measure.py` regression harness
|
||||||
string before settling on the tighter, `$`-anchored version. `_classify_money`'s
|
depends on determinism, and - more concretely - this exact statement's own
|
||||||
own numeric parsing also had to change - the existing `text.replace("$", "")`
|
currency-exchange footnotes ("1 CAD = 1.0000 CAD") are *also* digit-plus-
|
||||||
would leave `"CA"` behind in the string, which `float()` can't parse at all -
|
decimal-plus-currency-text without being money, so an AI asked to "find
|
||||||
replaced with `re.sub(r"[^\d.\-]", "", text.replace(",", ""))`, stripping any
|
whatever looks like it's missing" would have to make the same judgment call a
|
||||||
remaining non-numeric characters generically rather than special-casing every
|
human would, with a wrong guess producing a plausible-looking WRONG number
|
||||||
possible currency-code prefix by name.
|
instead of a loud failure. Agreed instead on a fully deterministic
|
||||||
|
zone-scoped fallback: generalize `_MONEY_RE`'s own narrow, one-prefix-at-a-time
|
||||||
|
fix into a standing rule that recognizes ANY currency-wrapped amount via
|
||||||
|
Unicode's own currency-symbol category, confined to columns the engine has
|
||||||
|
already geometrically proven are money columns.
|
||||||
|
|
||||||
**Verified, all real:** the actual retrieved file, run directly through the
|
**Stage 3 - the general fallback, and the real regression it introduced
|
||||||
real `table_extract.extract_pdf()`/`rows_to_transactions()` (not reimplemented),
|
before shipping.** Reverted `_MONEY_RE` back to its original bare-`$`-only
|
||||||
now correctly produces 3 transactions whose running balance matches the
|
form and built a new `_parse_money()`/`_money_value()` pair: tries the exact
|
||||||
statement's own printed figures exactly (747.74 → 361.73 → 295.61 → 280.37) and
|
`_MONEY_RE` format first, then falls back to finding the one clean
|
||||||
correctly extracts `opening_balance: 747.74`/`closing_balance: 280.37` from the
|
`[digits].[2 digits]` amount in a word and requiring every OTHER character to
|
||||||
in-table summary row. A real `/api/process` call against the rebuilt container
|
be either an uppercase letter or a real Unicode currency symbol (category
|
||||||
with that same file now returns `statement_balance`/`running_balance`/
|
`"Sc"` - `$`, `£`, `€`, `¥`, `₦`, `₹`, `₩`, and effectively every other real
|
||||||
`date_sanity`/`structure_sanity`/`page_coverage` all **pass** - the user's own
|
symbol, not a hand-maintained list), with at least one actual symbol present
|
||||||
reported symptom (no balance check available) is resolved. Overall `status` is
|
- so `"REF123.45"` (letters, no symbol) still correctly fails, while
|
||||||
still "Failed," correctly: Docling itself still finds zero tables on this page
|
`"CA$386.01"`, `"£386.01"`, `"-CA$50.00"` etc. all correctly pass. The core
|
||||||
(`docling_count: 0`) even though pdfplumber now correctly finds 3 - the same
|
regex's own trailing-digit lookahead (`(?!\d)`) keeps a 4-decimal exchange
|
||||||
already-documented, intentional `engine_agreement` disagreement every other
|
ratio like `"1.0000"` from being misread as a 2-decimal amount via its first
|
||||||
Equals Money statement in this codebase's own history has shown, not a defect
|
two digits.
|
||||||
this fix introduced or was ever meant to resolve. `backend/measure.py` re-run
|
|
||||||
against the full HSBC/RBC fixture corpus, byte-identical to the documented
|
**This alone reintroduced a real phantom-transaction bug**, caught by
|
||||||
baseline (field accuracy 1.0 on all three, same statuses, same transaction
|
re-testing the ALREADY-FIXED Equals Money USD statement (L.1's own fixture)
|
||||||
counts) - confirms the widened regex is a true no-op for every statement that
|
before this ever shipped: 37 transactions instead of the documented 36, with
|
||||||
already worked, including RBC's own CAD-denominated fixture (which doesn't use
|
a broken running-balance chain. Root cause: that statement's own currency-
|
||||||
a currency-code prefix at all, so it was never affected either way). The `app`
|
exchange footnotes print the CONVERTED foreign-currency amount right next to
|
||||||
container was rebuilt from this change (a backend edit - no hot reload).
|
the rate ("1 USD = 0.7104 GBP • £964.58") - a genuinely well-formed `£` amount,
|
||||||
|
now correctly recognized as money shape-wise, but NOT this ledger's own money.
|
||||||
|
Because this bank's narrative continuation lines span the FULL page width
|
||||||
|
(confirmed by inspecting the real word positions), that `£` token's x-position
|
||||||
|
happened to fall inside the already-resolved money column's zone purely by
|
||||||
|
coincidence of layout, and "a row is a txn if ANY money field has a value"
|
||||||
|
(table_extract.py's own existing, unrelated rule) promoted that whole
|
||||||
|
narrative line into a phantom extra transaction. Zone-scoping by x-position
|
||||||
|
alone, it turns out, isn't sufficient on this specific layout.
|
||||||
|
|
||||||
|
**Fixed by adding a dominant-marker gate**: `_dominant_money_marker()` scans
|
||||||
|
every money-shaped word on a page and tallies each one's own "marker" (the
|
||||||
|
non-numeric wrapper - `""`, `"$"`, `"CA$"`, `"£"`, etc.), and `_money_value()`
|
||||||
|
now only accepts the FALLBACK path (not the strict one) when a word's own
|
||||||
|
marker matches whichever marker is most common on that page - a real
|
||||||
|
statement's own transaction amounts use the same marker dozens of times over;
|
||||||
|
a one-off foreign marker (a currency-conversion annotation) is what marks
|
||||||
|
itself as NOT the ledger's own money. This is computed once in `_find_zones`
|
||||||
|
(stashed into `zones["_native_marker"]`, same pattern as the existing
|
||||||
|
`_debit_self_signed` flag) and threaded through to all three call sites that
|
||||||
|
used to test `_MONEY_RE.match()` directly - the zone-discovery clustering
|
||||||
|
step, the debit-self-signed check, and `_classify_money` itself - so the gate
|
||||||
|
applies everywhere a money-shaped word could ever influence the result, not
|
||||||
|
just final value extraction.
|
||||||
|
|
||||||
|
**Verified, all real, across all three stages:** 19 direct `_money_value()`
|
||||||
|
assertions (CA$/£/€/¥/₦/₹, negative amounts, trailing symbols, and the
|
||||||
|
`"REF123.45"`/`"USD386.01"`/`"1.0000"`/`"A1B2.34"` false-positive rejections).
|
||||||
|
The REGRESSION itself was confirmed real before fixing it (37 txns, broken
|
||||||
|
balance chain) by running the exact pre-dominant-marker code against the real
|
||||||
|
USD fixture, then confirmed fixed (36 txns, every running balance correct,
|
||||||
|
`statement_balance`/`running_balance`/`date_sanity`/`structure_sanity` all
|
||||||
|
pass via a real `/api/process` call) after adding the gate. The ORIGINAL CAD
|
||||||
|
bug was re-verified too - the original uploaded file's own PocketBase record
|
||||||
|
had since been deleted, so a hand-built synthetic PDF replicating its exact
|
||||||
|
text/structure (`"CA$"`-prefixed amounts, no other currency present) was run
|
||||||
|
through the real `_find_zones()`/`extract_pdf()` directly, confirming
|
||||||
|
`_native_marker` resolves to `"CA$"` and the real transaction rows classify
|
||||||
|
with the correct running-balance values. `backend/measure.py` re-run against
|
||||||
|
the full HSBC/RBC fixture corpus after every stage, byte-identical to the
|
||||||
|
documented baseline throughout (field accuracy 1.0, same statuses, same
|
||||||
|
transaction counts) - RBC's own CAD-denominated fixture doesn't use a
|
||||||
|
currency-code prefix at all, so it was never affected either way. The `app`
|
||||||
|
container was rebuilt from each stage of this change (backend edits - no hot
|
||||||
|
reload).
|
||||||
|
|
||||||
**"Show on source" extended to every row's own click, not just the flag panel's
|
**"Show on source" extended to every row's own click, not just the flag panel's
|
||||||
dedicated button, 2026-10-30.** Previously this highlight (R.1's `source_bbox`/
|
dedicated button, 2026-10-30.** Previously this highlight (R.1's `source_bbox`/
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
# Bank-agnostic pdfplumber table extractor - derives column roles and row grouping from word geometry.
|
# Bank-agnostic pdfplumber table extractor - derives column roles and row grouping from word geometry.
|
||||||
import re
|
import re
|
||||||
|
import unicodedata
|
||||||
from services.extraction import layout_rules
|
from services.extraction import layout_rules
|
||||||
from services.extraction import layout_quirks
|
from services.extraction import layout_quirks
|
||||||
|
|
||||||
|
|
@ -12,22 +13,20 @@ X_TOLERANCE = 1.5
|
||||||
_FORCED_ZONE_PADDING = 3
|
_FORCED_ZONE_PADDING = 3
|
||||||
# Optional leading "$" - confirmed necessary for real on an Equals Money
|
# Optional leading "$" - confirmed necessary for real on an Equals Money
|
||||||
# USD statement, which prints every amount as "$33.62" rather than the
|
# USD statement, which prints every amount as "$33.62" rather than the
|
||||||
# bare "33.62"/"1,280.25" HSBC/RBC both use. An optional 1-3 letter
|
# bare "33.62"/"1,280.25" HSBC/RBC both use. This is deliberately the
|
||||||
# currency-code prefix immediately before that "$" is ALSO confirmed
|
# ONLY format hardcoded here - every OTHER real currency-wrapping shape
|
||||||
# necessary for real: the same product's own CAD statement prints every
|
# (a 2-letter country prefix like "CA$386.01", any non-"$" symbol) is
|
||||||
# amount as "CA$386.01" instead - Equals Money disambiguates non-USD
|
# handled generically by _money_value()'s own fallback below, not by
|
||||||
# accounts this way, so a GBP/EUR account would plausibly do the same
|
# growing this regex a branch at a time every time a new one shows up.
|
||||||
# with its own prefix. The letters are only ever accepted when a "$"
|
_MONEY_RE = re.compile(r"^-?\$?[\d,]+\.\d{2}$")
|
||||||
# immediately follows them (not bare, e.g. "USD386.01") - loosening this
|
# _money_value()'s fallback core - the bare numeral alone, no currency
|
||||||
# to "any 1-3 uppercase letters, optionally followed by $" would also
|
# marker of any kind (that's stripped and validated separately, see
|
||||||
# match a plain alphanumeric reference code shaped like "REF123.45",
|
# _money_value) - but anchored with a negative lookahead against a
|
||||||
# which is exactly the kind of false positive this extractor's own
|
# trailing digit so a 4-decimal exchange-rate ratio like "1.0000" (which
|
||||||
# governing "never silently misclassify" discipline exists to avoid; a
|
# shows up right next to a real amount in this exact statement's own
|
||||||
# $ sign is what actually marks a token as money, so it stays required
|
# footnote lines - "1 CAD = 1.0000 CAD") can't be mistaken for a 2-decimal
|
||||||
# whenever a currency-code prefix is present. No real statement seen so
|
# amount by matching only its own first two decimal digits.
|
||||||
# far prints the "$" (or a currency prefix) after a leading "-", so that
|
_MONEY_FALLBACK_CORE_RE = re.compile(r"[\d,]+\.\d{2}(?!\d)")
|
||||||
# ordering isn't supported.
|
|
||||||
_MONEY_RE = re.compile(r"^-?(?:[A-Z]{1,3}\$|\$)?[\d,]+\.\d{2}$")
|
|
||||||
_REF_RE = re.compile(r"^\d{6,}$")
|
_REF_RE = re.compile(r"^\d{6,}$")
|
||||||
# Two real page-footer pagination patterns seen so far: "Page N of M"
|
# 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
|
# (HSBC) and a bare "N of M" with no leading word at all (confirmed on a
|
||||||
|
|
@ -159,6 +158,13 @@ def _find_zones(page_words, lines_by_top):
|
||||||
if header_row is None:
|
if header_row is None:
|
||||||
return None, None, lines_by_top
|
return None, None, lines_by_top
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
zones = {}
|
zones = {}
|
||||||
for field in ("date", "status", "description"):
|
for field in ("date", "status", "description"):
|
||||||
anchor = resolved.get(field)
|
anchor = resolved.get(field)
|
||||||
|
|
@ -169,7 +175,7 @@ def _find_zones(page_words, lines_by_top):
|
||||||
# that repeats balance figures - those are money-shaped too and would
|
# that repeats balance figures - those are money-shaped too and would
|
||||||
# otherwise form a phantom extra cluster. Anything above the header
|
# otherwise form a phantom extra cluster. Anything above the header
|
||||||
# row itself isn't transaction data.
|
# 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]
|
money_x1 = [w["x1"] for w in page_words if _money_value(w["text"], native_marker) is not None and w["top"] > header_top]
|
||||||
cluster_ranges = [(min(c), max(c)) for c in _cluster_by_gap(money_x1)]
|
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)
|
cluster_ranges.sort(key=lambda r: (r[0] + r[1]) / 2)
|
||||||
|
|
||||||
|
|
@ -180,6 +186,14 @@ def _find_zones(page_words, lines_by_top):
|
||||||
for field, (cmin, cmax) in assigned.items():
|
for field, (cmin, cmax) in assigned.items():
|
||||||
zones[field] = (cmin - 80, cmax + 5)
|
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
|
||||||
|
|
||||||
# Some banks' debit column already prints its own leading minus sign
|
# Some banks' debit column already prints its own leading minus sign
|
||||||
# (confirmed: HSBC); others print a plain positive magnitude that
|
# (confirmed: HSBC); others print a plain positive magnitude that
|
||||||
# needs explicit negation when combined into one signed amount
|
# needs explicit negation when combined into one signed amount
|
||||||
|
|
@ -190,7 +204,7 @@ def _find_zones(page_words, lines_by_top):
|
||||||
# signed value by definition, and "credit" is never negated.
|
# signed value by definition, and "credit" is never negated.
|
||||||
if "debit" in zones:
|
if "debit" in zones:
|
||||||
zones["_debit_self_signed"] = any(
|
zones["_debit_self_signed"] = any(
|
||||||
_MONEY_RE.match(w["text"]) and zones["debit"][0] <= w["x1"] <= zones["debit"][1] and w["text"].startswith("-")
|
_money_value(w["text"], native_marker) is not None and zones["debit"][0] <= w["x1"] <= zones["debit"][1] and w["text"].startswith("-")
|
||||||
for w in page_words
|
for w in page_words
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -210,17 +224,128 @@ def _find_zones(page_words, lines_by_top):
|
||||||
return zones, header_top, lines_by_top
|
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 _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.
|
||||||
|
|
||||||
|
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. 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 = text.startswith("-")
|
||||||
|
body = text[1:] if negative else text
|
||||||
|
if _MONEY_RE.match(text):
|
||||||
|
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 _dominant_money_marker(page_words):
|
||||||
|
"""
|
||||||
|
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.
|
||||||
|
|
||||||
|
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(w["text"])
|
||||||
|
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 _money_value(text, native_marker=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.
|
||||||
|
"""
|
||||||
|
parsed = _parse_money(text)
|
||||||
|
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):
|
def _classify_money(text, x1, zones):
|
||||||
if not _MONEY_RE.match(text):
|
value = _money_value(text, zones.get("_native_marker"))
|
||||||
|
if value is None:
|
||||||
return None
|
return None
|
||||||
for field in _MONEY_FIELDS:
|
for field in _MONEY_FIELDS:
|
||||||
z = zones.get(field)
|
z = zones.get(field)
|
||||||
if z and z[0] <= x1 <= z[1]:
|
if z and z[0] <= x1 <= z[1]:
|
||||||
# Strips any currency-code letters alongside the existing
|
return field, value
|
||||||
# "$"/comma handling - a plain .replace("$", "") alone would
|
|
||||||
# leave a "CA$386.01"-style prefix's letters behind, which
|
|
||||||
# float() can't parse at all.
|
|
||||||
return field, float(re.sub(r"[^\d.\-]", "", text.replace(",", "")))
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue