import table_extract import docling_client 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.""" return {p: sum(1 for r in rows if r["type"] == "txn") for p, rows in pages_rows.items()} 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(pdf_path, docling_url): """ Runs both engines on the same PDF and cross-checks them per page. 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}. `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. """ 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, }