"""Model backends. The rest of the pipeline only calls .pose() and .balls(), so swapping YOLO for RTMPose, MediaPipe or a fine-tuned ball model is local.""" import os import shutil from pathlib import Path import numpy as np def pick_device(requested): """Return a device that really works. torch.cuda.is_available() can say True for GPUs too old for the installed PyTorch (e.g. GT 730, compute 3.5), so we run one tiny CUDA op and fall back to CPU if it fails.""" import torch if str(requested).lower() == "cpu": return "cpu", "requested in config" if not torch.cuda.is_available(): return "cpu", "CUDA not available" idx = 0 if str(requested).lower() == "auto" else int(requested) name = torch.cuda.get_device_name(idx) major, minor = torch.cuda.get_device_capability(idx) try: x = torch.ones(8, device=f"cuda:{idx}") * 2 torch.cuda.synchronize() float(x.sum()) return idx, f"{name} (compute {major}.{minor})" except Exception: return "cpu", f"{name} (compute {major}.{minor}) is too old for this PyTorch" class UltralyticsVision: name = "ultralytics" def __init__(self, mcfg, models_dir: Path): import warnings warnings.filterwarnings("ignore", message=".*cuda capability.*") import torch from ultralytics import YOLO self.device, why = pick_device(mcfg.get("device", "auto")) if self.device == "cpu": torch.set_num_threads(max(1, os.cpu_count() or 1)) print(f" running on CPU ({why}), {torch.get_num_threads()} threads") else: print(f" running on GPU: {why}") self.half = bool(mcfg.get("half", True)) and self.device != "cpu" models_dir.mkdir(parents=True, exist_ok=True) pose_w = self._weights(models_dir, mcfg["pose_weights"]) det_w = self._weights(models_dir, mcfg["det_weights"]) fmt = mcfg.get("cpu_format", "pytorch") if self.device == "cpu" else "pytorch" self.pose_model = self._load(YOLO, pose_w, fmt, mcfg) self.det_model = self._load(YOLO, det_w, fmt, mcfg) bw = mcfg.get("bat_weights") self.bat_model = YOLO(str(models_dir / bw)) if bw and (models_dir / bw).exists() else None names = getattr(self.det_model, "names", {}) or {} self.ball_classes = [i for i, n in names.items() if str(n).lower() == "ball" or str(n).lower().endswith(" ball")] or [32] self.versions = {"bat": bw if self.bat_model else None, "pose": Path(pose_w).name, "ball": Path(det_w).name, "device": str(self.device), "half": self.half, "format": self.format} def _load(self, YOLO, weights, fmt, mcfg): """Optionally export to OpenVINO for 2-3x faster CPU inference (Intel CPUs).""" self.format = "pytorch" if fmt == "openvino": out = Path(weights).with_name(Path(weights).stem + "_openvino_model") try: if not out.exists(): print(f" exporting {Path(weights).name} to OpenVINO (one time)...") YOLO(weights).export(format="openvino", imgsz=mcfg.get("export_imgsz", 640), dynamic=True) m = YOLO(str(out), task="pose" if "pose" in Path(weights).stem else "detect") self.format = "openvino" return m except Exception as e: print(f" ! OpenVINO export failed ({e}); using PyTorch on CPU") return YOLO(weights) @staticmethod def _weights(models_dir: Path, name: str) -> str: target = models_dir / name if target.exists(): return str(target) from ultralytics.utils.downloads import attempt_download_asset print(f" downloading {name} -> {target}") got = Path(attempt_download_asset(str(target))) if not got.exists(): got = Path(attempt_download_asset(name)) if got.resolve() != target.resolve(): shutil.move(str(got), str(target)) return str(target) def _kw(self): kw = {"device": self.device, "verbose": False} if self.half: kw["half"] = True return kw def pose(self, frame, imgsz=640, conf=0.25): r = self.pose_model.predict(frame, imgsz=imgsz, conf=conf, **self._kw())[0] if r.boxes is None or len(r.boxes) == 0 or r.keypoints is None: return [] boxes = r.boxes.xyxy.cpu().numpy() confs = r.boxes.conf.cpu().numpy() k = r.keypoints.data.cpu().numpy() if k.shape[-1] == 2: k = np.concatenate([k, np.ones(k.shape[:-1] + (1,))], -1) return [{"box": boxes[i].tolist(), "conf": float(confs[i]), "kpts": k[i]} for i in range(len(boxes))] def bats(self, frame, imgsz=960, conf=0.2): """Bat keypoints [handle, toe] from a model trained with train_bat.py (empty if none).""" if self.bat_model is None: return [] r = self.bat_model.predict(frame, imgsz=imgsz, conf=conf, **self._kw())[0] if r.keypoints is None or r.boxes is None or len(r.boxes) == 0: return [] k = r.keypoints.data.cpu().numpy() c = r.boxes.conf.cpu().numpy() return [{"handle": k[i, 0, :2].tolist(), "toe": k[i, 1, :2].tolist(), "conf": float(c[i])} for i in range(len(c))] def balls(self, frame, imgsz=1280, conf=0.1): r = self.det_model.predict(frame, imgsz=imgsz, conf=conf, classes=self.ball_classes, **self._kw())[0] if r.boxes is None or len(r.boxes) == 0: return [] b = r.boxes.xyxy.cpu().numpy() c = r.boxes.conf.cpu().numpy() return [(float((x1 + x2) / 2), float((y1 + y2) / 2), float(cc)) for (x1, y1, x2, y2), cc in zip(b, c)] def build_vision(kind, cfg): if kind == "fake": from tests.synthetic import FakeVision return FakeVision() if kind == "fake_mv": from tests.synthetic_multiview import FakeMultiVision return FakeMultiVision() v = UltralyticsVision(cfg["models"], cfg["_paths"]["models"]) if v.device == "cpu": # lighter settings so CPU runs finish in reasonable time for section, vals in (cfg.get("cpu_overrides") or {}).items(): cfg[section].update(vals) print(f" CPU settings for {section}: {vals}") return v