224 lines
9.8 KiB
Python
224 lines
9.8 KiB
Python
"""
|
|
Raw-OCR-word-box extraction - the fallback for reconcile._run_ocr_only
|
|
when Docling's own table-structure recognition (TableFormer) fails to
|
|
produce usable rows on a scanned/photographed statement. Confirmed for
|
|
real: TableFormer can merge unrelated page content into one table, or
|
|
merge two real columns into one cell, on a page it structures correctly
|
|
as a native PDF - see CLAUDE.md's "OCR / scanned statements" section.
|
|
|
|
Instead of trusting ANY external table-structure model's row/column
|
|
grouping, this runs OCR directly (tesserocr) for raw per-word text +
|
|
pixel position, then reuses table_extract.py's EXISTING column-clustering
|
|
logic (_find_zones/_classify_money/etc - the same code already proven
|
|
correct for two real bank formats on the pdfplumber path) to derive
|
|
column zones from word geometry itself, the same way it already does for
|
|
a native PDF's own word positions.
|
|
|
|
Two adaptations beyond the pdfplumber path, both confirmed necessary by
|
|
testing against real statement pages:
|
|
|
|
1. Pixel-to-point scaling. table_extract.py's distance thresholds
|
|
(_assign_money_columns's max_distance=60) are tuned for PDF POINTS
|
|
(72/inch) - meaningless for raw pixel coordinates, which vary with
|
|
image resolution. For a PDF-sourced scan, the exact scale is knowable
|
|
(pdfplumber reports a scanned page's own point dimensions even with no
|
|
text layer) and used directly - no guessing. For a bare photo upload
|
|
with no PDF page to anchor against, there's no way to know the true
|
|
scale, so the image's own width is treated as if it were a standard
|
|
portrait US Letter page (612pt) - a real assumption, not a fact, and
|
|
wrong for a landscape photo or non-Letter paper.
|
|
|
|
2. Cross-page zone sharing. A single page can have degenerate data (e.g.
|
|
zero debit transactions) that makes its OWN column-clustering
|
|
ambiguous - confirmed for real: HSBC's page 1 (all credits) had its
|
|
lone money-value cluster misassigned to "debit" purely by pixel
|
|
proximity to that header word, nothing on the page itself able to
|
|
correct it. table_extract.py's own carry_zones only carries FORWARD
|
|
(an earlier page's zones fill a later page's gaps) - this instead
|
|
resolves zones on EVERY page first, keeps whichever page resolved the
|
|
MOST complete shape (ideally both credit and debit present), and
|
|
applies that single zone definition to every page's row-building -
|
|
fixing page 1 using page 2's cleaner data, which a forward-only carry
|
|
can't do. If no page ever resolves a complete shape, this honestly
|
|
returns nothing rather than extracting with an unresolved or guessed
|
|
field.
|
|
"""
|
|
import os
|
|
import sys
|
|
|
|
sys.path.insert(0, os.path.dirname(__file__))
|
|
import table_extract
|
|
import layout_rules
|
|
|
|
_REFERENCE_PAGE_WIDTH_PT = 612.0 # US Letter portrait - the photo-upload fallback assumption
|
|
|
|
|
|
def _extract_words(image, page_no):
|
|
"""[{"text","x0","x1","top","bottom","page_no"}] for every word
|
|
tesserocr finds on one PIL Image, in raw pixel coordinates (scaled to
|
|
points by the caller - see _scale_to_points)."""
|
|
import tesserocr
|
|
words = []
|
|
with tesserocr.PyTessBaseAPI() as api:
|
|
api.SetImage(image)
|
|
api.Recognize()
|
|
ri = api.GetIterator()
|
|
level = tesserocr.RIL.WORD
|
|
for r in tesserocr.iterate_level(ri, level):
|
|
text = r.GetUTF8Text(level)
|
|
if text and text.strip():
|
|
bbox = r.BoundingBox(level)
|
|
words.append({
|
|
"text": text.strip(), "x0": bbox[0], "x1": bbox[2],
|
|
"top": bbox[1], "bottom": bbox[3], "page_no": page_no,
|
|
})
|
|
return words
|
|
|
|
|
|
def _scale_to_points(words, scale):
|
|
for w in words:
|
|
w["x0"] *= scale
|
|
w["x1"] *= scale
|
|
w["top"] *= scale
|
|
w["bottom"] *= scale
|
|
|
|
|
|
def _lines_by_top(words):
|
|
lines = {}
|
|
for w in words:
|
|
lines.setdefault(round(w["top"]), []).append(w)
|
|
return lines
|
|
|
|
|
|
def _zone_completeness(zones):
|
|
"""How many usable fields this zone set resolved - the signal used to
|
|
pick which page's zones to trust across the whole document (see this
|
|
module's own docstring on cross-page zone sharing)."""
|
|
if not zones:
|
|
return -1
|
|
return len(set(zones.keys()) - {"_debit_self_signed"})
|
|
|
|
|
|
def _build_rows(words, lines, zones, header_top, page_no):
|
|
"""Per-line row classification identical to table_extract.extract_page's
|
|
own loop, adapted for a plain OCR word list instead of a pdfplumber
|
|
Page object - produces the exact same row shape (see extract_page's
|
|
docstring for the full contract), so table_extract.rows_to_transactions/
|
|
extract_statement_facts run unchanged on this too."""
|
|
rows = []
|
|
last_date = ""
|
|
for top in sorted(lines.keys()):
|
|
if header_top is not None and top <= header_top:
|
|
continue
|
|
line_words = sorted(lines[top], key=lambda w: w["x0"])
|
|
leftmost = line_words[0]
|
|
text_all = " ".join(w["text"] for w in line_words)
|
|
if table_extract._PAGE_FOOTER_RE.search(text_all) or table_extract._BARE_PAGE_FOOTER_RE.match(text_all.strip()):
|
|
continue
|
|
if leftmost["text"] == "Bank":
|
|
continue
|
|
if text_all in table_extract._HEADER_BOILERPLATE:
|
|
continue
|
|
|
|
date_parts, status_parts, desc_parts = [], [], []
|
|
money = {}
|
|
for w in line_words:
|
|
amount = table_extract._classify_money(w["text"], w["x1"], zones)
|
|
if amount:
|
|
field, value = amount
|
|
money[field] = value
|
|
continue
|
|
dz, sz, descz = zones.get("date"), zones.get("status"), zones.get("description")
|
|
if dz and dz[0] <= w["x0"] <= dz[1]:
|
|
date_parts.append(w["text"])
|
|
elif sz and sz[0] <= w["x0"] <= sz[1]:
|
|
status_parts.append(w["text"])
|
|
elif descz and descz[0] <= w["x0"] <= descz[1]:
|
|
desc_parts.append(w["text"])
|
|
|
|
row_date = " ".join(date_parts)
|
|
if row_date:
|
|
last_date = row_date
|
|
if money.get("debit") is not None and not zones.get("_debit_self_signed", True):
|
|
money["debit"] = -abs(money["debit"])
|
|
|
|
row_text_lower = (" ".join(desc_parts) or text_all).strip().lower()
|
|
if set(money.keys()) == {"balance"} and row_text_lower in layout_rules.OPENING_BALANCE_PHRASES:
|
|
rows.append({"type": "opening_balance", "balance": money["balance"]})
|
|
continue
|
|
if set(money.keys()) == {"balance"} and row_text_lower in layout_rules.CLOSING_BALANCE_PHRASES:
|
|
rows.append({"type": "closing_balance", "balance": money["balance"]})
|
|
continue
|
|
|
|
if money:
|
|
rows.append({
|
|
"type": "txn", "date": row_date or last_date, "status": " ".join(status_parts),
|
|
"inline_description": " ".join(desc_parts), "credit": money.get("credit"),
|
|
"debit": money.get("debit"), "amount": money.get("amount"), "balance": money.get("balance"),
|
|
"top": top, "page_no": page_no,
|
|
})
|
|
elif leftmost["text"].lower() in layout_rules.NARRATIVE_LABEL_WORDS:
|
|
rows.append({"type": "narrative", "text": " ".join(w["text"] for w in line_words[1:]),
|
|
"explicit_label": True, "top": top, "page_no": page_no})
|
|
elif table_extract._REF_RE.match(leftmost["text"]):
|
|
continue
|
|
else:
|
|
rows.append({"type": "narrative", "text": text_all, "explicit_label": False, "top": top, "page_no": page_no})
|
|
return rows
|
|
|
|
|
|
def _extract_from_images(images_with_scale):
|
|
"""images_with_scale: [(PIL.Image, points_per_pixel_scale), ...], one
|
|
per page in order. Returns {page_no: [rows...]}, same per-page shape
|
|
table_extract.extract_pdf/docling_client.ocr_extract_pdf return."""
|
|
page_data = []
|
|
best_zones, best_score = None, -1
|
|
for page_no, (image, scale) in enumerate(images_with_scale, start=1):
|
|
words = _extract_words(image, page_no)
|
|
if not words:
|
|
page_data.append((page_no, words, {}, None))
|
|
continue
|
|
_scale_to_points(words, scale)
|
|
lines = _lines_by_top(words)
|
|
zones, header_top = table_extract._find_zones(words, lines)
|
|
page_data.append((page_no, words, lines, header_top))
|
|
score = _zone_completeness(zones)
|
|
if zones and score > best_score:
|
|
best_zones, best_score = zones, score
|
|
|
|
if not best_zones or not layout_rules.has_required_shape(set(best_zones.keys()) - {"_debit_self_signed"}):
|
|
return {p: [] for p, _, _, _ in page_data}
|
|
|
|
return {
|
|
page_no: (_build_rows(words, lines, best_zones, header_top, page_no) if words else [])
|
|
for page_no, words, lines, header_top in page_data
|
|
}
|
|
|
|
|
|
def extract_pdf(pdf_path, resolution=200):
|
|
"""{page_no: [rows...]} for a PDF with no text layer (a scanned PDF) -
|
|
each page is rendered to an image via pdfplumber's own pypdfium2
|
|
backend, scaled using the PAGE'S OWN KNOWN point dimensions (exact,
|
|
not guessed - a scanned PDF still reports real page geometry even
|
|
with nothing in its text layer)."""
|
|
import pdfplumber
|
|
images_with_scale = []
|
|
with pdfplumber.open(pdf_path) as pdf:
|
|
for page in pdf.pages:
|
|
img = page.to_image(resolution=resolution).original
|
|
scale = page.width / img.width
|
|
images_with_scale.append((img, scale))
|
|
return _extract_from_images(images_with_scale)
|
|
|
|
|
|
def extract_image(image_path):
|
|
"""{1: [rows...]} for a single raw image upload (a phone photo, no PDF
|
|
container) - true physical scale is unknowable here, so the image's
|
|
own pixel width is treated as if it were a standard portrait US
|
|
Letter page (612pt). A real assumption - see this module's own
|
|
docstring - not a measurement."""
|
|
from PIL import Image
|
|
image = Image.open(image_path)
|
|
scale = _REFERENCE_PAGE_WIDTH_PT / image.width
|
|
return _extract_from_images([(image, scale)])
|