move_detect/edge/detectors/immobility.py
유창욱 752aabaff1 fix(edge): forget per-track state on lost tracks (FIX 5)
fall._states, immobility._still_since/_fired, zone._inside_since/_fired,
and engine._last_emit were never pruned when a track was lost (ghost
already pruned via on_lost). On a 24/7 edge device this is unbounded
growth as track IDs keep incrementing.

Add forget(track_id) to FallDetector, ImmobilityWatchdog, and
ZoneIntrusionDetector (drops that track's per-track keys/sets).
EventEngine.forget(track_id) calls each sub-detector's forget and removes
_last_emit cooldown keys whose tuple's second element is that track_id
(covers FALL/NO_MOTION/IMMOBILITY/zone/GHOST — GHOST keys are
(GHOST, track_id) after FIX 4). EventEngine.process now calls
self.forget(tr.track_id) for every track in lost_tracks after emitting,
since ghost.on_lost already consumed that track's ghost-relevant state at
the top of process().

app.py run_once already calls pool.forget(tr.track_id) for lost tracks as
part of FIX 1, completing the cleanup chain (smoother pool + detector
state + dedup cache).

Tests: tests/test_engine.py adds test_forget_prunes_state_on_lost —
fires a FALL event, then passes the track as lost, and asserts
engine._last_emit no longer has that track's keys and fall._states no
longer has the track id.
2026-07-11 22:19:39 +09:00

49 lines
1.7 KiB
Python

from dataclasses import dataclass
from edge.tracking import Track
from edge.geometry import normalize
@dataclass
class ImmobilityConfig:
motion_thr: float = 0.02
immobile_s: float = 120.0
zone_immobile_s: float = 30.0
class ImmobilityWatchdog:
def __init__(self, cfg: ImmobilityConfig):
self.cfg = cfg
self._still_since: dict[int, float] = {}
self._fired: set[int] = set()
def forget(self, track_id: int) -> None:
self._still_since.pop(track_id, None)
self._fired.discard(track_id)
def _displacement(self, track: Track) -> float:
if len(track.frames) < 2:
return 1.0
a, b = track.frames[-2], track.frames[-1]
h = b.bbox.height or 1.0
d = sum(((p.x - q.x) ** 2 + (p.y - q.y) ** 2) ** 0.5
for p, q in zip(a.keypoints, b.keypoints)) / len(b.keypoints)
return normalize(d, h)
def update(self, track: Track, now: float, in_danger_zone: bool = False) -> tuple[bool, dict]:
tid = track.track_id
window = self.cfg.zone_immobile_s if in_danger_zone else self.cfg.immobile_s
if self._displacement(track) >= self.cfg.motion_thr:
self._still_since.pop(tid, None)
self._fired.discard(tid)
return False, {}
if tid not in self._still_since:
if len(track.frames) >= 2:
self._still_since[tid] = track.frames[-2].t
else:
self._still_since[tid] = now
start = self._still_since[tid]
if now - start >= window and tid not in self._fired:
self._fired.add(tid)
return True, {"immobility_s": round(now - start, 1)}
return False, {}