move_detect/edge/detectors/ghost.py
유창욱 9386dfc580 feat(delivery): install-path fixes + cafe24 package + delivery-audit hardening
Three intertwined bodies of work developed and tested together this session.
Full test suite green: python (edge) + phpunit (cloud).

## Edge/Pi install path
- setup_online.sh: apt-lock retry (apt-daily contention), Type=exec unit +
  StartLimitIntervalSec in [Unit], journalctl-on-failure, crash-loop detection.
- onnxruntime is now best-effort (no sdist / no 32-bit-ARM wheel); [6/8] probes the
  real backend and hard-fails if none works.
- Hailo HEF auto-fetch: edge/tools/fetch_hailo_hef.py (pinned sha256, refuses to guess
  8 vs 8L, HAILO_ARCH override for serial-less boards); hailo_pose.py run() timeout fix.
- install_offline.sh: mirrors the backend gate; onnxruntime optional.

## Cafe24 cloud package (cloud/deploy/)
- build_cafe24_package.sh emits move_detect_app/ (private, one folder) + www/move_detect/
  (docroot subdir); no-dev classmap autoloader; preflight.php; hardened .htaccess.
- Subdirectory mount support: Request::baseFrom/pathFor strip the mount prefix; index.php
  walks up to find the app root; views/JS prefix every URL with APP_BASE; session cookie
  scoped to the mount.

## Delivery audit — silent-failure & correctness (docs/delivery-audit.md)
All 4 blockers + all Phase-1 silent-failure + Phase-2 HIGH correctness:
- Edge cloud clients send a custom User-Agent (cafe24 WAF blocks python-requests) and
  allow_redirects=False.
- Daemon fails loud on blank CAFE24_URL/DEVICE_SECRET; run_loop logs swallowed exceptions;
  heartbeat carries real fps + per-camera health; UvcSource reopens a dead camera;
  offline queue is size-capped and drops poison rows; TARGET_FPS/QUEUE_DB validated.
- Zone coordinates normalized 0..1 on both sides (were canvas-px vs camera-px — every zone
  misplaced); pinch zones emit PINCH/HIGH (were downgraded to WARNING).
- Fall detection uses bbox cues when keypoints are low-confidence (occluded fallen person);
  ghost incident not cancelled by a bystander; displacement normalized per-second (FPS-invariant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 09:07:33 +09:00

55 lines
2.5 KiB
Python

from dataclasses import dataclass
from edge.tracking import Track
_DANGEROUS = {"FALLING", "FALLEN", "NO_MOTION"}
@dataclass
class GhostConfig:
reappear_s: float = 10.0
reappear_dist: float = 1.0 # bbox 높이 배수
class GhostIncidentDetector:
def __init__(self, cfg: GhostConfig):
self.cfg = cfg
self._states: dict[int, str] = {}
# 후보: track_id -> (spatial(x,y), last_state, height, lost_at)
self._candidates: dict[int, tuple] = {}
def note_state(self, track_id: int, state: str) -> None:
self._states[track_id] = state
def on_lost(self, lost_tracks: list[Track], now: float) -> None:
for tr in lost_tracks:
state = self._states.get(tr.track_id, "STANDING")
if state in _DANGEROUS:
b = tr.latest.bbox
# Snapshot the OTHER tracks active at loss time. Only a track that did NOT
# exist then can be the victim re-appearing (a re-acquired track gets a new
# id); a track already present is a bystander/colleague and must not cancel
# the incident by walking over the loss point.
bystanders = set(self._states) - {tr.track_id}
self._candidates[tr.track_id] = ((b.cx, b.cy), state, b.height, now, bystanders)
self._states.pop(tr.track_id, None)
def update(self, active_tracks: list[Track], now: float) -> list[dict]:
# 인근 재출현이면 후보 취소 — 단, 손실 시점에 없던 새 트랙만 (진짜 재출현).
for tid, (spatial, _state, height, _lost_at, bystanders) in list(self._candidates.items()):
for tr in active_tracks:
if tr.track_id in bystanders:
continue # a colleague who was already here — not the reappearing victim
b = tr.latest.bbox
dist = ((b.cx - spatial[0]) ** 2 + (b.cy - spatial[1]) ** 2) ** 0.5
if dist <= self.cfg.reappear_dist * (height or 1.0):
self._candidates.pop(tid, None)
break
# 대기 초과 방출
out = []
for tid, (spatial, state, _height, lost_at, _by) in list(self._candidates.items()):
if now - lost_at >= self.cfg.reappear_s:
out.append({"track_id": tid, "spatial": spatial, "last_state": state,
"waited_s": round(now - lost_at, 1)})
self._candidates.pop(tid, None)
return out