535 lines
28 KiB
Python
535 lines
28 KiB
Python
# Orchestrates text-PDF-vs-OCR routing and the dual-engine cross-check - no HTTP or filesystem access of its own.
|
|
import pdfplumber
|
|
|
|
from services.extraction import table_extract
|
|
from services.extraction import docling_parser
|
|
from services.extraction import raw_ocr_extract
|
|
from services.extraction import layout_fingerprint
|
|
from repositories import docling_repository
|
|
|
|
AMOUNT_TOLERANCE = 0.01
|
|
|
|
|
|
class LayoutMappingRequired(ValueError):
|
|
"""
|
|
Raised instead of the plain "could not recognize this layout" error
|
|
when BOTH the keyword/geometry auto-detector AND the layout_quirks
|
|
fallback have failed on every page - the layout mapper's own entry
|
|
point (not built yet; this is the backend contract it depends on,
|
|
see CLAUDE.md's "Layout mapper" entry). Carries the computed
|
|
fingerprint so the frontend can look up (or later save) a mapping
|
|
without re-deriving it. A ValueError subclass so existing
|
|
`except ValueError` handlers that haven't been updated yet still
|
|
catch it (as the old generic error, with a worse message) rather
|
|
than crashing with an unhandled exception - routes/extraction.py
|
|
adds a more specific handler ahead of that fallback.
|
|
"""
|
|
|
|
def __init__(self, fingerprint, fingerprint_hash):
|
|
super().__init__("Could not recognize this statement's column layout.")
|
|
self.fingerprint = fingerprint
|
|
self.fingerprint_hash = fingerprint_hash
|
|
|
|
|
|
class ValueRecognitionRequired(ValueError):
|
|
"""
|
|
Raised when the auto-detector found a real, usable header (so
|
|
`LayoutMappingRequired` above never fires - `pages_rows` is NOT
|
|
empty, it's full of narrative-only rows) but every page still came
|
|
back with zero actual transaction rows - the column POSITIONS are
|
|
known, only the VALUES in them don't parse (confirmed for real: a
|
|
"CA$386.01"-style amount this extractor had never seen before, which
|
|
used to just silently return an empty, useless "Needs review" result
|
|
with no error at all - this is the fix for that silent gap, see
|
|
CLAUDE.md's "Value-pattern mapping" entry). Carries a representative
|
|
example row (whatever this extractor managed to read for each known
|
|
field, raw) so the frontend can show it to the user and ask for ONE
|
|
correction per field, rather than the full from-scratch region-
|
|
drawing `LayoutMappingRequired` needs. A ValueError subclass for the
|
|
same reason `LayoutMappingRequired` is - existing `except ValueError`
|
|
handlers still catch it, with a worse message, rather than crashing;
|
|
`routes/extraction.py` adds a more specific handler ahead of that
|
|
fallback.
|
|
"""
|
|
|
|
def __init__(self, fingerprint, fingerprint_hash, candidate_row, field_order):
|
|
super().__init__("Could not recognize this statement's values - column positions look right, but the values in them don't.")
|
|
self.fingerprint = fingerprint
|
|
self.fingerprint_hash = fingerprint_hash
|
|
self.candidate_row = candidate_row
|
|
self.field_order = field_order
|
|
|
|
|
|
def _pdfplumber_page_counts(pages_rows):
|
|
"""{page_no: txn-row count} - counting raw rows (before narrative
|
|
grouping) is enough here: joining narrative text never changes how
|
|
many "txn"-type rows a page has, so this is directly comparable to
|
|
Docling's own per-page transaction count without needing cross-page
|
|
grouping at all. Also reused for the OCR-only path's own page
|
|
counts (see _run_ocr_only) - counting "txn" rows is engine-agnostic."""
|
|
return {p: sum(1 for r in rows if r["type"] == "txn") for p, rows in pages_rows.items()}
|
|
|
|
|
|
def _needs_ocr(path):
|
|
"""True if this upload has no usable embedded text to read at all -
|
|
either because it isn't a PDF container (a raw JPG/PNG phone photo)
|
|
or because it's a PDF wrapping a scanned/photographed page with no
|
|
text layer (confirmed for real: pdfplumber.open() raises
|
|
PDFSyntaxError on a raw image file; a scanned-but-PDF-wrapped page
|
|
opens fine but extract_text() returns nothing on every page). Both
|
|
cases need Docling's OCR as the PRIMARY source (there's no
|
|
pdfplumber pass possible either way) - not just the secondary
|
|
cross-check role it plays for a normal text PDF.
|
|
|
|
Deliberately a narrower, cheaper check than table_extract.extract_pdf
|
|
itself (which also tries to resolve a recognizable column layout) -
|
|
conflating "no text at all" with "has text, but this extractor
|
|
doesn't recognize this particular bank's column layout" would wrongly
|
|
route the second, different problem through OCR instead of today's
|
|
actual (and correctly scoped) "only supports HSBC/RBC-shaped layouts"
|
|
error.
|
|
"""
|
|
try:
|
|
with pdfplumber.open(path) as pdf:
|
|
return not any((page.extract_text() or "").strip() for page in pdf.pages)
|
|
except Exception:
|
|
return True
|
|
|
|
|
|
def _docling_amount(d):
|
|
"""A Docling row's credit/debit/amount collapsed into one signed
|
|
amount, the same shape as the pdfplumber canonical transaction's own
|
|
"amount" - see table_extract.rows_to_transactions."""
|
|
if d.get("amount") is not None:
|
|
return d["amount"]
|
|
return d["credit"] if d["credit"] is not None else d["debit"]
|
|
|
|
|
|
def _compare_amounts(pdf_txns, docling_txns):
|
|
"""Per-field mismatches between two same-length, same-order
|
|
transaction lists for one page (both newest-first, matching the
|
|
statement's own row order) - signed amount and balance compared with
|
|
a cent of tolerance. Returns a list of {"index","field","pdfplumber",
|
|
"docling"} dicts, empty if everything agrees."""
|
|
mismatches = []
|
|
for i, (p, d) in enumerate(zip(pdf_txns, docling_txns)):
|
|
pairs = [("amount", p.get("amount"), _docling_amount(d)), ("balance", p.get("balance"), d.get("balance"))]
|
|
for field, pv, dv in pairs:
|
|
if pv is None and dv is None:
|
|
continue
|
|
if pv is None or dv is None or abs(pv - dv) > AMOUNT_TOLERANCE:
|
|
mismatches.append({"index": i, "field": field, "pdfplumber": pv, "docling": dv})
|
|
return mismatches
|
|
|
|
|
|
def _ocr_header_candidate_geometry(file_path):
|
|
"""raw_ocr_extract.header_candidate_geometry(file_path, is_image) with
|
|
is_image resolved the same way _try_raw_ocr_fallback already
|
|
distinguishes a real (if textless) PDF container from a bare image
|
|
file - try opening it as a PDF first, only treat it as a bare image
|
|
if that fails. None if neither produces anything recognizable."""
|
|
try:
|
|
with pdfplumber.open(file_path):
|
|
return raw_ocr_extract.header_candidate_geometry(file_path, is_image=False)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
return raw_ocr_extract.header_candidate_geometry(file_path, is_image=True)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _ocr_fingerprint(file_path):
|
|
"""(fingerprint, fingerprint_hash) via raw_ocr_extract's own geometry
|
|
function, or (None, None) if nothing recognizable at all - the
|
|
OCR-side equivalent of the fingerprint computation run() itself does
|
|
for the pdfplumber path below. Computed fresh here (not threaded
|
|
through from whatever extraction already ran) - the same "recompute
|
|
rather than carry state" tradeoff the pdfplumber path already
|
|
accepts, just a second OCR pass instead of a second pdfplumber one."""
|
|
geometry = _ocr_header_candidate_geometry(file_path)
|
|
if geometry is None:
|
|
return None, None
|
|
fingerprint = layout_fingerprint.compute_fingerprint(*geometry)
|
|
return fingerprint, layout_fingerprint.fingerprint_hash(fingerprint)
|
|
|
|
|
|
def _run_ocr_only(file_path, docling_url, forced_mapping=None):
|
|
"""
|
|
Docling-OCR-primary path for an upload with no embedded text layer at
|
|
all (see _needs_ocr) - a scan, or a phone photo. There is no
|
|
pdfplumber pass possible here, so there's no second engine to cross-
|
|
check against either - Docling's own OCR'd table structure IS the
|
|
canonical source, reshaped (docling_parser.ocr_extract_pdf) into the
|
|
exact same row format table_extract.extract_page() produces, so
|
|
rows_to_transactions/extract_statement_facts - already proven correct
|
|
for the dual-engine path - run completely unchanged rather than
|
|
duplicating that logic for this engine.
|
|
|
|
`forced_mapping` - the OCR-side equivalent of run()'s own
|
|
forced_mapping handling below (manual layout mapping for a scanned/
|
|
photographed statement, not just a born-digital PDF - see CLAUDE.md's
|
|
"Manual layout mapping for OCR sources" entry). When it carries a
|
|
`columnMap`, Docling's own table-structure call is skipped entirely -
|
|
no reason to run TableFormer once the user has already overridden its
|
|
job - and extraction goes straight through raw_ocr_extract.py, the
|
|
same geometry-based, point-range-compatible module that already
|
|
stands in whenever Docling's own recognition fails. docling_parser's
|
|
own column-INDEX grid has no x-coordinate concept a forced zone could
|
|
even apply to, which is why this never routes a forced mapping
|
|
through Docling at all, not even as a first attempt.
|
|
|
|
"page_reports" entries carry "pdfplumber_count" populated with
|
|
whichever engine actually ran's own per-page count (not literally
|
|
from pdfplumber - there is none here) so checks_service.check_page_coverage
|
|
can run unmodified; there is no "docling_count" to compare it
|
|
against, so "status" is "ocr_only" or "ocr_raw_words" (never
|
|
"ok"/"fallback_only"/"mismatch" - those values specifically mean
|
|
something about engine AGREEMENT, which doesn't apply when only one
|
|
engine ran). See pipeline_service.py/checks_service.py for how
|
|
"extraction_method": "ocr" is used to keep this path from ever
|
|
reaching "Verified" - there's no second opinion to earn that on.
|
|
|
|
Docling's table-structure recognition (TableFormer) is tried first -
|
|
it's usually fine - but confirmed for real to sometimes merge
|
|
unrelated page content into a table, or merge two real columns into
|
|
one cell, or miss a page's table entirely, on a page it would
|
|
structure correctly as a native PDF (see CLAUDE.md's "OCR / scanned
|
|
statements" section). The fallback is PER-PAGE, not document-level -
|
|
confirmed necessary for real: on a genuine multi-page scan, Docling
|
|
succeeded on one page and completely missed another in the SAME
|
|
conversion call, and a document-level "any page got rows at all"
|
|
check would have silently kept the failed page empty instead of
|
|
retrying it, exactly the silent-data-loss this product exists to
|
|
avoid. raw_ocr_extract is run across the WHOLE document whenever ANY
|
|
page is empty (not just the empty ones) so its own cross-page zone-
|
|
sharing (see its docstring) can still use a good page to fix a
|
|
degenerate one - then only the pages Docling actually failed are
|
|
replaced with its result; a page Docling got right is never
|
|
second-guessed. Still genuinely possible for a page to fail in both
|
|
engines (nothing OCR-detectable on it at all) - that page just stays
|
|
empty, same as it would with no fallback.
|
|
"""
|
|
if forced_mapping and forced_mapping.get("columnMap"):
|
|
kwargs = dict(
|
|
forced_zones=forced_mapping.get("columnMap"),
|
|
forced_sign_convention=forced_mapping.get("signConvention"),
|
|
ignored_row_rules=forced_mapping.get("ignoredRowRules"),
|
|
date_format=forced_mapping.get("dateFormat", "textual"),
|
|
value_patterns=forced_mapping.get("valuePatterns"),
|
|
# header_bottom applies on a bare image too (excludes
|
|
# preamble/letterhead text above the user's own drawn
|
|
# columns, same as on a PDF's start page) - only start_page
|
|
# is genuinely PDF-only (extract_image has no multi-page
|
|
# concept to skip whole pages of), so it's passed separately
|
|
# below, only on the extract_pdf call.
|
|
header_bottom=forced_mapping.get("headerBottom"),
|
|
)
|
|
try:
|
|
with pdfplumber.open(file_path):
|
|
pages_rows = raw_ocr_extract.extract_pdf(
|
|
file_path, start_page=forced_mapping.get("startPage", 1), **kwargs,
|
|
)
|
|
except Exception:
|
|
pages_rows = raw_ocr_extract.extract_image(file_path, **kwargs)
|
|
if not any(pages_rows.values()):
|
|
# Same reasoning as the pdfplumber forced-mapping path below -
|
|
# a bad column selection, not "this layout needs mapping" (we
|
|
# already have one); never LayoutMappingRequired again here,
|
|
# that would loop the mapper back on itself.
|
|
raise ValueError("This mapping produced no transaction rows - check the column selections.")
|
|
all_rows = [r for p in sorted(pages_rows.keys()) for r in pages_rows[p]]
|
|
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
|
|
statement_facts = table_extract.extract_statement_facts(all_rows)
|
|
counts = _pdfplumber_page_counts(pages_rows)
|
|
page_reports = [
|
|
{"page": p, "pdfplumber_count": counts.get(p, 0), "docling_count": None,
|
|
"status": "ocr_raw_words", "mismatches": []}
|
|
for p in sorted(pages_rows.keys())
|
|
]
|
|
fingerprint, fingerprint_hash = _ocr_fingerprint(file_path)
|
|
return {
|
|
"transactions": transactions, "page_reports": page_reports, "docling_error": None,
|
|
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
|
|
"extraction_method": "ocr",
|
|
"fingerprint": fingerprint, "fingerprintHash": fingerprint_hash,
|
|
}
|
|
|
|
pages_rows = docling_parser.ocr_extract_pdf(file_path, docling_url)
|
|
engine_by_page = {p: "ocr_only" for p in pages_rows}
|
|
|
|
empty_pages = [p for p, rows in pages_rows.items() if not any(r["type"] == "txn" for r in rows)]
|
|
if empty_pages:
|
|
fallback_rows = _try_raw_ocr_fallback(file_path)
|
|
if fallback_rows:
|
|
for p in empty_pages:
|
|
fb_rows = fallback_rows.get(p, [])
|
|
if any(r["type"] == "txn" for r in fb_rows):
|
|
pages_rows[p] = fb_rows
|
|
engine_by_page[p] = "ocr_raw_words"
|
|
|
|
if not any(pages_rows.values()):
|
|
# As of manual layout mapping for OCR sources, a never-seen OCR
|
|
# statement gets the SAME auto-triggered "needs mapping" banner a
|
|
# never-seen PDF statement already does, rather than just a bare,
|
|
# unrecoverable error - raw_ocr_extract's own geometry function is
|
|
# the OCR-side equivalent of table_extract.header_candidate_geometry
|
|
# (which needs a real text layer, which doesn't exist here).
|
|
fingerprint, fingerprint_hash = _ocr_fingerprint(file_path)
|
|
if fingerprint is None:
|
|
raise ValueError(
|
|
"Could not read this statement via OCR - no table structure was recognized in the "
|
|
"scanned or photographed image. Try a clearer photo, or a text-based PDF export "
|
|
"if one is available."
|
|
)
|
|
raise LayoutMappingRequired(fingerprint, fingerprint_hash)
|
|
|
|
all_rows = [r for p in sorted(pages_rows.keys()) for r in pages_rows[p]]
|
|
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
|
|
statement_facts = table_extract.extract_statement_facts(all_rows)
|
|
counts = _pdfplumber_page_counts(pages_rows)
|
|
page_reports = [
|
|
{"page": p, "pdfplumber_count": counts.get(p, 0), "docling_count": None,
|
|
"status": engine_by_page.get(p, "ocr_only"), "mismatches": []}
|
|
for p in sorted(pages_rows.keys())
|
|
]
|
|
# Computed unconditionally now (success or failure, mirroring the
|
|
# pdfplumber path in run() below) - this is what lets the frontend's
|
|
# manual "Map" button open the mapper against an OCR document that
|
|
# extracted just fine but still got something wrong (the wrong start
|
|
# page/header boundary, say), not just a document that failed outright.
|
|
fingerprint, fingerprint_hash = _ocr_fingerprint(file_path)
|
|
return {
|
|
"transactions": transactions, "page_reports": page_reports, "docling_error": None,
|
|
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
|
|
"extraction_method": "ocr",
|
|
"fingerprint": fingerprint, "fingerprintHash": fingerprint_hash,
|
|
}
|
|
|
|
|
|
def _try_raw_ocr_fallback(file_path):
|
|
"""None if the fallback itself errors (e.g. a genuinely corrupt file) -
|
|
distinct from an empty-but-successful result, so the caller can tell
|
|
"fallback ran and found nothing" from "fallback couldn't run at all"
|
|
without either one masking a real exception."""
|
|
try:
|
|
with pdfplumber.open(file_path):
|
|
return raw_ocr_extract.extract_pdf(file_path)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
return raw_ocr_extract.extract_image(file_path)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def run(file_path, docling_url, forced_mapping=None):
|
|
"""
|
|
Runs both engines on the same PDF and cross-checks them per page - or,
|
|
for an upload with no text layer at all (a scan or phone photo),
|
|
routes to _run_ocr_only instead, where Docling's OCR is the sole
|
|
source (see _needs_ocr).
|
|
|
|
`forced_mapping` ({"columnMap"?, "signConvention"?, "ignoredRowRules"?,
|
|
"dateFormat"?, "valuePatterns"?} or None) - supplied by the layout
|
|
mapper when a statement's layout needed a human (or a previously-
|
|
saved mapping) to resolve. A normal call with no forced_mapping
|
|
behaves exactly as before. When `columnMap` is present, this bypasses
|
|
the keyword/geometry auto-detector and layout_quirks fallback
|
|
entirely, extracting directly from the given column positions
|
|
instead (the full manual-mapping case). `valuePatterns` is different:
|
|
it composes WITH auto-detection rather than replacing it - a
|
|
"value-pattern mapping" (see CLAUDE.md's own entry) supplies ONLY
|
|
this key, no `columnMap` at all, for a statement whose columns the
|
|
auto-detector already finds fine but whose raw VALUES it can't
|
|
parse - see table_extract.extract_pdf's own docstring for why this
|
|
one field alone is safe to apply either way.
|
|
|
|
Returns {"transactions": [...] (the canonical list, from pdfplumber -
|
|
see table_extract.py and docling_parser.py's own docstrings for why),
|
|
"page_reports": [{"page", "pdfplumber_count", "docling_count",
|
|
"status", "mismatches"}, ...], "docling_error": str or None,
|
|
"statement_facts": {"opening_balance", "closing_balance"} (whatever
|
|
table_extract.extract_statement_facts found printed INSIDE the table
|
|
itself - None for a layout like HSBC's that doesn't print these there),
|
|
"narrative_direction": table_extract.rows_to_transactions's own
|
|
direction_info - see checks_service.check_narrative_direction for how
|
|
it's surfaced, "extraction_method": "dual_engine" or "ocr",
|
|
"fingerprint"/"fingerprintHash": this statement's own header-geometry
|
|
fingerprint, computed unconditionally (success or failure, pdfplumber
|
|
OR OCR-sourced - see raw_ocr_extract.header_candidate_geometry for
|
|
the OCR-side equivalent) so the frontend's manual "Map" button can
|
|
open the mapper against an already-successful extraction, not just a
|
|
failed one - None/None only when neither a real text layer nor OCR
|
|
found anything recognizable at all}.
|
|
|
|
`status` per page is one of:
|
|
- "ok": both engines found the same transaction count (and, where
|
|
checked, agreeing amounts).
|
|
- "fallback_only": Docling did not recognize a table on this page at
|
|
all (confirmed to happen for real - see the plan/spike notes) -
|
|
pdfplumber's result is used with no second opinion.
|
|
- "mismatch": both engines found a table, but disagree on count or
|
|
on specific amounts - surfaced for review, never silently resolved.
|
|
- "ocr_only"/"ocr_raw_words": no text layer existed at all - see
|
|
_run_ocr_only.
|
|
"""
|
|
if _needs_ocr(file_path):
|
|
# Passed through now (was silently discarded before manual OCR
|
|
# mapping existed) - a forced_mapping request for a file that
|
|
# needs OCR used to reach this return with no way to ever apply
|
|
# it; _run_ocr_only's own forced_mapping handling is what makes
|
|
# the manual "Map" button actually work for a scanned/
|
|
# photographed statement.
|
|
return _run_ocr_only(file_path, docling_url, forced_mapping=forced_mapping)
|
|
|
|
if forced_mapping:
|
|
pages_rows = table_extract.extract_pdf(
|
|
file_path,
|
|
forced_zones=forced_mapping.get("columnMap"),
|
|
forced_sign_convention=forced_mapping.get("signConvention"),
|
|
ignored_row_rules=forced_mapping.get("ignoredRowRules"),
|
|
date_format=forced_mapping.get("dateFormat", "textual"),
|
|
start_page=forced_mapping.get("startPage", 1),
|
|
header_bottom=forced_mapping.get("headerBottom"),
|
|
value_patterns=forced_mapping.get("valuePatterns"),
|
|
)
|
|
if not any(pages_rows.values()):
|
|
# The mapping itself didn't produce anything - a bad column
|
|
# selection, not "this layout needs mapping" (we already have
|
|
# one). Distinct message, and deliberately NOT
|
|
# LayoutMappingRequired again - raising that here would loop
|
|
# the mapper back on itself instead of surfacing the real
|
|
# problem (the mapping the user just built/picked is wrong).
|
|
raise ValueError("This mapping produced no transaction rows - check the column selections.")
|
|
else:
|
|
pages_rows = table_extract.extract_pdf(file_path, value_patterns=forced_mapping.get("valuePatterns") if forced_mapping else None)
|
|
if not any(pages_rows.values()):
|
|
# Every page came back completely empty - not "a valid statement
|
|
# with no transactions this period" (that still produces page
|
|
# furniture/narrative rows, since table_extract only returns []
|
|
# for a page where it never found a recognizable header at all).
|
|
# Confirmed for real: uploading an RBC statement - a different
|
|
# column layout this extractor doesn't know about yet - silently
|
|
# produced zero transactions instead of telling the user why.
|
|
# As of the layout-mapper work, this is the signal that tier
|
|
# 1 (keyword detector) AND tier 2 (layout_quirks) have both
|
|
# failed - compute a fingerprint so tier 3/4 (a stored
|
|
# mapping, or the manual mapping screen) have something to
|
|
# key off of, rather than a bare, unrecoverable error.
|
|
geometry = table_extract.header_candidate_geometry(file_path)
|
|
if geometry is None:
|
|
raise ValueError("Could not recognize this statement's column layout.")
|
|
fingerprint = layout_fingerprint.compute_fingerprint(*geometry)
|
|
raise LayoutMappingRequired(fingerprint, layout_fingerprint.fingerprint_hash(fingerprint))
|
|
# Narrower than the check above: the header WAS recognized
|
|
# (pages_rows isn't empty - it has narrative rows), but every
|
|
# page still produced zero actual TRANSACTION rows. Confirmed
|
|
# for real on a CAD-denominated Equals Money statement whose
|
|
# amounts print as "CA$386.01" - a currency-code prefix this
|
|
# extractor had never seen - which used to silently return an
|
|
# empty, useless "Needs review" result with no error at all.
|
|
# The column POSITIONS are known here (that's exactly what
|
|
# distinguishes this from the empty-pages_rows case above); only
|
|
# the VALUES in them don't parse - value_recognition_preview's
|
|
# own rough, label-anchored zones are what let this show the
|
|
# user something concrete to correct, one field at a time,
|
|
# rather than the full from-scratch region-drawing
|
|
# LayoutMappingRequired needs.
|
|
elif sum(_pdfplumber_page_counts(pages_rows).values()) == 0:
|
|
preview = table_extract.value_recognition_preview(file_path)
|
|
if preview is None:
|
|
# No plausible candidate row either - nothing concrete
|
|
# to show, so this falls through to the exact same
|
|
# "full manual mapping" path as a totally-unrecognized
|
|
# layout, not a blank confirmation form.
|
|
geometry = table_extract.header_candidate_geometry(file_path)
|
|
if geometry is None:
|
|
raise ValueError("Could not recognize this statement's column layout.")
|
|
fingerprint = layout_fingerprint.compute_fingerprint(*geometry)
|
|
raise LayoutMappingRequired(fingerprint, layout_fingerprint.fingerprint_hash(fingerprint))
|
|
words, lines_by_top, page_width, page_height, candidate_row, field_order = preview
|
|
fingerprint = layout_fingerprint.compute_fingerprint(words, lines_by_top, page_width, page_height)
|
|
raise ValueRecognitionRequired(
|
|
fingerprint, layout_fingerprint.fingerprint_hash(fingerprint), candidate_row, field_order,
|
|
)
|
|
all_rows = [r for p in sorted(pages_rows.keys()) for r in pages_rows[p]]
|
|
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
|
|
statement_facts = table_extract.extract_statement_facts(all_rows)
|
|
|
|
# Computed unconditionally for a SUCCESSFUL extraction too, not just
|
|
# the failure paths above - this is what lets the frontend's own
|
|
# "Map" button (TransactionsTable.vue, launched manually when
|
|
# auto-detection technically succeeded but got something wrong - a
|
|
# real report: the wrong start page/header boundary silently pulled
|
|
# preamble text into the first transaction's own description) open
|
|
# the exact same manual-mapping screen a failed extraction would
|
|
# have, with a real fingerprint to save a correcting mapping
|
|
# against. A cheap, independent re-derivation from the raw PDF's own
|
|
# header geometry (the same call the failure path above already
|
|
# makes), not threaded through from the extraction that just ran -
|
|
# None for a statement header_candidate_geometry itself can't find
|
|
# anything on (vanishingly rare for an extraction that just
|
|
# succeeded, but possible), in which case the Map button simply has
|
|
# nothing to seed itself with.
|
|
geometry = table_extract.header_candidate_geometry(file_path)
|
|
fingerprint = layout_fingerprint.compute_fingerprint(*geometry) if geometry is not None else None
|
|
fingerprint_hash = layout_fingerprint.fingerprint_hash(fingerprint) if fingerprint is not None else None
|
|
|
|
pdf_counts = _pdfplumber_page_counts(pages_rows)
|
|
|
|
docling_error = None
|
|
tables = {}
|
|
try:
|
|
result = docling_repository.convert(file_path, docling_url)
|
|
json_content = result["document"]["json_content"]
|
|
if isinstance(json_content, str):
|
|
import json
|
|
json_content = json.loads(json_content)
|
|
tables = docling_parser.tables_by_page(json_content)
|
|
except Exception as e:
|
|
docling_error = str(e)
|
|
|
|
# Attribute canonical transactions to the page their own txn-row
|
|
# started on, so per-page Docling comparisons can be made against the
|
|
# right slice of the canonical list (narrative joining doesn't change
|
|
# a transaction's own starting page).
|
|
txns_by_page = {}
|
|
idx = 0
|
|
for p in sorted(pages_rows.keys()):
|
|
count = pdf_counts.get(p, 0)
|
|
txns_by_page[p] = transactions[idx: idx + count]
|
|
idx += count
|
|
|
|
page_reports = []
|
|
for p in sorted(pages_rows.keys()):
|
|
pdf_count = pdf_counts.get(p, 0)
|
|
table = tables.get(p)
|
|
if table is None:
|
|
page_reports.append({
|
|
"page": p, "pdfplumber_count": pdf_count, "docling_count": None,
|
|
"status": "fallback_only", "mismatches": [],
|
|
})
|
|
continue
|
|
|
|
docling_txns = docling_parser.extract_transactions(table)
|
|
if len(docling_txns) != pdf_count:
|
|
page_reports.append({
|
|
"page": p, "pdfplumber_count": pdf_count, "docling_count": len(docling_txns),
|
|
"status": "mismatch", "mismatches": [],
|
|
})
|
|
continue
|
|
|
|
mismatches = _compare_amounts(txns_by_page[p], docling_txns)
|
|
page_reports.append({
|
|
"page": p, "pdfplumber_count": pdf_count, "docling_count": len(docling_txns),
|
|
"status": "mismatch" if mismatches else "ok", "mismatches": mismatches,
|
|
})
|
|
|
|
return {
|
|
"transactions": transactions, "page_reports": page_reports, "docling_error": docling_error,
|
|
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
|
|
"extraction_method": "dual_engine",
|
|
"fingerprint": fingerprint, "fingerprintHash": fingerprint_hash,
|
|
}
|