bettersight-statement-extra.../app/pipeline.py

145 lines
6.3 KiB
Python

import re
import pdfplumber
import table_extract
import reconcile
import checks
# HSBC-specific header text matching, same honest tradeoff noted in
# table_extract.py/docling_client.py - a different bank's statement would
# need its own equivalent, which is exactly what the spec's own layout
# mapper (Phase 3) is for.
_PERIOD_RE = re.compile(r"Specified date range")
_BROUGHT_FORWARD_RE = re.compile(r"Closing ledger balance brought forward")
_MONEY_RE = re.compile(r"([\d,]+\.\d{2})")
_PERIOD_RANGE_RE = re.compile(r"(\d{2} \w{3} \d{4}) to (\d{2} \w{3} \d{4})")
def _extract_header_info(full_text):
"""{"period_start_text", "period_end_text", "brought_forward_balance"} -
informational statement facts, not used as a true opening/closing
balance (see checks.check_statement_balance's own docstring on why)."""
result = {}
lines = full_text.splitlines()
for i, line in enumerate(lines):
if _PERIOD_RE.search(line) and i + 1 < len(lines):
m = _PERIOD_RANGE_RE.search(lines[i + 1])
if m:
result["period_start_text"] = m.group(1)
result["period_end_text"] = m.group(2)
if _BROUGHT_FORWARD_RE.search(line) and "brought_forward_balance" not in result:
for candidate in (line, lines[i - 1] if i > 0 else "", lines[i + 1] if i + 1 < len(lines) else ""):
m = _MONEY_RE.search(candidate)
if m:
result["brought_forward_balance"] = float(m.group(1).replace(",", ""))
break
return result
def run(pdf_path, docling_url, opening_balance=None, closing_balance=None):
"""
The full section-3 pipeline for one statement: run both extraction
engines and cross-check them (reconcile.py) - or, for an upload with
no text layer at all, route through Docling's OCR alone (see
reconcile.run/_needs_ocr) - locate statement-level facts, run the
checks (+ the engine-agreement or ocr-source flag), and return
everything the UI/export need.
"""
recon = reconcile.run(pdf_path, docling_url)
transactions = recon["transactions"]
ocr_only = recon.get("extraction_method") == "ocr"
# _extract_header_info's regexes (period range, brought-forward
# balance) need pdfplumber's own text layer - genuinely nothing to
# read here for an OCR-sourced upload (that's the whole premise), so
# header_info just stays empty rather than calling pdfplumber.open()
# on a file it may not even be able to parse as a PDF at all (a raw
# JPG/PNG upload raises PDFSyntaxError, not an empty result).
header_info = {}
if not ocr_only:
with pdfplumber.open(pdf_path) as pdf:
full_text = "\n".join(p.extract_text(x_tolerance=table_extract.X_TOLERANCE) or "" for p in pdf.pages)
header_info = _extract_header_info(full_text)
# A figure the user explicitly supplied always wins; otherwise fall
# back to whatever extract_statement_facts found printed inside the
# table itself (confirmed for real on RBC, which prints "Opening
# balance"/"Closing balance" as ordinary rows) - the check should use
# a statement's own printed figure automatically rather than asking
# the user to retype a number that's already right there.
facts = recon["statement_facts"]
if opening_balance is None:
opening_balance = facts.get("opening_balance")
if closing_balance is None:
closing_balance = facts.get("closing_balance")
period_start = checks._parse_date(header_info.get("period_start_text", ""))
period_end = checks._parse_date(header_info.get("period_end_text", ""))
check_results = checks.run_all(
transactions, recon["page_reports"],
opening_balance=opening_balance, closing_balance=closing_balance,
period_start=period_start, period_end=period_end,
narrative_direction=recon["narrative_direction"],
ocr_only=ocr_only,
)
period_text = None
if header_info.get("period_start_text"):
period_text = f"{header_info['period_start_text']} to {header_info.get('period_end_text', '?')}"
return {
"transactions": transactions,
"page_reports": recon["page_reports"],
"docling_error": recon["docling_error"],
"period": period_text,
"brought_forward_balance": header_info.get("brought_forward_balance"),
"opening_balance": opening_balance,
"closing_balance": closing_balance,
"narrative_direction": recon["narrative_direction"],
"extraction_method": recon.get("extraction_method", "dual_engine"),
**check_results,
}
_PERIOD_TEXT_RE = re.compile(r"(.+) to (.+)")
def recheck(transactions, page_reports, period_text=None, opening_balance=None, closing_balance=None,
narrative_direction=None):
"""
Re-runs the checks against a transaction list the user may have
edited in the UI (see the web app's inline-editable cells) - without
re-running either extraction engine. `page_reports` and
`narrative_direction` are passed through unchanged: neither which
pages the two engines agreed on, nor which narrative direction this
statement uses, changes just because a user corrected a value.
Returns the same {"status","checks"} shape as run()'s own check
results, so the UI can live-update after an edit and the Excel
export can reflect the edited values instead of going stale the
moment someone fixes a mistake.
Whether the original extraction was OCR-sourced is inferred from
`page_reports` itself (reconcile._run_ocr_only marks every entry
"status": "ocr_only") rather than needing a new field threaded
through the UI's save/export round trip - the caller already has to
pass page_reports through unchanged for other reasons, so this adds
no new surface for the frontend to keep in sync.
"""
period_start = period_end = None
if period_text:
m = _PERIOD_TEXT_RE.match(period_text)
if m:
period_start = checks._parse_date(m.group(1))
period_end = checks._parse_date(m.group(2))
ocr_only = any(pr.get("status") == "ocr_only" for pr in page_reports)
return checks.run_all(
transactions, page_reports,
opening_balance=opening_balance, closing_balance=closing_balance,
period_start=period_start, period_end=period_end,
narrative_direction=narrative_direction,
ocr_only=ocr_only,
)