""" System-level evaluation. Writes reports/evaluation.json and reports/EVALUATION.md (the Streamlit "Model performance" page reads the JSON). python tools/evaluate.py --all python tools/evaluate.py --vehicles --violations --plates --seatbelt --models --speed Sections -------- vehicles UVH-26 (Bengaluru CCTV) sample: UVH YOLO11-S vs COCO YOLOv8-S, coarse classes, P/R/F1/AP50. violations Two-wheeler violation classification on the Kaggle "triple riding / no helmet" test set (vehicle-level GT boxes): No Helmet and Triple Riding precision / recall / F1. seatbelt Image-level No-Seatbelt detection on the Seatbelt test split through the full pipeline. plates End-to-end ANPR (detect + OCR) on held-out Indian plate images; OCR-only on held-out crops. models Component detector metrics (mAP50, mAP50-95, P, R) on their test splits. speed Per-stage latency on Bengaluru CCTV frames. """ from __future__ import annotations import argparse import csv import json import os import re import sys import time from collections import defaultdict from pathlib import Path import cv2 import numpy as np import yaml ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) os.chdir(ROOT) from core.geometry import bbox_iou # noqa: E402 REPORT_DIR = ROOT / "reports" UVH = ROOT / "ext_data" / "uvh26_val_sample" TRIPLE_DS = ROOT / "ext_data" / "trafffic-violations-triple-riding-no-helmet-plate" / "master_traffic_violation_dataset" COARSE = {"Hatchback": "car", "Sedan": "car", "SUV": "car", "MUV": "car", "Van": "car", "Bus": "bus", "Mini-bus": "bus", "Tempo-traveller": "bus", "tempo-traveller": "bus", "Truck": "truck", "LCV": "truck", "Three-wheeler": "auto", "Two-wheeler": "two_wheeler", "Bicycle": "bicycle", "bicycle": "bicycle"} def prf(tp: int, fp: int, fn: int) -> dict[str, float]: p = tp / (tp + fp) if tp + fp else 0.0 r = tp / (tp + fn) if tp + fn else 0.0 return {"tp": tp, "fp": fp, "fn": fn, "precision": round(p, 4), "recall": round(r, 4), "f1": round(2 * p * r / (p + r), 4) if p + r else 0.0} def ap50(preds: list[tuple[float, bool]], n_gt: int) -> float: if n_gt == 0: return float("nan") preds = sorted(preds, key=lambda x: -x[0]) tp = np.cumsum([1 if t else 0 for _, t in preds]) fp = np.cumsum([0 if t else 1 for _, t in preds]) rec = tp / n_gt prec = tp / np.maximum(tp + fp, 1) ap = 0.0 for thr in np.linspace(0, 1, 101): p = prec[rec >= thr].max() if np.any(rec >= thr) else 0.0 ap += p / 101 return round(float(ap), 4) def match(preds, gts, iou_thr=0.5): """preds: [(conf, cls, box)], gts: [(cls, box)] -> list of (conf, cls, is_tp), per-class gt counts""" used = set() out = [] for conf, cls, box in sorted(preds, key=lambda x: -x[0]): best, best_iou = None, iou_thr for j, (gcls, gbox) in enumerate(gts): if j in used or gcls != cls: continue iou = bbox_iou(box, gbox) if iou >= best_iou: best, best_iou = j, iou if best is not None: used.add(best) out.append((conf, cls, best is not None)) return out # --------------------------------------------------------------------------- def eval_vehicles(limit: int = 0) -> dict: from ultralytics import YOLO from core.models import COCO_CATEGORY, UVH_CATEGORY ann = json.loads((UVH / "annotations.json").read_text()) cats = {c["id"]: c["name"] for c in ann["categories"]} gts = defaultdict(list) for a in ann["annotations"]: x, y, w, h = a["bbox"] cls = COARSE.get(cats[a["category_id"]]) if cls: gts[a["image_id"]].append((cls, (x, y, x + w, y + h))) images = ann["images"][:limit] if limit else ann["images"] results = {} for name, weights, mapping in (("UVH-26 YOLO11-S (ours)", "models/uvh26_yolo11s.pt", UVH_CATEGORY), ("COCO YOLOv8-S (previous)", "yolov8s.pt", COCO_CATEGORY)): model = YOLO(weights) per_cls_preds, per_cls_gt = defaultdict(list), defaultdict(int) for img in images: path = UVH / "images" / Path(img["file_name"]).name frame = cv2.imread(str(path)) if frame is None: continue res = model.predict(frame, conf=0.05, imgsz=960, verbose=False)[0] preds = [] for b, c, k in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy(), res.boxes.cls.cpu().numpy().astype(int)): key = str(res.names[int(k)]).strip().lower().replace("_", "-").replace(" ", "-") cls = mapping.get(key) if cls: preds.append((float(c), cls, tuple(b))) g = gts.get(img["id"], []) for cls, _ in g: per_cls_gt[cls] += 1 for conf, cls, tp in match(preds, g): per_cls_preds[cls].append((conf, tp)) classes = sorted(per_cls_gt) per_class = {} for cls in classes: preds = per_cls_preds[cls] at = [(c, t) for c, t in preds if c >= 0.3] tp = sum(t for _, t in at) per_class[cls] = {"AP50": ap50(preds, per_cls_gt[cls]), "gt": per_cls_gt[cls], **prf(tp, len(at) - tp, per_cls_gt[cls] - tp)} valid = [v["AP50"] for v in per_class.values() if not np.isnan(v["AP50"])] results[name] = {"mAP50": round(float(np.mean(valid)), 4), "per_class": per_class, "images": len(images)} print(name, results[name]["mAP50"], {k: v["AP50"] for k, v in per_class.items()}) return results # --------------------------------------------------------------------------- def _read_yolo(path: Path, W: int, H: int): out = [] if path.exists(): for line in path.read_text().splitlines(): p = line.split() if len(p) == 5: c, x, y, w, h = int(p[0]), *map(float, p[1:]) out.append((c, ((x - w / 2) * W, (y - h / 2) * H, (x + w / 2) * W, (y + h / 2) * H))) return out def engine_config(overrides: dict[str, str] | None = None, **kwargs): """EngineConfig with CLI ``--set key=value`` overrides (values cast to the field's type).""" from core.detection_engine import EngineConfig cfg = EngineConfig(**kwargs) for key, value in (overrides or {}).items(): if not hasattr(cfg, key): raise SystemExit(f"unknown EngineConfig field: {key}") cur = getattr(cfg, key) setattr(cfg, key, (value.lower() in {"1", "true", "yes"}) if isinstance(cur, bool) else type(cur)(value)) return cfg def eval_violations(limit: int = 0, overrides: dict[str, str] | None = None) -> dict: """ Top-level HELMET / TRIPLE entries are the *test* split. The valid split is reported under "valid"; use it (not test) when choosing thresholds. """ from core.detection_engine import TrafficEnforcementEngine from core.rules import HELMET, TRIPLE engine = TrafficEnforcementEngine(engine_config(overrides, enabled=(HELMET, TRIPLE)), plate_reader=None) out = _eval_violation_split(engine, "test", limit) out["valid"] = _eval_violation_split(engine, "valid", limit) out["config"] = {k: v for k, v in vars(engine.config).items() if k.startswith(("rider", "helmet", "no_helmet", "triple", "photo", "min_two"))} return out def _eval_violation_split(engine, split: str, limit: int = 0) -> dict: from core.rules import HELMET, TRIPLE from core.scene import SceneConfig names = yaml.safe_load((TRIPLE_DS / "data.yaml").read_text(encoding="utf-8-sig"))["names"] c_with, c_without, c_triple = names.index("WithHelmet"), names.index("WithoutHelmet"), names.index("TripleRiding") counts = {HELMET: [0, 0, 0], TRIPLE: [0, 0, 0]} unmatched_preds = {HELMET: 0, TRIPLE: 0} image_level = {HELMET: [0, 0, 0, 0], TRIPLE: [0, 0, 0, 0]} # tp fp fn tn files = [] for img in sorted((TRIPLE_DS / split / "images").glob("*")): lab = TRIPLE_DS / split / "labels" / f"{img.stem}.txt" if lab.exists(): files.append((img, lab)) if limit: files = files[:limit] failures = [] for img_path, lab in files: frame = cv2.imread(str(img_path)) if frame is None: continue H, W = frame.shape[:2] gt = [(c, b) for c, b in _read_yolo(lab, W, H) if c in (c_with, c_without, c_triple)] if not gt: continue _, incidents = engine.process_image(frame, SceneConfig()) preds = {HELMET: [], TRIPLE: []} for inc in incidents: for v in inc.violations: if v in preds: preds[v].append(inc.bbox) for vtype, positive in ((HELMET, {c_without}), (TRIPLE, {c_triple})): negative = {c_with, c_without, c_triple} - positive - ({c_triple} if vtype == HELMET else set()) pos_gt = [b for c, b in gt if c in positive] neg_gt = [b for c, b in gt if c in negative] matched_pos = set() for pb in preds[vtype]: ious_pos = [(bbox_iou(pb, g), j) for j, g in enumerate(pos_gt) if j not in matched_pos] best = max(ious_pos, default=(0, None)) if best[0] >= 0.3: matched_pos.add(best[1]) counts[vtype][0] += 1 elif any(bbox_iou(pb, g) >= 0.3 for g in neg_gt): counts[vtype][1] += 1 if len(failures) < 30: failures.append({"image": img_path.name, "type": vtype, "kind": "false_positive"}) else: unmatched_preds[vtype] += 1 fn = len(pos_gt) - len(matched_pos) counts[vtype][2] += fn if fn and len(failures) < 30: failures.append({"image": img_path.name, "type": vtype, "kind": "missed", "count": fn}) has_gt, has_pred = bool(pos_gt), bool(preds[vtype]) il = image_level[vtype] il[0 if has_gt and has_pred else 1 if has_pred else 2 if has_gt else 3] += 1 out = {} for v in (HELMET, TRIPLE): tp, fp, fn, tn = image_level[v] out[v] = {"vehicle_level": prf(*counts[v]), "image_level": {**prf(tp, fp, fn), "tn": tn, "accuracy": round((tp + tn) / max(1, tp + fp + fn + tn), 4)}, "predictions_on_unlabelled_vehicles": unmatched_preds[v]} print(split, v, {k: out[v]["vehicle_level"][k] for k in ("tp", "fp", "fn", "precision", "recall", "f1")}) out["images"] = len(files) out["split"] = split out["sample_failures"] = failures return out # --------------------------------------------------------------------------- def eval_seatbelt(limit: int = 0) -> dict: from core.detection_engine import EngineConfig, TrafficEnforcementEngine from core.rules import SEATBELT from core.scene import SceneConfig ds = ROOT / "Seatbelt" names = yaml.safe_load((ds / "data.yaml").read_text(encoding="utf-8-sig"))["names"] c_no = names.index("person-noseatbelt") c_yes = names.index("person-seatbelt") engine = TrafficEnforcementEngine(EngineConfig(enabled=(SEATBELT,), min_car_width_px=60), plate_reader=None) tp = fp = fn = tn = skipped = 0 files = sorted((ds / "test" / "images").glob("*")) if limit: files = files[:limit] for img in files: frame = cv2.imread(str(img)) H, W = frame.shape[:2] gt = _read_yolo(ds / "test" / "labels" / f"{img.stem}.txt", W, H) classes = {c for c, _ in gt} if not classes & {c_no, c_yes}: skipped += 1 continue positive = c_no in classes _, incidents = engine.process_image(frame, SceneConfig()) pred = any(SEATBELT in i.violations for i in incidents) if positive and pred: tp += 1 elif pred: fp += 1 elif positive: fn += 1 else: tn += 1 out = {**prf(tp, fp, fn), "tn": tn, "accuracy": round((tp + tn) / max(1, tp + fp + fn + tn), 4), "images": tp + fp + fn + tn, "skipped_no_occupant_label": skipped} print("seatbelt", out) return out # --------------------------------------------------------------------------- def eval_plates(limit: int = 0) -> dict: from core.ocr_engine import UNKNOWN_PLATE_TEXT, get_recognizer, read_vehicle_license_plate out: dict = {} # OCR only, held-out crops rows = [r for r in csv.DictReader((ROOT / "datasets_built" / "ocr" / "labels.csv").open()) if r["split"] == "test"] test_texts = {r["text"] for r in rows} from tools.eval_ocr import levenshtein # type: ignore from core.ocr_engine import recognize_plate_text stats = defaultdict(lambda: [0, 0, 0, 0, 0]) # n, exact, char_err, chars, rejected for r in rows[: limit or None]: img = cv2.imread(str(ROOT / "datasets_built" / "ocr" / "crops" / r["file"])) res = recognize_plate_text(img) pred = res.raw_text for key in ("all", "two_line" if r["two_line"] == "1" else "one_line"): s = stats[key] s[0] += 1 s[1] += int(pred == r["text"]) s[2] += min(levenshtein(pred, r["text"]), len(r["text"])) s[3] += len(r["text"]) s[4] += int(res.text == UNKNOWN_PLATE_TEXT) out["ocr_backend"] = get_recognizer().source out["ocr_on_crops"] = {k: {"n": v[0], "exact_match": round(v[1] / v[0], 4), "char_accuracy": round(1 - v[2] / v[3], 4), "sent_to_manual_review": round(v[4] / v[0], 4)} for k, v in stats.items()} # accepted-only precision: when the system commits to a plate, how often is it right? acc_n = acc_ok = 0 for r in rows[: limit or None]: res = recognize_plate_text(cv2.imread(str(ROOT / "datasets_built" / "ocr" / "crops" / r["file"]))) if res.text != UNKNOWN_PLATE_TEXT: acc_n += 1 acc_ok += int(res.text == r["text"]) out["ocr_on_crops"]["accepted_precision"] = round(acc_ok / max(acc_n, 1), 4) out["ocr_on_crops"]["accepted_rate"] = round(acc_n / max(len(rows[: limit or None]), 1), 4) # End-to-end: whole vehicle image -> plate text (NumberPlate images whose text is held out) names = yaml.safe_load((ROOT / "NumberPlate" / "data.yaml").read_text(encoding="utf-8-sig"))["names"] n = exact = detected = 0 seen = set() for split in ("test", "valid", "train"): for img in sorted((ROOT / "NumberPlate" / split / "images").glob("*")): labels = (ROOT / "NumberPlate" / split / "labels" / f"{img.stem}.txt") if not labels.exists(): continue lines = [l.split() for l in labels.read_text().splitlines() if l.strip()] if len(lines) != 1: continue text = str(names[int(lines[0][0])]).upper() if text not in test_texts or text in seen: continue seen.add(text) res = read_vehicle_license_plate(cv2.imread(str(img))) n += 1 detected += int(res.plate_detected) exact += int(res.text == text) if limit and n >= limit: break out["end_to_end"] = {"images": n, "plate_detected": round(detected / max(n, 1), 4), "exact_match": round(exact / max(n, 1), 4)} print("plates", json.dumps(out)) return out # --------------------------------------------------------------------------- def eval_models() -> dict: from ultralytics import YOLO out = {} jobs = [ ("helmet (head-level Helmet/NoHelmet)", "models/helmet_best.pt", "datasets_built/helmet_heads/data.yaml"), ("seatbelt", "models/seatbelt_best.pt", "configs/normalized_datasets/seatbelt_data.yaml"), ("plate detector", "models/lp_best.pt", "datasets_built/plates/data.yaml"), ] for name, weights, data in jobs: if not Path(weights).exists() or not Path(data).exists(): continue try: m = YOLO(weights) # map class names between model and dataset when needed (helmet model may be 3-class legacy) metrics = m.val(data=data, split="test", imgsz=640, batch=16, verbose=False, plots=False, project=str(ROOT / "runs" / "val"), name="eval_" + Path(weights).stem, exist_ok=True) p, r = float(metrics.box.mp), float(metrics.box.mr) out[name] = {"weights": weights, "precision": round(p, 4), "recall": round(r, 4), "f1": round(2 * p * r / (p + r), 4) if p + r else 0.0, "mAP50": round(float(metrics.box.map50), 4), "mAP50-95": round(float(metrics.box.map), 4), "per_class_AP50": {metrics.names[i]: round(float(v), 4) for i, v in enumerate(metrics.box.ap50)}} except Exception as exc: out[name] = {"error": str(exc)} print(name, out[name]) return out def eval_speed(n: int = 15) -> dict: from core.detection_engine import EngineConfig, TrafficEnforcementEngine from core.scene import SceneConfig engine = TrafficEnforcementEngine(EngineConfig()) files = sorted((UVH / "images").glob("*.png"))[:n] totals = defaultdict(list) for i, f in enumerate(files): frame = cv2.imread(str(f)) t0 = time.perf_counter() out, _ = engine.process_image(frame, SceneConfig()) if i == 0: continue # warm-up totals["total"].append((time.perf_counter() - t0) * 1000) for k, v in out.timings_ms.items(): totals[k].append(v) import torch res = {k: round(float(np.mean(v)), 1) for k, v in totals.items()} res["device"] = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu" res["frames"] = len(files) - 1 print("speed", res) return res # --------------------------------------------------------------------------- def write_markdown(report: dict) -> None: lines = ["# Evaluation report", "", f"Generated: {report.get('generated')}", ""] if "vehicles" in report: lines += ["## Vehicle detection (UVH-26 Bengaluru CCTV sample)", "", "| Model | mAP50 | " + " | ".join(sorted(next(iter(report["vehicles"].values()))["per_class"])) + " |", "|---|---|" + "---|" * len(next(iter(report["vehicles"].values()))["per_class"])] for name, r in report["vehicles"].items(): lines.append(f"| {name} | {r['mAP50']} | " + " | ".join(str(v["AP50"]) for _, v in sorted(r["per_class"].items())) + " |") lines.append("") if "violations" in report: vr = report["violations"] lines += ["## Two-wheeler violations (vehicle-level, Indian photo set)", "", f"Test split: {vr.get('images')} images. Thresholds were chosen on the valid split.", "", "| Violation | Split | Precision | Recall | F1 | TP / FP / FN | Image accuracy |", "|---|---|---|---|---|---|---|"] for v in ("No Helmet", "Triple Riding"): for split, src in (("test", vr), ("valid", vr.get("valid", {}))): r = src.get(v) if r: vl, il = r["vehicle_level"], r["image_level"] lines.append(f"| {v} | {split} | {vl['precision']} | {vl['recall']} | {vl['f1']} | " f"{vl['tp']} / {vl['fp']} / {vl['fn']} | {il['accuracy']} |") lines.append("") if "seatbelt" in report: r = report["seatbelt"] lines += ["## Seatbelt (image-level, full pipeline)", "", f"Precision {r['precision']}, recall {r['recall']}, F1 {r['f1']}, accuracy {r['accuracy']} on {r['images']} images.", ""] if "plates" in report: p = report["plates"] lines += ["## Number plates", "", f"OCR backend: `{p.get('ocr_backend')}`", "", "| Set | Exact match | Char accuracy | Manual review |", "|---|---|---|---|"] for k, v in p.get("ocr_on_crops", {}).items(): if isinstance(v, dict): lines.append(f"| crops: {k} ({v['n']}) | {v['exact_match']} | {v['char_accuracy']} | {v['sent_to_manual_review']} |") e = p.get("end_to_end", {}) lines += ["", f"Accepted-plate precision: {p['ocr_on_crops'].get('accepted_precision')} (accepted rate {p['ocr_on_crops'].get('accepted_rate')})", "", f"End-to-end (vehicle image -> text, {e.get('images')} held-out plates): detected {e.get('plate_detected')}, exact {e.get('exact_match')}", ""] if "models" in report: lines += ["## Component detectors (test splits)", "", "| Model | P | R | F1 | mAP50 | mAP50-95 |", "|---|---|---|---|---|---|"] for name, r in report["models"].items(): if "error" not in r: lines.append(f"| {name} | {r['precision']} | {r['recall']} | {r['f1']} | {r['mAP50']} | {r['mAP50-95']} |") lines.append("") if "speed" in report: s = report["speed"] lines += ["## Speed (ms per 1080p frame)", "", ", ".join(f"{k}: {v}" for k, v in s.items()), ""] (REPORT_DIR / "EVALUATION.md").write_text("\n".join(lines), encoding="utf-8") def main() -> None: ap = argparse.ArgumentParser() for name in ("vehicles", "violations", "seatbelt", "plates", "models", "speed", "all"): ap.add_argument(f"--{name}", action="store_true") ap.add_argument("--limit", type=int, default=0) ap.add_argument("--set", action="append", default=[], metavar="KEY=VALUE", help="EngineConfig override for --violations, e.g. --set rider_evidence=heads") ap.add_argument("--no-write", action="store_true", help="print results without updating the report") args = ap.parse_args() overrides = dict(s.split("=", 1) for s in args.set) REPORT_DIR.mkdir(exist_ok=True) path = REPORT_DIR / "evaluation.json" report = json.loads(path.read_text()) if path.exists() else {} sel = lambda n: args.all or getattr(args, n) # noqa: E731 if sel("vehicles"): report["vehicles"] = eval_vehicles(args.limit) if sel("violations"): report["violations"] = eval_violations(args.limit, overrides) if sel("seatbelt"): report["seatbelt"] = eval_seatbelt(args.limit) if sel("plates"): report["plates"] = eval_plates(args.limit) if sel("models"): report["models"] = eval_models() if sel("speed"): report["speed"] = eval_speed() if args.no_write: return report["generated"] = time.strftime("%Y-%m-%d %H:%M") path.write_text(json.dumps(report, indent=2)) write_markdown(report) print("wrote", path) if __name__ == "__main__": main()