"""ScanSessionWorker — lightweight per-camera inference loop for the alerting "scan mode" (no HLS preview, low fps, ring buffer + rules). How it differs from ``CameraWorker``: - No HLS encoder, no pacer thread. Just **capture → infer → rules**. - Tick fps is intentionally low (default 1 fps via ``SCAN_TARGET_FPS``) — alerting cares about sustained or sudden changes, not smooth bbox refresh. 1 fps × 12 sessions = 12 inference calls / second total, comfortably under the shared Detector's CPU budget on the VPS pool. - Owns a ``FrameRingBuffer`` so a rule fire can attach the last N seconds of pre-event video to the alert. - Owns a ``RuleEngine``; the analyst configures rules at session start (preset + threshold knobs) and can edit them live via ``update_rules``. Frames in the ring buffer carry baked-in bboxes — the analyst opening a clip from an alert sees *what triggered*, not raw video. We resize to ``SCAN_OUTPUT_WIDTH×HEIGHT`` (default 640×360) before storing so 30 s of buffer per session × 12 sessions ≈ 250 MB rather than ~1 GB at 720p.""" from __future__ import annotations import logging import threading import time import uuid from datetime import datetime, timezone from pathlib import Path from typing import Optional import cv2 import numpy as np import supervision as sv from app.config import settings from app.services.alerts import Alert, AlertsDAO from app.services.detector import Detector from app.services.geo import coverage_polygon, project_bbox from app.services.ring_buffer import FrameRingBuffer from app.services.rule_engine import AlertFire, Rule, RuleEngine from app.services.scan_events import ScanEventBus from app.services.stream_reader import StreamReader log = logging.getLogger(__name__) class ScanSessionWorker: def __init__( self, session_id: str, camera_id: str, location: str, url: str, cam_lat: Optional[float], cam_lng: Optional[float], cam_heading_deg: Optional[float], cam_fov_deg: Optional[float], tenant_id: Optional[str], detector: Detector, rules: list[Rule], alerts_dao: Optional[AlertsDAO], event_bus: ScanEventBus, alerts_dir: Path, target_fps: float, ring_seconds: float, output_width: int, output_height: int, ): self.session_id = session_id self.camera_id = camera_id self.location = location self.url = url self.cam_lat = cam_lat self.cam_lng = cam_lng self.cam_heading_deg = cam_heading_deg self.cam_fov_deg = cam_fov_deg self.tenant_id = tenant_id # Coverage polygon is static for the session — heading/fov from # cctv_streams, fallback to GEO_* env. FE renders it as a wedge # on the map so the analyst sees what the camera "sees" without # needing the HLS preview. self.coverage_polygon = coverage_polygon( cam_lat=cam_lat, cam_lng=cam_lng, heading_deg=cam_heading_deg, fov_deg=cam_fov_deg, ) self.detector = detector self.alerts_dao = alerts_dao self.event_bus = event_bus self.alerts_dir = alerts_dir self.target_fps = max(0.1, float(target_fps)) self.ring_seconds = max(2.0, float(ring_seconds)) self.output_size = (int(output_width), int(output_height)) self.engine = RuleEngine(rules) self.ring = FrameRingBuffer( max_seconds=self.ring_seconds, # 1.25× headroom over target_fps so a small overshoot doesn't # trim the head of the requested window. fps_hint=self.target_fps * 1.25, ) # Single label-style annotator — no tracker IDs in scan mode, so # we render class name + confidence directly off the detection # arrays. Cheaper than instantiating BoxAnnotator / LabelAnnotator # for every frame. self._class_names = dict(detector.class_names) self.started_at = datetime.now(timezone.utc) self._running = False self._infer_thread: Optional[threading.Thread] = None self.reader: Optional[StreamReader] = None # Telemetry — exposed via /scan/sessions list endpoint. self.infer_count = 0 self.fire_count = 0 self.last_tick_at: Optional[float] = None self.last_vehicle = 0 self.last_person = 0 self._proc_fps_ema = 0.0 # ---------- lifecycle ---------- def start(self) -> None: if self._running: return self._running = True self.reader = StreamReader( camera_id=self.camera_id, url=self.url, reconnect_delay=settings.reconnect_delay, # Scan reader doesn't need the segment-pacing dance that # preview reader does — we only sample once per # 1/target_fps seconds and discard the rest. read_pace_fps=max(2.0, self.target_fps * 2.0), ) self.reader.start() self._infer_thread = threading.Thread( target=self._run_inference, daemon=True, name=f"scan-{self.session_id[:8]}", ) self._infer_thread.start() log.info( "[scan %s] started camera=%s target_fps=%.2f ring=%.0fs rules=%d", self.session_id, self.camera_id, self.target_fps, self.ring_seconds, len(self.engine.rules), ) def stop(self) -> None: self._running = False if self.reader is not None: self.reader.stop() log.info( "[scan %s] stopped (ticks=%d fires=%d)", self.session_id, self.infer_count, self.fire_count, ) @property def is_running(self) -> bool: return self._running # ---------- rule editing ---------- def update_rules(self, rules: list[Rule]) -> None: self.engine.update_rules(rules) log.info("[scan %s] rules updated → %d active", self.session_id, len(self.engine.rules)) # ---------- introspection ---------- def status(self) -> dict: # Rule progress uses the most recent tick timestamp so the # cooldown / sustained-progress numbers stay accurate even if # the analyst polls between ticks. ts_for_progress = self.last_tick_at or self.started_at.timestamp() return { "session_id": self.session_id, "camera_id": self.camera_id, "location": self.location, "started_at": self.started_at.isoformat(), "running": self._running, "connected": bool(self.reader and self.reader.connected), "infer_count": self.infer_count, "fire_count": self.fire_count, "last_tick_at": ( datetime.fromtimestamp(self.last_tick_at, tz=timezone.utc).isoformat() if self.last_tick_at else None ), "last_vehicle": self.last_vehicle, "last_person": self.last_person, "fps_process": round(self._proc_fps_ema, 2), "target_fps": self.target_fps, "ring_seconds": self.ring_seconds, "rules": [r.to_dict() for r in self.engine.rules], "rule_progress": self.engine.progress_snapshot(ts_for_progress), "coverage_polygon": self.coverage_polygon, "cam_lat": self.cam_lat, "cam_lng": self.cam_lng, "cam_heading_deg": self.cam_heading_deg, "cam_fov_deg": self.cam_fov_deg, } # ---------- inference loop ---------- def _run_inference(self) -> None: log.info("[scan %s] inference thread starting", self.session_id) period = 1.0 / self.target_fps last_seen_id = -1 last_infer_at = 0.0 tw, th = self.output_size while self._running: now = time.time() elapsed = now - last_infer_at if elapsed < period: time.sleep(period - elapsed) continue assert self.reader is not None frame, capture_ts = self.reader.read_with_ts() cur_id = self.reader.read_count if frame is None or cur_id == last_seen_id: time.sleep(0.05) continue last_seen_id = cur_id last_infer_at = time.time() # Mask HUD bands before inference — same rationale as # CameraWorker. Watermarks otherwise pollute counts. top_pct = settings.hud_mask_top_pct bot_pct = settings.hud_mask_bottom_pct if top_pct > 0 or bot_pct > 0: h = frame.shape[0] if top_pct > 0: frame[: int(h * top_pct), :] = 0 if bot_pct > 0: frame[-int(h * bot_pct):, :] = 0 try: t0 = time.time() detections = self.detector.infer(frame) dt = max(time.time() - t0, 1e-6) inst = 1.0 / dt self._proc_fps_ema = ( 0.2 * inst + 0.8 * self._proc_fps_ema if self._proc_fps_ema > 0 else inst ) vehicle, person = _count( detections, self.detector.vehicle_ids, self.detector.person_ids, ) # Down-size + annotate, push to ring. Stored frames carry # bboxes so an alert clip shows what triggered. annotated = self._annotate(frame, detections, tw, th) self.ring.append(annotated, capture_ts) self.infer_count += 1 self.last_tick_at = capture_ts self.last_vehicle = vehicle self.last_person = person # Push live tick payload so the FE can render scanned-object # icons on the map (analog to YOLO preview's yolo:metrics). # frame.shape is the *source* native pixel size — bbox coords # from the detector are in source space. src_h, src_w = frame.shape[:2] self._emit_tick( frame_w=src_w, frame_h=src_h, detections=detections, vehicle=vehicle, person=person, capture_ts=capture_ts, ) fires = self.engine.tick(capture_ts, vehicle, person) for fire in fires: self.fire_count += 1 # Snapshot the latest frame *before* the offload thread # mutates the ring — copy is cheap at 640×360. self._dispatch_fire(fire, annotated.copy()) except Exception as e: # noqa: BLE001 log.exception("[scan %s] tick error: %s", self.session_id, e) time.sleep(0.2) log.info("[scan %s] inference thread stopped", self.session_id) # ---------- live tick (icon push) ---------- def _emit_tick( self, frame_w: int, frame_h: int, detections: sv.Detections, vehicle: int, person: int, capture_ts: float, ) -> None: """Publish a ``scan.tick`` event with per-detection geo so the FE can render the same kind of object icons it shows for YOLO preview. Schema (shape kept compatible with ``yolo:metrics`` so the FE normaliser can mostly be shared):: { "type": "scan.tick", "session_id": ..., "camera_id": ..., "location": ..., "timestamp": ISO-8601, "frame_size": [w, h], "vehicle_count": int, "person_count": int, "detections": [ {"class": str, "class_id": int, "conf": float, "bbox": [x1,y1,x2,y2], "geo": {lat, lng, distance_m, ...}} ] } """ items: list[dict] = [] if detections is not None and len(detections) > 0: xyxy = detections.xyxy class_ids = ( detections.class_id if detections.class_id is not None else [None] * len(detections) ) confs = ( detections.confidence if detections.confidence is not None else [None] * len(detections) ) for i in range(len(detections)): cls_id = int(class_ids[i]) if class_ids[i] is not None else None conf = float(confs[i]) if confs[i] is not None else None x1, y1, x2, y2 = (float(v) for v in xyxy[i]) geo = project_bbox( bbox=(x1, y1, x2, y2), frame_w=frame_w, frame_h=frame_h, cam_lat=self.cam_lat, cam_lng=self.cam_lng, heading_deg=self.cam_heading_deg, fov_deg=self.cam_fov_deg, ) items.append({ "class": self._class_names.get(cls_id, "obj") if cls_id is not None else None, "class_id": cls_id, "conf": round(conf, 3) if conf is not None else None, "bbox": [round(x1, 1), round(y1, 1), round(x2, 1), round(y2, 1)], "geo": geo, }) self.event_bus.publish({ "type": "scan.tick", "session_id": self.session_id, "camera_id": self.camera_id, "location": self.location, "timestamp": datetime.fromtimestamp(capture_ts, tz=timezone.utc).isoformat(), "frame_size": [int(frame_w), int(frame_h)], "vehicle_count": int(vehicle), "person_count": int(person), "detections": items, }) # ---------- fire handling ---------- def _dispatch_fire(self, fire: AlertFire, snapshot_frame: np.ndarray) -> None: """Publish the alert immediately + schedule I/O off-thread. Two-phase: the WS push + DB insert happen now (analysts see the alert pop in <100 ms even on a busy session). Snapshot encode and MP4 mux land on disk a beat later, then the DB row's paths are patched.""" alert = Alert.new( camera_id=self.camera_id, location=self.location, rule_name=fire.rule.name, rule_kind=fire.rule.kind, rule_config=fire.rule.to_dict(), severity=fire.rule.severity, metrics=fire.metrics, tenant_id=self.tenant_id, cam_lat=self.cam_lat, cam_lng=self.cam_lng, session_id=self.session_id, ) # Insert immediately (paths null for now). if self.alerts_dao is not None: self.alerts_dao.insert(alert) # Push to WS subscribers. self.event_bus.publish({ "type": "alert.fired", "session_id": self.session_id, "camera_id": self.camera_id, "location": self.location, "alert": alert.to_dict(), }) # Offload I/O (snapshot + clip + DB UPDATE) to a daemon thread so # the inference loop never blocks on disk encode. threading.Thread( target=self._persist_artifacts, args=(alert, snapshot_frame), daemon=True, name=f"scan-fire-{alert.id[:8]}", ).start() def _persist_artifacts(self, alert: Alert, snapshot_frame: np.ndarray) -> None: """Write JPEG snapshot + MP4 clip + UPDATE row.""" day = alert.fired_at.strftime("%Y%m%d") out_dir = self.alerts_dir / day / self.camera_id snapshot_path: Optional[str] = None clip_path: Optional[str] = None jpeg = out_dir / f"{alert.id}.jpg" if self.ring.snapshot_jpeg(jpeg, frame=snapshot_frame): snapshot_path = str(jpeg) mp4 = out_dir / f"{alert.id}.mp4" if self.ring.encode_mp4(mp4, fps=self.target_fps): clip_path = str(mp4) if self.alerts_dao is not None: self.alerts_dao.update_paths(alert.id, snapshot_path, clip_path) # Re-broadcast a small update event so a long-lived analyst panel # can swap the placeholder with the real artifact URLs. self.event_bus.publish({ "type": "alert.artifacts_ready", "session_id": self.session_id, "camera_id": self.camera_id, "alert_id": alert.id, "snapshot_path": snapshot_path, "clip_path": clip_path, }) # ---------- annotation ---------- def _annotate( self, frame: np.ndarray, detections: sv.Detections, out_w: int, out_h: int, ) -> np.ndarray: """Resize to scan-output resolution and burn boxes + labels. Source bboxes are in capture coords; we scale during draw so they land on the resized canvas. Tracker IDs are absent in scan mode, so labels carry just class name + confidence.""" src_h, src_w = frame.shape[:2] if src_w != out_w or src_h != out_h: sized = cv2.resize(frame, (out_w, out_h), interpolation=cv2.INTER_LINEAR) sx, sy = out_w / src_w, out_h / src_h else: sized = frame.copy() sx = sy = 1.0 if detections is None or len(detections) == 0: return sized xyxy = detections.xyxy class_ids = detections.class_id confs = detections.confidence for i in range(len(detections)): cid = int(class_ids[i]) if class_ids is not None else -1 label_name = self._class_names.get(cid, "obj") conf = float(confs[i]) if confs is not None else 0.0 x1 = int(round(xyxy[i][0] * sx)) y1 = int(round(xyxy[i][1] * sy)) x2 = int(round(xyxy[i][2] * sx)) y2 = int(round(xyxy[i][3] * sy)) color = (0, 215, 255) # citrine — matches FE marker layer cv2.rectangle(sized, (x1, y1), (x2, y2), color, 2) text = f"{label_name} {conf:.2f}" (tw, th_), _ = cv2.getTextSize( text, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1, ) cv2.rectangle( sized, (x1, max(0, y1 - th_ - 4)), (x1 + tw + 4, y1), color, -1, ) cv2.putText( sized, text, (x1 + 2, max(th_, y1 - 2)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1, cv2.LINE_AA, ) return sized def _count( detections: sv.Detections, vehicle_ids: set[int], person_ids: set[int], ) -> tuple[int, int]: veh = 0 ppl = 0 if detections.class_id is not None: for cls in detections.class_id: c = int(cls) if c in person_ids: ppl += 1 elif c in vehicle_ids: veh += 1 return veh, ppl def new_session_id() -> str: return uuid.uuid4().hex