bettersight-statement-extra.../backend/measure.py

189 lines
7.9 KiB
Python

# The measurement harness: runs the fixture corpus through pipeline_service and diffs against ground truth.
"""
The measurement harness from the original plan's step 10 (docs/bankstatement.md
section 11): run the fixture corpus through the real pipeline, diff against
hand-verified ground truth, and log a dated, re-runnable result under results/.
Reports the spec's own two measures (section 11), kept separate because one can
look good while the other is wrong:
- Untouched pass rate: share of statements that reach "Verified" with no edits.
- Field accuracy: share of extracted fields (date, description, amount, balance)
that match a hand-verified ground truth file, for statements that have one.
Run from the repo root: python3 backend/measure.py
"""
import glob
import json
import os
import sys
from datetime import datetime, timezone
sys.path.insert(0, os.path.dirname(__file__))
from services import pipeline_service as pipeline
import openpyxl
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "..", "fixtures")
RESULTS_DIR = os.path.join(os.path.dirname(__file__), "..", "results")
DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5101")
# Fields compared between an extracted transaction and its ground-truth row.
# "status" isn't compared: RBC doesn't print one at all (always ""), so a
# TRN-status mismatch there would be noise, not signal.
COMPARED_FIELDS = ("date", "description", "amount", "balance")
def _discover_corpus():
"""One corpus entry per fixture PDF that has a matching
"<name>_ground_truth.xlsx" sibling file - skips any fixture without one
(flagged, not silently excluded) rather than assuming every PDF in
fixtures/ is measurable."""
entries = []
for pdf_path in sorted(glob.glob(os.path.join(FIXTURES_DIR, "*.pdf"))):
name = os.path.splitext(os.path.basename(pdf_path))[0]
gt_path = os.path.join(FIXTURES_DIR, f"{name}_ground_truth.xlsx")
entries.append({
"name": name, "pdf": pdf_path,
"ground_truth": gt_path if os.path.exists(gt_path) else None,
})
return entries
def _load_ground_truth(gt_path):
wb = openpyxl.load_workbook(gt_path, data_only=True)
txn_rows = []
for row in wb["Transactions"].iter_rows(min_row=2, values_only=True):
date, status, description, amount, balance = row
txn_rows.append({"date": date, "status": status, "description": description,
"amount": amount, "balance": balance})
summary = {r[0]: r[1] for r in wb["Summary"].iter_rows(min_row=2, values_only=True)}
return txn_rows, summary
def _norm(value):
"""Loose equality for a single field: None/""/whitespace treated as
equivalent (openpyxl returns None for a blank cell, pipeline output
uses "" for an absent narrative), text whitespace-collapsed (cosmetic
multi-space-vs-single-space differences from PDF layout aren't a real
extraction error), floats rounded to cents."""
if value is None:
return None
if isinstance(value, float):
return round(value, 2)
if isinstance(value, str):
collapsed = " ".join(value.split())
return collapsed or None
return value
def _compare_fields(actual_txns, gt_txns):
"""Per-field mismatches between the extracted transaction list and its
ground truth, matched by position - both are the same canonical,
newest-first order, so index alignment is valid as long as the
transaction count itself matches (checked separately, by the caller)."""
mismatches = []
total_fields = 0
for i, (a, g) in enumerate(zip(actual_txns, gt_txns)):
for field in COMPARED_FIELDS:
total_fields += 1
if _norm(a.get(field)) != _norm(g.get(field)):
mismatches.append({"index": i, "field": field, "actual": a.get(field), "expected": g.get(field)})
return mismatches, total_fields
def _measure_one(entry):
result = {"name": entry["name"]}
try:
run = pipeline.run(entry["pdf"], DOCLING_URL)
except Exception as e:
result["error"] = str(e)
return result
result["status"] = run["status"]
result["untouched_pass"] = run["status"] == "Verified"
result["docling_error"] = run["docling_error"]
result["transaction_count"] = len(run["transactions"])
if entry["ground_truth"] is None:
result["field_accuracy"] = None
return result
gt_txns, gt_summary = _load_ground_truth(entry["ground_truth"])
count_mismatch = len(run["transactions"]) != len(gt_txns)
result["count_mismatch"] = count_mismatch
result["expected_count"] = len(gt_txns)
compare_n = min(len(run["transactions"]), len(gt_txns))
mismatches, total_fields = _compare_fields(run["transactions"][:compare_n], gt_txns[:compare_n])
# An extra/missing transaction costs every one of its fields, same as
# any other mismatch - not counting it would understate the error.
if count_mismatch:
total_fields += abs(len(run["transactions"]) - len(gt_txns)) * len(COMPARED_FIELDS)
result["field_accuracy"] = round(1 - len(mismatches) / total_fields, 4) if total_fields else None
result["field_mismatches"] = mismatches
result["fields_compared"] = total_fields
expected_opening = gt_summary.get("opening_balance")
expected_closing = gt_summary.get("closing_balance")
result["opening_balance_match"] = _norm(run["opening_balance"]) == _norm(expected_opening)
result["closing_balance_match"] = _norm(run["closing_balance"]) == _norm(expected_closing)
return result
def run():
corpus = _discover_corpus()
entries = [_measure_one(e) for e in corpus]
measured = [e for e in entries if "error" not in e]
untouched_pass_rate = round(sum(1 for e in measured if e["untouched_pass"]) / len(measured), 4) if measured else None
with_gt = [e for e in measured if e.get("field_accuracy") is not None]
total_mismatches = sum(len(e["field_mismatches"]) for e in with_gt)
total_fields = sum(e["fields_compared"] for e in with_gt)
overall_field_accuracy = round(1 - total_mismatches / total_fields, 4) if total_fields else None
report = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"corpus_size": len(corpus),
"untouched_pass_rate": untouched_pass_rate,
"overall_field_accuracy": overall_field_accuracy,
"statements": entries,
}
os.makedirs(RESULTS_DIR, exist_ok=True)
out_path = os.path.join(RESULTS_DIR, f"measure_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json")
with open(out_path, "w") as f:
json.dump(report, f, indent=2, default=str)
_print_summary(report, out_path)
return report
def _print_summary(report, out_path):
print(f"Corpus: {report['corpus_size']} fixture(s)")
print(f"Untouched pass rate: {report['untouched_pass_rate']}")
print(f"Overall field accuracy: {report['overall_field_accuracy']}")
print()
for e in report["statements"]:
if "error" in e:
print(f" {e['name']}: ERROR - {e['error']}")
continue
gt_part = f"field_accuracy={e['field_accuracy']}" if e["field_accuracy"] is not None else "no ground truth"
print(f" {e['name']}: status={e['status']} ({e['transaction_count']} txns) - {gt_part}")
if e.get("count_mismatch"):
print(f" COUNT MISMATCH: expected {e['expected_count']}, got {e['transaction_count']}")
if e.get("opening_balance_match") is False:
print(f" opening_balance mismatch")
if e.get("closing_balance_match") is False:
print(f" closing_balance mismatch")
for m in e.get("field_mismatches", [])[:10]:
print(f" [{m['index']}] {m['field']}: expected {m['expected']!r}, got {m['actual']!r}")
if len(e.get("field_mismatches", [])) > 10:
print(f" ... and {len(e['field_mismatches']) - 10} more")
print(f"\nFull report: {out_path}")
if __name__ == "__main__":
run()