feat(rep_counter): implement exercise-specific rep counters for push-ups, shoulder presses, and squats; add dependency on fastapi
Browse filesFiles changed (11)
- pyproject.toml+1
- requirements.txt+3-1
- src/pozify/steps/rep_counter.py+3-216
- src/pozify/steps/rep_counters/__init__.pyAdded+5
- src/pozify/steps/rep_counters/base.pyAdded+180
- src/pozify/steps/rep_counters/push_up.pyAdded+40
- src/pozify/steps/rep_counters/registry.pyAdded+34
- src/pozify/steps/rep_counters/shoulder_press.pyAdded+38
- src/pozify/steps/rep_counters/squat.pyAdded+35
- tests/test_rep_counter.py+9
- uv.lock+2
4 unmodified lines56789104 unmodified linesreadme = "README.md"requires-python = ">=3.11"dependencies = ["gradio>=4.44.0","mediapipe>=0.10.35","numpy>=1.26.0",4 unmodified lines5678910114 unmodified linesreadme = "README.md"requires-python = ">=3.11"dependencies = ["fastapi>=0.136.3","gradio>=4.44.0","mediapipe>=0.10.35","numpy>=1.26.0",
37 unmodified lines3839404142434437 unmodified linescycler==0.12.1# via matplotlibfastapi==0.136.3# via gradiofilelock==3.29.1# via huggingface-hubflatbuffers==25.12.1937 unmodified lines38394041424344454637 unmodified linescycler==0.12.1# via matplotlibfastapi==0.136.3# via# gradio# pozifyfilelock==3.29.1# via huggingface-hubflatbuffers==25.12.19
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_payload12345678910from __future__ import annotationsfrom typing import Anyfrom pozify.contracts import ExerciseClassification, PoseSequence, Repsfrom pozify.steps.rep_counters import get_rep_counterdef run(classification: ExerciseClassification, sequence: PoseSequence) -> tuple[Reps, dict[str, Any]]:return get_rep_counter(classification.exercise).count(sequence)
12345from pozify.steps.rep_counters.base import ExerciseRepCounterfrom pozify.steps.rep_counters.registry import get_rep_counter
__all__ = ["ExerciseRepCounter", "get_rep_counter"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180from __future__ import annotations
from abc import ABC, abstractmethodfrom dataclasses import asdictfrom typing import Any
from pozify.contracts import PoseSequence, Rep, Repsfrom pozify.steps.rep_signals import SignalSample, normalize_optional, samples_from_values, smooth_signalfrom pozify.steps.rep_state_machine import RepSegment, find_local_extrema, segment_low_high_low
MIN_CYCLE_FRAMES = 12MIN_PHASE_FRAMES = 4MIN_USABLE_SIGNAL_SAMPLES = 9MIN_SIGNAL_RANGE = 0.22
def mean_optional(values: list[float | None]) -> float | None: usable = [value for value in values if value is not None] if not usable: return None return 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) continue if secondary_value is None: combined.append(primary_value) continue combined.append(primary_value + secondary_value * weight) return combined
def normalized_samples( sequence: PoseSequence, raw_signal: list[float | None],) -> tuple[list[SignalSample], float]: smoothed_signal = smooth_signal(raw_signal) normalized_signal = normalize_optional(smoothed_signal) samples = samples_from_values(sequence, normalized_signal) signal_range = 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, ) return samples, round(signal_range, 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 partials
first_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 partials
class ExerciseRepCounter(ABC): exercise: str min_cycle_frames = MIN_CYCLE_FRAMES min_phase_frames = MIN_PHASE_FRAMES min_signal_range = MIN_SIGNAL_RANGE min_usable_signal_samples = MIN_USABLE_SIGNAL_SAMPLES
@abstractmethod def build_signal(self, sequence: PoseSequence) -> tuple[list[SignalSample], dict[str, Any]]: """Build the exercise-specific normalized motion signal."""
def count(self, sequence: PoseSequence) -> tuple[Reps, dict[str, Any]]: samples, debug = self.build_signal(sequence) signal_range = debug["raw_signal_range"] extrema = find_local_extrema(samples) min_amplitude = max(self.min_signal_range, signal_range * 0.35) segments = ( segment_low_high_low( extrema, min_cycle_frames=self.min_cycle_frames, min_phase_frames=self.min_phase_frames, min_amplitude=min_amplitude, ) if len(samples) >= self.min_usable_signal_samples else [] ) partials = partial_reps(sequence, segments, samples, signal_range=signal_range) if sequence.pose_valid_ratio < 0.8: partials.append({"reason": "low_pose_valid_ratio"})
reps = Reps( exercise=self.exercise, reps=segments_to_reps(segments), partial_reps=partials, ) debug_payload = { **debug, "thresholds": { "min_cycle_frames": self.min_cycle_frames, "min_phase_frames": self.min_phase_frames, "min_amplitude": round(min_amplitude, 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
12345678910111213141516171819202122232425262728293031323334353637383940from __future__ import annotations
from typing import Any
from pozify.contracts import PoseSequencefrom pozify.steps.rep_counters.base import ExerciseRepCounter, combine, mean_optional, normalized_samplesfrom pozify.steps.rep_signals import SignalSample, angle_deg, average_axis, body_line_score
class PushUpRepCounter(ExerciseRepCounter): exercise = "push_up"
def build_signal(self, sequence: PoseSequence) -> 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] 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] chest_proxy = [ mean_optional([shoulder_value, hip_value]) for shoulder_value, hip_value in zip(shoulder_y, hip_y, strict=False) ] samples, signal_range = normalized_samples(sequence, combine(chest_proxy, elbow_bend, weight=0.25)) return samples, { "selected_signal": "chest_y_plus_elbow_bend", "raw_signal_range": signal_range, "usable_signal_samples": len(samples), "body_line_mean": round(mean_optional(body_line) or 0.0, 4), }
12345678910111213141516171819202122232425262728293031323334from __future__ import annotations
from typing import Any
from pozify.contracts import PoseSequence, Repsfrom pozify.steps.rep_counters.base import ExerciseRepCounterfrom pozify.steps.rep_counters.push_up import PushUpRepCounterfrom pozify.steps.rep_counters.shoulder_press import ShoulderPressRepCounterfrom pozify.steps.rep_counters.squat import SquatRepCounterfrom pozify.steps.rep_signals import SignalSample
class UnknownRepCounter(ExerciseRepCounter): exercise = "unknown"
def build_signal(self, sequence: PoseSequence) -> tuple[list[SignalSample], dict[str, Any]]: return [], {"selected_signal": "none", "thresholds": {}, "extrema": [], "accepted_reps": []}
def count(self, sequence: PoseSequence) -> tuple[Reps, dict[str, Any]]: reps = Reps(exercise=self.exercise, reps=[], partial_reps=[{"reason": "unknown_exercise"}]) return reps, {"selected_signal": "none", "thresholds": {}, "extrema": [], "accepted_reps": []}
REP_COUNTERS: dict[str, ExerciseRepCounter] = { "push_up": PushUpRepCounter(), "shoulder_press": ShoulderPressRepCounter(), "squat": SquatRepCounter(), "unknown": UnknownRepCounter(),}
def get_rep_counter(exercise: str) -> ExerciseRepCounter: return REP_COUNTERS.get(exercise, REP_COUNTERS["unknown"])
1234567891011121314151617181920212223242526272829303132333435363738from __future__ import annotations
from typing import Any
from pozify.contracts import PoseSequencefrom pozify.steps.rep_counters.base import ExerciseRepCounter, combine, mean_optional, normalized_samplesfrom pozify.steps.rep_signals import SignalSample, angle_deg, average_axis, body_line_score
class ShoulderPressRepCounter(ExerciseRepCounter): exercise = "shoulder_press"
def build_signal(self, sequence: PoseSequence) -> tuple[list[SignalSample], dict[str, Any]]: wrist_y = [average_axis(frame, ("left_wrist", "right_wrist"), "y") 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] inverted_wrist = [None if value is None else -value for value in wrist_y] inverted_elbow_bend = [None if value is None else -value for value in elbow_bend] raw_signal = combine(inverted_wrist, inverted_elbow_bend, weight=0.2) samples, signal_range = normalized_samples(sequence, raw_signal) return samples, { "selected_signal": "negative_wrist_y_plus_elbow_extension_proxy", "raw_signal_range": signal_range, "usable_signal_samples": len(samples), "body_line_mean": round(mean_optional(body_line) or 0.0, 4), }
1234567891011121314151617181920212223242526272829303132333435from __future__ import annotations
from typing import Any
from pozify.contracts import PoseSequencefrom pozify.steps.rep_counters.base import ExerciseRepCounter, combine, mean_optional, normalized_samplesfrom pozify.steps.rep_signals import SignalSample, angle_deg, average_axis, body_line_score
class SquatRepCounter(ExerciseRepCounter): exercise = "squat"
def build_signal(self, sequence: PoseSequence) -> tuple[list[SignalSample], dict[str, Any]]: hip_y = [average_axis(frame, ("left_hip", "right_hip"), "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 ] body_line = [body_line_score(frame) for frame in sequence.frames] samples, signal_range = normalized_samples(sequence, combine(hip_y, knee_bend, weight=0.35)) return samples, { "selected_signal": "hip_y_plus_knee_bend", "raw_signal_range": signal_range, "usable_signal_samples": len(samples), "body_line_mean": round(mean_optional(body_line) or 0.0, 4), }
8 unmodified lines91011121314130 unmodified lines1451461471481491508 unmodified linesfrom pozify.contracts import ExerciseClassification, PoseFrame, PoseSequencefrom pozify.steps import rep_counterdef _frame(frame_index: int, landmarks: dict[str, dict[str, float]]) -> PoseFrame:130 unmodified linesself.assertEqual(reps.partial_reps, [{"reason": "unknown_exercise"}])self.assertEqual(debug["selected_signal"], "none")if __name__ == "__main__":unittest.main()8 unmodified lines9101112131415161718130 unmodified lines1491501511521531541551561571581598 unmodified linesfrom pozify.contracts import ExerciseClassification, PoseFrame, PoseSequencefrom pozify.steps import rep_counterfrom pozify.steps.rep_counters import get_rep_counterfrom pozify.steps.rep_counters.push_up import PushUpRepCounterfrom pozify.steps.rep_counters.shoulder_press import ShoulderPressRepCounterfrom pozify.steps.rep_counters.squat import SquatRepCounterdef _frame(frame_index: int, landmarks: dict[str, dict[str, float]]) -> PoseFrame:130 unmodified linesself.assertEqual(reps.partial_reps, [{"reason": "unknown_exercise"}])self.assertEqual(debug["selected_signal"], "none")def test_exercises_resolve_to_specific_rep_counter_strategies(self) -> None:self.assertIsInstance(get_rep_counter("push_up"), PushUpRepCounter)self.assertIsInstance(get_rep_counter("shoulder_press"), ShoulderPressRepCounter)self.assertIsInstance(get_rep_counter("squat"), SquatRepCounter)if __name__ == "__main__":unittest.main()
1288 unmodified lines1289129012911292129312948 unmodified lines1303130413051306130713081288 unmodified linesversion = "0.1.0"source = { virtual = "." }dependencies = [{ name = "gradio" },{ name = "mediapipe" },{ name = "numpy" },8 unmodified lines[package.metadata]requires-dist = [{ name = "gradio", specifier = ">=4.44.0" },{ name = "mediapipe", specifier = ">=0.10.35" },{ name = "numpy", specifier = ">=1.26.0" },1288 unmodified lines12891290129112921293129412958 unmodified lines13041305130613071308130913101288 unmodified linesversion = "0.1.0"source = { virtual = "." }dependencies = [{ name = "fastapi" },{ name = "gradio" },{ name = "mediapipe" },{ name = "numpy" },8 unmodified lines[package.metadata]requires-dist = [{ name = "fastapi", specifier = ">=0.136.3" },{ name = "gradio", specifier = ">=4.44.0" },{ name = "mediapipe", specifier = ">=0.10.35" },{ name = "numpy", specifier = ">=1.26.0" },
pyproject.toml+1
requirements.txt+3-1
src/pozify/steps/rep_counter.py+3-216
src/pozify/steps/rep_counters/__init__.pyAdded+5
src/pozify/steps/rep_counters/base.pyAdded+180
src/pozify/steps/rep_counters/push_up.pyAdded+40
src/pozify/steps/rep_counters/registry.pyAdded+34
src/pozify/steps/rep_counters/shoulder_press.pyAdded+38
src/pozify/steps/rep_counters/squat.pyAdded+35
tests/test_rep_counter.py+9
uv.lock+2