Merge branch 'main' into NLag/issue4
Browse filesFiles changed (9)
- src/pozify/steps/exercise_analyzers/__init__.pyAdded+19
- src/pozify/steps/exercise_analyzers/base.pyAdded+135
- src/pozify/steps/exercise_analyzers/push_up.pyAdded+117
- src/pozify/steps/exercise_analyzers/shoulder_press.pyAdded+89
- src/pozify/steps/exercise_analyzers/squat.pyAdded+126
- src/pozify/steps/exercise_analyzers/unknown.pyAdded+26
- src/pozify/steps/rep_analysis.py+26-397
- src/pozify/steps/variation_detector.py+1-1
- tests/test_rep_analysis_variation.py+87
12345678910111213141516171819from __future__ import annotations
from pozify.steps.exercise_analyzers.base import ExerciseAnalyzer, ExerciseMetricResultfrom pozify.steps.exercise_analyzers.push_up import PushUpAnalyzerfrom pozify.steps.exercise_analyzers.shoulder_press import ShoulderPressAnalyzerfrom pozify.steps.exercise_analyzers.squat import SquatAnalyzerfrom pozify.steps.exercise_analyzers.unknown import UnknownAnalyzer
def analyzer_for(exercise: str) -> ExerciseAnalyzer: analyzers: dict[str, ExerciseAnalyzer] = { "push_up": PushUpAnalyzer(), "shoulder_press": ShoulderPressAnalyzer(), "squat": SquatAnalyzer(), } return analyzers.get(exercise, UnknownAnalyzer())
__all__ = ["ExerciseAnalyzer", "ExerciseMetricResult", "analyzer_for"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135from __future__ import annotations
from statistics import pstdevfrom typing import Any, Callable, Protocol
from pozify.contracts import PoseFramefrom pozify.steps.rep_signals import angle_deg, average_axis, landmark_axis
NumberGetter = Callable[[PoseFrame], float | None]ExerciseMetricResult = tuple[dict[str, Any], float, float, float, list[str]]
class ExerciseAnalyzer(Protocol): def metrics(self, frames: list[PoseFrame]) -> ExerciseMetricResult: ...
def round_optional(value: float | None, digits: int = 2) -> float | None: if value is None: return None return round(value, digits)
def score(value: float) -> float: return round(min(1.0, max(0.0, value)), 2)
def usable(values: list[float | None]) -> list[float]: return [value for value in values if value is not None]
def mean_optional(values: list[float | None]) -> float | None: usable_values = usable(values) if not usable_values: return None return sum(usable_values) / len(usable_values)
def min_optional(values: list[float | None]) -> float | None: usable_values = usable(values) return min(usable_values) if usable_values else None
def max_optional(values: list[float | None]) -> float | None: usable_values = usable(values) return max(usable_values) if usable_values else None
def range_optional(values: list[float | None]) -> float | None: usable_values = usable(values) if not usable_values: return None return max(usable_values) - min(usable_values)
def std_optional(values: list[float | None]) -> float | None: usable_values = usable(values) if len(usable_values) < 2: return 0.0 if usable_values else None return pstdev(usable_values)
def safe_ratio(numerator: float | None, denominator: float | None) -> float | None: if numerator is None or denominator is None or abs(denominator) <= 1e-6: return None return numerator / denominator
def width(frame: PoseFrame, left: str, right: str) -> float | None: left_x = landmark_axis(frame, left, "x") right_x = landmark_axis(frame, right, "x") if left_x is None or right_x is None: return None return abs(right_x - left_x)
def mean_pair( frame: PoseFrame, first: tuple[str, str, str], second: tuple[str, str, str],) -> float | None: values = [angle_deg(frame, *first), angle_deg(frame, *second)] return mean_optional(values)
def side_delta( frame: PoseFrame, first: tuple[str, str, str], second: tuple[str, str, str],) -> float | None: first_value = angle_deg(frame, *first) second_value = angle_deg(frame, *second) if first_value is None or second_value is None: return None return abs(first_value - second_value)
def torso_lean_deg(frame: PoseFrame, side: str) -> float | None: shoulder_x = landmark_axis(frame, f"{side}_shoulder", "x") shoulder_y = landmark_axis(frame, f"{side}_shoulder", "y") hip_x = landmark_axis(frame, f"{side}_hip", "x") hip_y = landmark_axis(frame, f"{side}_hip", "y") if None in {shoulder_x, shoulder_y, hip_x, hip_y}: return None horizontal_offset = abs(float(shoulder_x) - float(hip_x)) vertical_offset = abs(float(shoulder_y) - float(hip_y)) if vertical_offset <= 1e-6: return None from math import atan2, degrees
return degrees(atan2(horizontal_offset, vertical_offset))
def value_series(frames: list[PoseFrame], getter: NumberGetter) -> list[float | None]: return [getter(frame) for frame in frames]
def mean_visibility(frames: list[PoseFrame]) -> float: values: list[float | None] = [] for frame in frames: if "mean_visibility" in frame.pose_quality: values.append(float(frame.pose_quality["mean_visibility"])) continue landmark_values = [ landmark.get("visibility") for landmark in frame.landmarks.values() if landmark.get("visibility") is not None ] values.extend(float(value) for value in landmark_values) return score(mean_optional(values) if values else 0.0)
def average_y(frame: PoseFrame, names: tuple[str, ...]) -> float | None: return average_axis(frame, names, "y")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117from __future__ import annotations
from pozify.contracts import PoseFramefrom pozify.steps.exercise_analyzers.base import ( ExerciseMetricResult, max_optional, mean_optional, mean_pair, min_optional, range_optional, round_optional, safe_ratio, score, side_delta, std_optional, value_series, width,)from pozify.steps.rep_signals import average_axis, body_line_score
class PushUpAnalyzer: def metrics(self, frames: list[PoseFrame]) -> ExerciseMetricResult: elbow_angles = value_series( frames, lambda frame: mean_pair( frame, ("left_shoulder", "left_elbow", "left_wrist"), ("right_shoulder", "right_elbow", "right_wrist"), ), ) elbow_deltas = value_series( frames, lambda frame: side_delta( frame, ("left_shoulder", "left_elbow", "left_wrist"), ("right_shoulder", "right_elbow", "right_wrist"), ), ) body_line = value_series(frames, body_line_score) shoulder_y = value_series( frames, lambda frame: average_axis(frame, ("left_shoulder", "right_shoulder"), "y"), ) hip_y = value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y")) ankle_y = value_series( frames, lambda frame: average_axis(frame, ("left_ankle", "right_ankle"), "y"), ) hand_width = value_series(frames, lambda frame: width(frame, "left_wrist", "right_wrist")) shoulder_width = value_series( frames, lambda frame: width(frame, "left_shoulder", "right_shoulder"), ) elbow_width = value_series(frames, lambda frame: width(frame, "left_elbow", "right_elbow")) knee_y = value_series( frames, lambda frame: average_axis(frame, ("left_knee", "right_knee"), "y"), )
min_elbow = min_optional(elbow_angles) max_elbow = max_optional(elbow_angles) elbow_rom = 0.0 if min_elbow is None or max_elbow is None else max_elbow - min_elbow chest_depth = range_optional(shoulder_y) or 0.0 hand_width_ratio = safe_ratio(mean_optional(hand_width), mean_optional(shoulder_width)) elbow_flare = safe_ratio(mean_optional(elbow_width), mean_optional(shoulder_width)) body_line_mean = mean_optional(body_line) hip_sag_score = None if body_line_mean is not None: hip_sag_score = max(0.0, 1.0 - body_line_mean) knee_support_score = self._knee_support_score(hip_y, knee_y, ankle_y)
rom_score = score((elbow_rom / 80.0) * 0.65 + (chest_depth / 0.16) * 0.35) hip_stability = 1.0 - min(1.0, (std_optional(hip_y) or 0.0) * 4.0) stability_score = score(((body_line_mean or 0.5) * 0.75) + hip_stability * 0.25) symmetry_score = score(1.0 - ((mean_optional(elbow_deltas) or 0.0) / 45.0))
metrics = { "min_elbow_angle_deg": round_optional(min_elbow), "max_elbow_angle_deg": round_optional(max_elbow), "body_line_score": round_optional(body_line_mean), "hip_sag_score": round_optional(hip_sag_score), "hip_pike_score": round_optional(max(0.0, ((body_line_mean or 1.0) - 1.0) * -1.0), 4), "chest_depth_proxy": round_optional(chest_depth, 4), "hand_width_ratio": round_optional(hand_width_ratio, 3), "elbow_flare_ratio": round_optional(elbow_flare, 3), "lockout_quality": score(((max_elbow or 120.0) - 120.0) / 55.0), "knee_support_score": knee_support_score, } hints = [] if hand_width_ratio is not None and hand_width_ratio > 1.45: hints.append("wide_grip_push_up") elif hand_width_ratio is not None and hand_width_ratio < 0.95: hints.append("close_grip_push_up") if knee_support_score >= 0.8: hints.append("knee_push_up") return metrics, rom_score, stability_score, symmetry_score, hints
def _knee_support_score( self, hip_y: list[float | None], knee_y: list[float | None], ankle_y: list[float | None], ) -> float: scores: list[float] = [] for hip, knee, ankle in zip(hip_y, knee_y, ankle_y, strict=False): if hip is None or knee is None or ankle is None: continue
hip_to_ankle = abs(ankle - hip) if hip_to_ankle <= 1e-6: continue knee_to_hip = abs(knee - hip) bent_leg_score = score(1.0 - knee_to_hip / max(hip_to_ankle * 0.55, 0.01)) scores.append(bent_leg_score)
return score(mean_optional(scores) or 0.0)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889from __future__ import annotations
from statistics import mean
from pozify.contracts import PoseFramefrom pozify.steps.exercise_analyzers.base import ( ExerciseMetricResult, max_optional, mean_optional, mean_pair, min_optional, range_optional, round_optional, score, side_delta, value_series,)from pozify.steps.rep_signals import average_axis, landmark_axis
class ShoulderPressAnalyzer: def metrics(self, frames: list[PoseFrame]) -> ExerciseMetricResult: elbow_angles = value_series( frames, lambda frame: mean_pair( frame, ("left_shoulder", "left_elbow", "left_wrist"), ("right_shoulder", "right_elbow", "right_wrist"), ), ) elbow_deltas = value_series( frames, lambda frame: side_delta( frame, ("left_shoulder", "left_elbow", "left_wrist"), ("right_shoulder", "right_elbow", "right_wrist"), ), ) wrist_y = value_series( frames, lambda frame: average_axis(frame, ("left_wrist", "right_wrist"), "y"), ) wrist_x = value_series( frames, lambda frame: average_axis(frame, ("left_wrist", "right_wrist"), "x"), ) left_wrist_y = value_series(frames, lambda frame: landmark_axis(frame, "left_wrist", "y")) right_wrist_y = value_series(frames, lambda frame: landmark_axis(frame, "right_wrist", "y")) wrist_asymmetry = [ abs(left - right) for left, right in zip(left_wrist_y, right_wrist_y, strict=False) if left is not None and right is not None ] shoulder_y = value_series( frames, lambda frame: average_axis(frame, ("left_shoulder", "right_shoulder"), "y"), ) hip_y = value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"))
min_elbow = min_optional(elbow_angles) max_elbow = max_optional(elbow_angles) wrist_travel = range_optional(wrist_y) or 0.0 wrist_lateral_drift = range_optional(wrist_x) or 0.0 lockout_quality = score(((max_elbow or 120.0) - 120.0) / 55.0) verticality = score(1.0 - wrist_lateral_drift / max(0.01, wrist_travel)) asymmetry = mean(wrist_asymmetry) if wrist_asymmetry else 0.0 back_arch_proxy = abs((range_optional(hip_y) or 0.0) - (range_optional(shoulder_y) or 0.0))
rom_score = score((wrist_travel / 0.28) * 0.55 + lockout_quality * 0.45) stability_score = score(verticality * 0.65 + (1.0 - min(1.0, back_arch_proxy * 4.0)) * 0.35) symmetry_score = score(1.0 - max(asymmetry * 5.0, (mean_optional(elbow_deltas) or 0.0) / 45.0))
metrics = { "min_elbow_angle_deg": round_optional(min_elbow), "max_elbow_angle_deg": round_optional(max_elbow), "wrist_path_verticality": verticality, "lockout_quality": lockout_quality, "wrist_height_asymmetry": round_optional(asymmetry, 4), "left_right_wrist_delta": round_optional(asymmetry, 4), "back_arch_proxy": round_optional(back_arch_proxy, 4), "overhead_stability_score": stability_score, "wrist_travel": round_optional(wrist_travel, 4), } hints = [] if lockout_quality < 0.65: hints.append("partial_press") if asymmetry > 0.12: hints.append("asymmetric_press") return metrics, rom_score, stability_score, symmetry_score, hints123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126from __future__ import annotations
from pozify.contracts import PoseFramefrom pozify.steps.exercise_analyzers.base import ( ExerciseMetricResult, max_optional, mean_optional, mean_pair, min_optional, round_optional, safe_ratio, score, side_delta, std_optional, torso_lean_deg, value_series, width,)from pozify.steps.rep_signals import average_axis
class SquatAnalyzer: def metrics(self, frames: list[PoseFrame]) -> ExerciseMetricResult: knee_angles = value_series( frames, lambda frame: mean_pair( frame, ("left_hip", "left_knee", "left_ankle"), ("right_hip", "right_knee", "right_ankle"), ), ) hip_angles = value_series( frames, lambda frame: mean_pair( frame, ("left_shoulder", "left_hip", "left_knee"), ("right_shoulder", "right_hip", "right_knee"), ), ) knee_deltas = value_series( frames, lambda frame: side_delta( frame, ("left_hip", "left_knee", "left_ankle"), ("right_hip", "right_knee", "right_ankle"), ), ) hip_deltas = value_series( frames, lambda frame: side_delta( frame, ("left_shoulder", "left_hip", "left_knee"), ("right_shoulder", "right_hip", "right_knee"), ), ) hip_y = value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y")) knee_y = value_series( frames, lambda frame: average_axis(frame, ("left_knee", "right_knee"), "y"), ) ankle_width = value_series(frames, lambda frame: width(frame, "left_ankle", "right_ankle")) shoulder_width = value_series( frames, lambda frame: width(frame, "left_shoulder", "right_shoulder"), ) knee_width = value_series(frames, lambda frame: width(frame, "left_knee", "right_knee")) torso_lean = value_series( frames, lambda frame: mean_optional( [torso_lean_deg(frame, "left"), torso_lean_deg(frame, "right")] ), )
min_knee = min_optional(knee_angles) max_knee = max_optional(knee_angles) min_hip = min_optional(hip_angles) max_hip = max_optional(hip_angles) hip_depth_delta = None max_hip_y = max_optional(hip_y) mean_knee_y = mean_optional(knee_y) if max_hip_y is not None and mean_knee_y is not None: hip_depth_delta = max_hip_y - mean_knee_y
stance_ratio = safe_ratio(mean_optional(ankle_width), mean_optional(shoulder_width)) knee_tracking_ratio = safe_ratio(mean_optional(knee_width), mean_optional(ankle_width)) valgus_proxy = None if knee_tracking_ratio is None else max(0.0, 1.0 - knee_tracking_ratio) symmetry_delta = mean_optional(knee_deltas + hip_deltas) or 0.0 stability_noise = (std_optional(hip_y) or 0.0) + (std_optional(knee_width) or 0.0)
knee_rom = 0.0 if min_knee is None or max_knee is None else max_knee - min_knee depth_score = score((hip_depth_delta + 0.08) / 0.18) if hip_depth_delta is not None else 0.5 angle_score = score(knee_rom / 65.0) rom_score = score(angle_score * 0.55 + depth_score * 0.45) stability_score = score(1.0 - stability_noise * 5.0) symmetry_score = score(1.0 - symmetry_delta / 45.0)
hip_x = value_series( frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "x"), ) metrics = { "min_knee_angle_deg": round_optional(min_knee), "max_knee_angle_deg": round_optional(max_knee), "min_hip_angle_deg": round_optional(min_hip), "max_hip_angle_deg": round_optional(max_hip), "hip_depth_delta": round_optional(hip_depth_delta, 4), "hip_depth_relative_to_knee": ( "below_parallel" if hip_depth_delta is not None and hip_depth_delta >= 0.03 else "parallel" if hip_depth_delta is not None and hip_depth_delta >= -0.03 else "above_parallel" ), "max_torso_lean_deg": round_optional(max_optional(torso_lean)), "knee_valgus_proxy": round_optional(valgus_proxy, 4), "knee_tracking_score": score(1.0 - (valgus_proxy or 0.0)), "stance_width_ratio": round_optional(stance_ratio, 3), "hip_shift": round_optional(std_optional(hip_x), 4), "bottom_stability_score": stability_score, } hints = [] if stance_ratio is not None and stance_ratio > 1.35: hints.append("wide_squat_stance") elif stance_ratio is not None and stance_ratio < 0.85: hints.append("narrow_squat_stance") return metrics, rom_score, stability_score, symmetry_score, hints1234567891011121314151617181920212223242526from __future__ import annotations
from pozify.contracts import PoseFramefrom pozify.steps.exercise_analyzers.base import ( ExerciseMetricResult, mean_visibility, range_optional, score, value_series,)from pozify.steps.rep_signals import average_axis
class UnknownAnalyzer: def metrics(self, frames: list[PoseFrame]) -> ExerciseMetricResult: movement_signal = value_series( frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"), ) movement = range_optional(movement_signal) or 0.0 confidence = mean_visibility(frames) metrics = { "movement_consistency_score": score(1.0 - movement * 4.0), "landmark_confidence": confidence, } return metrics, 0.0, metrics["movement_consistency_score"], confidence, []11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912016 unmodified lines1371381391401411421431441451466 unmodified lines1531541551561571581591601611621635 unmodified lines1691701711721731741752 unmodified lines17817918018118218318429 unmodified lines2142152162172182192203 unmodified lines22422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954020 unmodified lines5615625635645655665675685695705715725735745756 unmodified lines58258358458558658758811 unmodified linesRepAnalysisItem,Reps,)from pozify.steps.rep_signals import angle_deg, average_axis, body_line_score, landmark_axisNumberGetter = Callable[[PoseFrame], float | None]ExerciseMetricResult = tuple[dict[str, Any], float, float, float, list[str]]def _round(value: float | None, digits: int = 2) -> float | None:if value is None:return Nonereturn round(value, digits)def _score(value: float) -> float:return round(min(1.0, max(0.0, value)), 2)def _usable(values: list[float | None]) -> list[float]:return [value for value in values if value is not None]def _mean(values: list[float | None]) -> float | None:usable_values = _usable(values)if not usable_values:return Nonereturn sum(usable_values) / len(usable_values)def _min(values: list[float | None]) -> float | None:usable_values = _usable(values)return min(usable_values) if usable_values else Nonedef _max(values: list[float | None]) -> float | None:usable_values = _usable(values)return max(usable_values) if usable_values else Nonedef _range(values: list[float | None]) -> float | None:usable_values = _usable(values)if not usable_values:return Nonereturn max(usable_values) - min(usable_values)def _std(values: list[float | None]) -> float | None:usable_values = _usable(values)if len(usable_values) < 2:return 0.0 if usable_values else Nonereturn pstdev(usable_values)def _safe_ratio(numerator: float | None, denominator: float | None) -> float | None:if numerator is None or denominator is None or abs(denominator) <= 1e-6:return Nonereturn numerator / denominatordef _width(frame: PoseFrame, left: str, right: str) -> float | None:left_x = landmark_axis(frame, left, "x")right_x = landmark_axis(frame, right, "x")if left_x is None or right_x is None:return Nonereturn abs(right_x - left_x)def _mean_pair(frame: PoseFrame,first: tuple[str, str, str],second: tuple[str, str, str],) -> float | None:values = [angle_deg(frame, *first), angle_deg(frame, *second)]return _mean(values)def _side_delta(frame: PoseFrame,first: tuple[str, str, str],second: tuple[str, str, str],) -> float | None:first_value = angle_deg(frame, *first)second_value = angle_deg(frame, *second)if first_value is None or second_value is None:return Nonereturn abs(first_value - second_value)def _torso_lean_deg(frame: PoseFrame, side: str) -> float | None:shoulder_x = landmark_axis(frame, f"{side}_shoulder", "x")shoulder_y = landmark_axis(frame, f"{side}_shoulder", "y")hip_x = landmark_axis(frame, f"{side}_hip", "x")hip_y = landmark_axis(frame, f"{side}_hip", "y")if None in {shoulder_x, shoulder_y, hip_x, hip_y}:return Nonehorizontal_offset = abs(float(shoulder_x) - float(hip_x))vertical_offset = abs(float(shoulder_y) - float(hip_y))if vertical_offset <= 1e-6:return Nonefrom math import atan2, degreesreturn degrees(atan2(horizontal_offset, vertical_offset))def _frames_for_rep(sequence: PoseSequence, rep: Rep) -> list[PoseFrame]:frames = [frame16 unmodified linesreturn [closest]def _value_series(frames: list[PoseFrame], getter: NumberGetter) -> list[float | None]:return [getter(frame) for frame in frames]def _mean_visibility(frames: list[PoseFrame]) -> float:values: list[float | None] = []for frame in frames:6 unmodified linesif landmark.get("visibility") is not None]values.extend(float(value) for value in landmark_values)return _score(_mean(values) if values else 0.0)def _smoothness_score(signal_values: list[float | None]) -> tuple[float, float | None]:usable_values = _usable(signal_values)if len(usable_values) < 4:return 0.5, None5 unmodified linesif not jerks:return 0.5, Nonejerk = mean(abs(value) for value in jerks)return _score(1.0 - jerk * 8.0), jerkdef _pause_duration(2 unmodified lines*,target: str,) -> float:usable_values = _usable(signal_values)if len(usable_values) < 3 or len(frames) < 3:return 0.029 unmodified linesconcentric_duration = round(max(0.0, rep.end_sec - rep.mid_sec), 2)duration = round(max(0.0, rep.end_sec - rep.start_sec), 2)smoothness_score, jerk_score = _smoothness_score(primary_signal)stability_axis = _value_series(frames,lambda frame: average_axis(frame, ("left_hip", "right_hip"), "x"),)3 unmodified lines"rep_duration_sec": duration,"eccentric_duration_sec": eccentric_duration,"concentric_duration_sec": concentric_duration,"tempo_ratio": _round(_safe_ratio(eccentric_duration, concentric_duration), 2),"top_pause_sec": _pause_duration(frames, primary_signal, target="top"),"bottom_pause_sec": _pause_duration(frames, primary_signal, target="bottom"),"smoothness_score": smoothness_score,"jerk_score": _round(jerk_score, 4),"landmark_confidence": _mean_visibility(frames),"hip_lateral_drift": _round(stability_noise, 4),}def _squat_metrics(frames: list[PoseFrame]) -> ExerciseMetricResult:knee_angles = _value_series(frames,lambda frame: _mean_pair(frame,("left_hip", "left_knee", "left_ankle"),("right_hip", "right_knee", "right_ankle"),),)hip_angles = _value_series(frames,lambda frame: _mean_pair(frame,("left_shoulder", "left_hip", "left_knee"),("right_shoulder", "right_hip", "right_knee"),),)knee_deltas = _value_series(frames,lambda frame: _side_delta(frame,("left_hip", "left_knee", "left_ankle"),("right_hip", "right_knee", "right_ankle"),),)hip_deltas = _value_series(frames,lambda frame: _side_delta(frame,("left_shoulder", "left_hip", "left_knee"),("right_shoulder", "right_hip", "right_knee"),),)hip_y = _value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"))knee_y = _value_series(frames,lambda frame: average_axis(frame, ("left_knee", "right_knee"), "y"),)ankle_width = _value_series(frames, lambda frame: _width(frame, "left_ankle", "right_ankle"))shoulder_width = _value_series(frames,lambda frame: _width(frame, "left_shoulder", "right_shoulder"),)knee_width = _value_series(frames, lambda frame: _width(frame, "left_knee", "right_knee"))torso_lean = _value_series(frames,lambda frame: _mean([_torso_lean_deg(frame, "left"), _torso_lean_deg(frame, "right")]),)min_knee = _min(knee_angles)max_knee = _max(knee_angles)min_hip = _min(hip_angles)max_hip = _max(hip_angles)hip_depth_delta = Nonemax_hip_y = _max(hip_y)mean_knee_y = _mean(knee_y)if max_hip_y is not None and mean_knee_y is not None:hip_depth_delta = max_hip_y - mean_knee_ystance_ratio = _safe_ratio(_mean(ankle_width), _mean(shoulder_width))knee_tracking_ratio = _safe_ratio(_mean(knee_width), _mean(ankle_width))valgus_proxy = None if knee_tracking_ratio is None else max(0.0, 1.0 - knee_tracking_ratio)symmetry_delta = _mean(knee_deltas + hip_deltas) or 0.0stability_noise = (_std(hip_y) or 0.0) + (_std(knee_width) or 0.0)knee_rom = 0.0 if min_knee is None or max_knee is None else max_knee - min_kneedepth_score = _score((hip_depth_delta + 0.08) / 0.18) if hip_depth_delta is not None else 0.5angle_score = _score(knee_rom / 65.0)rom_score = _score(angle_score * 0.55 + depth_score * 0.45)stability_score = _score(1.0 - stability_noise * 5.0)symmetry_score = _score(1.0 - symmetry_delta / 45.0)hip_x = _value_series(frames,lambda frame: average_axis(frame, ("left_hip", "right_hip"), "x"),)metrics = {"min_knee_angle_deg": _round(min_knee),"max_knee_angle_deg": _round(max_knee),"min_hip_angle_deg": _round(min_hip),"max_hip_angle_deg": _round(max_hip),"hip_depth_delta": _round(hip_depth_delta, 4),"hip_depth_relative_to_knee": ("below_parallel"if hip_depth_delta is not None and hip_depth_delta >= 0.03else "parallel"if hip_depth_delta is not None and hip_depth_delta >= -0.03else "above_parallel"),"max_torso_lean_deg": _round(_max(torso_lean)),"knee_valgus_proxy": _round(valgus_proxy, 4),"knee_tracking_score": _score(1.0 - (valgus_proxy or 0.0)),"stance_width_ratio": _round(stance_ratio, 3),"hip_shift": _round(_std(hip_x), 4),"bottom_stability_score": stability_score,}hints = []if stance_ratio is not None and stance_ratio > 1.35:hints.append("wide_squat_stance")elif stance_ratio is not None and stance_ratio < 0.85:hints.append("narrow_squat_stance")return metrics, rom_score, stability_score, symmetry_score, hintsdef _push_up_metrics(frames: list[PoseFrame]) -> ExerciseMetricResult:elbow_angles = _value_series(frames,lambda frame: _mean_pair(frame,("left_shoulder", "left_elbow", "left_wrist"),("right_shoulder", "right_elbow", "right_wrist"),),)elbow_deltas = _value_series(frames,lambda frame: _side_delta(frame,("left_shoulder", "left_elbow", "left_wrist"),("right_shoulder", "right_elbow", "right_wrist"),),)body_line = _value_series(frames, body_line_score)shoulder_y = _value_series(frames,lambda frame: average_axis(frame, ("left_shoulder", "right_shoulder"), "y"),)hip_y = _value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"))ankle_y = _value_series(frames,lambda frame: average_axis(frame, ("left_ankle", "right_ankle"), "y"),)hand_width = _value_series(frames, lambda frame: _width(frame, "left_wrist", "right_wrist"))shoulder_width = _value_series(frames,lambda frame: _width(frame, "left_shoulder", "right_shoulder"),)elbow_width = _value_series(frames, lambda frame: _width(frame, "left_elbow", "right_elbow"))knee_y = _value_series(frames,lambda frame: average_axis(frame, ("left_knee", "right_knee"), "y"),)min_elbow = _min(elbow_angles)max_elbow = _max(elbow_angles)elbow_rom = 0.0 if min_elbow is None or max_elbow is None else max_elbow - min_elbowchest_depth = _range(shoulder_y) or 0.0hand_width_ratio = _safe_ratio(_mean(hand_width), _mean(shoulder_width))elbow_flare = _safe_ratio(_mean(elbow_width), _mean(shoulder_width))body_line_mean = _mean(body_line)hip_sag_score = Noneif body_line_mean is not None:hip_sag_score = max(0.0, 1.0 - body_line_mean)knee_support_score = 0.0mean_knee_y = _mean(knee_y)mean_ankle_y = _mean(ankle_y)if mean_knee_y is not None and mean_ankle_y is not None:knee_support_score = _score(1.0 - abs(mean_ankle_y - mean_knee_y) / 0.18)rom_score = _score((elbow_rom / 80.0) * 0.65 + (chest_depth / 0.16) * 0.35)hip_stability = 1.0 - min(1.0, (_std(hip_y) or 0.0) * 4.0)stability_score = _score(((body_line_mean or 0.5) * 0.75) + hip_stability * 0.25)symmetry_score = _score(1.0 - ((_mean(elbow_deltas) or 0.0) / 45.0))metrics = {"min_elbow_angle_deg": _round(min_elbow),"max_elbow_angle_deg": _round(max_elbow),"body_line_score": _round(body_line_mean),"hip_sag_score": _round(hip_sag_score),"hip_pike_score": _round(max(0.0, ((body_line_mean or 1.0) - 1.0) * -1.0), 4),"chest_depth_proxy": _round(chest_depth, 4),"hand_width_ratio": _round(hand_width_ratio, 3),"elbow_flare_ratio": _round(elbow_flare, 3),"lockout_quality": _score(((max_elbow or 120.0) - 120.0) / 55.0),"knee_support_score": knee_support_score,}hints = []if hand_width_ratio is not None and hand_width_ratio > 1.45:hints.append("wide_grip_push_up")elif hand_width_ratio is not None and hand_width_ratio < 0.95:hints.append("close_grip_push_up")if knee_support_score >= 0.65:hints.append("knee_push_up")return metrics, rom_score, stability_score, symmetry_score, hintsdef _shoulder_press_metrics(frames: list[PoseFrame]) -> ExerciseMetricResult:elbow_angles = _value_series(frames,lambda frame: _mean_pair(frame,("left_shoulder", "left_elbow", "left_wrist"),("right_shoulder", "right_elbow", "right_wrist"),),)elbow_deltas = _value_series(frames,lambda frame: _side_delta(frame,("left_shoulder", "left_elbow", "left_wrist"),("right_shoulder", "right_elbow", "right_wrist"),),)wrist_y = _value_series(frames,lambda frame: average_axis(frame, ("left_wrist", "right_wrist"), "y"),)wrist_x = _value_series(frames,lambda frame: average_axis(frame, ("left_wrist", "right_wrist"), "x"),)left_wrist_y = _value_series(frames, lambda frame: landmark_axis(frame, "left_wrist", "y"))right_wrist_y = _value_series(frames, lambda frame: landmark_axis(frame, "right_wrist", "y"))wrist_asymmetry = [abs(left - right)for left, right in zip(left_wrist_y, right_wrist_y, strict=False)if left is not None and right is not None]shoulder_y = _value_series(frames,lambda frame: average_axis(frame, ("left_shoulder", "right_shoulder"), "y"),)hip_y = _value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"))min_elbow = _min(elbow_angles)max_elbow = _max(elbow_angles)wrist_travel = _range(wrist_y) or 0.0wrist_lateral_drift = _range(wrist_x) or 0.0lockout_quality = _score(((max_elbow or 120.0) - 120.0) / 55.0)verticality = _score(1.0 - wrist_lateral_drift / max(0.01, wrist_travel))asymmetry = mean(wrist_asymmetry) if wrist_asymmetry else 0.0back_arch_proxy = abs((_range(hip_y) or 0.0) - (_range(shoulder_y) or 0.0))rom_score = _score((wrist_travel / 0.28) * 0.55 + lockout_quality * 0.45)stability_score = _score(verticality * 0.65 + (1.0 - min(1.0, back_arch_proxy * 4.0)) * 0.35)symmetry_score = _score(1.0 - max(asymmetry * 5.0, (_mean(elbow_deltas) or 0.0) / 45.0))metrics = {"min_elbow_angle_deg": _round(min_elbow),"max_elbow_angle_deg": _round(max_elbow),"wrist_path_verticality": verticality,"lockout_quality": lockout_quality,"wrist_height_asymmetry": _round(asymmetry, 4),"left_right_wrist_delta": _round(asymmetry, 4),"back_arch_proxy": _round(back_arch_proxy, 4),"overhead_stability_score": stability_score,"wrist_travel": _round(wrist_travel, 4),}hints = []if lockout_quality < 0.65:hints.append("partial_press")if asymmetry > 0.12:hints.append("asymmetric_press")return metrics, rom_score, stability_score, symmetry_score, hintsdef _unknown_metrics(frames: list[PoseFrame]) -> ExerciseMetricResult:movement_signal = _value_series(frames,lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"),)movement = _range(movement_signal) or 0.0confidence = _mean_visibility(frames)metrics = {"movement_consistency_score": _score(1.0 - movement * 4.0),"landmark_confidence": confidence,}return metrics, 0.0, metrics["movement_consistency_score"], confidence, []def _exercise_metrics(exercise: str,frames: list[PoseFrame],) -> ExerciseMetricResult:if exercise == "squat":return _squat_metrics(frames)if exercise == "push_up":return _push_up_metrics(frames)if exercise == "shoulder_press":return _shoulder_press_metrics(frames)return _unknown_metrics(frames)def _primary_signal(exercise: str, frames: list[PoseFrame]) -> list[float | None]:if exercise == "shoulder_press":return _value_series(frames,lambda frame: average_axis(frame, ("left_wrist", "right_wrist"), "y"),)if exercise == "push_up":return _value_series(frames,lambda frame: _mean([average_axis(frame, ("left_shoulder", "right_shoulder"), "y"),average_axis(frame, ("left_hip", "right_hip"), "y"),]),)return _value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"))def _aggregate_numeric(items: list[RepAnalysisItem], metric_name: str) -> float | None:20 unmodified linesreps: Reps,sequence: PoseSequence,) -> RepAnalysis:draft_items: list[tuple[Rep, dict[str, Any], float, float, float, list[str]]] = []for rep in reps.reps:frames = _frames_for_rep(sequence, rep)primary_signal = _primary_signal(classification.exercise, frames)common_metrics = _common_metrics(rep, frames, primary_signal)exercise_metrics, rom_score, stability_score, symmetry_score, hints = _exercise_metrics(classification.exercise,frames,)metrics = {**common_metrics, **exercise_metrics}draft_items.append((rep, metrics, rom_score, stability_score, symmetry_score, hints))6 unmodified linesfor rep, metrics, rom_score, stability_score, symmetry_score, hints in draft_items:duration = metrics["rep_duration_sec"]metrics["tempo_consistency_score"] = (_score(1.0 - abs(duration - average_duration) / max(average_duration, 0.1))if average_durationelse 0.0)11 unmodified lines1213141516171819202122232425262728293031323334353637383916 unmodified lines5657585960616 unmodified lines68697071727374757677785 unmodified lines848586878889902 unmodified lines9394959697989929 unmodified lines1291301311321331341353 unmodified lines13914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017120 unmodified lines1921931941951961971981992002012022032046 unmodified lines21121221321421521621711 unmodified linesRepAnalysisItem,Reps,)from pozify.steps.exercise_analyzers import analyzer_forfrom pozify.steps.exercise_analyzers.base import (mean_optional,round_optional,safe_ratio,score,usable,value_series,)from pozify.steps.rep_signals import average_axisNumberGetter = Callable[[PoseFrame], float | None]def _std(values: list[float | None]) -> float | None:usable_values = usable(values)if len(usable_values) < 2:return 0.0 if usable_values else Nonereturn pstdev(usable_values)def _frames_for_rep(sequence: PoseSequence, rep: Rep) -> list[PoseFrame]:frames = [frame16 unmodified linesreturn [closest]def _mean_visibility(frames: list[PoseFrame]) -> float:values: list[float | None] = []for frame in frames:6 unmodified linesif landmark.get("visibility") is not None]values.extend(float(value) for value in landmark_values)return score(mean_optional(values) if values else 0.0)def _smoothness_score(signal_values: list[float | None]) -> tuple[float, float | None]:usable_values = usable(signal_values)if len(usable_values) < 4:return 0.5, None5 unmodified linesif not jerks:return 0.5, Nonejerk = mean(abs(value) for value in jerks)return score(1.0 - jerk * 8.0), jerkdef _pause_duration(2 unmodified lines*,target: str,) -> float:usable_values = usable(signal_values)if len(usable_values) < 3 or len(frames) < 3:return 0.029 unmodified linesconcentric_duration = round(max(0.0, rep.end_sec - rep.mid_sec), 2)duration = round(max(0.0, rep.end_sec - rep.start_sec), 2)smoothness_score, jerk_score = _smoothness_score(primary_signal)stability_axis = value_series(frames,lambda frame: average_axis(frame, ("left_hip", "right_hip"), "x"),)3 unmodified lines"rep_duration_sec": duration,"eccentric_duration_sec": eccentric_duration,"concentric_duration_sec": concentric_duration,"tempo_ratio": round_optional(safe_ratio(eccentric_duration, concentric_duration), 2),"top_pause_sec": _pause_duration(frames, primary_signal, target="top"),"bottom_pause_sec": _pause_duration(frames, primary_signal, target="bottom"),"smoothness_score": smoothness_score,"jerk_score": round_optional(jerk_score, 4),"landmark_confidence": _mean_visibility(frames),"hip_lateral_drift": round_optional(stability_noise, 4),}def _primary_signal(exercise: str, frames: list[PoseFrame]) -> list[float | None]:if exercise == "shoulder_press":return value_series(frames,lambda frame: average_axis(frame, ("left_wrist", "right_wrist"), "y"),)if exercise == "push_up":return value_series(frames,lambda frame: mean_optional([average_axis(frame, ("left_shoulder", "right_shoulder"), "y"),average_axis(frame, ("left_hip", "right_hip"), "y"),]),)return value_series(frames, lambda frame: average_axis(frame, ("left_hip", "right_hip"), "y"))def _aggregate_numeric(items: list[RepAnalysisItem], metric_name: str) -> float | None:20 unmodified linesreps: Reps,sequence: PoseSequence,) -> RepAnalysis:analyzer = analyzer_for(classification.exercise)draft_items: list[tuple[Rep, dict[str, Any], float, float, float, list[str]]] = []for rep in reps.reps:frames = _frames_for_rep(sequence, rep)primary_signal = _primary_signal(classification.exercise, frames)common_metrics = _common_metrics(rep, frames, primary_signal)exercise_metrics, rom_score, stability_score, symmetry_score, hints = analyzer.metrics(frames)metrics = {**common_metrics, **exercise_metrics}draft_items.append((rep, metrics, rom_score, stability_score, symmetry_score, hints))6 unmodified linesfor rep, metrics, rom_score, stability_score, symmetry_score, hints in draft_items:duration = metrics["rep_duration_sec"]metrics["tempo_consistency_score"] = (score(1.0 - abs(duration - average_duration) / max(average_duration, 0.1))if average_durationelse 0.0)
22 unmodified lines2324252627282922 unmodified linesknee_support = _metric(analysis, "avg_knee_support_score")not_issues: list[str] = []if knee_support is not None and knee_support >= 0.65:return "knee_push_up", _confidence(0.74, analysis, knee_support), ["knee_contact"]if hand_width is not None and hand_width >= 1.45:return "wide_grip_push_up", _confidence(0.72, analysis, hand_width), ["wide_hand_placement"]22 unmodified lines2324252627282922 unmodified linesknee_support = _metric(analysis, "avg_knee_support_score")not_issues: list[str] = []if knee_support is not None and knee_support >= 0.8:return "knee_push_up", _confidence(0.74, analysis, knee_support), ["knee_contact"]if hand_width is not None and hand_width >= 1.45:return "wide_grip_push_up", _confidence(0.72, analysis, hand_width), ["wide_hand_placement"]
2 unmodified lines34567845 unmodified lines54555657585947 unmodified lines10710810911011111236 unmodified lines1491501511521531542 unmodified linesfrom pathlib import Pathimport mathimport sysimport unittestsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))45 unmodified lines}def _squat_landmarks(depth: float, *, stance_ratio: float = 1.5) -> dict[str, dict[str, float]]:shoulder_width = 0.2stance_width = shoulder_width * stance_ratio47 unmodified lines)def _classification(exercise: str) -> ExerciseClassification:return ExerciseClassification(exercise=exercise,36 unmodified linesself.assertGreater(analysis.items[0].metrics["hand_width_ratio"], 1.45)self.assertIn("body_line_score", analysis.items[0].metrics)def test_squat_metrics_detect_wide_stance_variation(self) -> None:analysis = rep_analysis.run(_classification("squat"), _reps("squat"), _sequence("squat"))variation = variation_detector.run(_classification("squat"), analysis, _profile())2 unmodified lines345678945 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710847 unmodified lines15615715815916016116216316416516616716816917017117217317417536 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412 unmodified linesfrom pathlib import Pathimport mathimport sysfrom typing import Callableimport unittestsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))45 unmodified lines}def _knee_push_up_landmarks(depth: float, *, hand_ratio: float = 1.1) -> dict[str, dict[str, float]]:shoulder_y = 0.38 + depth * 0.16hip_y = 0.46 + depth * 0.16knee_y = hip_y + 0.03ankle_y = hip_y + 0.28elbow_y = 0.46 + depth * 0.1wrist_y = 0.5 + depth * 0.04shoulder_width = 0.4hand_width = shoulder_width * hand_ratioreturn {"left_shoulder": {"x": 0.3, "y": shoulder_y},"right_shoulder": {"x": 0.7, "y": shoulder_y},"left_elbow": {"x": 0.36 + depth * 0.02, "y": elbow_y},"right_elbow": {"x": 0.64 - depth * 0.02, "y": elbow_y},"left_wrist": {"x": 0.5 - hand_width / 2, "y": wrist_y},"right_wrist": {"x": 0.5 + hand_width / 2, "y": wrist_y},"left_hip": {"x": 0.42, "y": hip_y},"right_hip": {"x": 0.58, "y": hip_y},"left_knee": {"x": 0.44, "y": knee_y},"right_knee": {"x": 0.56, "y": knee_y},"left_ankle": {"x": 0.44, "y": ankle_y},"right_ankle": {"x": 0.56, "y": ankle_y},}def _straight_leg_push_up_landmarks(depth: float) -> dict[str, dict[str, float]]:shoulder_y = 0.38 + depth * 0.1hip_y = 0.46 + depth * 0.1knee_y = 0.5 + depth * 0.1ankle_y = 0.52 + depth * 0.1elbow_y = 0.46 + depth * 0.06wrist_y = 0.52 + depth * 0.02return {"left_shoulder": {"x": 0.3, "y": shoulder_y},"right_shoulder": {"x": 0.32, "y": shoulder_y},"left_elbow": {"x": 0.35, "y": elbow_y},"right_elbow": {"x": 0.37, "y": elbow_y},"left_wrist": {"x": 0.42, "y": wrist_y},"right_wrist": {"x": 0.44, "y": wrist_y},"left_hip": {"x": 0.58, "y": hip_y},"right_hip": {"x": 0.6, "y": hip_y},"left_knee": {"x": 0.72, "y": knee_y},"right_knee": {"x": 0.74, "y": knee_y},"left_ankle": {"x": 0.88, "y": ankle_y},"right_ankle": {"x": 0.9, "y": ankle_y},}def _squat_landmarks(depth: float, *, stance_ratio: float = 1.5) -> dict[str, dict[str, float]]:shoulder_width = 0.2stance_width = shoulder_width * stance_ratio47 unmodified lines)def _custom_sequence(landmark_factory: Callable[[float], dict[str, dict[str, float]]],) -> PoseSequence:frames = []for frame_index in range(25):frames.append(_frame(frame_index, landmark_factory(_wave(frame_index, 24))))return PoseSequence(frames=frames,normalized=True,smoothing_method="none",pose_valid_ratio=1.0,)def _classification(exercise: str) -> ExerciseClassification:return ExerciseClassification(exercise=exercise,36 unmodified linesself.assertGreater(analysis.items[0].metrics["hand_width_ratio"], 1.45)self.assertIn("body_line_score", analysis.items[0].metrics)def test_push_up_metrics_detect_knee_push_up_variation(self) -> None:analysis = rep_analysis.run(_classification("push_up"),_reps("push_up"),_custom_sequence(_knee_push_up_landmarks),)variation = variation_detector.run(_classification("push_up"), analysis, _profile())self.assertEqual(variation.detected_variation, "knee_push_up")self.assertIn("knee_contact", variation.not_issues)self.assertGreaterEqual(analysis.aggregate_metrics["avg_knee_support_score"], 0.8)def test_straight_leg_push_up_does_not_false_positive_as_knee_push_up(self) -> None:analysis = rep_analysis.run(_classification("push_up"),_reps("push_up"),_custom_sequence(_straight_leg_push_up_landmarks),)variation = variation_detector.run(_classification("push_up"), analysis, _profile())self.assertNotEqual(variation.detected_variation, "knee_push_up")self.assertNotIn("knee_contact", variation.not_issues)self.assertLess(analysis.aggregate_metrics["avg_knee_support_score"], 0.8)def test_squat_metrics_detect_wide_stance_variation(self) -> None:analysis = rep_analysis.run(_classification("squat"), _reps("squat"), _sequence("squat"))variation = variation_detector.run(_classification("squat"), analysis, _profile())
src/pozify/steps/exercise_analyzers/__init__.pyAdded+19
src/pozify/steps/exercise_analyzers/base.pyAdded+135
src/pozify/steps/exercise_analyzers/push_up.pyAdded+117
src/pozify/steps/exercise_analyzers/shoulder_press.pyAdded+89
src/pozify/steps/exercise_analyzers/squat.pyAdded+126
src/pozify/steps/exercise_analyzers/unknown.pyAdded+26
src/pozify/steps/rep_analysis.py+26-397
src/pozify/steps/variation_detector.py+1-1
tests/test_rep_analysis_variation.py+87