File size: 3,347 Bytes
40e0b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""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)