Spaces:
Runtime error
Runtime error
Download app/services/rule_engine.py from openscopelabs/cctv-object-detection: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/openscopelabs/cctv-object-detection/resolve/main/app/services/rule_engine.py
- Command line
-
hf download hf://spaces/openscopelabs/cctv-object-detection/app/services/rule_engine.py
-
curl -L -o rule_engine.py https://huggingface.co/spaces/openscopelabs/cctv-object-detection/resolve/main/app/services/rule_engine.py
17.3 kB
| """Rule engine for scan-mode alerting. | |
| Each scan session owns its own ``RuleEngine`` instance. On every | |
| inference tick the session calls ``engine.tick(ts, vehicle, person)`` | |
| which returns a (possibly empty) list of fires. | |
| Rule kinds shipped at v1: | |
| - **sustained_count** — fires when the target count stays at or above | |
| ``threshold`` for ``sustained_seconds`` of contiguous ticks. Used by | |
| the "Kemacetan" (kendaraan) and "Keramaian" (orang) presets. | |
| - **sudden_drop** — fires when the target count crashes by ``drop_pct`` | |
| (default 50 %) from a recent baseline of at least ``threshold``. Used | |
| as a (very rough) accident proxy: cars stop and either pile up or | |
| bystanders block the lane → count of detected vehicles plummets while | |
| the previous tick was still busy. Real crash detection needs a | |
| dedicated model; this just surfaces "something dramatic just changed." | |
| Time is wall-clock seconds (float) so the engine is independent of | |
| inference cadence — a rule with ``sustained_seconds=60`` fires after | |
| 60 wall seconds whether the session ticks at 1 fps or 5 fps.""" | |
| from __future__ import annotations | |
| import logging | |
| from collections import deque | |
| from dataclasses import dataclass, field | |
| from typing import Any, Optional | |
| log = logging.getLogger(__name__) | |
| RuleKind = str # "sustained_count" | "sudden_drop" | |
| RuleTarget = str # "vehicle" | "person" | "any" | |
| class Rule: | |
| name: str | |
| kind: RuleKind | |
| target: RuleTarget | |
| threshold: int | |
| cooldown_seconds: float = 60.0 | |
| severity: str = "info" | |
| # sustained_count knobs | |
| sustained_seconds: float = 30.0 | |
| # sudden_drop knobs | |
| window_seconds: float = 5.0 | |
| baseline_seconds: float = 5.0 | |
| drop_pct: float = 0.5 | |
| def to_dict(self) -> dict[str, Any]: | |
| return { | |
| "name": self.name, | |
| "kind": self.kind, | |
| "target": self.target, | |
| "threshold": self.threshold, | |
| "cooldown_seconds": self.cooldown_seconds, | |
| "severity": self.severity, | |
| "sustained_seconds": self.sustained_seconds, | |
| "window_seconds": self.window_seconds, | |
| "baseline_seconds": self.baseline_seconds, | |
| "drop_pct": self.drop_pct, | |
| } | |
| def from_dict(cls, d: dict[str, Any]) -> "Rule": | |
| return cls( | |
| name=str(d["name"]), | |
| kind=str(d.get("kind", "sustained_count")), | |
| target=str(d.get("target", "vehicle")), | |
| threshold=int(d.get("threshold", 10)), | |
| cooldown_seconds=float(d.get("cooldown_seconds", 60.0)), | |
| severity=str(d.get("severity", "info")), | |
| sustained_seconds=float(d.get("sustained_seconds", 30.0)), | |
| window_seconds=float(d.get("window_seconds", 5.0)), | |
| baseline_seconds=float(d.get("baseline_seconds", 5.0)), | |
| drop_pct=float(d.get("drop_pct", 0.5)), | |
| ) | |
| class AlertFire: | |
| rule: Rule | |
| fired_at: float | |
| metrics: dict[str, Any] | |
| # History entry — kept small; engine prunes by oldest ts past needed window. | |
| class _Sample: | |
| ts: float | |
| vehicle: int | |
| person: int | |
| def _count_for(sample: _Sample, target: RuleTarget) -> int: | |
| if target == "vehicle": | |
| return sample.vehicle | |
| if target == "person": | |
| return sample.person | |
| return sample.vehicle + sample.person | |
| class RuleEngine: | |
| def __init__(self, rules: list[Rule], history_capacity: int = 1024): | |
| self.rules: list[Rule] = list(rules) | |
| # Per-rule last fired ts (monotonic-style float, same domain as | |
| # the caller's ``ts`` argument). Zero = never fired. | |
| self._last_fired: dict[str, float] = {r.name: 0.0 for r in self.rules} | |
| # Rolling sample history, oldest → newest. Cap at history_capacity | |
| # so a misconfigured rule with a 1-hour window doesn't blow memory. | |
| self._history: deque[_Sample] = deque(maxlen=history_capacity) | |
| # ---------- public ---------- | |
| def update_rules(self, rules: list[Rule]) -> None: | |
| """Replace the active rule set. Cooldowns are preserved for | |
| rules whose name survives — by-name match, by design (analyst | |
| nudging a threshold shouldn't reset the cooldown).""" | |
| carry = {r.name: self._last_fired.get(r.name, 0.0) for r in rules} | |
| self.rules = list(rules) | |
| self._last_fired = carry | |
| def tick(self, ts: float, vehicle: int, person: int) -> list[AlertFire]: | |
| self._history.append(_Sample(ts=ts, vehicle=vehicle, person=person)) | |
| self._prune(ts) | |
| fires: list[AlertFire] = [] | |
| for rule in self.rules: | |
| # Cooldown gate. Each rule has its own clock. | |
| last = self._last_fired.get(rule.name, 0.0) | |
| if last > 0 and (ts - last) < rule.cooldown_seconds: | |
| continue | |
| fire = self._evaluate(rule, ts) | |
| if fire is not None: | |
| self._last_fired[rule.name] = ts | |
| fires.append(fire) | |
| return fires | |
| # ---------- progress (for FE probability bar) ---------- | |
| def progress_snapshot(self, ts: float) -> list[dict[str, Any]]: | |
| """Per-rule "probability of firing" snapshot for the FE. | |
| Each entry is a small dict: | |
| - ``name`` / ``kind`` / ``target`` / ``severity`` | |
| - ``progress`` — 0.0 → 1.0 (1.0 = fires now if cooldown clear) | |
| - ``current`` — current target count (latest sample) | |
| - ``threshold`` — copied from rule for FE display | |
| - ``cooldown_left`` — seconds remaining in cooldown (0 if ready) | |
| - kind-specific extras (sustained_progress, drop_ratio, …) | |
| The shape mirrors what an analyst wants to *eyeball*: how close | |
| the rule is to triggering right now. | |
| """ | |
| if not self._history: | |
| return [self._idle_progress(rule) for rule in self.rules] | |
| latest = self._history[-1] | |
| snapshots: list[dict[str, Any]] = [] | |
| for rule in self.rules: | |
| cooldown_left = self._cooldown_left(rule, ts) | |
| base = { | |
| "name": rule.name, | |
| "kind": rule.kind, | |
| "target": rule.target, | |
| "severity": rule.severity, | |
| "threshold": rule.threshold, | |
| "current": _count_for(latest, rule.target), | |
| "cooldown_left": round(cooldown_left, 1), | |
| } | |
| if rule.kind == "sustained_count": | |
| base.update(self._progress_sustained(rule, ts, latest)) | |
| elif rule.kind == "sudden_drop": | |
| base.update(self._progress_drop(rule, ts, latest)) | |
| else: | |
| base["progress"] = 0.0 | |
| snapshots.append(base) | |
| return snapshots | |
| def _idle_progress(self, rule: Rule) -> dict[str, Any]: | |
| return { | |
| "name": rule.name, | |
| "kind": rule.kind, | |
| "target": rule.target, | |
| "severity": rule.severity, | |
| "threshold": rule.threshold, | |
| "current": 0, | |
| "cooldown_left": 0.0, | |
| "progress": 0.0, | |
| } | |
| def _cooldown_left(self, rule: Rule, ts: float) -> float: | |
| last = self._last_fired.get(rule.name, 0.0) | |
| if last <= 0: | |
| return 0.0 | |
| remaining = rule.cooldown_seconds - (ts - last) | |
| return max(0.0, remaining) | |
| def _progress_sustained( | |
| self, rule: Rule, ts: float, latest: _Sample, | |
| ) -> dict[str, Any]: | |
| # Two factors blended into a single 0-1 progress: | |
| # - count_ratio: current / threshold (capped at 1) | |
| # - sustained_ratio: how much of the window has held at/above threshold | |
| # Geometric mean rewards "both factors high"; a brief spike to 2× | |
| # threshold without sustain doesn't peg the meter on its own. | |
| count = _count_for(latest, rule.target) | |
| count_ratio = min(1.0, count / max(1, rule.threshold)) | |
| lo = ts - rule.sustained_seconds | |
| window = [s for s in self._history if s.ts >= lo] | |
| if window: | |
| above = [s for s in window if _count_for(s, rule.target) >= rule.threshold] | |
| if above: | |
| span = above[-1].ts - above[0].ts | |
| sustained_ratio = min(1.0, span / max(0.1, rule.sustained_seconds)) | |
| else: | |
| sustained_ratio = 0.0 | |
| else: | |
| sustained_ratio = 0.0 | |
| progress = round((count_ratio * sustained_ratio) ** 0.5, 3) | |
| return { | |
| "progress": progress, | |
| "count_ratio": round(count_ratio, 3), | |
| "sustained_ratio": round(sustained_ratio, 3), | |
| "sustained_seconds": rule.sustained_seconds, | |
| } | |
| def _progress_drop( | |
| self, rule: Rule, ts: float, latest: _Sample, | |
| ) -> dict[str, Any]: | |
| baseline_lo = ts - rule.window_seconds - rule.baseline_seconds | |
| baseline_hi = ts - rule.window_seconds | |
| recent_lo = ts - rule.window_seconds | |
| baseline_window = [ | |
| s for s in self._history if baseline_lo <= s.ts < baseline_hi | |
| ] | |
| recent_window = [s for s in self._history if s.ts >= recent_lo] | |
| if not baseline_window or not recent_window: | |
| return { | |
| "progress": 0.0, | |
| "drop_ratio": 0.0, | |
| "baseline": 0, | |
| "recent": _count_for(latest, rule.target), | |
| } | |
| baseline = max(_count_for(s, rule.target) for s in baseline_window) | |
| recent_max = max(_count_for(s, rule.target) for s in recent_window) | |
| if baseline <= 0: | |
| drop_ratio = 0.0 | |
| else: | |
| drop_ratio = max(0.0, min(1.0, 1.0 - recent_max / baseline)) | |
| if baseline < rule.threshold: | |
| # Not enough activity in the baseline window for the rule | |
| # to be meaningful; floor progress to 0 so the meter isn't | |
| # alarming when nothing is happening. | |
| progress = 0.0 | |
| else: | |
| # Need both: enough drop AND a meaningful baseline. | |
| ratio_progress = drop_ratio / max(0.01, rule.drop_pct) | |
| progress = min(1.0, ratio_progress) | |
| return { | |
| "progress": round(progress, 3), | |
| "drop_ratio": round(drop_ratio, 3), | |
| "baseline": int(baseline), | |
| "recent": int(recent_max), | |
| } | |
| # ---------- internals ---------- | |
| def _prune(self, ts: float) -> None: | |
| needed = 0.0 | |
| for r in self.rules: | |
| if r.kind == "sustained_count": | |
| needed = max(needed, r.sustained_seconds) | |
| elif r.kind == "sudden_drop": | |
| needed = max(needed, r.window_seconds + r.baseline_seconds) | |
| # Add a small slop so the window evaluator has its lower bound. | |
| cutoff = ts - (needed + 5.0) | |
| while self._history and self._history[0].ts < cutoff: | |
| self._history.popleft() | |
| def _evaluate(self, rule: Rule, ts: float) -> Optional[AlertFire]: | |
| if rule.kind == "sustained_count": | |
| return self._eval_sustained(rule, ts) | |
| if rule.kind == "sudden_drop": | |
| return self._eval_drop(rule, ts) | |
| log.warning("unknown rule kind: %s (%s)", rule.kind, rule.name) | |
| return None | |
| def _eval_sustained(self, rule: Rule, ts: float) -> Optional[AlertFire]: | |
| lo = ts - rule.sustained_seconds | |
| window = [s for s in self._history if s.ts >= lo] | |
| if not window: | |
| return None | |
| # Require the window to actually span ``sustained_seconds`` so a | |
| # cold-start session doesn't fire on the first frame. | |
| if (window[-1].ts - window[0].ts) < rule.sustained_seconds * 0.9: | |
| return None | |
| counts = [_count_for(s, rule.target) for s in window] | |
| if min(counts) < rule.threshold: | |
| return None | |
| return AlertFire( | |
| rule=rule, | |
| fired_at=ts, | |
| metrics={ | |
| "trigger": "sustained_count", | |
| "target": rule.target, | |
| "threshold": rule.threshold, | |
| "sustained_seconds": rule.sustained_seconds, | |
| "min_in_window": int(min(counts)), | |
| "max_in_window": int(max(counts)), | |
| "avg_in_window": round(sum(counts) / len(counts), 2), | |
| "samples": len(counts), | |
| "last_vehicle": window[-1].vehicle, | |
| "last_person": window[-1].person, | |
| }, | |
| ) | |
| def _eval_drop(self, rule: Rule, ts: float) -> Optional[AlertFire]: | |
| baseline_lo = ts - rule.window_seconds - rule.baseline_seconds | |
| baseline_hi = ts - rule.window_seconds | |
| recent_lo = ts - rule.window_seconds | |
| baseline_window = [ | |
| s for s in self._history if baseline_lo <= s.ts < baseline_hi | |
| ] | |
| recent_window = [s for s in self._history if s.ts >= recent_lo] | |
| if not baseline_window or not recent_window: | |
| return None | |
| baseline = max(_count_for(s, rule.target) for s in baseline_window) | |
| if baseline < rule.threshold: | |
| return None | |
| recent_max = max(_count_for(s, rule.target) for s in recent_window) | |
| if baseline <= 0: | |
| return None | |
| ratio = recent_max / baseline | |
| if ratio > (1.0 - rule.drop_pct): | |
| return None | |
| return AlertFire( | |
| rule=rule, | |
| fired_at=ts, | |
| metrics={ | |
| "trigger": "sudden_drop", | |
| "target": rule.target, | |
| "threshold": rule.threshold, | |
| "baseline_count": int(baseline), | |
| "recent_count": int(recent_max), | |
| "drop_pct": round(1.0 - ratio, 3), | |
| "window_seconds": rule.window_seconds, | |
| "baseline_seconds": rule.baseline_seconds, | |
| "last_vehicle": recent_window[-1].vehicle, | |
| "last_person": recent_window[-1].person, | |
| }, | |
| ) | |
| # ---------- shipped presets ---------- | |
| # Threshold + window tuning sengaja di-baca dari env (lihat app/config.py) | |
| # supaya operator bisa geser ambang per kota tanpa redeploy. Diakses via | |
| # property ``PRESETS`` yang rebuild dari ``settings`` setiap call — biar | |
| # perubahan env (mis. via container restart) langsung ke-pick-up tanpa | |
| # perlu reload modul. | |
| # `kecelakaan` (sudden_drop) dihapus — terlalu eksperimental untuk | |
| # production: drop count vehicle bisa jadi karena banyak hal selain | |
| # kecelakaan (frame loss, occlusion, kamera buram). Real crash detection | |
| # butuh model dedicated. Bisa di-revisit nanti. | |
| def _build_presets() -> dict[str, Rule]: | |
| # Import dalam fungsi untuk menghindari circular import; rule_engine | |
| # tidak butuh ``settings`` saat module load (Detector/etc bisa dipakai | |
| # standalone untuk smoke test). | |
| # | |
| # Preset keys ("kemacetan", "keramaian") sengaja Indonesian — itu | |
| # user-facing slug yang FE pakai; tuning knob-nya di settings pakai | |
| # English (scan_traffic_jam_*, scan_crowd_*). | |
| from app.config import settings | |
| return { | |
| "kemacetan": Rule( | |
| name="Kemacetan", | |
| kind="sustained_count", | |
| target="vehicle", | |
| threshold=settings.scan_traffic_jam_threshold, | |
| sustained_seconds=settings.scan_traffic_jam_sustained_seconds, | |
| cooldown_seconds=settings.scan_traffic_jam_cooldown_seconds, | |
| severity="warning", | |
| ), | |
| "keramaian": Rule( | |
| name="Keramaian", | |
| kind="sustained_count", | |
| target="person", | |
| threshold=settings.scan_crowd_threshold, | |
| sustained_seconds=settings.scan_crowd_sustained_seconds, | |
| cooldown_seconds=settings.scan_crowd_cooldown_seconds, | |
| severity="warning", | |
| ), | |
| } | |
| class _PresetsProxy: | |
| """Dict-like view yang rebuild snapshot dari env setiap akses. | |
| Memungkinkan ``PRESETS["kemacetan"]`` dan ``PRESETS.values()`` tetap | |
| bekerja seperti dict biasa (route ``/scan/presets`` + ``routes_scan | |
| .start_scan`` fallback) tanpa perlu refactor caller-nya.""" | |
| def _snap(self) -> dict[str, Rule]: | |
| return _build_presets() | |
| def __getitem__(self, key: str) -> Rule: | |
| return self._snap()[key] | |
| def __contains__(self, key: object) -> bool: | |
| return key in self._snap() | |
| def __iter__(self): | |
| return iter(self._snap()) | |
| def __len__(self) -> int: | |
| return len(self._snap()) | |
| def keys(self): | |
| return self._snap().keys() | |
| def values(self): | |
| return self._snap().values() | |
| def items(self): | |
| return self._snap().items() | |
| def get(self, key: str, default: Optional[Rule] = None) -> Optional[Rule]: | |
| return self._snap().get(key, default) | |
| PRESETS = _PresetsProxy() | |
| def preset(name: str) -> Optional[Rule]: | |
| p = PRESETS.get(name.lower().strip()) | |
| if p is None: | |
| return None | |
| # Return a copy so the global preset isn't mutated by per-CCTV edits. | |
| return Rule(**{k: getattr(p, k) for k in p.__slots__}) | |