"""Acceptance-rate telemetry — instruments the human-review flywheel. Every time a human applies review decisions (bulk confirm in the Review tab, or move/resize/relabel/add/delete in the visual box editor) we already know which engine-detected boxes were accepted as-is vs. corrected vs. thrown away — we just used to discard that signal after rebuilding the result. This module records it. The single number it produces — the **acceptance rate** (engine boxes kept unchanged ÷ engine boxes the human actually ruled on) — is the proof that the data flywheel is working: as confirmed corrections accumulate in the training repo and the detector improves, acceptance should trend up and rework down. Storage: an append-only CSV at outputs/telemetry.csv (one row per review event). No external deps, no API cost. `summarize()` aggregates it for /api/telemetry. """ from __future__ import annotations import csv from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, List ROOT = Path(__file__).resolve().parent.parent TELEMETRY_CSV = ROOT / "outputs" / "telemetry.csv" _FIELDS = ["timestamp", "pdf", "event", "detected", "accepted", "relabeled", "deleted", "added", "cost_usd", "acceptance_rate"] def _is_relabel(orig_tag: str, action: str) -> bool: """An action that sets an explicit AC-tag different from the OCR tag is a human relabel (mirrors pipeline._resolve_tag's notion of an override tag).""" a = (action or "").strip() return a.upper().startswith("AC") and len(a) > 3 and a != (orig_tag or "").strip() def counts_from_apply_review(rows: List[dict], bulk: str, edits: Dict[tuple, str], file_name: str) -> Dict[str, int]: """Classify the outcome of one apply_review() call (bulk confirm + per-box edits) into accept/relabel/delete/add counts. `rows` is the pre-decision CSV, `edits` maps (file_name, id)->action, `bulk` is ''|'all'|'yellows'|'none'.""" bulk = (bulk or "").strip().lower() c = {"detected": 0, "accepted": 0, "relabeled": 0, "deleted": 0, "added": 0} for r in rows: if not r.get("x"): continue status = (r.get("status") or "").strip() # Resolve the final action the same way apply_review will. action = (r.get("action") or "").strip() if bulk == "all": action = "keep" elif bulk == "yellows" and status not in ("confirmed", "noise"): action = "keep" edited = edits.get((file_name, str(r.get("id")))) if edited is not None: action = edited.strip() if status == "added": # human-added in a prior session c["added"] += 1 continue if not action: # no decision made on this box yet continue c["detected"] += 1 if action.lower() == "delete": c["deleted"] += 1 elif _is_relabel(r.get("tag", ""), action): c["relabeled"] += 1 else: # 'keep' (or any non-delete) = accepted c["accepted"] += 1 return c def counts_from_box_edits(existing: List[dict], incoming: List[dict]) -> Dict[str, int]: """Classify one visual-editor save by diffing the pre-edit CSV (`existing`) against the boxes the editor sent back (`incoming`). Engine-detected boxes that survived unchanged = accepted; gone = deleted; tag changed = relabeled; boxes with a new (non-numeric) id = human-added.""" eng = {str(r.get("id")): r for r in existing if str(r.get("id")).isdigit() and (r.get("status") or "").strip() != "added"} seen: set[str] = set() c = {"detected": len(eng), "accepted": 0, "relabeled": 0, "deleted": 0, "added": 0} for b in incoming: bid = str(b.get("id") or "") if not bid.isdigit() or bid not in eng: c["added"] += 1 # brand-new box drawn by the human continue seen.add(bid) orig = (eng[bid].get("tag") or "").strip() new = (b.get("tag") or "").strip() if new and new != orig: c["relabeled"] += 1 else: c["accepted"] += 1 c["deleted"] = len(eng) - len(seen) # engine boxes the human dropped return c def log_review(pdf_stem: str, event: str, counts: Dict[str, int], cost_usd: float = 0.0) -> None: """Append one review event to outputs/telemetry.csv. Best-effort: never raises into the caller (telemetry must not break a review save).""" try: ruled = counts.get("accepted", 0) + counts.get("relabeled", 0) + counts.get("deleted", 0) rate = round(counts.get("accepted", 0) / ruled, 4) if ruled else "" TELEMETRY_CSV.parent.mkdir(parents=True, exist_ok=True) new = not TELEMETRY_CSV.exists() with open(TELEMETRY_CSV, "a", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=_FIELDS) if new: w.writeheader() w.writerow({ "timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"), "pdf": pdf_stem, "event": event, "detected": counts.get("detected", 0), "accepted": counts.get("accepted", 0), "relabeled": counts.get("relabeled", 0), "deleted": counts.get("deleted", 0), "added": counts.get("added", 0), "cost_usd": round(float(cost_usd or 0.0), 4), "acceptance_rate": rate, }) except Exception as exc: print(f" [telemetry] log failed (non-fatal): {exc}", flush=True) def summarize(pdf_stem: str | None = None) -> Dict[str, Any]: """Aggregate the telemetry log into overall + per-blueprint acceptance rates. Optionally scope to a single `pdf_stem`. Returns counts a GUI can chart.""" if not TELEMETRY_CSV.exists(): return {"events": 0, "detected": 0, "accepted": 0, "relabeled": 0, "deleted": 0, "added": 0, "acceptance_rate": None, "by_pdf": [], "recent": []} try: rows = list(csv.DictReader(open(TELEMETRY_CSV, encoding="utf-8"))) except Exception: rows = [] if pdf_stem: rows = [r for r in rows if r.get("pdf") == pdf_stem] def _i(r, k): try: return int(r.get(k) or 0) except (TypeError, ValueError): return 0 def _agg(rs: List[dict]) -> Dict[str, Any]: d = {k: sum(_i(r, k) for r in rs) for k in ("detected", "accepted", "relabeled", "deleted", "added")} ruled = d["accepted"] + d["relabeled"] + d["deleted"] d["events"] = len(rs) d["acceptance_rate"] = round(d["accepted"] / ruled, 4) if ruled else None return d by_pdf = [] for stem in sorted({r.get("pdf", "") for r in rows}): a = _agg([r for r in rows if r.get("pdf") == stem]) a["pdf"] = stem by_pdf.append(a) out = _agg(rows) out["by_pdf"] = by_pdf out["recent"] = rows[-10:] return out