Spaces:
Sleeping

VisionGuard-AI / core /models.py
Abhyuday-06's picture
feat: Bengaluru-ready detection pipeline with retrained models
29088fd
Raw History Blame Contribute Delete
13.3 kB
"""
Model wrappers. Each wrapper returns plain Python objects so the engine (and the
tests, which substitute fakes) never touch Ultralytics result objects directly.
Models
------
vehicle UVH-26 YOLO11-S, trained by IISc on 26k Bengaluru Safe-City CCTV frames
(14 Indian vehicle classes incl. auto-rickshaw; two-wheeler boxes include riders).
coco COCO detector: traffic lights, and the photo fallback for close-up vehicles.
riders Photo mode only. Detects a two-wheeler together with its riders and classifies it as
WithHelmet / WithoutHelmet / TripleRiding (trained on ground-level Indian road photos,
where the CCTV-trained vehicle model misses most bikes).
helmet Helmet / NoHelmet head detector, applied to two-wheeler crops.
seatbelt windshield / person-seatbelt / person-noseatbelt detector, applied to car crops.
plate Indian licence-plate localiser (see core.ocr_engine for OCR).
"""
from __future__ import annotations
import logging
import threading
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Sequence
import numpy as np
from core.geometry import BBox, clip_bbox, expand_bbox
from core.rules import Head
LOGGER = logging.getLogger(__name__)
PROJECT_ROOT = Path(__file__).resolve().parent.parent
MODELS_DIR = PROJECT_ROOT / "models"
# UVH-26 label -> (category, display label)
UVH_CATEGORY = {
"hatchback": "car", "sedan": "car", "suv": "car", "muv": "car", "van": "car",
"bus": "bus", "mini-bus": "bus", "tempo-traveller": "bus",
"truck": "truck", "lcv": "truck",
"three-wheeler": "auto", "two-wheeler": "two_wheeler", "bicycle": "bicycle", "others": "other",
}
# COCO label -> category (used if a COCO model is configured as the vehicle model)
COCO_CATEGORY = {"car": "car", "bus": "bus", "truck": "truck", "motorcycle": "two_wheeler",
"bicycle": "bicycle"}
CATEGORY_DISPLAY = {"car": "Car", "bus": "Bus", "truck": "Truck", "auto": "Auto-rickshaw",
"two_wheeler": "Two-wheeler", "bicycle": "Bicycle", "other": "Vehicle"}
@dataclass
class Detection:
track_id: int
category: str
label: str
confidence: float
bbox: BBox
# extra per-vehicle evidence, e.g. {"rider_class": "WithoutHelmet", "rider_conf": 0.81} from the rider model
attributes: dict[str, Any] = field(default_factory=dict)
@dataclass
class SeatbeltObservation:
observable: bool # a windshield / occupant was visible
no_seatbelt_conf: float | None
boxes: list[tuple[str, float, BBox]] = field(default_factory=list) # frame coordinates
def _resolve(path: str | Path) -> Path:
p = Path(path)
if p.exists():
return p
for c in (MODELS_DIR / p.name, PROJECT_ROOT / p.name):
if c.exists():
return c
return p
def _label_key(name: str) -> str:
return str(name).strip().lower().replace("_", "-").replace(" ", "-")
class YoloModels:
"""Loads and runs all YOLO models used by the engine."""
def __init__(
self,
vehicle_model: str | Path = MODELS_DIR / "uvh26_yolo11s.pt",
helmet_model: str | Path = MODELS_DIR / "helmet_best.pt",
seatbelt_model: str | Path = MODELS_DIR / "seatbelt_best.pt",
coco_model: str | Path = PROJECT_ROOT / "yolov8s.pt",
device: Any = None,
tracker: str | Path = PROJECT_ROOT / "configs" / "bytetrack_traffic.yaml",
rider_model: str | Path | None = MODELS_DIR / "riders_best.pt",
) -> None:
from ultralytics import YOLO
def load(path: str | Path, required: bool = True):
resolved = _resolve(path)
if not resolved.exists():
if required:
raise FileNotFoundError(f"Model weights not found: {resolved}")
return None
return YOLO(str(resolved))
self.device = device
self.vehicle = load(vehicle_model)
self.helmet = load(helmet_model, required=False)
self.seatbelt = load(seatbelt_model, required=False)
self.coco = load(coco_model, required=False)
self.riders = load(rider_model, required=False) if rider_model else None
self.tracker = str(_resolve(tracker)) if _resolve(tracker).exists() else "bytetrack.yaml"
self.paths = {"vehicle": str(vehicle_model), "helmet": str(helmet_model),
"seatbelt": str(seatbelt_model), "coco": str(coco_model), "riders": str(rider_model)}
names = {_label_key(n) for n in self.vehicle.names.values()}
self._vehicle_map = UVH_CATEGORY if names & set(UVH_CATEGORY) else COCO_CATEGORY
self._lock = threading.Lock()
def _kw(self, **kwargs: Any) -> dict[str, Any]:
kwargs.setdefault("verbose", False)
if self.device is not None:
kwargs["device"] = self.device
return kwargs
# ------------------------------------------------------------------
def vehicles(self, frame: np.ndarray, track: bool, conf: float = 0.3, imgsz: int = 960,
iou: float = 0.5) -> list[Detection]:
with self._lock:
if track:
res = self.vehicle.track(frame, persist=True, tracker=self.tracker, conf=conf, iou=iou,
imgsz=imgsz, **self._kw())[0]
else:
res = self.vehicle.predict(frame, conf=conf, iou=iou, imgsz=imgsz, **self._kw())[0]
boxes = res.boxes
if boxes is None or len(boxes) == 0:
return []
ids = boxes.id.cpu().numpy().astype(int) if boxes.id is not None else None
out: list[Detection] = []
for i, (xyxy, c, cls) in enumerate(zip(boxes.xyxy.cpu().numpy(), boxes.conf.cpu().numpy(),
boxes.cls.cpu().numpy().astype(int))):
raw = str(res.names.get(int(cls), cls))
category = self._vehicle_map.get(_label_key(raw))
if category is None:
continue
bbox = clip_bbox(xyxy, frame.shape)
if bbox[2] - bbox[0] < 4 or bbox[3] - bbox[1] < 4:
continue
tid = int(ids[i]) if ids is not None else -(i + 1)
out.append(Detection(tid, category, raw, float(c), bbox))
return out
# ------------------------------------------------------------------
def heads(self, frame: np.ndarray, regions: Sequence[BBox], conf: float = 0.3, imgsz: int = 416) -> list[Head]:
"""Run the helmet model on each region (two-wheeler + rider zone); return heads in frame coords."""
if self.helmet is None or not regions:
return []
crops, offsets = [], []
for r in regions:
x1, y1, x2, y2 = clip_bbox(r, frame.shape)
if x2 - x1 < 12 or y2 - y1 < 12:
continue
crops.append(frame[y1:y2, x1:x2])
offsets.append((x1, y1))
if not crops:
return []
with self._lock:
results = self.helmet.predict(crops, conf=conf, imgsz=imgsz, **self._kw())
heads: list[Head] = []
for res, (ox, oy) in zip(results, offsets):
if res.boxes is None:
continue
for xyxy, c, cls in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy(),
res.boxes.cls.cpu().numpy().astype(int)):
key = _label_key(res.names.get(int(cls), cls)).replace("-", "")
if key not in {"helmet", "nohelmet", "withouthelmet", "withhelmet"}:
continue
helmet = key in {"helmet", "withhelmet"}
bbox = (int(xyxy[0] + ox), int(xyxy[1] + oy), int(xyxy[2] + ox), int(xyxy[3] + oy))
heads.append(Head(bbox, helmet, float(c)))
return heads
# ------------------------------------------------------------------
def seatbelt_check(self, frame: np.ndarray, car_boxes: Sequence[BBox], conf: float = 0.3,
imgsz: int = 640) -> list[SeatbeltObservation]:
if self.seatbelt is None or not car_boxes:
return [SeatbeltObservation(False, None) for _ in car_boxes]
crops, offsets = [], []
for b in car_boxes:
x1, y1, x2, y2 = expand_bbox(b, 0.05, 0.05, 0.05, 0.0, frame.shape)
crops.append(frame[y1:y2, x1:x2])
offsets.append((x1, y1))
with self._lock:
results = self.seatbelt.predict(crops, conf=conf, imgsz=imgsz, **self._kw())
out: list[SeatbeltObservation] = []
for res, (ox, oy) in zip(results, offsets):
boxes: list[tuple[str, float, BBox]] = []
if res.boxes is not None:
for xyxy, c, cls in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy(),
res.boxes.cls.cpu().numpy().astype(int)):
name = _label_key(res.names.get(int(cls), cls))
boxes.append((name, float(c), (int(xyxy[0] + ox), int(xyxy[1] + oy),
int(xyxy[2] + ox), int(xyxy[3] + oy))))
no_belt = [c for n, c, _ in boxes if "noseatbelt" in n.replace("-", "")]
observable = any(n == "windshield" or n.startswith("person") for n, _, _ in boxes)
out.append(SeatbeltObservation(observable, max(no_belt) if no_belt else None, boxes))
return out
# ------------------------------------------------------------------
def traffic_lights(self, frame: np.ndarray, conf: float = 0.25, imgsz: int = 960) -> list[tuple[BBox, float]]:
if self.coco is None:
return []
with self._lock:
res = self.coco.predict(frame, conf=conf, imgsz=imgsz, classes=[9], **self._kw())[0]
if res.boxes is None:
return []
return [(clip_bbox(b, frame.shape), float(c))
for b, c in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy())]
def coco_vehicles(self, frame: np.ndarray, conf: float = 0.35, imgsz: int = 640) -> list[Detection]:
"""
COCO detections for ground-level / close-up photos, where the CCTV-trained UVH model is out
of domain. Motorcycle boxes are grown to include the riders sitting on them so they match the
UVH "Two-wheeler" convention (vehicle + riders).
"""
if self.coco is None:
return []
with self._lock:
res = self.coco.predict(frame, conf=conf, imgsz=imgsz, classes=[0, 1, 2, 3, 5, 7], **self._kw())[0]
if res.boxes is None or len(res.boxes) == 0:
return []
persons, out = [], []
for b, c, k in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy(),
res.boxes.cls.cpu().numpy().astype(int)):
name = str(res.names[int(k)])
box = clip_bbox(b, frame.shape)
if name == "person":
persons.append(box)
elif name in COCO_CATEGORY:
out.append(Detection(-1, COCO_CATEGORY[name], name.capitalize(), float(c), box))
for d in out:
if d.category not in {"two_wheeler", "bicycle"}:
continue
x1, y1, x2, y2 = d.bbox
w, h = x2 - x1, y2 - y1
for p in persons:
px = (p[0] + p[2]) / 2.0
# rider: horizontally over the bike, lower body within the bike's vertical span
if x1 - 0.15 * w <= px <= x2 + 0.15 * w and y1 - 0.5 * h <= p[3] <= y2 + 0.25 * h and p[1] < y1 + 0.5 * h:
x1, y1, x2, y2 = min(x1, p[0]), min(y1, p[1]), max(x2, p[2]), max(y2, p[3])
d.bbox = clip_bbox((x1, y1, x2, y2), frame.shape)
return out
def rider_units(self, frame: np.ndarray, conf: float = 0.25, imgsz: int = 640) -> list[Detection]:
"""
Two-wheeler + riders boxes from the rider model, each tagged with the model's class
(WithHelmet / WithoutHelmet / TripleRiding) in ``attributes``. Photo mode only.
Overlapping boxes of different classes describe the same bike, so class-agnostic NMS is used.
"""
if self.riders is None:
return []
with self._lock:
res = self.riders.predict(frame, conf=conf, imgsz=imgsz, agnostic_nms=True, **self._kw())[0]
if res.boxes is None or len(res.boxes) == 0:
return []
out = []
for b, c, k in zip(res.boxes.xyxy.cpu().numpy(), res.boxes.conf.cpu().numpy(),
res.boxes.cls.cpu().numpy().astype(int)):
box = clip_bbox(b, frame.shape)
if box[2] - box[0] < 8 or box[3] - box[1] < 8:
continue
out.append(Detection(-1, "two_wheeler", "Two-wheeler", float(c), box,
{"rider_class": str(res.names[int(k)]), "rider_conf": float(c)}))
return out
def reset_tracker(self) -> None:
predictor = getattr(self.vehicle, "predictor", None)
if predictor is not None and getattr(predictor, "trackers", None):
for t in predictor.trackers:
t.reset()
# force a fresh tracker on next .track() call
if predictor is not None:
self.vehicle.predictor = None