"""Metrics + the human-readable report. The owner reads this BEFORE anything ships; the floor decision is made on these numbers. Pure Python, no torch.""" from __future__ import annotations from dataclasses import asdict, dataclass, field from typing import Any @dataclass class ClassMetrics: support: int recall: float # of the true members, how many the model caught precision: float # of the model's picks, how many were right @dataclass class Metrics: n: int accuracy: float macro_recall: float per_class: dict[str, ClassMetrics] confusion: list[list[int]] # rows = true class, cols = predicted, in `classes` order camera_agreement: float | None = None # how often the model equals the detector's class onnx_agreement: float | None = None # exported graph vs the torch model, argmax extra: dict[str, Any] = field(default_factory=dict) def to_dict(self) -> dict[str, Any]: return asdict(self) def compute_metrics( classes: tuple[str, ...] | list[str], y_true: list[int], y_pred: list[int], camera: list[str] | None = None, ) -> Metrics: k = len(classes) conf = [[0] * k for _ in range(k)] for t, p in zip(y_true, y_pred, strict=True): conf[t][p] += 1 per: dict[str, ClassMetrics] = {} recalls: list[float] = [] for i, c in enumerate(classes): support = sum(conf[i]) tp = conf[i][i] picked = sum(conf[r][i] for r in range(k)) recall = tp / support if support else 0.0 precision = tp / picked if picked else 0.0 per[c] = ClassMetrics(support=support, recall=recall, precision=precision) if support: recalls.append(recall) n = len(y_true) acc = sum(1 for t, p in zip(y_true, y_pred, strict=True) if t == p) / n if n else 0.0 agree = None if camera is not None and n: agree = sum(1 for p, cam in zip(y_pred, camera, strict=True) if classes[p] == cam) / n return Metrics( n=n, accuracy=acc, macro_recall=sum(recalls) / len(recalls) if recalls else 0.0, per_class=per, confusion=conf, camera_agreement=agree, ) def _pct(x: float | None) -> str: return "—" if x is None else f"{x * 100:.1f} %" def render_report( *, version: str, trained_at: str, mode: str, backbone: str, epochs: int, classes: tuple[str, ...] | list[str], train_counts: dict[str, int], val_counts: dict[str, int], dropped: dict[str, int], missing_files: int, weights: list[float], metrics: Metrics, min_accuracy: float, written: bool, notes: list[str] | None = None, ) -> str: lines: list[str] = [] verdict = "MODEL WRITTEN" if written else "MODEL NOT WRITTEN — below the floor" lines.append(f"# Body-type classifier {version}") lines.append("") lines.append( f"**{verdict}** · validation accuracy {_pct(metrics.accuracy)} vs floor {_pct(min_accuracy)}" ) lines.append("") lines.append(f"- trained: {trained_at}") lines.append(f"- mode: {mode} · backbone: {backbone} · epochs: {epochs}") lines.append(f"- classes ({len(classes)}): {', '.join(classes)}") lines.append( f"- labels: {sum(train_counts.values())} train · {sum(val_counts.values())} validation " "(validation = the NEWEST slice, by time seen)" ) if dropped: lines.append( "- dropped (too few labels this run): " + ", ".join(f"{c} ({n})" for c, n in sorted(dropped.items())) ) if missing_files: lines.append(f"- labelled rows whose crop is missing on disk (skipped): {missing_files}") lines.append("") lines.append("## Validation") lines.append("") lines.append(f"- accuracy: {_pct(metrics.accuracy)} on {metrics.n} crops") lines.append(f"- macro recall (each class counted equally): {_pct(metrics.macro_recall)}") if metrics.camera_agreement is not None: lines.append( f"- agrees with the detector's coarse class: {_pct(metrics.camera_agreement)} " "(informational — the detector only knows car/truck/bus/motorcycle)" ) if metrics.onnx_agreement is not None: lines.append( f"- exported ONNX matches the trained model on validation: {_pct(metrics.onnx_agreement)}" ) lines.append("") lines.append("| class | train | val | recall | precision | loss weight |") lines.append("|---|---:|---:|---:|---:|---:|") for c, w in zip(classes, weights, strict=True): m = metrics.per_class[c] lines.append( f"| {c} | {train_counts.get(c, 0)} | {m.support} | {_pct(m.recall) if m.support else '—'} | " f"{_pct(m.precision) if m.support else '—'} | {w:.2f} |" ) lines.append("") lines.append("## Confusion (rows = reviewer's label, columns = model)") lines.append("") lines.append("| | " + " | ".join(classes) + " |") lines.append("|---|" + "---:|" * len(classes)) for c, row in zip(classes, metrics.confusion, strict=True): lines.append(f"| **{c}** | " + " | ".join(str(n) for n in row) + " |") lines.append("") if notes: lines.append("## Notes") lines.append("") lines.extend(f"- {n}" for n in notes) lines.append("") lines.append( "The flag on the booth records, it never bills: even a model that passes the floor is " "advisory (the site threshold gates the flag)." ) return "\n".join(lines) + "\n"