bettersight-statement-extra.../backend/services/pipeline_service.py

167 lines
7.8 KiB
Python

# Composes extraction_service + checks_service into the full run()/recheck() pipeline.
import re
import pdfplumber
from services.extraction import table_extract
from services import extraction_service
from services import checks_service
# HSBC-specific header text matching, same honest tradeoff noted in
# table_extract.py/docling_parser.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_service.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(file_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 (extraction_service.py) - or, for an
upload with no text layer at all, route through Docling's OCR alone
(see extraction_service.run/_needs_ocr) - locate statement-level
facts, run the checks (+ the engine-agreement or ocr-source flag),
and return everything the UI/export need.
Data flow:
file_path (str) - local path to the saved upload
docling_url (str) - base URL of the self-hosted Docling container
opening_balance (float or None) - user-supplied, wins over anything auto-detected
closing_balance (float or None) - user-supplied, wins over anything auto-detected
returns (dict) - transactions, page_reports, checks, status,
period, balances, extraction_method
"""
recon = extraction_service.run(file_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(file_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_service._parse_date(header_info.get("period_start_text", ""))
period_end = checks_service._parse_date(header_info.get("period_end_text", ""))
check_results = checks_service.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.
Data flow:
transactions (list) - possibly user-edited transaction rows
page_reports (list) - passed through unchanged (which pages the
two engines agreed on doesn't change just
because a user corrected a value)
period_text (str or None) - "DD Mon YYYY to DD Mon YYYY"
opening_balance (float or None)
closing_balance (float or None)
narrative_direction (dict or None) - passed through unchanged
returns (dict) - the same {"status","checks"} shape as
run()'s own check results
Whether the original extraction was OCR-sourced is inferred from
`page_reports` itself (extraction_service._run_ocr_only marks every
entry "status": "ocr_only"/"ocr_raw_words") 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_service._parse_date(m.group(1))
period_end = checks_service._parse_date(m.group(2))
# Both "ocr_only" (Docling succeeded) and "ocr_raw_words" (the
# per-page fallback rescued a page Docling failed on) mean this
# page's data came from OCR with no second engine to check it -
# checking only "ocr_only" would wrongly treat a statement where
# EVERY page needed the fallback as non-OCR-sourced, letting it
# reach "Verified" when it shouldn't be able to (see CLAUDE.md's
# "Key decisions & lessons" entry on this bug).
ocr_only = any(pr.get("status") in ("ocr_only", "ocr_raw_words") for pr in page_reports)
return checks_service.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,
)