"""The training set: reviewed, usable rows off the collector's SQLite, and how they are split and weighed. Pure Python + sqlite3 — no torch, so `inspect` and the tests run light. Rules (wiki/decisions/bodytype-classifier-training.md): - Only rows a REVIEWER labelled count; the operator's pick and the camera's class are never labels. `unusable` rows are dropped. - Split by TIME (`at` = when the vehicle was seen): validation = the newest slice, so the number reflects tomorrow's traffic rather than a random shuffle of the same days. - Classes with too few labels are dropped from the run (and reported), never trained on a handful of examples that would make the softmax confidently wrong. - Class imbalance is weighed in the loss (inverse frequency, damped) and reported. """ from __future__ import annotations import math import sqlite3 from collections import Counter from dataclasses import dataclass from pathlib import Path # The shared vocabulary (packages/shared VEHICLE_CLASSES) — the only labels a reviewer can # give, and the only classes a model may emit. Order is the canonical one; the model's own # class list (sidecar) is the subset it trained on, in this order. VEHICLE_CLASSES: tuple[str, ...] = ( "car", "sedan", "hatchback", "suv", "minivan", "pickup", "van", "truck", "bus", "motorcycle", ) DB_FILE = "collector.sqlite" @dataclass(frozen=True) class Sample: item: str booth: str kind: str # wash | entry at: str # ISO-8601, when the vehicle was seen (the split key) label: str # the reviewer's class vision_class: str # what the detector said (for the report, never a label) path: Path # the crop on disk @dataclass(frozen=True) class Split: classes: tuple[str, ...] train: list[Sample] val: list[Sample] dropped: dict[str, int] # class → count, below the per-class minimum missing_files: int # labelled rows whose crop is not on disk @property def class_index(self) -> dict[str, int]: return {c: i for i, c in enumerate(self.classes)} def counts(self, part: str) -> dict[str, int]: rows = self.train if part == "train" else self.val c = Counter(s.label for s in rows) return {k: c.get(k, 0) for k in self.classes} _SELECT = "SELECT id, booth, kind, at, review_label, vision_class, image_path FROM items " def _rows( data_dir: Path, where: str, params: tuple[object, ...], db_file: Path | None = None ) -> list[Sample]: db = db_file or data_dir / DB_FILE if not db.exists(): raise FileNotFoundError(f"collector database not found: {db}") con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) try: rows = con.execute(_SELECT + where, params).fetchall() finally: con.close() out: list[Sample] = [] for item, booth, kind, at, label, vision_class, image_path in rows: out.append(Sample(item, booth, kind, at, label or "", vision_class, data_dir / image_path)) return out def load_labelled(data_dir: Path, db_file: Path | None = None) -> tuple[list[Sample], int]: """Every reviewed, usable row with its crop path resolved. Returns (samples, missing) where `missing` counts rows whose crop file is gone (pruned/moved) — skipped.""" rows = _rows( data_dir, "WHERE reviewed_at IS NOT NULL AND review_label != 'unusable' ORDER BY at, id", (), db_file, ) out: list[Sample] = [] missing = 0 for s in rows: if s.label not in VEHICLE_CLASSES: continue # a label outside the vocabulary can only be a future/foreign row if not s.path.is_file(): missing += 1 continue out.append(s) return out, missing def load_reviewed_since(data_dir: Path, since: str, db_file: Path | None = None) -> list[Sample]: """Usable labels whose REVIEW happened after `since` (ISO) — a clean held-out check for a model trained before then. Rows whose crop is gone are skipped.""" rows = _rows( data_dir, "WHERE reviewed_at IS NOT NULL AND review_label != 'unusable' AND reviewed_at > ? " "ORDER BY reviewed_at, id", (since,), db_file, ) return [s for s in rows if s.label in VEHICLE_CLASSES and s.path.is_file()] def load_unlabelled(data_dir: Path, limit: int = 2000, db_file: Path | None = None) -> list[Sample]: """The pending pile, newest first — what the model would say about traffic nobody has labelled (its class histogram and detector agreement are the cheap drift check).""" rows = _rows(data_dir, "WHERE reviewed_at IS NULL ORDER BY received_at DESC LIMIT ?", (limit,), db_file) return [s for s in rows if s.path.is_file()] def make_split(samples: list[Sample], val_fraction: float = 0.2, min_per_class: int = 20) -> Split: """Drop thin classes, then cut by time: the newest `val_fraction` is validation.""" if not 0.0 < val_fraction < 1.0: raise ValueError("val_fraction must be in (0, 1)") counts = Counter(s.label for s in samples) kept = tuple(c for c in VEHICLE_CLASSES if counts.get(c, 0) >= min_per_class) dropped = {c: n for c, n in counts.items() if c not in kept} rows = sorted((s for s in samples if s.label in kept), key=lambda s: (s.at, s.item)) n_val = int(round(len(rows) * val_fraction)) if rows and n_val == 0: n_val = 1 cut = len(rows) - n_val return Split(classes=kept, train=rows[:cut], val=rows[cut:], dropped=dropped, missing_files=0) def class_weights(split: Split, damping: float = 0.5) -> list[float]: """Inverse-frequency weights for the loss, damped by `damping` (0.5 = square root, so a 1:9 imbalance becomes 1:3 rather than 1:9 — full inverse weights over-correct on small sets). Normalised to mean 1 so the learning rate keeps its meaning.""" counts = split.counts("train") total = sum(counts.values()) k = len(split.classes) raw = [(total / (k * max(1, counts[c]))) ** damping for c in split.classes] mean = sum(raw) / max(1, len(raw)) return [w / mean for w in raw] def summarise(samples: list[Sample]) -> dict[str, object]: """What `inspect` prints: per-class counts, per-booth counts, time range.""" by_class = Counter(s.label for s in samples) by_booth = Counter(s.booth for s in samples) by_kind = Counter(s.kind for s in samples) ats = sorted(s.at for s in samples) return { "total": len(samples), "byClass": {c: by_class.get(c, 0) for c in VEHICLE_CLASSES if by_class.get(c, 0)}, "byBooth": dict(sorted(by_booth.items())), "byKind": dict(sorted(by_kind.items())), "from": ats[0] if ats else None, "to": ats[-1] if ats else None, } def suggested_epochs(n_train: int, mode: str) -> int: """A sane default when the owner gives none: enough passes for a small set, fewer as it grows. Feature-extraction heads converge fast; fine-tunes need more but cost more.""" if mode == "features": return int(min(200, max(30, 4000 / max(1, n_train) * 10))) return int(min(30, max(8, math.ceil(3000 / max(1, n_train)) * 4)))