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

95 lines
4.4 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_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).
"""
resolved_by_x0 = {}
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))
header_labels.append(" ".join(w["text"] for w in line_sorted))
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.strip().lower() for label in header_labels if label.strip())),
"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()