269 lines
12 KiB
Python
269 lines
12 KiB
Python
import pdfplumber
|
|
|
|
import table_extract
|
|
import docling_client
|
|
import raw_ocr_extract
|
|
|
|
AMOUNT_TOLERANCE = 0.01
|
|
|
|
|
|
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 _run_ocr_only(pdf_path, docling_url):
|
|
"""
|
|
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_client.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.
|
|
|
|
"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.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.py/checks.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.
|
|
"""
|
|
pages_rows = docling_client.ocr_extract_pdf(pdf_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(pdf_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()):
|
|
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."
|
|
)
|
|
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())
|
|
]
|
|
return {
|
|
"transactions": transactions, "page_reports": page_reports, "docling_error": None,
|
|
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
|
|
"extraction_method": "ocr",
|
|
}
|
|
|
|
|
|
def _try_raw_ocr_fallback(pdf_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(pdf_path):
|
|
return raw_ocr_extract.extract_pdf(pdf_path)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
return raw_ocr_extract.extract_image(pdf_path)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def run(pdf_path, docling_url):
|
|
"""
|
|
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).
|
|
|
|
Returns {"transactions": [...] (the canonical list, from pdfplumber -
|
|
see table_extract.py and docling_client.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.check_narrative_direction for how it's
|
|
surfaced, "extraction_method": "dual_engine" or "ocr"}.
|
|
|
|
`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": no text layer existed at all - see _run_ocr_only.
|
|
"""
|
|
if _needs_ocr(pdf_path):
|
|
return _run_ocr_only(pdf_path, docling_url)
|
|
|
|
pages_rows = table_extract.extract_pdf(pdf_path)
|
|
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.
|
|
raise ValueError(
|
|
"Could not recognize this statement's column layout. This extractor currently "
|
|
"only supports HSBC Business Account statements."
|
|
)
|
|
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)
|
|
|
|
pdf_counts = _pdfplumber_page_counts(pages_rows)
|
|
|
|
docling_error = None
|
|
tables = {}
|
|
try:
|
|
result = docling_client.convert(pdf_path, docling_url)
|
|
json_content = result["document"]["json_content"]
|
|
if isinstance(json_content, str):
|
|
import json
|
|
json_content = json.loads(json_content)
|
|
tables = docling_client.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_client.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",
|
|
}
|