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

165 lines
6.4 KiB
Python

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 PDF 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.
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).
"""
with open(pdf_path, "rb") as f:
response = requests.post(
f"{docling_url}/v1/convert/file",
files={"files": (pdf_path.split("/")[-1], f, "application/pdf")},
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 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 = {}
for cell in data.get("table_cells", []):
key = (cell.get("start_row_offset_idx"), cell.get("start_col_offset_idx"))
cells[key] = cell.get("text", "")
col_for_field = {}
for col in range(num_cols):
label = cells.get((0, col), "") or ""
m = layout_rules.match_field(label)
if m:
col_for_field.setdefault(m[0], col)
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