Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ and rejected.
### Testing and tuning

- Regression tests are behind the `regression` pytest marker and deselected by default; run them with `-m regression`. A shot whose footage is absent locally skips.
- Labels are per shot in `tests/labels/shots.yaml`. `expected_event` and `onset_window` are set together or not at all. Camera geometry lives in a named `CameraProfile`, with the pool zone as a polygon.
- Labels are per shot and mode in `tests/labels/shots.yaml`. Every label names its `mode`; each of its `expected_events` carries its own `onset_window`. Camera geometry lives in a named `CameraProfile`, with the pool zone as a polygon.
- Loosening `MAX_FRAGMENTATION` is a regression that must be argued for in review.
- `submersion_timeout_seconds` (12.0) is provisional and was fitted to clip lengths. Re-derive it on real footage before it ships.
- Run inference near native resolution: `imgsz=640` detects nothing on the 1080p backyard footage.
Expand Down
7 changes: 6 additions & 1 deletion PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@ Work happens in reviewable PRs against `main`.
`tracking.py`, `--track` on poolguard-replay (PR 5)
- [~] Rules engine v0: distress / submersion / entry over track histories
(thresholds in config). Submersion landed (`rules.py`, runs under
`--track`); distress and entry are not written
`--track`). Entry landed: armed, a track in the water raises
UNSUPERVISED_ENTRY once (1.3 s into `drowning-test.mp4`, armed).
Labels carry a `mode`; distress is not written
- **Open: no armed footage with an empty pool for longer than a
second.** Entry's false-alarm rate (shadow phantoms over the water,
people on the coping) is unmeasured until there is some
- **Resolved (provisional): submersion timeout 15 s → 12 s** so the POC
clip library can exercise the rule at all. Fitted to footage, not
derived from safety — must be re-derived on real P1 footage against
Expand Down
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@ Currently: **PD phase — no hardware, everything runs on a dev machine**
| Pose detection on video files | Works, via the replay CLI below |
| Tracking (persistent IDs, coasting through dropouts) | Works |
| Annotated replay video with HUD | Works |
| Regression suite over labeled footage | Tracker assertions run; event assertions wait on the rules engine |
| Regression suite over labeled footage | Tracker and event assertions run per shot and operating mode |
| ntfy push and heartbeat alert channels | Built and testable with `poolguard-alert-test`; not yet driven by a live pipeline |
| Rules engine (distress / submersion / entry) | **Not built — next** |
| Rules engine (distress / submersion / entry) | Submersion and entry work on replayed footage; distress not built |
| Siren, Home Assistant, call escalation | Not built |
| Live camera pipeline, Hailo backend | Not built; no hardware purchased |

So today the code can show you who it sees in a clip and for how long it has
lost them. It cannot yet decide that anyone is in trouble.
So today the code can replay a clip, track who it sees, and raise an event
when someone gets into the pool while armed or stays under too long. Nothing
yet acts on those events, and it has no notion of a struggling swimmer.

Where to read more:

Expand Down Expand Up @@ -142,8 +143,10 @@ running detection rate, and a meter filling toward the submersion timeout:
uv run poolguard-replay --video path/to/clip.mp4 --render out.mp4
```

Add `--labels tests/labels/shots.yaml` to show the expected event for that
clip on the HUD, when the manifest has an entry matching the file name.
Add `--labels tests/labels/shots.yaml` to show the expected events for that
clip on the HUD, when the manifest has an entry matching the file name. The
rules run in the label's mode, or pass `--mode armed|swim`: armed, anyone in
the water raises an entry; swim, only submersion is watched.

This is the primary debugging tool for tracker behavior — watch the ghost
box hold a person's identity through a splash or brief occlusion instead of
Expand Down
4 changes: 4 additions & 0 deletions docs/decision-log.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,7 @@ decisions with full context and alternatives are the ADRs in
- 2026-10-13: `adult-exits` now tracks 2 IDs for 3 people and fails `test_finds_everyone`. The hand-off did not lose anyone: with or without it, no frame of that clip has more than two people tracked, and the two IDs it merged were at the same spot (one person split in two). The test (`track IDs >= people`) passed before only because fragmentation made up for a person the detector never boxes. Left failing on purpose: it is the headcount check doing its job.
- 2026-10-13: Second camera profile, `backyard_simplisafe_remount`, for the angle after the camera went back up (first seen in `drowning-test.mp4`); the old clips keep `backyard_simplisafe`. Each shot already names its profile in `tests/labels/shots.yaml`, so no code changed. Traced from a median frame of that one clip with the cover half on: colour mask with a higher saturation floor than the first trace (bluish deck shadow leaked in at the old one), then the far edge corrected by hand where the piled-up cover sits above the waterline. The covered half counts as pool, since a person can end up under a cover. `drowning-test.mp4` is now labeled `submersion` with an onset window of 34 to 39 s.
- 2026-10-13: **A correct outline does not stop the jump-in false alarm.** Re-run on `drowning-test.mp4` with the new profile: still SUBMERSION at 13.5 s, 37.0 s and 37.0 s. Traced: track #1 is last seen at 1.4 s mid-entry, a tall standing box whose centre is over the water, so "in the water" is the right call. The swimmer is then under for about 2 s and surfaces as #2 about one box width away at 3.4 s. The fault is the tracker not linking #1 to #2. The containment pass cannot do it: the boxes do not overlap and the gap is twice its 1 s window.
- 2026-11-13: **Entry rule lands** (`rules.py`). While armed, a track in the pool zone raises one `UNSUPERVISED_ENTRY` at the emergency tier, on the first frame it is in the water, with the detection's timestamp as `started_at`. No confirmation delay: the PRD makes any armed entry an immediate emergency, tuning is sensitivity-biased, and there is no armed empty-pool footage to fit a delay against. A track that is already lost still raises (in_water reflects where it was last seen), so a person who falls in and goes straight under is not left to the 12 s submersion rule. Once per track while armed, even if it climbs out and back in, so a box centre jittering across the coping does not re-alert; leaving armed mode clears that memory, so re-arming with someone still in the water raises again. Submersion keeps running in armed mode. Known duplicate path: a person whose track fragments raises one entry per track ID; de-duplicating an incident is the alert manager's job.
- 2026-11-13: **Shot labels carry an operating mode, and a shot may list several expected events.** `ShotLabel.mode` is required (no default): people in the water are a swim session in one mode and an emergency in the other, and a silent default had been replaying every clip armed. `expected_event` + `onset_window` became `expected_events: [{event, onset_window}]`, since an armed replay of `drowning-test.mp4` correctly raises both an entry and a submersion and the old schema would have counted one as a false alarm. Each window still has to be ordered, at least 0.1 s wide and inside the shot. A file may be labeled once per mode; the regression harness runs detection and tracking once per file and the rules once per labeled mode, so a second mode costs no inference. `poolguard-replay` gains `--mode`, defaulting to the label's mode. All six backyard clips are swim sessions with people in the water from frame one, so they are labeled `swim`; armed they would raise an entry at t=0 and test nothing. `drowning-test.mp4` is the only clip that starts with an empty pool and is also labeled `armed`: entry in [0, 5] s, submersion in [34, 39] s.
- 2026-11-13: Measured, armed replay of `drowning-test.mp4`: entry at 1.3 s (the swimmer jumps at about 1.4 s; the standing box's centre is already over the water), submersion at 37.0 s, one track, nothing else. Regression suite on the six backyard clips: every event assertion passes in both modes; the only failure is the known `adult-exits` headcount miss (2026-10-13). **Not measured: entry's false-alarm rate.** No clip shows an empty pool armed for more than a second, so shadow phantoms over the water and people standing on the near coping (whose box centre projects over the water from this angle) are untested as entry triggers. An empty-pool clip is the next footage that matters for this rule.

108 changes: 58 additions & 50 deletions src/poolguard/labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import yaml
from pydantic import BaseModel, ConfigDict, Field, model_validator

from poolguard.events import EventType
from poolguard.events import EventType, OperatingMode
from poolguard.geometry import Polygon, validate_polygon

MIN_ONSET_WINDOW_SECONDS = 0.1
Expand Down Expand Up @@ -81,8 +81,38 @@ def crop_rect(self) -> tuple[float, float, float, float]:
return (x0, y0, x1 - x0, y1 - y0)


class ExpectedEvent(BaseModel):
"""One event a shot must raise, and when.

The window is part of the verdict: a verdict with no timing would pass even
if the rule fired 40 seconds late, which is not a save.
"""

model_config = ConfigDict(frozen=True)

event: EventType
onset_window: tuple[float, float] = Field(
description="Seconds from shot start within which the event must fire; a fire outside "
"this window is a failure even though the verdict is right",
)

@model_validator(mode="after")
def _window_is_ordered_and_plausible(self) -> "ExpectedEvent":
start, end = self.onset_window
if start < 0:
raise ValueError(f"onset_window start must be >= 0, got {start}")
if end <= start:
raise ValueError(f"onset_window must be ordered, got {self.onset_window}")
if end - start < MIN_ONSET_WINDOW_SECONDS:
raise ValueError(
f"onset_window is too narrow ({end - start:.3f}s); must be at least "
f"{MIN_ONSET_WINDOW_SECONDS}s to allow for human annotation error"
)
return self


class ShotLabel(BaseModel):
"""What a human asserts is true about one continuous shot."""
"""What a human asserts is true about one continuous shot in one operating mode."""

model_config = ConfigDict(frozen=True)

Expand All @@ -94,58 +124,29 @@ class ShotLabel(BaseModel):
description="Distinct humans visible in the shot; the tracker should converge to this "
"many track IDs, so track_count > people is fragmentation",
)
mode: OperatingMode = Field(
description="Mode the shot is replayed in. Required: people in the water are a swim "
"session in one mode and an emergency in the other",
)
camera: str | None = Field(
default=None,
description="Name of a profile in the manifest's `cameras` block. None for footage "
"with no known geometry — the scraped clips, where every shot is a different mount",
)
expected_event: EventType | None = Field(
default=None,
description="Event the rules engine must raise, or None if the shot must stay quiet",
)
onset_window: tuple[float, float] | None = Field(
default=None,
description="Seconds from shot start within which the event must fire; a fire outside "
"this window is a failure even though the verdict is right",
expected_events: tuple[ExpectedEvent, ...] = Field(
default=(),
description="Every event the rules engine must raise; empty if the shot must stay quiet",
)
notes: str = ""

@model_validator(mode="after")
def _window_is_ordered_and_in_bounds(self) -> "ShotLabel":
if self.onset_window is None:
return self
start, end = self.onset_window
if start < 0:
raise ValueError(f"{self.shot}: onset_window start must be >= 0, got {start}")
if end <= start:
raise ValueError(f"{self.shot}: onset_window must be ordered, got {self.onset_window}")
if end > self.duration_seconds:
raise ValueError(
f"{self.shot}: onset_window end ({end}) exceeds "
f"duration_seconds ({self.duration_seconds})"
)
return self

@model_validator(mode="after")
def _event_and_window_agree(self) -> "ShotLabel":
"""Require both fields or neither: a verdict is not a label until it is timed."""
if self.expected_event is None and self.onset_window is not None:
raise ValueError(
f"{self.shot}: onset_window is set but expected_event is None; "
"must either set both or neither"
)
if self.expected_event is not None and self.onset_window is None:
raise ValueError(
f"{self.shot}: expected_event is set but onset_window is None; "
"must either set both or neither"
)
if self.onset_window is not None:
start, end = self.onset_window
if end - start < MIN_ONSET_WINDOW_SECONDS:
def _windows_end_inside_the_shot(self) -> "ShotLabel":
for expected in self.expected_events:
end = expected.onset_window[1]
if end > self.duration_seconds:
raise ValueError(
f"{self.shot}: onset_window is too narrow ({end - start:.3f}s); "
f"must be at least {MIN_ONSET_WINDOW_SECONDS}s to allow for "
"human annotation error"
f"{self.shot}: {expected.event.value} onset_window end ({end}) exceeds "
f"duration_seconds ({self.duration_seconds})"
)
return self

Expand Down Expand Up @@ -178,20 +179,27 @@ def camera_for(self, shot: ShotLabel) -> CameraProfile | None:
return self.cameras.get(shot.camera) if shot.camera is not None else None

@model_validator(mode="after")
def _shot_names_are_unique(self) -> "ShotLabels":
names = [shot.shot for shot in self.shots]
duplicates = {name for name in names if names.count(name) > 1}
def _one_label_per_shot_and_mode(self) -> "ShotLabels":
keys = [(shot.shot, shot.mode.value) for shot in self.shots]
duplicates = {key for key in keys if keys.count(key) > 1}
if duplicates:
raise ValueError(f"duplicate shot names in manifest: {sorted(duplicates)}")
raise ValueError(f"duplicate (shot, mode) labels in manifest: {sorted(duplicates)}")
return self

def label_for(self, shot_name: str, mode: OperatingMode) -> ShotLabel | None:
"""The label for this file in this mode, or None if it has none."""
for shot in self.shots:
if shot.shot == shot_name and shot.mode is mode:
return shot
return None

def positives(self) -> tuple[ShotLabel, ...]:
"""Shots where an event must fire."""
return tuple(shot for shot in self.shots if shot.expected_event is not None)
return tuple(shot for shot in self.shots if shot.expected_events)

def negatives(self) -> tuple[ShotLabel, ...]:
"""Shots that must stay quiet — the false-alarm budget."""
return tuple(shot for shot in self.shots if shot.expected_event is None)
return tuple(shot for shot in self.shots if not shot.expected_events)


def load_shot_labels(path: Path) -> ShotLabels:
Expand Down
10 changes: 6 additions & 4 deletions src/poolguard/replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field

from poolguard.config import RulesSettings, TrackingSettings
from poolguard.events import Detection, SafetyEvent, TrackedPerson
from poolguard.events import Detection, OperatingMode, SafetyEvent, TrackedPerson
from poolguard.rules import RulesState, evaluate
from poolguard.tracking import TrackerState, advance
from poolguard.vision.frames import FrameSource
Expand Down Expand Up @@ -67,20 +67,22 @@ def run_tracked_replay(
estimator: PoseEstimator,
settings: TrackingSettings,
rules: RulesSettings | None = None,
mode: OperatingMode | None = None,
) -> Iterator[TrackedFrameResult]:
"""run_replay with the tracking and rules stages folded in.

The frame timestamp is the clock for both stages, so replay behaves
identically at any processing speed — coasting timers and rule timeouts
measure video time, not wall-clock time. The operating mode is the
rules settings' default_mode.
measure video time, not wall-clock time. The operating mode is `mode`,
or the rules settings' default_mode when it is not given.
"""
rules = rules or RulesSettings()
mode = mode or rules.default_mode
tracker_state = TrackerState()
rules_state = RulesState()
for result in run_replay(source, estimator):
tracker_state, people = advance(tracker_state, result.detections, result.ts, settings)
rules_state, events = evaluate(rules_state, people, result.ts, rules.default_mode, rules)
rules_state, events = evaluate(rules_state, people, result.ts, mode, rules)
yield TrackedFrameResult(
frame_index=result.frame_index,
ts=result.ts,
Expand Down
Loading
Loading