feat(rep): implement deterministic exercise rep segmentation
Browse filesFiles changed (2)
- src/pozify/steps/rep_counter.py+213-20
- tests/test_rep_counter.pyAdded+150
123456789101112131415161718192021222324252627282930from __future__ import annotationsfrom pozify.contracts import ExerciseClassification, PoseSequence, Rep, Repsdef run(classification: ExerciseClassification, sequence: PoseSequence) -> Reps:fps = 30.0reps: list[Rep] = []for idx in range(5):start_frame = 30 + idx * 60mid_frame = start_frame + 30end_frame = start_frame + 60reps.append(Rep(rep_id=idx + 1,start_frame=start_frame,mid_frame=mid_frame,end_frame=end_frame,start_sec=round(start_frame / fps, 2),mid_sec=round(mid_frame / fps, 2),end_sec=round(end_frame / fps, 2),))return Reps(exercise=classification.exercise,reps=reps,partial_reps=[] if sequence.pose_valid_ratio > 0.8 else [{"reason": "low_pose_valid_ratio"}],)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223from __future__ import annotationsfrom dataclasses import asdictfrom typing import Anyfrom pozify.contracts import ExerciseClassification, PoseSequence, Rep, Repsfrom pozify.steps.rep_signals import (SignalSample,angle_deg,average_axis,body_line_score,normalize_optional,samples_from_values,smooth_signal,)from pozify.steps.rep_state_machine import RepSegment, find_local_extrema, segment_low_high_lowMIN_CYCLE_FRAMES = 12MIN_PHASE_FRAMES = 4MIN_USABLE_SIGNAL_SAMPLES = 9MIN_SIGNAL_RANGE = 0.22def _mean_optional(values: list[float | None]) -> float | None:usable = [value for value in values if value is not None]if not usable:return Nonereturn sum(usable) / len(usable)def _combine(primary: list[float | None], secondary: list[float | None], *, weight: float) -> list[float | None]:normalized_secondary = normalize_optional(secondary)combined: list[float | None] = []for primary_value, secondary_value in zip(primary, normalized_secondary, strict=False):if primary_value is None:combined.append(None)continueif secondary_value is None:combined.append(primary_value)continuecombined.append(primary_value + secondary_value * weight)return combineddef _primary_signal_for_exercise(sequence: PoseSequence, exercise: str) -> tuple[list[SignalSample], dict[str, Any]]:hip_y = [average_axis(frame, ("left_hip", "right_hip"), "y") for frame in sequence.frames]shoulder_y = [average_axis(frame, ("left_shoulder", "right_shoulder"), "y") for frame in sequence.frames]wrist_y = [average_axis(frame, ("left_wrist", "right_wrist"), "y") for frame in sequence.frames]knee_bend = [_mean_optional([None if angle is None else max(0.0, 180.0 - angle)for angle in (angle_deg(frame, "left_hip", "left_knee", "left_ankle"),angle_deg(frame, "right_hip", "right_knee", "right_ankle"),)])for frame in sequence.frames]elbow_bend = [_mean_optional([None if angle is None else max(0.0, 180.0 - angle)for angle in (angle_deg(frame, "left_shoulder", "left_elbow", "left_wrist"),angle_deg(frame, "right_shoulder", "right_elbow", "right_wrist"),)])for frame in sequence.frames]body_line = [body_line_score(frame) for frame in sequence.frames]if exercise == "squat":raw_signal = _combine(hip_y, knee_bend, weight=0.35)selected_signal = "hip_y_plus_knee_bend"elif exercise == "shoulder_press":inverted_wrist = [None if value is None else -value for value in wrist_y]raw_signal = _combine(inverted_wrist, [None if value is None else -value for value in elbow_bend], weight=0.2)selected_signal = "negative_wrist_y_plus_elbow_extension_proxy"else:chest_proxy = [_mean_optional([shoulder_value, hip_value])for shoulder_value, hip_value in zip(shoulder_y, hip_y, strict=False)]raw_signal = _combine(chest_proxy, elbow_bend, weight=0.25)selected_signal = "chest_y_plus_elbow_bend"smoothed_signal = smooth_signal(raw_signal)normalized_signal = normalize_optional(smoothed_signal)samples = samples_from_values(sequence, normalized_signal)return samples, {"selected_signal": selected_signal,"raw_signal_range": (round(max((value for value in normalized_signal if value is not None), default=0.0)- min((value for value in normalized_signal if value is not None), default=0.0), 4)),"usable_signal_samples": len(samples),"body_line_mean": round(_mean_optional(body_line) or 0.0, 4),}def _segments_to_reps(segments: list[RepSegment]) -> list[Rep]:return [Rep(rep_id=index + 1,start_frame=segment.start.frame_index,mid_frame=segment.middle.frame_index,end_frame=segment.end.frame_index,start_sec=round(segment.start.timestamp_sec, 3),mid_sec=round(segment.middle.timestamp_sec, 3),end_sec=round(segment.end.timestamp_sec, 3),)for index, segment in enumerate(segments)]def _partial_reps(sequence: PoseSequence,segments: list[RepSegment],samples: list[SignalSample],*,signal_range: float,) -> list[dict[str, Any]]:if not samples:return [{"reason": "low_signal_quality"}]partials: list[dict[str, Any]] = []if not segments:if signal_range >= MIN_SIGNAL_RANGE * 0.7:partials.append({"reason": "insufficient_rom","start_frame": samples[0].frame_index,"end_frame": samples[-1].frame_index,"start_sec": round(samples[0].timestamp_sec, 3),"end_sec": round(samples[-1].timestamp_sec, 3),})return partialsfirst_segment = segments[0]if first_segment.start.frame_index - samples[0].frame_index >= MIN_PHASE_FRAMES:partials.append({"reason": "starts_mid_rep","start_frame": samples[0].frame_index,"end_frame": first_segment.start.frame_index,"start_sec": round(samples[0].timestamp_sec, 3),"end_sec": round(first_segment.start.timestamp_sec, 3),})last_segment = segments[-1]if samples[-1].frame_index - last_segment.end.frame_index >= MIN_PHASE_FRAMES:partials.append({"reason": "ends_mid_rep","start_frame": last_segment.end.frame_index,"end_frame": samples[-1].frame_index,"start_sec": round(last_segment.end.timestamp_sec, 3),"end_sec": round(samples[-1].timestamp_sec, 3),})return partialsdef run(classification: ExerciseClassification, sequence: PoseSequence) -> tuple[Reps, dict[str, Any]]:if classification.exercise == "unknown":reps = Reps(exercise=classification.exercise, reps=[], partial_reps=[{"reason": "unknown_exercise"}])return reps, {"selected_signal": "none", "thresholds": {}, "extrema": [], "accepted_reps": []}samples, debug = _primary_signal_for_exercise(sequence, classification.exercise)signal_range = debug["raw_signal_range"]extrema = find_local_extrema(samples)segments = (segment_low_high_low(extrema,min_cycle_frames=MIN_CYCLE_FRAMES,min_phase_frames=MIN_PHASE_FRAMES,min_amplitude=max(MIN_SIGNAL_RANGE, signal_range * 0.35),)if len(samples) >= MIN_USABLE_SIGNAL_SAMPLESelse [])partial_reps = _partial_reps(sequence, segments, samples, signal_range=signal_range)if sequence.pose_valid_ratio < 0.8:partial_reps.append({"reason": "low_pose_valid_ratio"})reps = Reps(exercise=classification.exercise,reps=_segments_to_reps(segments),partial_reps=partial_reps,)debug_payload = {**debug,"thresholds": {"min_cycle_frames": MIN_CYCLE_FRAMES,"min_phase_frames": MIN_PHASE_FRAMES,"min_amplitude": round(max(MIN_SIGNAL_RANGE, signal_range * 0.35), 4),},"extrema": [{"kind": extrema_item.kind,"frame_index": extrema_item.sample.frame_index,"timestamp_sec": round(extrema_item.sample.timestamp_sec, 3),"value": round(extrema_item.sample.value, 4),}for extrema_item in extrema],"accepted_reps": [{"start": asdict(segment.start),"middle": asdict(segment.middle),"end": asdict(segment.end),"amplitude": round(segment.amplitude, 4),}for segment in segments],}return reps, debug_payload
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150from __future__ import annotations
import mathfrom pathlib import Pathimport sysimport unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from pozify.contracts import ExerciseClassification, PoseFrame, PoseSequencefrom pozify.steps import rep_counter
def _frame(frame_index: int, landmarks: dict[str, dict[str, float]]) -> PoseFrame: return PoseFrame( frame_index=frame_index, timestamp_sec=round(frame_index / 30.0, 3), landmarks=landmarks, world_landmarks={}, pose_quality={"mean_visibility": 0.95, "normalized": True}, )
def _wave(frame_index: int, cycle_frames: int, *, phase_shift: float = 0.0) -> float: return (1.0 - math.cos(2.0 * math.pi * ((frame_index + phase_shift) / cycle_frames))) / 2.0
def _squat_landmarks(depth: float) -> dict[str, dict[str, float]]: hip_y = 0.52 + depth * 0.18 shoulder_y = 0.28 + depth * 0.06 knee_y = 0.7 ankle_y = 0.92 hip_x_left, hip_x_right = 0.43, 0.57 knee_x_left = hip_x_left + depth * 0.06 knee_x_right = hip_x_right - depth * 0.06 return { "left_shoulder": {"x": 0.4, "y": shoulder_y, "smoothed_x": 0.4, "smoothed_y": shoulder_y}, "right_shoulder": {"x": 0.6, "y": shoulder_y, "smoothed_x": 0.6, "smoothed_y": shoulder_y}, "left_hip": {"x": hip_x_left, "y": hip_y, "smoothed_x": hip_x_left, "smoothed_y": hip_y}, "right_hip": {"x": hip_x_right, "y": hip_y, "smoothed_x": hip_x_right, "smoothed_y": hip_y}, "left_knee": {"x": knee_x_left, "y": knee_y, "smoothed_x": knee_x_left, "smoothed_y": knee_y}, "right_knee": {"x": knee_x_right, "y": knee_y, "smoothed_x": knee_x_right, "smoothed_y": knee_y}, "left_ankle": {"x": 0.42, "y": ankle_y, "smoothed_x": 0.42, "smoothed_y": ankle_y}, "right_ankle": {"x": 0.58, "y": ankle_y, "smoothed_x": 0.58, "smoothed_y": ankle_y}, }
def _push_up_landmarks(depth: float) -> dict[str, dict[str, float]]: shoulder_y = 0.38 + depth * 0.16 hip_y = 0.46 + depth * 0.16 ankle_y = 0.54 + depth * 0.16 elbow_y = 0.46 + depth * 0.1 wrist_y = 0.5 + depth * 0.04 elbow_x_left = 0.36 + depth * 0.02 elbow_x_right = 0.64 - depth * 0.02 return { "left_shoulder": {"x": 0.3, "y": shoulder_y, "smoothed_x": 0.3, "smoothed_y": shoulder_y}, "right_shoulder": {"x": 0.7, "y": shoulder_y, "smoothed_x": 0.7, "smoothed_y": shoulder_y}, "left_elbow": {"x": elbow_x_left, "y": elbow_y, "smoothed_x": elbow_x_left, "smoothed_y": elbow_y}, "right_elbow": {"x": elbow_x_right, "y": elbow_y, "smoothed_x": elbow_x_right, "smoothed_y": elbow_y}, "left_wrist": {"x": 0.34, "y": wrist_y, "smoothed_x": 0.34, "smoothed_y": wrist_y}, "right_wrist": {"x": 0.66, "y": wrist_y, "smoothed_x": 0.66, "smoothed_y": wrist_y}, "left_hip": {"x": 0.42, "y": hip_y, "smoothed_x": 0.42, "smoothed_y": hip_y}, "right_hip": {"x": 0.58, "y": hip_y, "smoothed_x": 0.58, "smoothed_y": hip_y}, "left_ankle": {"x": 0.44, "y": ankle_y, "smoothed_x": 0.44, "smoothed_y": ankle_y}, "right_ankle": {"x": 0.56, "y": ankle_y, "smoothed_x": 0.56, "smoothed_y": ankle_y}, }
def _shoulder_press_landmarks(lift: float) -> dict[str, dict[str, float]]: wrist_y = 0.76 - lift * 0.34 elbow_y = 0.6 - lift * 0.1 elbow_x_left = 0.4 - lift * 0.05 elbow_x_right = 0.6 + lift * 0.05 return { "left_shoulder": {"x": 0.42, "y": 0.42, "smoothed_x": 0.42, "smoothed_y": 0.42}, "right_shoulder": {"x": 0.58, "y": 0.42, "smoothed_x": 0.58, "smoothed_y": 0.42}, "left_elbow": {"x": elbow_x_left, "y": elbow_y, "smoothed_x": elbow_x_left, "smoothed_y": elbow_y}, "right_elbow": {"x": elbow_x_right, "y": elbow_y, "smoothed_x": elbow_x_right, "smoothed_y": elbow_y}, "left_wrist": {"x": 0.4, "y": wrist_y, "smoothed_x": 0.4, "smoothed_y": wrist_y}, "right_wrist": {"x": 0.6, "y": wrist_y, "smoothed_x": 0.6, "smoothed_y": wrist_y}, }
def _sequence_for_exercise(exercise: str, cycles: int, *, partial_tail: bool = False) -> PoseSequence: cycle_frames = 24 total_frames = cycles * cycle_frames + (cycle_frames // 2 if partial_tail else 0) frames: list[PoseFrame] = [] for frame_index in range(total_frames): wave = _wave(frame_index, cycle_frames) if exercise == "squat": landmarks = _squat_landmarks(wave) elif exercise == "shoulder_press": landmarks = _shoulder_press_landmarks(wave) else: landmarks = _push_up_landmarks(wave) frames.append(_frame(frame_index, landmarks)) return PoseSequence( frames=frames, normalized=True, smoothing_method="exponential_smoothing", pose_valid_ratio=1.0, )
class RepCounterTests(unittest.TestCase): def _classification(self, exercise: str) -> ExerciseClassification: return ExerciseClassification( exercise=exercise, # type: ignore[arg-type] confidence=0.95, window_predictions=[], fallback_required=False, )
def test_segments_squat_reps(self) -> None: reps, debug = rep_counter.run(self._classification("squat"), _sequence_for_exercise("squat", 3)) self.assertEqual(len(reps.reps), 3) self.assertEqual(reps.reps[0].start_frame, 0) self.assertTrue(debug["accepted_reps"])
def test_segments_push_up_reps(self) -> None: reps, _debug = rep_counter.run(self._classification("push_up"), _sequence_for_exercise("push_up", 3)) self.assertEqual(len(reps.reps), 3) self.assertEqual(reps.partial_reps, [])
def test_segments_shoulder_press_reps(self) -> None: reps, _debug = rep_counter.run( self._classification("shoulder_press"), _sequence_for_exercise("shoulder_press", 3), ) self.assertEqual(len(reps.reps), 3) self.assertEqual(reps.reps[0].mid_frame, 12)
def test_reports_partial_last_rep(self) -> None: reps, _debug = rep_counter.run( self._classification("push_up"), _sequence_for_exercise("push_up", 2, partial_tail=True), ) self.assertEqual(len(reps.reps), 2) self.assertIn("ends_mid_rep", {item["reason"] for item in reps.partial_reps})
def test_unknown_exercise_is_not_segmented(self) -> None: reps, debug = rep_counter.run(self._classification("unknown"), _sequence_for_exercise("push_up", 1)) self.assertEqual(reps.reps, []) self.assertEqual(reps.partial_reps, [{"reason": "unknown_exercise"}]) self.assertEqual(debug["selected_signal"], "none")
if __name__ == "__main__": unittest.main()src/pozify/steps/rep_counter.py+213-20
tests/test_rep_counter.pyAdded+150