import json import mimetypes import re import requests import layout_rules CONVERT_TIMEOUT = 300 _MONEY_RE = re.compile(r"-?[\d,]+\.\d{2}") _MONEY_FIELDS = ("debit", "credit", "amount", "balance") def convert(pdf_path, docling_url): """ POST a file to Docling's /v1/convert/file, requesting both Markdown and structured JSON. do_table_structure is left at Docling's own default (true) - confirmed via its /openapi.json schema. The content-type is guessed from the file's own extension rather than hardcoded to "application/pdf" - this function also handles raw image uploads (a scanned/photographed statement with no PDF container at all) via Docling's own OCR, confirmed for real to work when sent with its correct image/* content-type. Returns the raw response dict: {"document": {"md_content", "json_content", ...}, "status", "errors", "confidence", ...}. Raises on a non-2xx response or network/timeout error - callers decide how to surface that (this module doesn't know about Flask error responses). """ content_type = mimetypes.guess_type(pdf_path)[0] or "application/octet-stream" with open(pdf_path, "rb") as f: response = requests.post( f"{docling_url}/v1/convert/file", files={"files": (pdf_path.split("/")[-1], f, content_type)}, data={"to_formats": ["md", "json"]}, timeout=CONVERT_TIMEOUT, ) response.raise_for_status() return response.json() def _page_no(item): """An item's page number from its own provenance list - every table/ text item we've seen carries exactly one prov entry with a page_no.""" prov = item.get("prov") or [] return prov[0]["page_no"] if prov else None def tables_by_page(json_content): """ {page_no: table_dict} for every page where Docling recognized a table. A page missing from this dict is a page Docling did NOT structure as a table (confirmed for real: page 4 of a real 4-page HSBC statement came back as loose text items instead) - reconcile.py is what decides what to do about that, not this module. """ result = {} for table in json_content.get("tables", []): page_no = _page_no(table) if page_no is not None: result[page_no] = table return result def table_rows(table): """ A Docling table's cells, keyed by (row_idx, col_idx) -> text. Docling gives flat table_cells with start_row_offset_idx/start_col_offset_idx; this just re-indexes them for convenient row-by-row access. """ cells = {} for cell in table.get("data", {}).get("table_cells", []): r = cell.get("start_row_offset_idx") c = cell.get("start_col_offset_idx") cells[(r, c)] = cell.get("text", "") return cells def num_pages(json_content): return len(json_content.get("pages", {})) def _all_field_matches(text): """Every (field, phrase) hit for one header cell's text, across ALL fields - unlike layout_rules.match_field (which returns only the single overall-best match, the right tool for table_extract.py's own sliding-word-window header detection), this is what lets _resolve_columns tell apart two genuinely different situations that both look like "a field has multiple candidate columns" (see its own docstring): a single cell's text containing vocabulary from more than one semantic field at once (corruption) versus two separately-clean cells that each legitimately match the same field on their own.""" text = text.lower() hits = [] for field, phrases in layout_rules.COLUMN_FIELD_KEYWORDS.items(): for phrase in phrases: if phrase in text: hits.append((field, phrase)) break # phrases are longest-first per field - first hit is that field's own best return hits def _resolve_columns(cells, num_cols, header_row=0): """{field: col} for one row of a table, treated as the header - each column's semantic role via the same keyword vocabulary table_extract.py uses (layout_rules.py). `header_row` defaults to 0 (true for every cross-check table seen so far - see extract_transactions) but ocr_table_to_rows searches multiple candidate rows with this same function (see its own docstring on why row 0 isn't a safe assumption for an OCR'd page). A plain first-match-wins scan over match_field's own single-best result per cell isn't safe here - confirmed necessary for real, two different ways: 1. SELF-CONTAMINATED cell: on an RBC statement, Docling's own table- structure model mis-segmented a wrapped two-line header ("Cheques & Debits ($)" / "Deposits & Credits ($)") into a phantom extra column, scrambling "Debits"/"Deposits" text across the wrong cells - the resulting cell text ("&Debits ($) Deposits") contains vocabulary from BOTH "debit" and "credit" at once. A column whose text matches more than one distinct field this way is excluded outright - trustworthy for neither - rather than letting whichever field match_field's own internal tie-break happened to rank highest silently claim it (confirmed to pick the WRONG one here: "deposits", 8 characters, outranks "credit", 6, even though the clean credit column is the OTHER cell). 2. LEGITIMATE duplicate coverage: on an HSBC statement, two entirely separate, individually-CLEAN columns - "Value date" and "Post date" - both genuinely and correctly match the "date" field, with neither cell's text containing any other field's vocabulary at all. Excluding "date" entirely here (as a blanket "any collision means ambiguous" rule would) broke a previously-working column resolution for real - confirmed by running the fixture corpus after that version shipped. The fix: among only the non- contaminated candidates for a field, prefer the one matched by the longer, more specific phrase ("value date" beats the bare "date" fallback keyword); only leave the field genuinely unresolved if that's still a tie. """ col_fields = {} for col in range(num_cols): label = cells.get((header_row, col), "") or "" best = layout_rules.match_field(label) if best is None: continue best_field, best_phrase = best # A losing field's own matched phrase that's simply a SUBSTRING # of the winning phrase isn't a second concept, just a smaller # piece of the same one match_field already picked (confirmed # necessary for real: "Credit amount" matches both "credit" field # via "credit amount" AND "amount" field via the bare "amount" # keyword it happens to contain - "amount" is literally inside # "credit amount", not a separate concept, so this must NOT count # as contamination the way "&Debits ($) Deposits" matching both # "debit" via "debit" and "credit" via "deposits" - two completely # disjoint fragments of text - genuinely does). contaminated = any( phrase not in best_phrase for field, phrase in _all_field_matches(label) if field != best_field ) if not contaminated: col_fields[col] = (best_field, best_phrase) by_field = {} for col, (field, phrase) in col_fields.items(): by_field.setdefault(field, []).append((col, phrase)) resolved = {} for field, candidates in by_field.items(): candidates.sort(key=lambda c: (-len(c[1]), c[0])) if len(candidates) == 1 or len(candidates[0][1]) > len(candidates[1][1]): resolved[field] = candidates[0][0] return resolved def extract_transactions(table): """ Best-effort transaction list from a Docling-recognized table: [{"date", "status", "credit", "debit", "amount", "balance"}, ...]. Used by reconcile.py purely as an independent cross-check signal (count and amounts per page) against the pdfplumber extraction - NOT as a source of displayed descriptions. Docling's own cell-grouping has already shown it can merge logically distinct columns together (e.g. "Time" and "Balance" came back as one cell, "20:09 1,357,108.18", on a real statement) - the money regex below pulls just the numeric value back out of whatever cell a field lands in, regardless. Column roles are resolved with the same keyword dictionary table_extract.py uses (layout_rules.py) - matched directly against each header cell's own text (already a complete phrase here, unlike pdfplumber's raw per-word output, since Docling's table structure groups cells itself). """ data = table.get("data", {}) num_cols = data.get("num_cols", 0) num_rows = data.get("num_rows", 0) cells = table_rows(table) col_for_field = _resolve_columns(cells, num_cols) if not layout_rules.has_required_shape(col_for_field.keys()): return [] def text_at(row, field): col = col_for_field.get(field) return (cells.get((row, col), "") or "").strip() if col is not None else "" def money_at(row, field): col = col_for_field.get(field) if col is None: return None m = _MONEY_RE.search(cells.get((row, col), "") or "") return float(m.group().replace(",", "")) if m else None # Same bank-specific sign ambiguity table_extract.py resolves: some # banks' debit column already prints its own leading minus sign # (HSBC), others print a plain positive magnitude needing explicit # negation (RBC) - detected from the real cell text across the whole # column, not assumed, so the two engines stay comparable in # reconcile.py instead of differing by sign alone. debit_col = col_for_field.get("debit") debit_self_signed = False if debit_col is not None: for row in range(1, num_rows): text = cells.get((row, debit_col), "") or "" if _MONEY_RE.search(text) and text.strip().startswith("-"): debit_self_signed = True break desc_col = col_for_field.get("description") transactions = [] for row in range(1, num_rows): money = {f: money_at(row, f) for f in _MONEY_FIELDS if f in col_for_field} if not any(v is not None for v in money.values()): continue # a narrative/continuation row, not a transaction row if money.get("debit") is not None and not debit_self_signed: money["debit"] = -abs(money["debit"]) # An "Opening balance"/"Closing balance" summary line has a # balance value and nothing else - would otherwise get counted # as a transaction (confirmed for real: RBC prints these as # ordinary rows inside the same table). row_text = (text_at(row, "description") if desc_col is not None else "").lower() if set(k for k, v in money.items() if v is not None) == {"balance"} and ( row_text in layout_rules.OPENING_BALANCE_PHRASES or row_text in layout_rules.CLOSING_BALANCE_PHRASES ): continue transactions.append({ "date": text_at(row, "date"), "status": text_at(row, "status"), "credit": money.get("credit"), "debit": money.get("debit"), "amount": money.get("amount"), "balance": money.get("balance"), }) return transactions def ocr_table_to_rows(table, page_no): """ One Docling-recognized page's table reshaped into EXACTLY the row format table_extract.extract_page() produces for a pdfplumber page - {"type": "txn"/"narrative"/"opening_balance"/"closing_balance", ...} - so table_extract.rows_to_transactions() and extract_statement_facts() (already proven correct for the dual-engine path) can run unchanged on OCR'd data too, instead of duplicating that row-grouping/narrative- attachment logic a second time for Docling's shape. Used only when there's no text layer to read at all (see reconcile.py's routing) - here Docling's own result IS the canonical source, not just a cross-check signal, unlike extract_transactions() above. A data row is a "txn" if it has any money value, same general-purpose signal table_extract.py uses, with the date forward-filled onto rows that leave it blank (confirmed necessary for real on RBC, which only prints a day's first row with its own date - true of Docling's own row-grouping too). Docling's own table-structure model already MERGES most wrapped descriptions into their owning row's single cell (confirmed for real on RBC's own two-line "Regular transaction fee..." row - Docling returned it as one cell, unlike pdfplumber which sees two separate physical text lines) - so the genuinely-separate-row narrative case pdfplumber's _decide_gap exists for is rarer here. HSBC's explicit "Narrative" label convention is still a genuinely separate row though (confirmed for real), detected the same way as pdfplumber - by checking the row's own leftmost non-empty cell against layout_rules.NARRATIVE_LABEL_WORDS - rather than via a resolved "description" column, since HSBC's own header has no such column at all (its narrative always arrives via this separate labeled row, per the same evidence). A non-label row with no money and no resolved description-column content is left unrecognized rather than guessed at by sweeping in unrelated columns (HSBC's own txn rows carry real, unrelated reference numbers in columns that never got a semantic field resolved - treating those as narrative text would misattribute real data, not just miss some). The header row is SEARCHED FOR (first row whose own text resolves a usable shape), not assumed to be row 0 - confirmed necessary for real: OCR'ing a rasterized page 1 (with its account-summary preamble above the real transaction table) produced a single Docling table that merged the preamble's own rows in ABOVE the real header row, unlike the clean text-PDF path where Docling always kept them as separate tables. Same search pattern table_extract._find_header_row uses for pdfplumber's own per-line scan, for the same reason. """ data = table.get("data", {}) num_cols = data.get("num_cols", 0) num_rows = data.get("num_rows", 0) cells = table_rows(table) col_for_field, header_row = {}, None for candidate in range(num_rows): resolved = _resolve_columns(cells, num_cols, header_row=candidate) if layout_rules.has_required_shape(resolved.keys()): col_for_field, header_row = resolved, candidate break if header_row is None: return [] desc_col = col_for_field.get("description") def text_at(row, field): col = col_for_field.get(field) return (cells.get((row, col), "") or "").strip() if col is not None else "" def money_at(row, field): col = col_for_field.get(field) if col is None: return None m = _MONEY_RE.search(cells.get((row, col), "") or "") return float(m.group().replace(",", "")) if m else None def leftmost_text(row): for col in range(num_cols): text = (cells.get((row, col), "") or "").strip() if text: return col, text return None, "" # Same bank-specific sign ambiguity extract_transactions() resolves - # see its own comment for why this is detected rather than assumed. debit_col = col_for_field.get("debit") debit_self_signed = False if debit_col is not None: for row in range(header_row + 1, num_rows): text = cells.get((row, debit_col), "") or "" if _MONEY_RE.search(text) and text.strip().startswith("-"): debit_self_signed = True break rows = [] last_date = "" for row in range(header_row + 1, num_rows): money = {f: money_at(row, f) for f in _MONEY_FIELDS if f in col_for_field} if money.get("debit") is not None and not debit_self_signed: money["debit"] = -abs(money["debit"]) present = {k for k, v in money.items() if v is not None} row_date = text_at(row, "date") if row_date: last_date = row_date desc_text = text_at(row, "description") if present == {"balance"} and desc_text.lower() in layout_rules.OPENING_BALANCE_PHRASES: rows.append({"type": "opening_balance", "balance": money["balance"]}) continue if present == {"balance"} and desc_text.lower() in layout_rules.CLOSING_BALANCE_PHRASES: rows.append({"type": "closing_balance", "balance": money["balance"]}) continue if present: rows.append({ "type": "txn", "date": row_date or last_date, "status": text_at(row, "status"), "inline_description": desc_text, "credit": money.get("credit"), "debit": money.get("debit"), "amount": money.get("amount"), "balance": money.get("balance"), "top": row, "page_no": page_no, }) continue label_col, label_text = leftmost_text(row) if label_text.lower() in layout_rules.NARRATIVE_LABEL_WORDS: rest = " ".join( t for c in range(label_col + 1, num_cols) if (t := (cells.get((row, c), "") or "").strip()) ) rows.append({"type": "narrative", "text": rest, "explicit_label": True, "top": row, "page_no": page_no}) elif desc_col is not None and desc_text: rows.append({"type": "narrative", "text": desc_text, "explicit_label": False, "top": row, "page_no": page_no}) # else: no money, no label, no resolved description column with # content - nothing usable on this row (page furniture, or a # layout this still doesn't generalize to - same honest gap # table_extract.py documents for its own pdfplumber path). return rows def ocr_extract_pdf(pdf_path, docling_url): """ {page_no: [rows...]} for every page of a statement with no text layer at all (a scan, or a phone photo) - Docling's OCR is the PRIMARY (only) extraction source here, unlike its cross-check-only role for a normal text PDF (see reconcile.py's routing). A page Docling didn't structure as a table at all contributes an empty list, same per-page shape as table_extract.extract_pdf's own return value, so callers (table_extract. rows_to_transactions, extract_statement_facts) don't need to know which engine produced the rows they're grouping. """ result = convert(pdf_path, docling_url) json_content = result["document"]["json_content"] if isinstance(json_content, str): json_content = json.loads(json_content) tables = tables_by_page(json_content) total_pages = num_pages(json_content) pages = range(1, total_pages + 1) if total_pages else sorted(tables.keys()) return {p: (ocr_table_to_rows(tables[p], p) if p in tables else []) for p in pages}