#!/usr/bin/env python3 """Train a bat keypoint detector (handle top + toe) from reviewer clicks (standard 7.4, 9.2). python code/train_bat.py export # results/training/bat_dataset (YOLO pose format) python code/train_bat.py train --epochs 60 # -> models/bat_cricket_vN.pt (GPU/Colab recommended) python code/train_bat.py eval # hand-based estimate vs trained model, held-out frames then set models.bat_weights: bat_cricket_vN.pt in code/config.yaml and rerun analyze (--force) Labels come from the Bat labels tab (two clicks per frame: top of the handle, then the toe). Split by source video so evaluation is not fooled by near-identical frames.""" import argparse import hashlib import json import shutil import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from common import absp, load_config, rel, write_json # noqa: E402 from review import load_review # noqa: E402 def labelled(R): man = {m["id"]: m for m in json.load(open(R / "labeling" / "manifest.json"))} latest = {} for r in sorted((r for r in load_review(R) if r["kind"] == "bat_label"), key=lambda r: r["created_at"]): latest[r["field"]] = r["value"] return [(man[k], v) for k, v in latest.items() if k in man] def split_of(key): return "val" if int(hashlib.md5(key.encode()).hexdigest(), 16) % 5 == 0 else "train" def export(cfg, min_labels=20): import numpy as np R = cfg["_paths"]["results"] rows = labelled(R) if len(rows) < min_labels: raise SystemExit(f"only {len(rows)} bat-labelled frames; label at least ~150 in the Bat labels tab first") key = "source_id" if len({m["source_id"] for m, _ in rows}) > 1 else "delivery_id" splits = {m[key]: split_of(m[key]) for m, _ in rows} if "val" not in splits.values(): splits[sorted(splits)[-1]] = "val" if "train" not in splits.values() and len(splits) > 1: splits[sorted(splits)[0]] = "train" out = R / "training" / "bat_dataset" shutil.rmtree(out, ignore_errors=True) n = {"train": 0, "val": 0} for m, v in rows: sp = splits[m[key]] (out / "images" / sp).mkdir(parents=True, exist_ok=True) (out / "labels" / sp).mkdir(parents=True, exist_ok=True) shutil.copy(absp(m["image"]), out / "images" / sp / f"{m['id']}.jpg") W, H = m["size"] line = "" if v.get("visible") is not False: h, t = np.array(v["handle"], float), np.array(v["toe"], float) pad = 0.07 * np.linalg.norm(t - h) + 4 # about half a blade width x1, y1 = np.minimum(h, t) - pad x2, y2 = np.maximum(h, t) + pad x1, y1, x2, y2 = max(0, x1), max(0, y1), min(W, x2), min(H, y2) line = (f"0 {(x1 + x2) / 2 / W:.6f} {(y1 + y2) / 2 / H:.6f} {(x2 - x1) / W:.6f} {(y2 - y1) / H:.6f} " f"{h[0] / W:.6f} {h[1] / H:.6f} 2 {t[0] / W:.6f} {t[1] / H:.6f} 2\n") (out / "labels" / sp / f"{m['id']}.txt").write_text(line) n[sp] += 1 (out / "data.yaml").write_text(f"path: {out.resolve()}\ntrain: images/train\nval: images/val\n" "kpt_shape: [2, 3]\nflip_idx: [0, 1]\nnames:\n 0: bat\n") write_json(out / "split.json", {"by": key, "groups": splits, "counts": n}) print(f"dataset -> {rel(out)} {n}") def train(cfg, epochs, imgsz, device): from ultralytics import YOLO from vision import pick_device R, M = cfg["_paths"]["results"], cfg["_paths"]["models"] data = R / "training" / "bat_dataset" / "data.yaml" if not data.exists(): export(cfg) dev = pick_device(device)[0] if device == "auto" else device base = M / "yolo11n-pose.pt" res = YOLO(str(base if base.exists() else "yolo11n-pose.pt")).train( data=str(data), epochs=epochs, imgsz=imgsz, device=dev, batch=8 if dev == "cpu" else 16, project=str(R / "training" / "runs"), name="bat", patience=20, verbose=False) n = 1 + len(list(M.glob("bat_cricket_v*.pt"))) dst = M / f"bat_cricket_v{n}.pt" shutil.copy(Path(res.save_dir) / "weights" / "best.pt", dst) print(f"saved {rel(dst)}. Next: python code/train_bat.py eval --weights {rel(dst)}") def evaluate(cfg, weights, imgsz): """Endpoint error (px) and angle error (deg): trained model vs the hand-based estimate.""" import cv2 import numpy as np from bat import bat_length_torso, estimate_from_hands, load_equipment from ultralytics import YOLO R, M = cfg["_paths"]["results"], cfg["_paths"]["models"] split = json.load(open(R / "training" / "bat_dataset" / "split.json")) rows = [(m, v) for m, v in labelled(R) if v.get("visible") is not False and split["groups"].get(m[split["by"]]) == "val"] pose = YOLO(str(M / cfg["models"]["pose_weights"])) batm = YOLO(str(weights)) if weights else None scale = bat_length_torso(load_equipment())[0] ang = lambda h, t: np.degrees(np.arctan2(t[0] - h[0], t[1] - h[1])) res = {"frames": len(rows), "weights": str(weights) if weights else None} errs = {"hand_estimate": [], "model": []} for m, v in rows: img = cv2.imread(str(absp(m["image"]))) gh, gt = np.array(v["handle"]), np.array(v["toe"]) r = pose.predict(img, imgsz=imgsz, verbose=False, device="cpu")[0] if r.keypoints is not None and len(r.boxes): K = r.keypoints.data.cpu().numpy() hands = [np.nanmean(k[[9, 10], :2], axis=0) for k in K] k = K[int(np.argmin([np.linalg.norm(h - gh) for h in hands]))] pts, _ = estimate_from_hands(np.repeat(k[None], 6, axis=0), scale) if np.isfinite(pts[0]).all(): errs["hand_estimate"].append((np.linalg.norm(pts[0, 1] - gt), abs(ang(*pts[0]) - ang(gh, gt)))) if batm is not None: b = batm.predict(img, imgsz=imgsz, verbose=False, device="cpu")[0] if b.keypoints is not None and len(b.boxes): kp = b.keypoints.data.cpu().numpy()[:, :, :2] best = kp[int(np.argmin([np.linalg.norm(x[0] - gh) for x in kp]))] errs["model"].append((np.linalg.norm(best[1] - gt), abs(ang(best[0], best[1]) - ang(gh, gt)))) for k, e in errs.items(): if e: e = np.array(e); e[:, 1] = np.minimum(e[:, 1], 360 - e[:, 1]) res[k] = {"found": len(e), "toe_error_px_median": round(float(np.median(e[:, 0])), 1), "angle_error_deg_median": round(float(np.median(e[:, 1])), 1)} write_json(R / "qa" / "bat_eval.json", res) print(json.dumps(res, indent=2)) def main(): ap = argparse.ArgumentParser() ap.add_argument("cmd", choices=["export", "train", "eval"]) ap.add_argument("--epochs", type=int, default=60) ap.add_argument("--imgsz", type=int, default=960) ap.add_argument("--device", default="auto") ap.add_argument("--weights") a = ap.parse_args() cfg = load_config() if a.cmd == "export": export(cfg) elif a.cmd == "train": train(cfg, a.epochs, a.imgsz, a.device) else: w = a.weights or (sorted(cfg["_paths"]["models"].glob("bat_cricket_v*.pt")) or [None])[-1] evaluate(cfg, absp(w) if w and not Path(str(w)).is_absolute() else w, a.imgsz) if __name__ == "__main__": main()