"""Per-camera analytics: vehicle/person counts + traffic/crowd status for the latest tick. History lives in ``cctv_session_metrics`` (running aggregates), not in memory.""" from __future__ import annotations import threading import time from dataclasses import asdict, dataclass from typing import Optional import supervision as sv from app.config import settings GREEN = (0, 200, 0) YELLOW = (0, 215, 255) RED = (0, 0, 220) def traffic_status(n: int) -> tuple[str, tuple[int, int, int]]: if n < settings.traffic_smooth_max: return "SMOOTH", GREEN if n < settings.traffic_moderate_max: return "MODERATE", YELLOW return "HEAVY", RED def crowd_status(n: int) -> tuple[str, tuple[int, int, int]]: if n < settings.crowd_normal_max: return "NORMAL", GREEN if n < settings.crowd_busy_max: return "BUSY", YELLOW return "OVERCROWDED", RED @dataclass class Snapshot: camera_id: str location: str timestamp: float vehicle_count: int person_count: int traffic_status: str crowd_status: str fps_capture: float fps_process: float connected: bool def to_dict(self) -> dict: return asdict(self) class AnalyticsEngine: """Maintains the latest snapshot per camera. No history buffer — historical aggregates live in the persistent session table.""" def __init__( self, vehicle_ids: Optional[set[int]] = None, person_ids: Optional[set[int]] = None, ): self._latest: dict[str, Snapshot] = {} self._lock = threading.Lock() # Resolved at boot by Detector. Defaults cover the COCO mapping # so tests that construct AnalyticsEngine directly still work. self.vehicle_ids: set[int] = set(vehicle_ids) if vehicle_ids else {2, 3, 5, 7} self.person_ids: set[int] = set(person_ids) if person_ids else {0} def update( self, camera_id: str, location: str, detections: sv.Detections, fps_capture: float, fps_process: float, connected: bool, ) -> Snapshot: veh = 0 ppl = 0 if detections.class_id is not None: for cls in detections.class_id: c = int(cls) if c in self.person_ids: ppl += 1 elif c in self.vehicle_ids: veh += 1 snap = Snapshot( camera_id=camera_id, location=location, timestamp=time.time(), vehicle_count=veh, person_count=ppl, traffic_status=traffic_status(veh)[0], crowd_status=crowd_status(ppl)[0], fps_capture=round(fps_capture, 2), fps_process=round(fps_process, 2), connected=connected, ) with self._lock: self._latest[camera_id] = snap return snap def get_latest(self, camera_id: str) -> Optional[Snapshot]: with self._lock: return self._latest.get(camera_id) def all_latest(self) -> dict[str, Snapshot]: with self._lock: return dict(self._latest) def clear(self, camera_id: str) -> None: """Drop the latest snapshot for one camera. Called on disconnect.""" with self._lock: self._latest.pop(camera_id, None)