Manual layout mapping: correct successful extractions, OCR-sourced statements, money-parsing fixes

- Compute a fingerprint unconditionally on every successful extraction
  (not just the two failure paths), so a "Map" button on an already-
  successful document can open the manual mapping screen to CORRECT it
  via a real fingerprint, not just the auto-triggered failure flow.
- Extend forced-mapping support to OCR-sourced statements (scanned PDFs
  and raw photos): raw_ocr_extract.py gains forced_zones/header_bottom/
  date_format/value_patterns support and a new header_candidate_geometry
  for OCR-derived fingerprinting; a forced OCR mapping bypasses Docling's
  table-structure call entirely.
- Recognize parenthesized negative amounts ("(25.00)") via a shared
  _split_sign() helper used by both _parse_money() and
  _parse_money_with_patterns() - fixes a real blank-extraction bug on a
  single-Amount-column statement using this accounting convention.
- Upscale a low-resolution image before OCR (_MIN_OCR_WIDTH_PX) - a real
  480x800px phone photo was barely readable by tesserocr at native size.
- ManualMappingView.vue: no longer requires a Balance column (some real
  statements don't print one), and imagePointScale converts a drawn
  region's coordinates from an image's natural-pixel space into PDF
  points before sending a forced mapping - every image-sourced mapping
  before this sent zones in the wrong coordinate space entirely.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-11-24 08:15:34 -04:00
parent 0c66edf48b
commit db11c1f7c5
8 changed files with 803 additions and 95 deletions

View File

@ -49,16 +49,49 @@ 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)."""
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(image)
api.SetImage(ocr_image)
api.Recognize()
ri = api.GetIterator()
level = tesserocr.RIL.WORD
@ -67,8 +100,10 @@ def _extract_words(image, page_no):
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,
"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
@ -97,17 +132,31 @@ def _zone_completeness(zones):
return len(set(zones.keys()) - {"_debit_self_signed"})
def _build_rows(words, lines, zones, header_top, page_no):
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."""
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)
@ -117,6 +166,12 @@ def _build_rows(words, lines, zones, header_top, page_no):
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 = {}
@ -134,7 +189,20 @@ def _build_rows(words, lines, zones, header_top, page_no):
elif descz and descz[0] <= w["x0"] <= descz[1]:
desc_parts.append(w["text"])
row_date = table_extract._normalize_date_text(" ".join(date_parts))
# 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):
@ -167,10 +235,46 @@ def _build_rows(words, lines, zones, header_top, page_no):
return rows
def _extract_from_images(images_with_scale):
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."""
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):
@ -195,17 +299,52 @@ def _extract_from_images(images_with_scale):
return {p: [] for p, _, _, _ in page_data}
return {
page_no: (_build_rows(words, lines, best_zones, header_top, page_no) if words else [])
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 extract_pdf(pdf_path, resolution=200):
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)."""
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:
@ -213,16 +352,89 @@ def extract_pdf(pdf_path, resolution=200):
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)
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):
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."""
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
return _extract_from_images([(image, scale)])
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

View File

@ -11,14 +11,16 @@ X_TOLERANCE = 1.5
# fraction of a point past an unpadded zone boundary, silently excluding
# it) and why a user's own hand-drawn region needs this margin too.
_FORCED_ZONE_PADDING = 3
# Optional leading "$" - confirmed necessary for real on an Equals Money
# USD statement, which prints every amount as "$33.62" rather than the
# bare "33.62"/"1,280.25" HSBC/RBC both use. This is deliberately the
# ONLY format hardcoded here - every OTHER real currency-wrapping shape
# (a 2-letter country prefix like "CA$386.01", any non-"$" symbol) is
# The BODY shape only (sign/parens already stripped off by _parse_money
# before this is ever checked, see below) - optional leading "$"
# confirmed necessary for real on an Equals Money USD statement, which
# prints every amount as "$33.62" rather than the bare "33.62"/
# "1,280.25" HSBC/RBC both use. This is deliberately the ONLY currency
# format hardcoded here - every OTHER real currency-wrapping shape (a
# 2-letter country prefix like "CA$386.01", any non-"$" symbol) is
# handled generically by _money_value()'s own fallback below, not by
# growing this regex a branch at a time every time a new one shows up.
_MONEY_RE = re.compile(r"^-?\$?[\d,]+\.\d{2}$")
_MONEY_RE = re.compile(r"^\$?[\d,]+\.\d{2}$")
# _money_value()'s fallback core - the bare numeral alone, no currency
# marker of any kind (that's stripped and validated separately, see
# _money_value) - but anchored with a negative lookahead against a
@ -249,6 +251,28 @@ def _is_currency_symbol(ch):
return unicodedata.category(ch) == "Sc"
def _split_sign(text):
"""
(negative, body) - pulls a leading "-" or a full parenthesized wrap
("(25.00)", the standard accounting convention for a negative
amount - confirmed necessary for real: a single signed "Amount"
column statement using this instead of a minus sign produced a
fully blank extraction, since nothing recognized "(25.00)" as money
at all) off `text`, leaving the sign-free body either way. Shared by
_parse_money and _parse_money_with_patterns so both recognize
exactly the same negative forms, rather than two copies of this
logic that could quietly drift apart - a value-pattern mapping's own
stripPrefix/stripSuffix has to be matched against the SIGN-FREE body
too, the same reasoning _parse_money_with_patterns' own docstring
already gives for "-".
"""
if text.startswith("-"):
return True, text[1:]
if text.startswith("(") and text.endswith(")") and len(text) > 2:
return True, text[1:-1]
return False, text
def _parse_money(text):
"""
(value, marker) if `text` is money-shaped at all, else None. `marker`
@ -257,6 +281,11 @@ def _parse_money(text):
_dominant_money_marker/_money_value for why this is returned
separately from the value rather than just the value alone.
The sign (see _split_sign) comes off FIRST, leaving the sign-free
body everything below actually operates on - a parenthesized
currency-wrapped value like "(CA$386.01)" is handled for free this
way, not as a separate case.
Tries the exact, already-confirmed-real _MONEY_RE format first (fast,
zero ambiguity - a bare amount or one with a plain "$" in front). If
that fails, falls back to a deliberately more permissive check: find
@ -272,15 +301,16 @@ def _parse_money(text):
"CA$386.01" (where the USD version of the same product just prints
"$33.62"). Deliberately requires a REAL currency symbol, not letters
alone - "REF123.45" (a plain reference code, all letters, no symbol)
must still fail this, exactly as it fails _MONEY_RE today. And the
core regex's own trailing-digit lookahead keeps a 4-decimal currency-
exchange ratio printed right next to a real amount on this exact
statement ("1 CAD = 1.0000 CAD") from being misread as a 2-decimal
amount by matching only its first two decimal digits.
must still fail this, exactly as it fails _MONEY_RE today - still
true with the sign/parens handling factored out above, since
"REF123.45" has neither and `body` is just `text` unchanged for it.
And the core regex's own trailing-digit lookahead keeps a 4-decimal
currency-exchange ratio printed right next to a real amount on this
exact statement ("1 CAD = 1.0000 CAD") from being misread as a
2-decimal amount by matching only its first two decimal digits.
"""
negative = text.startswith("-")
body = text[1:] if negative else text
if _MONEY_RE.match(text):
negative, body = _split_sign(text)
if _MONEY_RE.match(body):
marker = "$" if "$" in body else ""
value = float(body.replace(",", "").replace("$", ""))
else:
@ -382,21 +412,21 @@ def _parse_money_with_patterns(text, patterns):
first pattern (see _money_value's own docstring for the discovery-
vs-classification breadth distinction) that parses once stripped.
The sign is pulled off BEFORE stripping and put back on the
candidate afterward, the same way _parse_money's own strict path
already handles it - a real bug, caught before this ever reached a
real statement: a first version stripped the pattern against the
raw text as-is, so a negative value like "-CAD50.00" never matched
a learned `stripPrefix: "CAD"` pattern at all (the string literally
starts with "-", not "CAD") - every negative amount on the one real
test statement that exercised this silently failed to parse, even
though the exact same pattern worked fine on every positive one.
The sign (see _split_sign) is pulled off BEFORE stripping and put
back on the candidate afterward, the same way _parse_money's own
strict path already handles it - a real bug, caught before this
ever reached a real statement: a first version stripped the pattern
against the raw text as-is, so a negative value like "-CAD50.00"
never matched a learned `stripPrefix: "CAD"` pattern at all (the
string literally starts with "-", not "CAD") - every negative
amount on the one real test statement that exercised this silently
failed to parse, even though the exact same pattern worked fine on
every positive one.
"""
parsed = _parse_money(text)
if parsed is not None or not patterns:
return parsed
negative = text.startswith("-")
body = text[1:] if negative else text
negative, body = _split_sign(text)
for pattern in patterns:
stripped = _strip_pattern(body, pattern)
candidate = ("-" + stripped) if negative else stripped

View File

@ -122,7 +122,39 @@ def _compare_amounts(pdf_txns, docling_txns):
return mismatches
def _run_ocr_only(file_path, docling_url):
def _ocr_header_candidate_geometry(file_path):
"""raw_ocr_extract.header_candidate_geometry(file_path, is_image) with
is_image resolved the same way _try_raw_ocr_fallback already
distinguishes a real (if textless) PDF container from a bare image
file - try opening it as a PDF first, only treat it as a bare image
if that fails. None if neither produces anything recognizable."""
try:
with pdfplumber.open(file_path):
return raw_ocr_extract.header_candidate_geometry(file_path, is_image=False)
except Exception:
pass
try:
return raw_ocr_extract.header_candidate_geometry(file_path, is_image=True)
except Exception:
return None
def _ocr_fingerprint(file_path):
"""(fingerprint, fingerprint_hash) via raw_ocr_extract's own geometry
function, or (None, None) if nothing recognizable at all - the
OCR-side equivalent of the fingerprint computation run() itself does
for the pdfplumber path below. Computed fresh here (not threaded
through from whatever extraction already ran) - the same "recompute
rather than carry state" tradeoff the pdfplumber path already
accepts, just a second OCR pass instead of a second pdfplumber one."""
geometry = _ocr_header_candidate_geometry(file_path)
if geometry is None:
return None, None
fingerprint = layout_fingerprint.compute_fingerprint(*geometry)
return fingerprint, layout_fingerprint.fingerprint_hash(fingerprint)
def _run_ocr_only(file_path, docling_url, forced_mapping=None):
"""
Docling-OCR-primary path for an upload with no embedded text layer at
all (see _needs_ocr) - a scan, or a phone photo. There is no
@ -134,6 +166,19 @@ def _run_ocr_only(file_path, docling_url):
for the dual-engine path - run completely unchanged rather than
duplicating that logic for this engine.
`forced_mapping` - the OCR-side equivalent of run()'s own
forced_mapping handling below (manual layout mapping for a scanned/
photographed statement, not just a born-digital PDF - see CLAUDE.md's
"Manual layout mapping for OCR sources" entry). When it carries a
`columnMap`, Docling's own table-structure call is skipped entirely -
no reason to run TableFormer once the user has already overridden its
job - and extraction goes straight through raw_ocr_extract.py, the
same geometry-based, point-range-compatible module that already
stands in whenever Docling's own recognition fails. docling_parser's
own column-INDEX grid has no x-coordinate concept a forced zone could
even apply to, which is why this never routes a forced mapping
through Docling at all, not even as a first attempt.
"page_reports" entries carry "pdfplumber_count" populated with
whichever engine actually ran's own per-page count (not literally
from pdfplumber - there is none here) so checks_service.check_page_coverage
@ -165,6 +210,51 @@ def _run_ocr_only(file_path, docling_url):
engines (nothing OCR-detectable on it at all) - that page just stays
empty, same as it would with no fallback.
"""
if forced_mapping and forced_mapping.get("columnMap"):
kwargs = dict(
forced_zones=forced_mapping.get("columnMap"),
forced_sign_convention=forced_mapping.get("signConvention"),
ignored_row_rules=forced_mapping.get("ignoredRowRules"),
date_format=forced_mapping.get("dateFormat", "textual"),
value_patterns=forced_mapping.get("valuePatterns"),
# header_bottom applies on a bare image too (excludes
# preamble/letterhead text above the user's own drawn
# columns, same as on a PDF's start page) - only start_page
# is genuinely PDF-only (extract_image has no multi-page
# concept to skip whole pages of), so it's passed separately
# below, only on the extract_pdf call.
header_bottom=forced_mapping.get("headerBottom"),
)
try:
with pdfplumber.open(file_path):
pages_rows = raw_ocr_extract.extract_pdf(
file_path, start_page=forced_mapping.get("startPage", 1), **kwargs,
)
except Exception:
pages_rows = raw_ocr_extract.extract_image(file_path, **kwargs)
if not any(pages_rows.values()):
# Same reasoning as the pdfplumber forced-mapping path below -
# a bad column selection, not "this layout needs mapping" (we
# already have one); never LayoutMappingRequired again here,
# that would loop the mapper back on itself.
raise ValueError("This mapping produced no transaction rows - check the column selections.")
all_rows = [r for p in sorted(pages_rows.keys()) for r in pages_rows[p]]
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
statement_facts = table_extract.extract_statement_facts(all_rows)
counts = _pdfplumber_page_counts(pages_rows)
page_reports = [
{"page": p, "pdfplumber_count": counts.get(p, 0), "docling_count": None,
"status": "ocr_raw_words", "mismatches": []}
for p in sorted(pages_rows.keys())
]
fingerprint, fingerprint_hash = _ocr_fingerprint(file_path)
return {
"transactions": transactions, "page_reports": page_reports, "docling_error": None,
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
"extraction_method": "ocr",
"fingerprint": fingerprint, "fingerprintHash": fingerprint_hash,
}
pages_rows = docling_parser.ocr_extract_pdf(file_path, docling_url)
engine_by_page = {p: "ocr_only" for p in pages_rows}
@ -179,11 +269,21 @@ def _run_ocr_only(file_path, docling_url):
engine_by_page[p] = "ocr_raw_words"
if not any(pages_rows.values()):
raise ValueError(
"Could not read this statement via OCR - no table structure was recognized in the "
"scanned or photographed image. Try a clearer photo, or a text-based PDF export "
"if one is available."
)
# As of manual layout mapping for OCR sources, a never-seen OCR
# statement gets the SAME auto-triggered "needs mapping" banner a
# never-seen PDF statement already does, rather than just a bare,
# unrecoverable error - raw_ocr_extract's own geometry function is
# the OCR-side equivalent of table_extract.header_candidate_geometry
# (which needs a real text layer, which doesn't exist here).
fingerprint, fingerprint_hash = _ocr_fingerprint(file_path)
if fingerprint is None:
raise ValueError(
"Could not read this statement via OCR - no table structure was recognized in the "
"scanned or photographed image. Try a clearer photo, or a text-based PDF export "
"if one is available."
)
raise LayoutMappingRequired(fingerprint, fingerprint_hash)
all_rows = [r for p in sorted(pages_rows.keys()) for r in pages_rows[p]]
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
statement_facts = table_extract.extract_statement_facts(all_rows)
@ -193,10 +293,17 @@ def _run_ocr_only(file_path, docling_url):
"status": engine_by_page.get(p, "ocr_only"), "mismatches": []}
for p in sorted(pages_rows.keys())
]
# Computed unconditionally now (success or failure, mirroring the
# pdfplumber path in run() below) - this is what lets the frontend's
# manual "Map" button open the mapper against an OCR document that
# extracted just fine but still got something wrong (the wrong start
# page/header boundary, say), not just a document that failed outright.
fingerprint, fingerprint_hash = _ocr_fingerprint(file_path)
return {
"transactions": transactions, "page_reports": page_reports, "docling_error": None,
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
"extraction_method": "ocr",
"fingerprint": fingerprint, "fingerprintHash": fingerprint_hash,
}
@ -247,7 +354,14 @@ def run(file_path, docling_url, forced_mapping=None):
itself - None for a layout like HSBC's that doesn't print these there),
"narrative_direction": table_extract.rows_to_transactions's own
direction_info - see checks_service.check_narrative_direction for how
it's surfaced, "extraction_method": "dual_engine" or "ocr"}.
it's surfaced, "extraction_method": "dual_engine" or "ocr",
"fingerprint"/"fingerprintHash": this statement's own header-geometry
fingerprint, computed unconditionally (success or failure, pdfplumber
OR OCR-sourced - see raw_ocr_extract.header_candidate_geometry for
the OCR-side equivalent) so the frontend's manual "Map" button can
open the mapper against an already-successful extraction, not just a
failed one - None/None only when neither a real text layer nor OCR
found anything recognizable at all}.
`status` per page is one of:
- "ok": both engines found the same transaction count (and, where
@ -261,7 +375,13 @@ def run(file_path, docling_url, forced_mapping=None):
_run_ocr_only.
"""
if _needs_ocr(file_path):
return _run_ocr_only(file_path, docling_url)
# Passed through now (was silently discarded before manual OCR
# mapping existed) - a forced_mapping request for a file that
# needs OCR used to reach this return with no way to ever apply
# it; _run_ocr_only's own forced_mapping handling is what makes
# the manual "Map" button actually work for a scanned/
# photographed statement.
return _run_ocr_only(file_path, docling_url, forced_mapping=forced_mapping)
if forced_mapping:
pages_rows = table_extract.extract_pdf(
@ -337,6 +457,25 @@ def run(file_path, docling_url, forced_mapping=None):
transactions, narrative_direction = table_extract.rows_to_transactions(all_rows)
statement_facts = table_extract.extract_statement_facts(all_rows)
# Computed unconditionally for a SUCCESSFUL extraction too, not just
# the failure paths above - this is what lets the frontend's own
# "Map" button (TransactionsTable.vue, launched manually when
# auto-detection technically succeeded but got something wrong - a
# real report: the wrong start page/header boundary silently pulled
# preamble text into the first transaction's own description) open
# the exact same manual-mapping screen a failed extraction would
# have, with a real fingerprint to save a correcting mapping
# against. A cheap, independent re-derivation from the raw PDF's own
# header geometry (the same call the failure path above already
# makes), not threaded through from the extraction that just ran -
# None for a statement header_candidate_geometry itself can't find
# anything on (vanishingly rare for an extraction that just
# succeeded, but possible), in which case the Map button simply has
# nothing to seed itself with.
geometry = table_extract.header_candidate_geometry(file_path)
fingerprint = layout_fingerprint.compute_fingerprint(*geometry) if geometry is not None else None
fingerprint_hash = layout_fingerprint.fingerprint_hash(fingerprint) if fingerprint is not None else None
pdf_counts = _pdfplumber_page_counts(pages_rows)
docling_error = None
@ -391,4 +530,5 @@ def run(file_path, docling_url, forced_mapping=None):
"transactions": transactions, "page_reports": page_reports, "docling_error": docling_error,
"statement_facts": statement_facts, "narrative_direction": narrative_direction,
"extraction_method": "dual_engine",
"fingerprint": fingerprint, "fingerprintHash": fingerprint_hash,
}

View File

@ -111,6 +111,12 @@ def run(file_path, docling_url, opening_balance=None, closing_balance=None, forc
"closing_balance": closing_balance,
"narrative_direction": recon["narrative_direction"],
"extraction_method": recon.get("extraction_method", "dual_engine"),
# Passed through unchanged from extraction_service.run() - see
# that function's own docstring. Lets the frontend's "Map"
# button open the manual mapping screen against an already-
# successful extraction, to CORRECT it (not just the existing
# auto-triggered path for a failed one).
"fingerprint": recon.get("fingerprint"), "fingerprintHash": recon.get("fingerprintHash"),
"suggestions": suggested_fixes_service.suggest_fixes(transactions, check_results["checks"]),
**check_results,
}

Binary file not shown.

View File

@ -0,0 +1,117 @@
"""
Builds a minimal, hand-constructed PDF with gibberish column headers
(so the keyword detector AND layout_quirks both correctly fail to
resolve it) but real, transaction-shaped rows at known coordinates -
for manually testing the layout mapper's last-resort tier
(ManualMappingView.vue, /map-layout). Same raw-PDF-construction
technique used throughout this project's own test history (no
reportlab/fpdf available) - explicit per-word Tm/Tj positioning so
pdfplumber reports exact, predictable x/y coordinates.
`top` below is measured from the PAGE'S OWN TOP edge (0 = top),
pdfplumber's own convention - converted to PDF's bottom-up y just
before writing each Tm.
Run: python3 docs/unrecognized_layout_test.py
Produces: docs/unrecognized_layout_test.pdf
"""
import zlib
PAGE_W, PAGE_H = 612, 792 # US Letter, points
words = []
def add(text, x, top):
words.append((text, x, top))
add("Statement Sample Co.", 50, 60)
add("Opening balance 1,000.00 as of 01 Jan 2027", 50, 90)
# Gibberish header - deliberately NOT matching any real column
# vocabulary (date/description/debit/credit/balance/amount/status/etc)
# so tier 1 (keyword detector) fails, and nothing here is a mechanical
# quirk (no wrapped label, no stray symbol) so tier 2 (layout_quirks)
# correctly falls through too.
HEADER_TOP = 130
add("Qfield1", 50, HEADER_TOP)
add("Qfield2", 150, HEADER_TOP)
add("Qfield3", 360, HEADER_TOP)
add("Qfield4", 440, HEADER_TOP)
add("Qfield5", 520, HEADER_TOP)
# Three real transaction-shaped rows, going DOWN the page - a clean,
# self-consistent running-balance chain (1000.00 -> 975.00 -> 2975.00
# -> 2825.00) once correctly mapped, so Preview's own
# statement_balance/running_balance checks have something real to
# confirm.
TXN_ROWS = [
(160, "03 Jan 2027", "Coffee Shop Purchase", "25.00", "", "975.00"),
(180, "05 Jan 2027", "Salary Deposit", "", "2000.00", "2975.00"),
(200, "10 Jan 2027", "Electric Bill Payment", "150.00", "", "2825.00"),
]
for top, date, desc, debit, credit, balance in TXN_ROWS:
add(date, 50, top)
add(desc, 150, top)
if debit:
add(debit, 360, top)
if credit:
add(credit, 440, top)
add(balance, 520, top)
# --- Build the content stream (BT/Tm/Tj per word, Helvetica 10pt) ---
lines = ["BT", "/F1 10 Tf"]
for text, x, top in words:
y = PAGE_H - top # pdfplumber's "top" (from page top) -> PDF's bottom-up y
escaped = text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")
lines.append(f"1 0 0 1 {x} {y} Tm")
lines.append(f"({escaped}) Tj")
lines.append("ET")
content = "\n".join(lines).encode("latin-1")
compressed = zlib.compress(content)
objects = []
def obj(body):
objects.append(body)
return len(objects) # 1-based object number
font_num = obj(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
content_num = obj(
b"<< /Length " + str(len(compressed)).encode() + b" /Filter /FlateDecode >>\nstream\n"
+ compressed + b"\nendstream"
)
page_num = obj(
b"<< /Type /Page /Parent 4 0 R /MediaBox [0 0 "
+ f"{PAGE_W} {PAGE_H}".encode() + b"] /Resources << /Font << /F1 "
+ str(font_num).encode() + b" 0 R >> >> /Contents "
+ str(content_num).encode() + b" 0 R >>"
)
pages_num = obj(b"<< /Type /Pages /Kids [" + str(page_num).encode() + b" 0 R] /Count 1 >>")
catalog_num = obj(b"<< /Type /Catalog /Pages " + str(pages_num).encode() + b" 0 R >>")
# --- Assemble the file, tracking byte offsets for xref ---
out = bytearray(b"%PDF-1.4\n")
offsets = [0] # object 0 is the free-list head
for i, body in enumerate(objects, start=1):
offsets.append(len(out))
out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n"
xref_offset = len(out)
out += f"xref\n0 {len(objects) + 1}\n".encode()
out += b"0000000000 65535 f \n"
for off in offsets[1:]:
out += f"{off:010d} 00000 n \n".encode()
out += (
b"trailer\n<< /Size " + str(len(objects) + 1).encode()
+ b" /Root " + str(catalog_num).encode() + b" 0 R >>\nstartxref\n"
+ str(xref_offset).encode() + b"\n%%EOF"
)
with open("docs/unrecognized_layout_test.pdf", "wb") as f:
f.write(out)
print(f"Wrote docs/unrecognized_layout_test.pdf ({len(out)} bytes), {len(objects)} objects")

View File

@ -1,24 +1,25 @@
/**
* Holds the ONE statement currently waiting on manual layout mapping -
* set by useBatchExtraction.js when useLayoutMapping.js's own
* resolveNeedsMapping() comes back with reason: "no_match" (neither the
* keyword detector, layout_quirks, nor any stored mapping could resolve
* this statement's columns). A real `File` object can't survive a
* router navigation on its own (there's no way to serialize one into a
* route param/query string), so it's held here in memory instead -
* ExtractorView.vue shows a small banner linking to /map-layout while
* this is set; ManualMappingView.vue reads it on mount and clears it
* once the mapping is saved (or the user navigates away).
* Bridges ONE statement's worth of pending-mapping state across the
* /map-layout router navigation - set right before ManualMappingView.vue
* is opened, read on its mount, cleared once saved (or the user
* navigates away). A real `File` object can't survive a router
* navigation on its own (there's no way to serialize one into a route
* param/query string), so it's held here in memory instead.
*
* Deliberately holds only ONE pending file at a time, not a queue - a
* batch upload can still produce more than one "needs mapping" file,
* but mapping them one at a time (the second only reachable after the
* first is saved or dismissed) is the simpler, honest v1 behavior
* rather than building a queue UI nobody asked for yet. A second
* needs-mapping file in the same batch simply overwrites this (the
* earlier one's own extraction attempt already failed and was reported
* in the batch's own failure list - it isn't lost, just not
* auto-queued here).
* As of the per-document mapping queue (2026-11-15), this is purely a
* short-lived bridge, NOT where "which statements still need mapping"
* lives - that's extractionStore's own `pendingMapping` field on each
* placeholder document now (see addPendingMappingDocument/
* replacePendingMappingDocument there), which is what actually survives
* a batch producing more than one needs-mapping file and lets the user
* cycle through all of them via the ordinary document queue instead of
* only ever reaching whichever one happened to be here last. This store
* is set the moment the user clicks "Map now" on ONE specific document
* (TransactionsTable.vue's own pending-mapping reminder, or its
* existing "Map" button for an already-successful one) and cleared the
* moment that one screen is done with it - never a second slot's worth
* of state, by design, since only one /map-layout screen is ever open
* at a time anyway.
*
* `pendingCandidateRow`/`pendingFieldOrder` (value-pattern mapping work)
* are the sibling pending state for needs_value_confirmation - set by
@ -28,6 +29,30 @@
* ManualMappingView.vue tells the two modes apart purely by whether
* pendingCandidateRow is set - never both at once, since their own
* backend triggers are mutually exclusive.
*
* `pendingDocumentId` (manual "Map" button, TransactionsTable.vue) -
* set only when the mapper was launched to CORRECT an already-loaded,
* already-successfully-extracted document (the user noticed a wrong
* start page/header boundary, say), as opposed to the usual auto-
* triggered flow for a statement that failed outright. ManualMappingView
* .vue uses this to UPDATE that existing document's own result in
* place on Save, instead of creating a second, duplicate one - see its
* own handleSaveMapping(). null for the normal failed-extraction flow.
*
* `pendingDocKey` - set when the mapper was launched from a QUEUED
* placeholder document (one added via extractionStore
* .addPendingMappingDocument - as of the persisted pending-mapping work,
* this already has a real PocketBase record of its own, saved the
* moment it was queued, specifically so a page reload doesn't lose it)
* rather than either of the above two cases. ManualMappingView.vue uses
* this to UPDATE that existing record in place on Save (not create a
* new one) and REPLACE the placeholder's own queue slot (via
* extractionStore.replacePendingMappingDocument) instead of appending a
* brand new document at the end of the list - keeps the user's position
* in the queue stable. Mutually exclusive with pendingDocumentId (a
* document is either an existing, successful extraction being
* corrected, or a queued placeholder being resolved for the first
* time - never both).
*/
import { defineStore } from 'pinia'
@ -38,6 +63,8 @@ export const useLayoutMapperStore = defineStore('layoutMapper', {
pendingFingerprintHash: null,
pendingCandidateRow: null,
pendingFieldOrder: null,
pendingDocumentId: null,
pendingDocKey: null,
}),
getters: {
hasPending(state) {
@ -45,19 +72,23 @@ export const useLayoutMapperStore = defineStore('layoutMapper', {
},
},
actions: {
setPending(file, fingerprint, fingerprintHash) {
setPending(file, fingerprint, fingerprintHash, documentId = null, docKey = null) {
this.pendingFile = file
this.pendingFingerprint = fingerprint
this.pendingFingerprintHash = fingerprintHash
this.pendingCandidateRow = null
this.pendingFieldOrder = null
this.pendingDocumentId = documentId
this.pendingDocKey = docKey
},
setPendingValueConfirmation(file, fingerprint, fingerprintHash, candidateRow, fieldOrder) {
setPendingValueConfirmation(file, fingerprint, fingerprintHash, candidateRow, fieldOrder, docKey = null) {
this.pendingFile = file
this.pendingFingerprint = fingerprint
this.pendingFingerprintHash = fingerprintHash
this.pendingCandidateRow = candidateRow
this.pendingFieldOrder = fieldOrder
this.pendingDocumentId = null
this.pendingDocKey = docKey
},
clearPending() {
this.pendingFile = null
@ -65,6 +96,8 @@ export const useLayoutMapperStore = defineStore('layoutMapper', {
this.pendingFingerprintHash = null
this.pendingCandidateRow = null
this.pendingFieldOrder = null
this.pendingDocumentId = null
this.pendingDocKey = null
},
},
})

View File

@ -38,12 +38,36 @@
* clean correction; a reusable strip-prefix/suffix pattern is derived
* from the diff, not drawn. Preview/Save below are shared, unchanged
* machinery either way - only what feeds `forcedMapping` differs.
*
* This screen can also be reached WITHOUT a failed extraction at all -
* TransactionsTable.vue's own "Map" button lets the user correct an
* already-loaded, already-successful extraction that still got
* something wrong (a real report: the wrong start page/header boundary
* silently pulled preamble text into the first transaction's own
* description). `layoutMapperStore.pendingDocumentId` is set only on
* that path - handleSaveMapping below UPDATES that existing document's
* result in place when it's set, instead of creating a second,
* duplicate document the way the normal failed-extraction flow does.
*
* A THIRD way to reach this screen: a QUEUED placeholder document
* (extractionStore.addPendingMappingDocument, from a batch upload where
* this one statement's columns/values couldn't be auto-resolved) -
* `layoutMapperStore.pendingDocKey` is set only on that path. As of the
* persisted pending-mapping work, that placeholder already has a REAL
* PocketBase record (saved the moment the batch found it needed
* mapping, specifically so a page reload doesn't lose it) - so
* handleSaveMapping below UPDATES it in place, the same as the
* pendingDocumentId case above, then REPLACES that placeholder's own
* queue slot (extractionStore.replacePendingMappingDocument) instead of
* appending a new document at the end of the list, so the user doesn't
* lose their place in the queue they were cycling through.
*/
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useExtractionStore } from '../stores/extractionStore'
import { useProjectsStore } from '../stores/projectsStore'
import { useLayoutMapperStore } from '../stores/layoutMapperStore'
import { useUsageStore } from '../stores/usageStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import * as layoutMappingsService from '../services/layoutMappingsService'
@ -55,6 +79,7 @@ const router = useRouter()
const extractionStore = useExtractionStore()
const projectsStore = useProjectsStore()
const layoutMapperStore = useLayoutMapperStore()
const usageStore = useUsageStore()
const pendingFile = layoutMapperStore.pendingFile
const previewUrl = pendingFile ? URL.createObjectURL(pendingFile) : null
@ -63,6 +88,36 @@ onBeforeUnmount(() => {
if (previewUrl) URL.revokeObjectURL(previewUrl)
})
/**
* Image-only: the backend's OCR path (raw_ocr_extract.py) scales every
* OCR'd word's position from the image's own natural pixel space to
* PDF POINTS (the same 612pt reference-width convention
* _REFERENCE_PAGE_WIDTH_PT uses there) before matching it against
* forced_zones - but useRegionDraw.js reports a drawn region's own
* bbox in that SAME natural pixel space, UNconverted
* (useImageZoom.js's own `zoom` is a pure CSS display scale, not a
* points-per-pixel ratio the way pdf.js's own zoom already is for the
* PDF case). A region drawn over a PDF page is correctly in points for
* free; one drawn over an image was NOT - a real, confirmed bug: the
* zones sent for an image-sourced mapping landed in an entirely
* different coordinate space than the OCR'd words they were meant to
* bound, so they essentially never overlapped, producing a blank (or
* badly misaligned) Preview regardless of where the user actually
* drew. `imagePointScale` mirrors the backend's own conversion exactly,
* computed from the image's real natural width (a plain Image() probe,
* not useImageZoom.js's own copy of this - that composable lives
* inside SourceDocumentPanel.vue, a sibling this view doesn't own;
* simplest to read it independently here).
*/
const _REFERENCE_PAGE_WIDTH_PT = 612.0
const imageNaturalWidth = ref(null)
if (isImage && previewUrl) {
const probe = new Image()
probe.onload = () => { imageNaturalWidth.value = probe.naturalWidth }
probe.src = previewUrl
}
const imagePointScale = computed(() => (isImage && imageNaturalWidth.value ? _REFERENCE_PAGE_WIDTH_PT / imageNaturalWidth.value : 1))
const sourcePanelRef = ref(null)
// ── Value confirmation mode (value-pattern mapping work) ────────────
@ -74,6 +129,22 @@ const candidateRow = layoutMapperStore.pendingCandidateRow
const fieldOrder = layoutMapperStore.pendingFieldOrder || []
const isValueConfirmationMode = !!candidateRow
// Set only when the mapper was launched manually, from
// TransactionsTable.vue's own "Map" button, to CORRECT an already-
// loaded document's wrong extraction - handleSaveMapping below updates
// that existing document in place instead of creating a second one.
const pendingDocumentId = layoutMapperStore.pendingDocumentId
// Set only when the mapper was launched from a QUEUED placeholder
// document (a batch-upload statement that needed mapping/value
// confirmation - already saved as a real PocketBase record the moment
// it was queued, see documentsService.savePendingMappingDocument) -
// handleSaveMapping below updates that existing record and replaces
// the placeholder's own queue slot on save, rather than creating a
// second, duplicate document. Mutually exclusive with
// pendingDocumentId (see layoutMapperStore's own docstring).
const pendingDocKey = layoutMapperStore.pendingDocKey
const FIELD_LABELS = {
date: 'Date', description: 'Description', status: 'Status',
debit: 'Debit', credit: 'Credit', amount: 'Amount', balance: 'Balance',
@ -184,7 +255,7 @@ const ROLES = [
{ key: 'debit', label: 'Debit', color: '#DC2626' },
{ key: 'credit', label: 'Credit', color: '#16A34A' },
{ key: 'amount', label: 'Amount (single column)', color: '#D97706' },
{ key: 'balance', label: 'Balance', color: '#0891B2' },
{ key: 'balance', label: 'Balance (optional)', color: '#0891B2' },
]
const armedRole = ref(null)
const regions = ref([]) // [{role, page, bbox}]
@ -236,15 +307,40 @@ const openingBalanceInput = ref('')
const closingBalanceInput = ref('')
// ── Assembling the forced_mapping the backend actually understands ──
// `* imagePointScale.value` is a no-op (scale stays 1) for a PDF - only
// an image needs the pixel-to-point conversion (see that computed's
// own docstring above for the real bug this fixes).
const columnMap = computed(() => {
const map = {}
for (const r of regions.value) map[r.role] = [r.bbox.x0, r.bbox.x1]
for (const r of regions.value) map[r.role] = [r.bbox.x0 * imagePointScale.value, r.bbox.x1 * imagePointScale.value]
return map
})
/** Same shape layout_rules.has_required_shape checks server-side - mirrored here only for an early, round-trip-free "Preview" disable, not duplicated validation logic. Only meaningful in region-drawing mode - see canPreview below for the unified gate both modes actually use. */
/**
* The real minimum a forced mapping needs to build any transaction row
* at all - Date, plus either a single Amount column or both Debit and
* Credit. Balance is deliberately NOT required here, even though the
* comment that used to sit on this line claimed it mirrored
* `layout_rules.has_required_shape` (REQUIRED_FIELDS = ("date",
* "balance")) - that check only ever runs for AUTO-DETECTION, where
* requiring balance is a real signal that a genuine table was found
* (confirmed by reading `table_extract.extract_pdf()` directly: its own
* forced_zones path never calls has_required_shape at all, and every
* money field - balance included - is read via `money.get("balance")`,
* `None` when that zone was never assigned). A user drawing a manual
* mapping has already told the system exactly where the real columns
* are - there's nothing left for a balance requirement to validate, and
* some real statements genuinely don't print a running balance column
* at all. This was a real reported bug: with balance unconditionally
* required, a statement with none forced the user to draw a box over
* BLANK page space just to satisfy the gate, which then fed garbage
* (whatever that blank region's own OCR/text happened to be) into the
* balance column instead of correctly leaving it empty. Only meaningful
* in region-drawing mode - see canPreview below for the unified gate
* both modes actually use.
*/
const hasRequiredShape = computed(() => {
const map = columnMap.value
if (!('date' in map) || !('balance' in map)) return false
if (!('date' in map)) return false
return 'amount' in map || ('debit' in map && 'credit' in map)
})
/**
@ -274,7 +370,7 @@ const startPage = computed(() => (regions.value.length ? Math.min(...regions.val
*/
const headerBottom = computed(() => {
const onStartPage = regions.value.filter((r) => (r.page || 1) === startPage.value)
return onStartPage.length ? Math.min(...onStartPage.map((r) => r.bbox.top)) : null
return onStartPage.length ? Math.min(...onStartPage.map((r) => r.bbox.top)) * imagePointScale.value : null
})
/**
* Value-confirmation mode sends ONLY valuePatterns - no columnMap/
@ -379,16 +475,99 @@ async function handleSaveMapping() {
source: 'user',
})
const docKey = extractionService.docKeyFor(pendingFile)
const record = await documentsService.saveDocument({
docKey, fileName: pendingFile.name, sourceFile: pendingFile, result: previewResult.value,
project: projectsStore.activeProjectId,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id,
layoutMappingVersionUsed: mapping.version,
layoutApplied: 'mapping',
layoutFingerprintHash: layoutMapperStore.pendingFingerprintHash,
})
let record
if (pendingDocumentId) {
// Correcting an already-loaded document (the "Map" button, not a
// failed-extraction's own auto-triggered flow) - UPDATE it in
// place rather than creating a second, duplicate document. The
// existing record already has its own sourceFile/project/balance
// inputs; only the result and layout-mapping fields actually
// changed.
record = await documentsService.updateDocument(pendingDocumentId, {
result: previewResult.value,
layoutMappingUsed: mapping.id,
layoutMappingVersionUsed: mapping.version,
layoutApplied: 'mapping',
layoutFingerprintHash: layoutMapperStore.pendingFingerprintHash,
})
extractionStore.replaceDocumentResult(pendingDocumentId, previewResult.value, {
layoutMappingUsed: mapping.id, layoutMappingVersionUsed: mapping.version,
})
} else if (pendingDocKey) {
// Resolving a QUEUED placeholder document - as of the persisted
// pending-mapping work, this already has a REAL pbId (it was
// saved to PocketBase the moment the batch found it needed
// mapping, specifically so a reload wouldn't lose it - see
// documentsService.savePendingMappingDocument/pb_migrations/12).
// UPDATE it in place, same as the pendingDocumentId branch above,
// rather than creating a second, duplicate document - also clears
// the persisted needsMapping/pending* fields so a future reload
// doesn't keep reading this as still-unresolved.
const existingDoc = extractionStore.documents.find((d) => d.docKey === pendingDocKey)
record = await documentsService.updateDocument(existingDoc.pbId, {
result: previewResult.value,
needsMapping: false,
needsValueConfirmation: false,
pendingFingerprint: null,
pendingFingerprintHash: null,
pendingCandidateRow: null,
pendingFieldOrder: null,
openingBalanceInput: openingBalanceInput.value,
closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id,
layoutMappingVersionUsed: mapping.version,
layoutApplied: 'mapping',
layoutFingerprintHash: layoutMapperStore.pendingFingerprintHash,
})
// Replaces the placeholder's own queue slot in place, instead of
// appending a new document at the end of the list - keeps the
// user's position in the queue they were cycling through. Not a
// second projectsStore.addDocumentToCache call - the placeholder
// was already cached under this same project when it was first
// created.
extractionStore.replacePendingMappingDocument(pendingDocKey, {
pbId: record.id, project: record.project,
previewUrl: URL.createObjectURL(pendingFile), isImage,
result: previewResult.value,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id, layoutMappingVersionUsed: mapping.version,
})
} else {
// A fresh, never-queued mapping - not reachable through any
// current UI path (every needs_mapping/needs_value_confirmation
// statement is persisted as a placeholder the moment the batch
// finds it, see useBatchExtraction.js), kept as a defensive
// fallback in case a future caller ever sets pending state
// without either id.
const docKey = extractionService.docKeyFor(pendingFile)
record = await documentsService.saveDocument({
docKey, fileName: pendingFile.name, sourceFile: pendingFile, result: previewResult.value,
project: projectsStore.activeProjectId,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id,
layoutMappingVersionUsed: mapping.version,
layoutApplied: 'mapping',
layoutFingerprintHash: layoutMapperStore.pendingFingerprintHash,
})
projectsStore.addDocumentToCache(record.project, record)
extractionStore.addDocument({
pbId: record.id, docKey, fileName: pendingFile.name, project: record.project,
previewUrl: URL.createObjectURL(pendingFile), isImage,
result: previewResult.value,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id, layoutMappingVersionUsed: mapping.version,
})
}
// Billing/usage-tracking foundation - one real extraction just got
// delivered, same as the normal batch-upload path
// (useBatchExtraction.js's own identical call). Applied uniformly
// across all three branches above, INCLUDING the pendingDocumentId
// correction case - re-mapping an already-successful document still
// re-runs real backend extraction against the source file and
// delivers a new result, the same genuine unit of work the other two
// branches do. Best-effort internally (see usageStore.js), never
// blocks Save from completing.
usageStore.recordExtraction(record.id, previewResult.value.page_reports?.length || 0)
// Backfills the mapping's own sourceDocument - couldn't be set at
// creation time above since the document didn't exist yet (the
// mapping's own id is needed first, for the document's
@ -403,15 +582,6 @@ async function handleSaveMapping() {
/* non-critical - Inspect will just have no source document to show for this mapping */
}
projectsStore.addDocumentToCache(record.project, record)
extractionStore.addDocument({
pbId: record.id, docKey, fileName: pendingFile.name, project: record.project,
previewUrl: URL.createObjectURL(pendingFile), isImage,
result: previewResult.value,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id, layoutMappingVersionUsed: mapping.version,
})
layoutMapperStore.clearPending()
router.push('/')
} catch (e) {
@ -560,7 +730,7 @@ function cancelMapping() {
{{ previewing ? 'Checking…' : 'Preview' }}
</button>
<p v-if="!canPreview && isValueConfirmationMode" class="note">Fix the highlighted field(s) above before previewing.</p>
<p v-else-if="!canPreview" class="note">Assign at least Date, Balance, and either Amount or both Debit and Credit before previewing.</p>
<p v-else-if="!canPreview" class="note">Assign at least Date and either Amount or both Debit and Credit before previewing - Balance is optional, for statements that don't print one.</p>
<div v-if="previewError" class="error-note visible">{{ previewError }}</div>
<template v-if="previewResult">