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

248 lines
9.5 KiB
Python

"""
PaddleOCR (PP-StructureV3) benchmark adapter - kept entirely separate from
docling_client.py/reconcile.py on purpose (per explicit request): this is a
spike to see whether PaddleOCR's table-structure recognition does better
than Docling's on the real statement image Docling struggled with
(docs/scan_test_page-1.png - see CLAUDE.md's "OCR / scanned statements"
section for what Docling did with it). Nothing in reconcile.py imports
this file; it is not wired into the live pipeline.
Requires a SEPARATE virtualenv from the main app - paddlepaddle has no
wheel for the Python version the app itself runs under (confirmed: pip
install failed in that venv), so this was built and run against a
Python 3.11 venv (`.venv_paddle`) instead. Not added to requirements.txt
or the Dockerfile - this is a benchmark, not a dependency the shipped app
takes on.
The public surface mirrors docling_client.py's OCR-canonical functions on
purpose (table_to_rows/extract_image produce the exact same row shape
ocr_table_to_rows/ocr_extract_pdf do) so the SAME table_extract.
rows_to_transactions()/extract_statement_facts() can run on its output
unchanged too, continuing into the real pipeline - the actual point of
this benchmark, not just comparing raw OCR text.
"""
import re
from html.parser import HTMLParser
import layout_rules
_MONEY_RE = re.compile(r"-?[\d,]+\.\d{2}")
_MONEY_FIELDS = ("debit", "credit", "amount", "balance")
def run_structure(image_path):
"""Every table PP-StructureV3 recognized on one image, as its raw
pred_html strings - lazy-imports paddleocr so this module can still be
read/imported (e.g. by the benchmark script) without the paddle stack
installed, only failing when actually asked to run it."""
from paddleocr import PPStructureV3
pipeline = PPStructureV3()
tables = []
for res in pipeline.predict(image_path):
for t in res["table_res_list"]:
tables.append(t["pred_html"])
return tables
class _HTMLTableGrid(HTMLParser):
"""Parses one <table> HTML string (PaddleOCR's pred_html) into a
{(row, col): text} cell grid, the same shape docling_client.table_rows
produces from Docling's own (structurally different) table JSON -
colspan/rowspan-aware via a grid-fill algorithm, since PP-StructureV3's
own HTML uses real colspan/rowspan attributes rather than emitting one
cell per grid position the way Docling's table_cells list does."""
def __init__(self):
super().__init__()
self.cells = {}
self.num_cols = 0
self._row = -1
self._col = 0
self._occupied = set()
self._in_cell = False
self._cell_text = []
self._colspan = 1
self._rowspan = 1
def handle_starttag(self, tag, attrs):
if tag == "tr":
self._row += 1
self._col = 0
elif tag in ("td", "th"):
attrs = dict(attrs)
self._colspan = int(attrs.get("colspan", 1) or 1)
self._rowspan = int(attrs.get("rowspan", 1) or 1)
while (self._row, self._col) in self._occupied:
self._col += 1
self._in_cell = True
self._cell_text = []
def handle_data(self, data):
if self._in_cell:
self._cell_text.append(data)
def handle_endtag(self, tag):
if tag in ("td", "th"):
text = " ".join("".join(self._cell_text).split())
start_col = self._col
for dr in range(self._rowspan):
for dc in range(self._colspan):
self._occupied.add((self._row + dr, start_col + dc))
self.cells[(self._row, start_col)] = text
self.num_cols = max(self.num_cols, start_col + self._colspan)
self._col += self._colspan
self._in_cell = False
@property
def num_rows(self):
return self._row + 1
def _parse_table_html(html):
parser = _HTMLTableGrid()
parser.feed(html)
return parser.cells, parser.num_cols, parser.num_rows
def _all_field_matches(text):
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
return hits
def _resolve_columns(cells, num_cols, header_row):
"""Same collision-aware column resolution as docling_client._resolve_columns
(see its own docstring for the full reasoning) - reimplemented here,
not imported, so this file has no dependency on docling_client.py at
all, per the "kept separate" request."""
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
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 table_to_rows(html, page_no):
"""One PaddleOCR-recognized table's HTML reshaped into the identical
row format table_extract.extract_page()/docling_client.ocr_table_to_rows
produce - {"type": "txn"/"narrative"/..., ...} - so the SAME
table_extract.rows_to_transactions()/extract_statement_facts() can run
on it unchanged, same reasoning as docling_client's own OCR path (see
its docstring). Header row is searched for, not assumed at row 0, same
reason as the Docling path - a real multi-block page can have other
content merged in above the actual header."""
cells, num_cols, num_rows = _parse_table_html(html)
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, ""
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})
return rows
def extract_image(image_path):
"""{page_no: [rows...]} for one image, the same per-page shape
docling_client.ocr_extract_pdf returns - a single image is "page 1"."""
tables = run_structure(image_path)
all_rows = []
for t in tables:
all_rows.extend(table_to_rows(t, 1))
return {1: all_rows}