bettersight-statement-extra.../backend/services/extraction/raw_ocr_extract.py

441 lines
22 KiB
Python

# Raw-OCR-word-box extraction - the fallback for extraction_service.py when Docling's table-structure recognition fails.
"""
Raw-OCR-word-box extraction - the fallback for extraction_service.py (see
its `_run_ocr_only`-equivalent) 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.
"""
from services.extraction import table_extract
from services.extraction import layout_rules
_REFERENCE_PAGE_WIDTH_PT = 612.0 # US Letter portrait - the photo-upload fallback assumption
# A real, narrow photo/screenshot upload can be low-resolution enough
# that tesserocr barely reads anything at its native size - confirmed
# directly on a real 480x800px statement screenshot: tesserocr found
# only 26 words (almost all large header/status-bar text, none of the
# actual table body) at native resolution, vs 180+ once upscaled ~3x
# before OCR - a real reported "Preview returns blank" statement whose
# own root cause had nothing to do with money-parsing at all; there was
# simply no text for the forced mapping's own zones to classify in the
# first place, regardless of where the user drew them. 1600px is picked
# from that same test - word count climbs sharply up to roughly this
# width, then plateaus (189 words at 3x/1440px, 186 at 4x/1920px, i.e.
# no further real gain) - a cheap, well-justified floor, not a guess.
_MIN_OCR_WIDTH_PX = 1600
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).
Upscales a low-resolution image to _MIN_OCR_WIDTH_PX before handing
it to tesserocr (never downscales an already-adequate one - that
would only throw away real detail for no gain) - purely an internal
OCR-quality step: the returned word coordinates are divided back
down by the same factor before returning, so they're still in the
ORIGINAL image's own pixel space either way. Every caller already
computes its own PDF-point scale factor from the original image's
own width (see _REFERENCE_PAGE_WIDTH_PT above) - that stays correct
unchanged, with no caller needing to know this upscaling ever
happened.
"""
import tesserocr
ocr_image = image
ocr_scale = 1.0
if image.width < _MIN_OCR_WIDTH_PX:
from PIL import Image
ocr_scale = _MIN_OCR_WIDTH_PX / image.width
ocr_image = image.resize(
(round(image.width * ocr_scale), round(image.height * ocr_scale)), Image.LANCZOS,
)
words = []
with tesserocr.PyTessBaseAPI() as api:
api.SetImage(ocr_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] / ocr_scale, "x1": bbox[2] / ocr_scale,
"top": bbox[1] / ocr_scale, "bottom": bbox[3] / ocr_scale,
"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, ignored_row_rules=None,
date_format="textual", header_bottom=None):
"""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.
`header_top` is this module's own auto-detected header exclusion (set
only by the cross-page auto-detect path in _extract_from_images - the
OCR-recognized header row on whichever page resolved the best zones).
`header_bottom` is the forced-mapping equivalent - table_extract.py's
own padding-subtracted check (table_extract.extract_page's docstring
has the full reasoning), applied only on the page a forced mapping's
own regions were actually drawn on. The two are never both non-None
at once - a forced mapping has no auto-detected header_top of its
own, and auto-detection never has a header_bottom.
"""
rows = []
last_date = ""
for top in sorted(lines.keys()):
if header_top is not None and top <= header_top:
continue
if header_bottom is not None and top <= header_bottom - table_extract._FORCED_ZONE_PADDING:
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
# A layout mapping can name specific lines to skip outright - see
# table_extract.extract_page's own identical check; never engaged
# by auto-detection, a no-op whenever ignored_row_rules isn't
# explicitly supplied.
if ignored_row_rules and any(rule in text_all for rule in ignored_row_rules):
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"])
# Same value-pattern-then-normalize_date sequence as
# table_extract.extract_page's own row loop - normalize_date with
# the default date_format="textual" is a guaranteed no-op change
# from the bare _normalize_date_text() this used to call directly
# (confirmed: normalize_date always returns _normalize_date_text's
# own result when date_format=="textual", regardless of whether
# it changed anything), so this is a safe substitution for the
# existing auto-detect call site too, not just the new
# forced-zones one.
date_text = " ".join(date_parts)
date_pattern = zones.get("_value_patterns", {}).get("date") if zones.get("_value_patterns") else None
if date_pattern:
date_text = table_extract._strip_pattern(date_text, date_pattern)
row_date = table_extract.normalize_date(date_text, date_format)
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, "bbox": table_extract._line_bbox(line_words),
})
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,
"bbox": table_extract._line_bbox(line_words)})
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,
"bbox": table_extract._line_bbox(line_words)})
return rows
def _extract_from_images(images_with_scale, forced_zones=None, ignored_row_rules=None,
date_format="textual", start_page=1, header_bottom=None):
"""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_parser.ocr_extract_pdf return.
`forced_zones` (layout-mapper work - a human, or a previously-saved
mapping, already told us exactly where each column is) is the
already-padded-and-built zones dict (see extract_pdf's/extract_image's
own docstrings for the padding/_debit_self_signed/_value_patterns
construction - this function receives it ready to use, the same
division of responsibility table_extract.extract_pdf has with
extract_page). When given, this skips the auto-detect scoring loop
below entirely - _find_zones's own cross-page "keep whichever page
resolved the most complete shape" logic has nothing to add once the
zones are already known - and applies the SAME forced zones to every
page's own OCR'd words directly. `start_page` skips pages before it
entirely (never classified as narrative or transaction data, mirroring
table_extract.extract_pdf exactly); `header_bottom` only ever applies
on the start page itself (see _build_rows's own docstring).
"""
if forced_zones is not None:
rows_by_page = {}
for page_no, (image, scale) in enumerate(images_with_scale, start=1):
if page_no < start_page:
rows_by_page[page_no] = []
continue
words = _extract_words(image, page_no)
if not words:
rows_by_page[page_no] = []
continue
_scale_to_points(words, scale)
lines = _lines_by_top(words)
rows_by_page[page_no] = _build_rows(
words, lines, forced_zones, header_top=None, page_no=page_no,
ignored_row_rules=ignored_row_rules, date_format=date_format,
header_bottom=header_bottom if page_no == start_page else None,
)
return rows_by_page
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)
# Shares table_extract's own quirks-module fallback (e.g. a
# wrapped header label) via _find_zones - if it merges lines to
# resolve the header, the merged `lines` is what gets used below
# for this page's own row-building too, same reasoning as
# extract_page's own call site.
zones, header_top, lines = 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,
ignored_row_rules=ignored_row_rules, date_format=date_format) if words else [])
for page_no, words, lines, header_top in page_data
}
def _build_forced_zones(forced_zones, forced_sign_convention, value_patterns):
"""The padded-zones-dict construction shared by extract_pdf/
extract_image below - identical in kind to table_extract.extract_pdf's
own construction (same _FORCED_ZONE_PADDING, same _debit_self_signed/
_value_patterns keys), factored out once both OCR entry points needed
it rather than duplicating it. None (not {}) when forced_zones itself
is empty/absent, so callers can tell "no forced mapping" from "a
forced mapping with literally no fields" the same way table_extract
does."""
if not forced_zones:
return None
zones = {field: (x0 - table_extract._FORCED_ZONE_PADDING, x1 + table_extract._FORCED_ZONE_PADDING)
for field, (x0, x1) in forced_zones.items()}
if forced_sign_convention is not None:
zones.setdefault("_debit_self_signed", forced_sign_convention.get("debitSelfSigned", True))
if value_patterns:
zones.setdefault("_value_patterns", value_patterns)
return zones
def extract_pdf(pdf_path, resolution=200, forced_zones=None, forced_sign_convention=None,
ignored_row_rules=None, date_format="textual", start_page=1,
header_bottom=None, value_patterns=None):
"""{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).
`forced_zones`/`forced_sign_convention`/`ignored_row_rules`/
`date_format`/`start_page`/`header_bottom`/`value_patterns` are the
OCR-side equivalent of table_extract.extract_pdf's own identically-
named parameters (manual layout mapping for a scanned/photographed
statement, not just a born-digital PDF) - every argument defaults to
"do nothing extra," so a normal auto-detect call behaves exactly as
before. See table_extract.extract_pdf's own docstring for the full
reasoning behind each (padding, start_page skipping whole pages,
header_bottom excluding the real header row text on the start page
itself) - identical here, just applied to OCR'd words instead of a
pdfplumber 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))
zones = _build_forced_zones(forced_zones, forced_sign_convention, value_patterns)
return _extract_from_images(
images_with_scale, forced_zones=zones, ignored_row_rules=ignored_row_rules,
date_format=date_format, start_page=start_page, header_bottom=header_bottom,
)
def extract_image(image_path, forced_zones=None, forced_sign_convention=None,
ignored_row_rules=None, date_format="textual", value_patterns=None, header_bottom=None):
"""{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.
`forced_zones`/`forced_sign_convention`/`ignored_row_rules`/
`date_format`/`value_patterns` - see extract_pdf's own docstring; no
`start_page` here, since a bare image has no MULTI-page concept at
all - there's only ever the one "page". `header_bottom` is still a
real, needed concept even so - it excludes preamble/letterhead text
ABOVE the user's own drawn columns on that one page/image, exactly
as it would on a PDF's own start page (confirmed necessary for real:
without it, a statement's own company-name/"Opening balance" header
text got swept straight into the first transaction's own
description, identical to the bug this already guards against on
the pdfplumber path)."""
from PIL import Image
image = Image.open(image_path)
scale = _REFERENCE_PAGE_WIDTH_PT / image.width
zones = _build_forced_zones(forced_zones, forced_sign_convention, value_patterns)
return _extract_from_images(
[(image, scale)], forced_zones=zones, ignored_row_rules=ignored_row_rules, date_format=date_format,
header_bottom=header_bottom,
)
def header_candidate_geometry(file_path, is_image, resolution=200):
"""(words, lines_by_top, page_width_pt, page_height_pt) for whichever
page/image looks MOST header-like - the OCR-side equivalent of
table_extract.header_candidate_geometry() (same scoring algorithm:
the page/image whose lines match the most distinct vocabulary
fields wins; same 4-tuple shape layout_fingerprint.compute_fingerprint
already expects), but built on this module's own OCR word-extraction
+ pixel-to-point scaling instead of pdfplumber's text layer, which
doesn't exist for an OCR source by definition - that function is
hard-wired to pdfplumber.open()/page.extract_words() and can't be
reused directly for this. None if no page/image has any recognizable
word at all - same honest-empty contract as the pdfplumber version.
This is what lets a never-seen OCR statement get the same auto-
triggered "needs mapping" banner a never-seen PDF statement already
does, and what lets a successful OCR extraction carry a real
fingerprint for the "Map" button to use later - see
extraction_service.py's own _run_ocr_only for both call sites.
"""
images_with_scale_and_size = []
if is_image:
from PIL import Image
image = Image.open(file_path)
scale = _REFERENCE_PAGE_WIDTH_PT / image.width
images_with_scale_and_size.append((image, scale, _REFERENCE_PAGE_WIDTH_PT, image.height * scale))
else:
import pdfplumber
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
img = page.to_image(resolution=resolution).original
scale = page.width / img.width
images_with_scale_and_size.append((img, scale, page.width, page.height))
best = None
best_score = -1
for page_no, (image, scale, page_width_pt, page_height_pt) in enumerate(images_with_scale_and_size, start=1):
words = _extract_words(image, page_no)
if not words:
continue
_scale_to_points(words, scale)
lines = _lines_by_top(words)
matched_fields = set()
for line in lines.values():
line_sorted = sorted(line, key=lambda w: w["x0"])
resolved = layout_rules.resolve_header_matches(layout_rules.match_line_fields(line_sorted))
matched_fields |= set(resolved.keys())
if len(matched_fields) > best_score:
best = (words, lines, page_width_pt, page_height_pt)
best_score = len(matched_fields)
return best