Spaces:
Sleeping
Sleeping
Download core/detection_engine.py from Abhyuday-06/VisionGuard-AI: direct link, hf CLI and curl.
- Browser
- Download file 28.3 kB
-
https://huggingface.co/spaces/Abhyuday-06/VisionGuard-AI/resolve/main/core/detection_engine.py
- Command line
-
hf download hf://spaces/Abhyuday-06/VisionGuard-AI/core/detection_engine.py
-
curl -L -o detection_engine.py https://huggingface.co/spaces/Abhyuday-06/VisionGuard-AI/resolve/main/core/detection_engine.py
28.3 kB
| """ | |
| Traffic violation engine: turns frames into tracked vehicles, rider/occupant | |
| evidence, rule hits and consolidated per-vehicle incidents. | |
| engine = TrafficEnforcementEngine(EngineConfig()) | |
| engine.reset(scene, fps=25) | |
| for frame in video: | |
| out = engine.process_frame(frame) # FrameOutput | |
| for incident in out.finalized: save(incident) | |
| for incident in engine.finalize_all(): save(incident) | |
| out = engine.process_image(image, scene) # single photo | |
| Appearance violations (helmet, triple riding, seatbelt) work on single images. | |
| Motion violations need video: wrong-side (direction over ~1.5 s), red light / | |
| stop line (crossing event; images get a static "past the line on red" check) | |
| and illegal parking (dwell time, seconds). | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import time | |
| from dataclasses import dataclass, field | |
| from typing import Any, Callable | |
| import cv2 | |
| import numpy as np | |
| from core.geometry import BBox, bbox_bottom_center, expand_bbox | |
| from core.models import CATEGORY_DISPLAY, Detection, YoloModels | |
| from core.rules import ( | |
| HELMET, | |
| PARKING, | |
| RED_LIGHT, | |
| SEATBELT, | |
| STOP_LINE, | |
| TRIPLE, | |
| WRONG_SIDE, | |
| ParkingRule, | |
| RuleHit, | |
| SignalFilter, | |
| StopLineRule, | |
| TemporalVote, | |
| TrackHistory, | |
| WrongSideRule, | |
| assign_heads, | |
| classify_traffic_light, | |
| nms_heads, | |
| rider_zone, | |
| ) | |
| from core.scene import SceneConfig | |
| from core.visualize import VIOLATION_COLORS, draw_frame, draw_scene, highlight | |
| from utils.preprocessing import preprocess_frame | |
| LOGGER = logging.getLogger(__name__) | |
| class EngineConfig: | |
| vehicle_model: str = "models/uvh26_yolo11s.pt" | |
| helmet_model: str = "models/helmet_best.pt" | |
| seatbelt_model: str = "models/seatbelt_best.pt" | |
| plate_model: str = "models/lp_best.pt" | |
| coco_model: str = "yolov8s.pt" | |
| device: Any = None | |
| vehicle_conf: float = 0.30 | |
| vehicle_imgsz: int = 960 | |
| helmet_conf: float = 0.35 # detector threshold for heads | |
| no_helmet_conf: float = 0.50 # a NoHelmet head must reach this to count | |
| helmet_imgsz: int = 640 | |
| min_two_wheeler_px: int = 48 # smaller bikes: rider heads are unreadable | |
| seatbelt_conf: float = 0.50 | |
| min_car_width_px: int = 110 # smaller cars: windshield unreadable | |
| triple_min_riders: int = 3 | |
| plate_conf: float = 0.30 | |
| ocr_conf: float = 0.45 | |
| read_all_plates: bool = False # OCR every vehicle, not only violators | |
| plate_max_reads: int = 10 # per track | |
| preprocessing: str = "auto" | |
| enabled: tuple[str, ...] = (HELMET, TRIPLE, SEATBELT, WRONG_SIDE, STOP_LINE, RED_LIGHT, PARKING) | |
| traffic_light_every_s: float = 0.4 | |
| incident_ttl_s: float = 2.0 | |
| min_votes: int = 2 # appearance violations in video need >= this many positive frames | |
| photo_fallback: bool = True # photos: also run COCO detector for ground-level / close-up vehicles | |
| rider_model: str = "models/riders_best.pt" # photos: two-wheeler+riders detector/classifier | |
| rider_det_conf: float = 0.25 # rider-model boxes below this are ignored | |
| # rider-model thresholds, chosen on the valid split (tools/evaluate.py --violations reports both splits) | |
| rider_no_helmet_conf: float = 0.40 # rider model "WithoutHelmet" at/above this flags No Helmet | |
| rider_triple_conf: float = 0.40 # rider model "TripleRiding" at/above this flags Triple Riding | |
| rider_evidence: str = "both" # photos: "heads", "rider_model" or "both" (either source can flag) | |
| class ViolationEvidence: | |
| violation: str | |
| confidence: float | |
| reason: str | |
| timestamp: float | |
| frame_index: int | |
| metadata: dict[str, Any] = field(default_factory=dict) | |
| snapshot: np.ndarray | None = field(default=None, repr=False) # annotated full frame | |
| class Incident: | |
| track_id: int | |
| category: str | |
| label: str | |
| first_t: float | |
| last_t: float | |
| violations: dict[str, ViolationEvidence] = field(default_factory=dict) | |
| vehicle_crop: np.ndarray | None = field(default=None, repr=False) | |
| plate_text: str = "MANUAL_REVIEW" | |
| plate_confidence: float = 0.0 | |
| plate_crop: np.ndarray | None = field(default=None, repr=False) | |
| plate_reads: int = 0 | |
| bbox: tuple[int, int, int, int] = (0, 0, 0, 0) | |
| def summary(self) -> dict[str, Any]: | |
| return { | |
| "track_id": self.track_id, | |
| "vehicle": CATEGORY_DISPLAY.get(self.category, self.category), | |
| "vehicle_class": self.label, | |
| "plate": self.plate_text, | |
| "plate_confidence": round(self.plate_confidence, 3), | |
| "bbox": [int(v) for v in self.bbox], | |
| "violations": [ | |
| {"type": v.violation, "confidence": round(v.confidence, 3), "reason": v.reason, | |
| "time_s": round(v.timestamp, 2)} | |
| for v in self.violations.values() | |
| ], | |
| } | |
| class FrameOutput: | |
| frame_index: int | |
| timestamp: float | |
| annotated: np.ndarray | |
| detections: list[Detection] | |
| signal: str | |
| new_violations: list[dict[str, Any]] | |
| active_incidents: list[dict[str, Any]] | |
| finalized: list[Incident] | |
| timings_ms: dict[str, float] | |
| counts: dict[str, int] | |
| debug: dict[str, Any] = field(default_factory=dict) | |
| class TrafficEnforcementEngine: | |
| def __init__(self, config: EngineConfig | None = None, models: Any = None, | |
| plate_reader: Callable[[np.ndarray], Any] | None | str = "default") -> None: | |
| """ | |
| models: object exposing vehicles/heads/seatbelt_check/traffic_lights (YoloModels by default; | |
| tests inject fakes). | |
| plate_reader: callable(vehicle_crop) -> core.ocr_engine.OCRResult; "default" uses the YOLO | |
| plate detector + OCR; None disables plate reading. | |
| """ | |
| self.config = config or EngineConfig() | |
| c = self.config | |
| self.models = models or YoloModels(c.vehicle_model, c.helmet_model, c.seatbelt_model, c.coco_model, | |
| device=c.device, rider_model=c.rider_model) | |
| if plate_reader == "default": | |
| from core.ocr_engine import read_vehicle_license_plate | |
| def plate_reader(crop: np.ndarray): | |
| return read_vehicle_license_plate(crop, c.plate_model, c.plate_conf, c.ocr_conf, device=c.device) | |
| self.plate_reader = plate_reader | |
| self.scene = SceneConfig() | |
| self.reset(self.scene) | |
| # ------------------------------------------------------------------ | |
| # State | |
| # ------------------------------------------------------------------ | |
| def reset(self, scene: SceneConfig | None = None, fps: float = 25.0, frame_shape: tuple[int, ...] | None = None) -> None: | |
| if scene is not None: | |
| self.scene = scene | |
| self.fps = fps or 25.0 | |
| self.frame_index = 0 | |
| self.history = TrackHistory() | |
| self.signal_filter = SignalFilter() | |
| self.votes = TemporalVote(min_hits=self.config.min_votes) | |
| self.incidents: dict[int, Incident] = {} | |
| self.voters: dict[int, Any] = {} | |
| self.plate_reads: dict[int, int] = {} | |
| self.track_meta: dict[int, Detection] = {} | |
| self._rules_shape: tuple[int, int] | None = None | |
| self._last_light_t = -1e9 | |
| self._light_box: BBox | None = None | |
| self._light_raw = "UNKNOWN" | |
| if hasattr(self.models, "reset_tracker"): | |
| self.models.reset_tracker() | |
| if frame_shape is not None: | |
| self._build_rules(frame_shape) | |
| def _build_rules(self, shape: tuple[int, ...]) -> None: | |
| self._rules_shape = tuple(shape[:2]) | |
| self.lanes = self.scene.build_lanes(shape) | |
| self.stop_line = self.scene.build_stop_line(shape) | |
| self.parking_zones = self.scene.build_parking_zones(shape) | |
| self.wrong_side = WrongSideRule(self.lanes) | |
| self.stop_rule = StopLineRule(self.stop_line) if self.stop_line is not None else None | |
| self.parking = ParkingRule(self.parking_zones, dwell_s=self.scene.parking_dwell_s) | |
| # ------------------------------------------------------------------ | |
| # Signal | |
| # ------------------------------------------------------------------ | |
| def _signal_state(self, frame: np.ndarray, t: float, debug: dict[str, Any]) -> str: | |
| mode = (self.scene.signal_mode or "auto").upper() | |
| if mode in {"RED", "YELLOW", "GREEN"}: | |
| return mode | |
| roi = self.scene.traffic_light_box(frame.shape) | |
| if roi is not None: | |
| x1, y1, x2, y2 = roi | |
| state, ratios = classify_traffic_light(frame[y1:y2, x1:x2]) | |
| self._light_box = roi | |
| debug["signal_ratios"] = ratios | |
| return self.signal_filter.update(state) | |
| needs_signal = self.stop_rule is not None and (STOP_LINE in self.config.enabled or RED_LIGHT in self.config.enabled) | |
| if not needs_signal: | |
| return "UNKNOWN" | |
| if t - self._last_light_t >= self.config.traffic_light_every_s: | |
| self._last_light_t = t | |
| lights = self.models.traffic_lights(frame) | |
| best_state, best_score = "UNKNOWN", 0.0 | |
| for box, conf in lights: | |
| x1, y1, x2, y2 = box | |
| state, ratios = classify_traffic_light(frame[y1:y2, x1:x2]) | |
| score = conf * (x2 - x1) * (y2 - y1) | |
| if state != "UNKNOWN" and score > best_score: | |
| best_state, best_score, self._light_box = state, score, box | |
| self._light_raw = best_state | |
| debug["traffic_lights"] = [{"bbox": list(b), "conf": round(c, 3)} for b, c in lights] | |
| return self.signal_filter.update(self._light_raw) | |
| # ------------------------------------------------------------------ | |
| # Plates | |
| # ------------------------------------------------------------------ | |
| def _read_plate(self, raw: np.ndarray, det: Detection) -> None: | |
| if self.plate_reader is None: | |
| return | |
| from core.ocr_engine import PlateVoter | |
| tid = det.track_id | |
| if self.plate_reads.get(tid, 0) >= self.config.plate_max_reads: | |
| return | |
| box = expand_bbox(det.bbox, 0.04, 0.04, 0.04, 0.06, raw.shape) | |
| crop = raw[box[1]:box[3], box[0]:box[2]] | |
| if crop.size == 0 or min(crop.shape[:2]) < 24: | |
| return | |
| self.plate_reads[tid] = self.plate_reads.get(tid, 0) + 1 | |
| try: | |
| result = self.plate_reader(crop) | |
| except Exception as exc: # pragma: no cover | |
| LOGGER.warning("plate read failed: %s", exc) | |
| return | |
| if not result.plate_detected: | |
| return | |
| voter = self.voters.setdefault(tid, PlateVoter()) | |
| voter.add(result) | |
| def _plate_for(self, tid: int) -> tuple[str, float, np.ndarray | None, int]: | |
| voter = self.voters.get(tid) | |
| if voter is None or len(voter) == 0: | |
| return "MANUAL_REVIEW", 0.0, None, 0 | |
| reading = voter.result(self.config.ocr_conf) | |
| return reading.text, reading.confidence, voter.best_crop, len(voter) | |
| # ------------------------------------------------------------------ | |
| # Incidents | |
| # ------------------------------------------------------------------ | |
| def _record(self, hit: RuleHit, det: Detection, raw: np.ndarray, t: float, | |
| snapshot_base: np.ndarray, new_events: list[dict[str, Any]]) -> None: | |
| if hit.violation not in self.config.enabled: | |
| return | |
| inc = self.incidents.get(det.track_id) | |
| if inc is None: | |
| inc = Incident(det.track_id, det.category, det.label, t, t, bbox=det.bbox) | |
| self.incidents[det.track_id] = inc | |
| if hit.violation in inc.violations: | |
| return | |
| # Red-light jump supersedes the stop-line event for the same vehicle | |
| if hit.violation == RED_LIGHT: | |
| inc.violations.pop(STOP_LINE, None) | |
| if hit.violation == STOP_LINE and RED_LIGHT in inc.violations: | |
| return | |
| snap = highlight(snapshot_base, det.bbox, hit.violation.upper(), VIOLATION_COLORS.get(hit.violation, (0, 0, 255))) | |
| inc.violations[hit.violation] = ViolationEvidence(hit.violation, hit.confidence, hit.reason, t, | |
| self.frame_index, hit.metadata, _shrink(snap, 1600)) | |
| self._update_crop(inc, raw, det) | |
| new_events.append({"track_id": det.track_id, "type": hit.violation, "confidence": round(hit.confidence, 3), | |
| "reason": hit.reason, "time_s": round(t, 2), "vehicle": CATEGORY_DISPLAY.get(det.category), | |
| "bbox": list(det.bbox)}) | |
| def _update_crop(inc: Incident, raw: np.ndarray, det: Detection) -> None: | |
| box = expand_bbox(det.bbox, 0.1, 0.1, 0.1, 0.1, raw.shape) | |
| crop = raw[box[1]:box[3], box[0]:box[2]] | |
| if crop.size and (inc.vehicle_crop is None or crop.size > inc.vehicle_crop.size): | |
| inc.vehicle_crop = crop.copy() | |
| def _finalize(self, tid: int) -> Incident | None: | |
| inc = self.incidents.pop(tid, None) | |
| if inc is None: | |
| return None | |
| inc.plate_text, inc.plate_confidence, inc.plate_crop, inc.plate_reads = self._plate_for(tid) | |
| return inc if inc.violations else None | |
| def finalize_all(self) -> list[Incident]: | |
| out = [self._finalize(tid) for tid in list(self.incidents)] | |
| return [i for i in out if i is not None] | |
| # ------------------------------------------------------------------ | |
| # Main entry points | |
| # ------------------------------------------------------------------ | |
| def process_image(self, image: np.ndarray, scene: SceneConfig | None = None, debug: bool = False) -> tuple[FrameOutput, list[Incident]]: | |
| self.reset(scene or self.scene, frame_shape=image.shape) | |
| out = self.process_frame(image, timestamp=0.0, debug=debug, video=False) | |
| return out, self.finalize_all() | |
| def process_frame(self, frame: np.ndarray, timestamp: float | None = None, debug: bool = False, | |
| video: bool = True) -> FrameOutput: | |
| if frame is None or frame.ndim != 3 or frame.shape[2] != 3: | |
| raise ValueError("frame must be a BGR image (H, W, 3)") | |
| timings: dict[str, float] = {} | |
| tick = time.perf_counter() | |
| c = self.config | |
| self.frame_index += 1 | |
| t = float(timestamp) if timestamp is not None else (self.frame_index - 1) / self.fps | |
| if self._rules_shape != tuple(frame.shape[:2]): | |
| self._build_rules(frame.shape) | |
| dbg: dict[str, Any] = {} | |
| raw = frame | |
| proc = preprocess_frame(frame, c.preprocessing) # type: ignore[arg-type] | |
| timings["preprocess"] = _ms(tick) | |
| # 1) vehicles | |
| tick = time.perf_counter() | |
| dets = self.models.vehicles(proc, track=video, conf=c.vehicle_conf, imgsz=c.vehicle_imgsz) | |
| if not video and c.rider_evidence != "heads" and hasattr(self.models, "rider_units"): | |
| dets = merge_detections(dets, self.models.rider_units(proc, conf=c.rider_det_conf), | |
| prefer_fallback_two_wheeler=True) | |
| if not video and c.photo_fallback and hasattr(self.models, "coco_vehicles"): | |
| dets = merge_detections(dets, self.models.coco_vehicles(proc)) | |
| if not video: | |
| for i, d in enumerate(dets): | |
| d.track_id = i + 1 | |
| else: | |
| dets = [d for d in dets if d.track_id >= 0] # untracked boxes cannot carry temporal evidence | |
| for d in dets: | |
| self.history.update(d.track_id, d.bbox, t) | |
| self.track_meta[d.track_id] = d | |
| timings["vehicles"] = _ms(tick) | |
| # 2) signal | |
| tick = time.perf_counter() | |
| signal = self._signal_state(proc, t, dbg) | |
| timings["signal"] = _ms(tick) | |
| hits: list[tuple[RuleHit, Detection]] = [] | |
| heads_by_track: dict[int, list[Any]] = {} | |
| extra: dict[int, str] = {} | |
| # 3) two-wheeler riders | |
| tick = time.perf_counter() | |
| bikes = [d for d in dets if d.category == "two_wheeler" and (d.bbox[3] - d.bbox[1]) >= c.min_two_wheeler_px] | |
| if bikes and (HELMET in c.enabled or TRIPLE in c.enabled): | |
| regions = [_union(rider_zone(d.bbox), d.bbox) for d in bikes] | |
| heads = nms_heads(self.models.heads(proc, regions, conf=c.helmet_conf, imgsz=c.helmet_imgsz)) | |
| assigned = assign_heads([(d.track_id, d.bbox) for d in bikes], heads) | |
| use_heads = video or c.rider_evidence != "rider_model" | |
| for d in bikes: | |
| hs = assigned.get(d.track_id, []) | |
| heads_by_track[d.track_id] = hs | |
| no_helmet = [h for h in hs if not h.helmet and h.confidence >= c.no_helmet_conf] | |
| riders = len(hs) | |
| extra[d.track_id] = f"riders:{riders}" + (f" no-helmet:{len(no_helmet)}" if no_helmet else "") | |
| # rider-model verdict for this bike (photos only) | |
| rclass, rconf = d.attributes.get("rider_class"), float(d.attributes.get("rider_conf", 0.0)) | |
| if video or c.rider_evidence == "heads": | |
| rclass = None | |
| r_no_helmet = rclass == "WithoutHelmet" and rconf >= c.rider_no_helmet_conf | |
| r_triple = rclass == "TripleRiding" and rconf >= c.rider_triple_conf | |
| if rclass: | |
| extra[d.track_id] += f" model:{rclass}" | |
| h_conf = max(h.confidence for h in no_helmet) if (no_helmet and use_heads) else None | |
| conf = max(filter(None, [h_conf, rconf if r_no_helmet else None]), default=None) | |
| if hs or rclass: | |
| reasons = [] | |
| if h_conf is not None: | |
| reasons.append(f"{len(no_helmet)} of {riders} rider(s) without helmet") | |
| if r_no_helmet: | |
| reasons.append(f"rider classifier: no helmet ({rconf:.2f})") | |
| hit = self._appearance(d.track_id, HELMET, conf, video, "; ".join(reasons) or "no helmet", | |
| {"riders": riders, "no_helmet": len(no_helmet), | |
| "rider_class": rclass, "rider_conf": round(rconf, 3)}) | |
| if hit: | |
| hits.append((hit, d)) | |
| h_tconf = float(np.mean([h.confidence for h in hs])) \ | |
| if (use_heads and riders >= c.triple_min_riders) else None | |
| tconf = max(filter(None, [h_tconf, rconf if r_triple else None]), default=None) | |
| reasons = [] | |
| if h_tconf is not None: | |
| reasons.append(f"{riders} riders on one two-wheeler") | |
| if r_triple: | |
| reasons.append(f"rider classifier: triple riding ({rconf:.2f})") | |
| hit = self._appearance(d.track_id, TRIPLE, tconf, video, "; ".join(reasons) or "triple riding", | |
| {"riders": riders, "rider_class": rclass, "rider_conf": round(rconf, 3)}) | |
| if hit: | |
| hits.append((hit, d)) | |
| if debug: | |
| dbg["heads"] = [{"bbox": list(h.bbox), "helmet": h.helmet, "conf": round(h.confidence, 3)} for h in heads] | |
| dbg["rider_regions"] = [list(r) for r in regions] | |
| timings["helmet"] = _ms(tick) | |
| # 4) seatbelt | |
| tick = time.perf_counter() | |
| cars = [d for d in dets if d.category == "car" and (d.bbox[2] - d.bbox[0]) >= c.min_car_width_px] | |
| if cars and SEATBELT in c.enabled: | |
| observations = self.models.seatbelt_check(proc, [d.bbox for d in cars], conf=0.25) | |
| for d, obs in zip(cars, observations): | |
| if not obs.observable: | |
| continue | |
| conf = obs.no_seatbelt_conf if (obs.no_seatbelt_conf or 0) >= c.seatbelt_conf else None | |
| hit = self._appearance(d.track_id, SEATBELT, conf, video, "Occupant without seatbelt", | |
| {"detections": [(n, round(s, 3)) for n, s, _ in obs.boxes]}) | |
| if hit: | |
| hits.append((hit, d)) | |
| if debug: | |
| dbg.setdefault("seatbelt", []).append({"track_id": d.track_id, "observable": obs.observable, | |
| "no_seatbelt_conf": obs.no_seatbelt_conf, | |
| "boxes": [(n, round(s, 3), list(b)) for n, s, b in obs.boxes]}) | |
| timings["seatbelt"] = _ms(tick) | |
| # 5) motion / geometry rules | |
| tick = time.perf_counter() | |
| movers = [d for d in dets if d.category != "bicycle"] | |
| if video: | |
| if WRONG_SIDE in c.enabled: | |
| for d in movers: | |
| hit = self.wrong_side.update(d.track_id, d.bbox, self.history) | |
| if hit: | |
| hits.append((hit, d)) | |
| if self.stop_rule is not None: | |
| for d in movers: | |
| for hit in self.stop_rule.update(d.track_id, d.bbox, signal): | |
| hits.append((hit, d)) | |
| if PARKING in c.enabled and self.parking_zones: | |
| by_id = {d.track_id: d for d in movers} | |
| for hit in self.parking.update([(d.track_id, d.bbox) for d in movers], t): | |
| if hit.track_id in by_id: | |
| hits.append((hit, by_id[hit.track_id])) | |
| for d in movers: | |
| dwell = self.parking.dwell(d.track_id, t) | |
| if dwell >= 1.0: | |
| extra[d.track_id] = (extra.get(d.track_id, "") + f" parked:{dwell:.0f}s").strip() | |
| elif self.stop_rule is not None: | |
| for d in movers: | |
| hit = self.stop_rule.evaluate_static(d.track_id, d.bbox, signal, frame.shape[0]) | |
| if hit: | |
| hits.append((hit, d)) | |
| timings["rules"] = _ms(tick) | |
| # 6) annotate + incidents | |
| tick = time.perf_counter() | |
| new_events: list[dict[str, Any]] = [] | |
| base = proc.copy() | |
| draw_scene(base, self.lanes, self.stop_line, self.parking_zones, signal, self._light_box) | |
| for hit, det in hits: | |
| self._record(hit, det, raw, t, base, new_events) | |
| for d in dets: | |
| if d.track_id in self.incidents: | |
| inc = self.incidents[d.track_id] | |
| inc.last_t = t | |
| inc.bbox = d.bbox | |
| self._update_crop(inc, raw, d) | |
| violations_by_track = {tid: list(inc.violations) for tid, inc in self.incidents.items()} | |
| plates = {} | |
| for tid in violations_by_track: | |
| text, conf, _, n = self._plate_for(tid) | |
| if n: | |
| plates[tid] = text if text != "MANUAL_REVIEW" else "plate?" | |
| annotated = draw_frame(base, dets, violations_by_track, heads_by_track, signal, extra, plates) | |
| timings["annotate"] = _ms(tick) | |
| # 7) plates (violators, or everyone) | |
| tick = time.perf_counter() | |
| for d in dets: | |
| if d.track_id in self.incidents or c.read_all_plates: | |
| self._read_plate(raw, d) | |
| timings["plates"] = _ms(tick) | |
| # 8) finalize incidents whose vehicle left | |
| finalized: list[Incident] = [] | |
| if video: | |
| seen_ids = {d.track_id for d in dets} | |
| for tid, inc in list(self.incidents.items()): | |
| if tid not in seen_ids and t - inc.last_t > c.incident_ttl_s: | |
| done = self._finalize(tid) | |
| if done: | |
| finalized.append(done) | |
| for tid in self.history.prune(t, max_age_s=max(3.0, c.incident_ttl_s + 1)): | |
| self.wrong_side.forget(tid) | |
| if self.stop_rule is not None: | |
| self.stop_rule.forget(tid) | |
| self.votes.forget(tid) | |
| self.voters.pop(tid, None) if tid not in self.incidents else None | |
| self.plate_reads.pop(tid, None) if tid not in self.incidents else None | |
| counts: dict[str, int] = {} | |
| for d in dets: | |
| counts[d.category] = counts.get(d.category, 0) + 1 | |
| if debug: | |
| dbg["detections"] = [{"track_id": d.track_id, "category": d.category, "label": d.label, | |
| "conf": round(d.confidence, 3), "bbox": list(d.bbox), | |
| **({"wrong_side": self.wrong_side.last_debug.get(d.track_id)} if video else {})} | |
| for d in dets] | |
| dbg["signal"] = signal | |
| dbg["preprocessed"] = proc is not raw | |
| return FrameOutput( | |
| frame_index=self.frame_index, | |
| timestamp=t, | |
| annotated=annotated, | |
| detections=dets, | |
| signal=signal, | |
| new_violations=new_events, | |
| active_incidents=[inc.summary() for inc in self.incidents.values()], | |
| finalized=finalized, | |
| timings_ms=timings, | |
| counts=counts, | |
| debug=dbg, | |
| ) | |
| # ------------------------------------------------------------------ | |
| def _appearance(self, tid: int, violation: str, positive_conf: float | None, video: bool, | |
| reason: str, metadata: dict[str, Any]) -> RuleHit | None: | |
| if violation not in self.config.enabled: | |
| return None | |
| if not video: | |
| if positive_conf is None: | |
| return None | |
| return RuleHit(tid, violation, float(positive_conf), reason, metadata) | |
| hit = self.votes.add(tid, violation, positive_conf) | |
| if hit is not None: | |
| hit.reason = f"{reason} ({hit.reason.lower()})" | |
| hit.metadata.update(metadata) | |
| return hit | |
| def merge_detections(primary: list[Detection], fallback: list[Detection], iou_thr: float = 0.45, | |
| prefer_fallback_two_wheeler: bool = False) -> list[Detection]: | |
| """ | |
| Merge CCTV-model detections with photo-mode fallback detections (COCO or rider model). | |
| * fallback boxes that match nothing are added (close-up / ground-level vehicles); | |
| * a confident fallback two-wheeler overlapping a primary non-two-wheeler box re-labels it | |
| (the CCTV model sometimes calls a close-up motorbike a truck); | |
| * a fallback two-wheeler matching a primary two-wheeler passes on its attributes; with | |
| ``prefer_fallback_two_wheeler`` it also replaces the box (the rider model's box always | |
| includes the riders, which the head search depends on); | |
| * everything else keeps the primary detection. | |
| """ | |
| from core.geometry import bbox_iou, containment | |
| merged = list(primary) | |
| for f in fallback: | |
| best, best_iou = None, 0.0 | |
| for p in merged: | |
| iou = bbox_iou(f.bbox, p.bbox) | |
| if iou > best_iou: | |
| best, best_iou = p, iou | |
| two = f.category == "two_wheeler" | |
| if best is not None and best.category == "two_wheeler" and two and best_iou >= 0.3: | |
| if f.attributes and not best.attributes: | |
| best.attributes = dict(f.attributes) | |
| if prefer_fallback_two_wheeler: | |
| best.bbox = f.bbox | |
| continue | |
| if best is not None and best_iou >= iou_thr: | |
| if two and best.category != "two_wheeler" and f.confidence >= 0.5: | |
| best.category, best.label, best.bbox = f.category, "Two-wheeler", f.bbox | |
| best.attributes = dict(f.attributes) | |
| continue | |
| if any(containment(f.bbox, p.bbox) > 0.7 or containment(p.bbox, f.bbox) > 0.7 for p in merged): | |
| continue | |
| merged.append(Detection(-1, f.category, f.label, f.confidence, f.bbox, dict(f.attributes))) | |
| return merged | |
| def _ms(start: float) -> float: | |
| return round((time.perf_counter() - start) * 1000.0, 1) | |
| def _union(a: BBox, b: BBox) -> BBox: | |
| return min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]) | |
| def _shrink(img: np.ndarray, max_w: int) -> np.ndarray: | |
| if img.shape[1] <= max_w: | |
| return img | |
| s = max_w / img.shape[1] | |
| return cv2.resize(img, (max_w, int(img.shape[0] * s)), interpolation=cv2.INTER_AREA) | |