116 lines
5.6 KiB
Python
116 lines
5.6 KiB
Python
"""
|
|
Computes a fingerprint for a statement layout the keyword/geometry
|
|
detector (and the layout_quirks module) couldn't resolve on their own -
|
|
used by the layout mapper (not built yet - this is the backend
|
|
contract only) to recognize "this is the same layout as a mapping
|
|
someone already created" without a human re-mapping it every time.
|
|
|
|
Only ever called on the failure path - extraction_service.py computes
|
|
this right before raising LayoutMappingRequired. A statement that
|
|
resolves normally (tier 1 or tier 2) never reaches this module at all.
|
|
"""
|
|
import hashlib
|
|
import json
|
|
|
|
from services.extraction import layout_rules
|
|
|
|
# field_positions are bucketed to this fraction of the page's own width -
|
|
# absorbs ordinary pixel/margin jitter between two statements of the same
|
|
# template (e.g. a slightly different margin on a continuation page)
|
|
# while still distinguishing a genuinely different column layout.
|
|
_POSITION_BUCKET = 0.02
|
|
# page dimensions bucketed to the nearest this many points - absorbs
|
|
# minor PDF-generator rounding without conflating Letter and A4.
|
|
_PAGE_SIZE_BUCKET = 6
|
|
|
|
_MONEY_FIELDS_ORDERED = ("date", "description", "debit", "credit", "amount", "balance", "status")
|
|
|
|
|
|
def compute_fingerprint(words, lines_by_top, page_width, page_height):
|
|
"""
|
|
{header_labels, field_labels, field_order, field_positions,
|
|
page_width_bucket, page_height_bucket, header_line_count,
|
|
has_status_column, has_single_amount_column} - see this module's own
|
|
docstring for how it's used. Built by resolving EVERY line on the
|
|
candidate page against the shared keyword vocabulary and unioning
|
|
the matches, since on a failing statement no single line resolves
|
|
the full required shape (that's the whole reason a fingerprint is
|
|
being computed at all).
|
|
|
|
`field_labels` ({field: literal matched text}, e.g. {"debit":
|
|
"debits", "credit": "credits"}) is what the frontend's own near-match
|
|
comparison (layoutMappingsService.js's scoreNearMatch) actually
|
|
reads - deliberately keyed by field, not just a flat text list, so
|
|
"only the Debit/Credit labels changed to Withdrawals/Deposits" can be
|
|
scored as "3 of 4 fields still match" rather than collapsing into an
|
|
undifferentiated set comparison that scores two still-identically-
|
|
shaped layouts as barely related just because a couple of words
|
|
changed (confirmed necessary for real - a flat-set Jaccard overlap
|
|
scored exactly that real case as only 33% similar, well under any
|
|
reasonable near-match threshold, when structurally it's the same
|
|
layout with 2 of 4 labels renamed). `header_labels` (the same text,
|
|
flattened to a sorted set) stays only as the literal-text component
|
|
of the EXACT-match hash (fingerprint_hash) - full text equality is
|
|
the right bar there, so no field-level leniency is wanted for it.
|
|
"""
|
|
resolved_by_x0 = {}
|
|
field_labels = {}
|
|
header_labels = []
|
|
header_line_count = 0
|
|
for top in sorted(lines_by_top.keys()):
|
|
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 not resolved:
|
|
continue
|
|
header_line_count += 1
|
|
for field, (x0, x1) in resolved.items():
|
|
# Earlier (higher on the page) and leftmost wins if the same
|
|
# field is somehow matched on more than one line - keeps the
|
|
# fingerprint stable rather than picking whichever happened
|
|
# to be last in dict-iteration order.
|
|
resolved_by_x0.setdefault(field, (x0, x1))
|
|
label_words = [w for w in line_sorted if x0 <= w["x0"] and w["x1"] <= x1]
|
|
label_text = " ".join(w["text"] for w in label_words).strip().lower()
|
|
field_labels.setdefault(field, label_text)
|
|
header_labels.append(label_text)
|
|
|
|
field_order = [f for f in _MONEY_FIELDS_ORDERED if f in resolved_by_x0]
|
|
field_positions = {}
|
|
for field, (x0, x1) in resolved_by_x0.items():
|
|
center = (x0 + x1) / 2
|
|
bucket = round((center / page_width) / _POSITION_BUCKET) * _POSITION_BUCKET
|
|
field_positions[field] = round(bucket, 4)
|
|
|
|
return {
|
|
"header_labels": sorted(set(label for label in header_labels if label)),
|
|
"field_labels": field_labels,
|
|
"field_order": field_order,
|
|
"field_positions": field_positions,
|
|
"page_width_bucket": round(page_width / _PAGE_SIZE_BUCKET) * _PAGE_SIZE_BUCKET,
|
|
"page_height_bucket": round(page_height / _PAGE_SIZE_BUCKET) * _PAGE_SIZE_BUCKET,
|
|
"header_line_count": header_line_count,
|
|
"has_status_column": "status" in resolved_by_x0,
|
|
"has_single_amount_column": "amount" in resolved_by_x0,
|
|
}
|
|
|
|
|
|
def fingerprint_hash(fingerprint):
|
|
"""
|
|
SHA-256 hex of the canonical JSON of the fields that define "this is
|
|
the SAME layout" for exact-match lookups - deliberately excludes
|
|
page_width_bucket/page_height_bucket/header_line_count (these can
|
|
vary innocuously, e.g. a slightly taller continuation page, without
|
|
the layout itself having changed) while keeping them in the stored
|
|
fingerprint object for the separate, looser near-match comparison
|
|
(frontend-only, see the layout mapper's own plan).
|
|
"""
|
|
hashed_fields = {
|
|
"header_labels": fingerprint["header_labels"],
|
|
"field_order": fingerprint["field_order"],
|
|
"field_positions": fingerprint["field_positions"],
|
|
"has_status_column": fingerprint["has_status_column"],
|
|
"has_single_amount_column": fingerprint["has_single_amount_column"],
|
|
}
|
|
canonical = json.dumps(hashed_fields, sort_keys=True, separators=(",", ":"))
|
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|