Merge branch 'main' into NLag/issue4
Browse filesFiles changed (6)
- README.md+5-5
- app.py+16-139
- src/pozify/pipeline.py-2
- src/pozify/steps/rep_analysis.py+601-20
- src/pozify/steps/variation_detector.py+114-10
- tests/test_rep_analysis_variation.pyAdded+196
167 unmodified lines1681691701711721731741751761771781791801811821831841851 unmodified line187188189190191192193167 unmodified lines## Adding ExercisesSupported exercise metadata is centralized in `src/pozify/exercise_catalog.py`. To add a new mockedexercise, add one `ExerciseSpec` with:- `key` and `display_name`- `default_variation` and confidence- `metric_factory` for mock per-rep metrics- optional `variation_hints`, default `not_issues`, and `mock_issue`The Gradio dropdown, profile validation, variation detector, rep analysis, and issue marker read fromthis catalog, so new exercises do not require changing each step just to become selectable. Realexercise-specific algorithms can still replace individual step implementations later while preservingthe same pipeline contracts.Recommended replacement order:1 unmodified line2. `pose_backends/`: add or refine pose model adapters such as MediaPipe or MMPose.3. `exercise_classifier.py`: load the exercise router model.4. `rep_counter.py`: implement exercise-specific state machines.5. `rep_analysis.py` and `issue_marker.py`: compute real metrics and issue scores.6. `annotated_renderer.py`: render skeleton overlays and issue highlights.7. `coach_summary.py`: call the selected small language model with retrieved knowledge cards.167 unmodified lines1681691701711721731741751761771781791801811821831841851 unmodified line187188189190191192193167 unmodified lines## Adding ExercisesSupported exercise metadata is centralized in `src/pozify/exercise_catalog.py`. To add a newexercise, add one `ExerciseSpec` with:- `key` and `display_name`- `default_variation` and confidence- `metric_factory` for legacy/mock fallback metadata- optional `variation_hints`, default `not_issues`, and `mock_issue`The Gradio dropdown, profile validation, variation detector, rep analysis, and issue marker read fromthis catalog, so new exercises do not require changing each step just to become selectable. Realexercise-specific rep metrics live in `src/pozify/steps/rep_analysis.py`; variation rules live in`src/pozify/steps/variation_detector.py`.Recommended replacement order:1 unmodified line2. `pose_backends/`: add or refine pose model adapters such as MediaPipe or MMPose.3. `exercise_classifier.py`: load the exercise router model.4. `rep_counter.py`: implement exercise-specific state machines.5. `issue_marker.py`: compute real issue scores and intervals from rep metrics.6. `annotated_renderer.py`: render skeleton overlays and issue highlights.7. `coach_summary.py`: call the selected small language model with retrieved knowledge cards.
26 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716 unmodified lines18418518618718818919034 unmodified lines22522622722822923023123223323423523621 unmodified lines25825926026126226326426 unmodified lines)QUALITY_GUIDANCE = {"too_short": "Record at least 10 seconds so the set contains enough movement context.","too_long": "Keep the clip under 60 seconds for the MVP analyzer.","too_dark": "Use brighter, even lighting and keep the body visible against the background.","too_blurry": "Stabilize the camera and avoid fast panning or heavy motion blur.","fps_too_low": "Use a camera mode with at least 15 FPS.","resolution_too_low": "Record at 480x360 or higher so joint positions are readable.","video_decode_failed": "Upload a playable video file; the current file could not be decoded.",}def _pretty_json(value: dict[str, Any]) -> str:return json.dumps(value, ensure_ascii=False, indent=2)def _quality_markdown(video_manifest: dict[str, Any]) -> str:warnings = video_manifest["quality_warnings"]if not warnings:return "## Video Quality\n\nNo quality warnings detected."warning_items = "\n".join(f"- `{warning}`: {QUALITY_GUIDANCE[warning]}" for warning in warnings)status = ("Analysis is blocked until the video can be decoded reliably."if not video_manifest["analysis_allowed"]else "Analysis completed, but capture quality may affect downstream feedback.")return f"""## Capture Quality{status}{warning_items}"""def _mock_status_markdown(report: dict[str, Any]) -> str:mock_steps = report["artifacts"].get("mock_steps", [])if not mock_steps:return ""steps = ", ".join(f"`{step}`" for step in mock_steps)return ("## Pipeline Status\n\n""The current run uses real video QC, pose extraction, rep segmentation, and annotated video rendering, "f"but these steps still use placeholders: {steps}.")def analyze_video(video_path: str | None,goal: str,experience_level: str,intended_exercise: str,intended_variation: str,limitations: list[str],equipment: str,) -> tuple[str | None, str, str, str]:result = run_pipeline(video_path=video_path,profile_input={"goal": goal,"experience_level": experience_level,"intended_exercise": intended_exercise,"intended_variation": intended_variation or None,"known_limitations": limitations,"equipment": equipment,},)report = result["final_report"]video_quality = _quality_markdown(report["video_manifest"])mock_status = _mock_status_markdown(report)summary = report["coach_summary"]if not report["video_manifest"]["analysis_allowed"]:markdown = f"""{video_quality}{mock_status}## Run- **Run ID:** `{report["run_id"]}`- **Saved report:** `{Path(result["run_dir"]) / "final_report.json"}`"""artifact_path = Path(result["run_dir"]) / "final_report.json"return (result["annotated_video_path"],markdown,_pretty_json(report),str(artifact_path),)fallback_note = ("\nRouter confidence is low or window predictions disagree. Select the exercise manually and rerun.\n"if report["exercise"]["fallback_required"]else "")markdown = f"""## Scan Summary| Signal | Result || --- | --- || Exercise router | {report["exercise"]["exercise"]} ({report["exercise"]["confidence"]:.0%}) || Router fallback required | {report["exercise"]["fallback_required"]} || Variation | {report["variation"]["detected_variation"]} ({report["variation"]["variation_confidence"]:.0%}) || Reps | {len(report["reps"]["reps"])} || Analysis mode | {report["artifacts"].get("analysis_mode", "unknown")} || Pose source | {report["artifacts"].get("pose_source", "unknown")} || Primary finding | {summary["main_findings"][0] if summary["main_findings"] else "No finding emitted"} || Run ID | `{report["run_id"]}` |{fallback_note}{mock_status}## Coach Notes{summary["summary"]}### What Went Well{chr(10).join(f"- {item}" for item in summary["what_went_well"])}### Top Fixes{chr(10).join(f"- {item}" for item in summary["top_fixes"])}### Next Session Plan{chr(10).join(f"- {item}" for item in summary["next_session_plan"])}{video_quality}"""artifact_path = Path(result["run_dir"]) / "final_report.json"return (result["annotated_video_path"],markdown,_pretty_json(report),str(artifact_path),)server = gr.Server(title="Pozify",summary="Video-based workout form review API",16 unmodified linesdef config() -> dict[str, Any]:return {"description": APP_DESCRIPTION,"goals": ["strength", "hypertrophy", "endurance", "mobility", "beginner_practice"],"experience_levels": ["beginner", "intermediate"],"exercises": ["auto", *USER_SELECTABLE_EXERCISES],"limitations": ["wrist_discomfort", "knee_discomfort", "shoulder_discomfort"],34 unmodified linestry:parsed_limitations = json.loads(limitations)except json.JSONDecodeError as exc:raise HTTPException(status_code=400, detail="Limitations must be valid JSON.") from excif not isinstance(parsed_limitations, list) or not all(isinstance(item, str) for item in parsed_limitations):raise HTTPException(status_code=400, detail="Limitations must be a JSON list of strings.")video_path: str | None = Noneif video is not None and video.filename:21 unmodified linesreturn {"run_id": result["run_id"],"run_dir": result["run_dir"],"annotated_video_url": _artifact_url(result["run_id"], result["annotated_video_path"]),"final_report_url": f"/api/artifacts/{result['run_id']}/final_report.json","report": result["final_report"],}26 unmodified lines27282930313216 unmodified lines4950515253545556575859606134 unmodified lines9697989910010110210310410510610710810911011121 unmodified lines13313413513613713813914014126 unmodified lines)server = gr.Server(title="Pozify",summary="Video-based workout form review API",16 unmodified linesdef config() -> dict[str, Any]:return {"description": APP_DESCRIPTION,"goals": ["strength","hypertrophy","endurance","mobility","beginner_practice",],"experience_levels": ["beginner", "intermediate"],"exercises": ["auto", *USER_SELECTABLE_EXERCISES],"limitations": ["wrist_discomfort", "knee_discomfort", "shoulder_discomfort"],34 unmodified linestry:parsed_limitations = json.loads(limitations)except json.JSONDecodeError as exc:raise HTTPException(status_code=400, detail="Limitations must be valid JSON.") from excif not isinstance(parsed_limitations, list) or not all(isinstance(item, str) for item in parsed_limitations):raise HTTPException(status_code=400, detail="Limitations must be a JSON list of strings.")video_path: str | None = Noneif video is not None and video.filename:21 unmodified linesreturn {"run_id": result["run_id"],"run_dir": result["run_dir"],"annotated_video_url": _artifact_url(result["run_id"], result["annotated_video_path"]),"final_report_url": f"/api/artifacts/{result['run_id']}/final_report.json","report": result["final_report"],}
94 unmodified lines959697989910010110294 unmodified lines)analysis_mode = "mock" if mock_mode else "real"mock_steps = ["rep_analysis","variation_detector","issue_marker","coach_summary","verifier",94 unmodified lines959697989910094 unmodified lines)analysis_mode = "mock" if mock_mode else "real"mock_steps = ["issue_marker","coach_summary","verifier",
123456789101112131415161718192021222324251 unmodified line272829303132333435363738394041424344454647484950515253545556from __future__ import annotationsfrom statistics import meanfrom typing import Anyfrom pozify.contracts import (ExerciseClassification,PoseSequence,RepAnalysis,RepAnalysisItem,Reps,)from pozify.exercise_catalog import get_exercise_specdef _clamp_score(value: float) -> float:return round(min(1.0, max(0.0, value)), 2)def _metrics_for_exercise(exercise: str, rep_id: int) -> dict[str, Any]:fatigue_penalty = max(0, rep_id - 3) * 0.08return get_exercise_spec(exercise).metric_factory(rep_id, fatigue_penalty)def run(1 unmodified linereps: Reps,sequence: PoseSequence,) -> RepAnalysis:items: list[RepAnalysisItem] = []exercise_spec = get_exercise_spec(classification.exercise)for rep in reps.reps:fatigue_penalty = max(0, rep.rep_id - 3) * 0.08items.append(RepAnalysisItem(rep_id=rep.rep_id,duration_sec=round(rep.end_sec - rep.start_sec, 2),range_of_motion_score=_clamp_score(0.88 - fatigue_penalty),stability_score=_clamp_score(0.86 - fatigue_penalty),symmetry_score=_clamp_score(0.9 - fatigue_penalty / 2),metrics=_metrics_for_exercise(classification.exercise, rep.rep_id),variation_hints=list(exercise_spec.variation_hints),))aggregate_metrics = {"avg_rom_score": round(mean(item.range_of_motion_score for item in items), 2) if items else 0.0,"avg_stability_score": round(mean(item.stability_score for item in items), 2) if items else 0.0,"avg_symmetry_score": round(mean(item.symmetry_score for item in items), 2) if items else 0.0,"pose_valid_ratio": sequence.pose_valid_ratio,"mock": True,}return RepAnalysis(exercise=classification.exercise,items=items,1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585591 unmodified line561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637from __future__ import annotationsfrom statistics import mean, pstdevfrom typing import Any, Callablefrom pozify.contracts import (ExerciseClassification,PoseFrame,PoseSequence,Rep,RepAnalysis,RepAnalysisItem,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 = [framefor frame in sequence.framesif rep.start_frame <= frame.frame_index <= rep.end_frame]if frames:return framesif not sequence.frames:return []closest = min(sequence.frames,key=lambda frame: min(abs(frame.frame_index - rep.start_frame),abs(frame.frame_index - rep.mid_frame),abs(frame.frame_index - rep.end_frame),),)return [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:if "mean_visibility" in frame.pose_quality:values.append(float(frame.pose_quality["mean_visibility"]))continuelandmark_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(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, Nonedeltas = [usable_values[index] - usable_values[index - 1]for index in range(1, len(usable_values))]jerks = [deltas[index] - deltas[index - 1] for index in range(1, len(deltas))]if not jerks:return 0.5, Nonejerk = mean(abs(value) for value in jerks)return _score(1.0 - jerk * 8.0), jerkdef _pause_duration(frames: list[PoseFrame],signal_values: list[float | None],*,target: str,) -> float:usable_values = _usable(signal_values)if len(usable_values) < 3 or len(frames) < 3:return 0.0min_value = min(usable_values)max_value = max(usable_values)tolerance = max((max_value - min_value) * 0.08, 0.01)if target == "bottom":active = [value is not None and value >= max_value - tolerance for value in signal_values]else:active = [value is not None and value <= min_value + tolerance for value in signal_values]longest = 0current = 0for item in active:if item:current += 1longest = max(longest, current)else:current = 0if longest <= 1:return 0.0frame_duration = (frames[-1].timestamp_sec - frames[0].timestamp_sec) / max(1, len(frames) - 1)return round(longest * frame_duration, 2)def _common_metrics(rep: Rep,frames: list[PoseFrame],primary_signal: list[float | None],) -> dict[str, Any]:eccentric_duration = round(max(0.0, rep.mid_sec - rep.start_sec), 2)concentric_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"),)stability_noise = _std(stability_axis) or 0.0return {"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:values = [item.metrics.get(metric_name)for item in itemsif isinstance(item.metrics.get(metric_name), (int, float))]if not values:return Nonereturn round(sum(float(value) for value in values) / len(values), 4)def _fatigue_trend(items: list[RepAnalysisItem]) -> float:if len(items) < 2:return 0.0first = items[0].range_of_motion_scorelast = items[-1].range_of_motion_scorereturn round(last - first, 4)def run(1 unmodified linereps: 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))average_duration = (mean(item[1]["rep_duration_sec"] for item in draft_items)if draft_itemselse 0.0)items: list[RepAnalysisItem] = []for 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)items.append(RepAnalysisItem(rep_id=rep.rep_id,duration_sec=duration,range_of_motion_score=rom_score,stability_score=stability_score,symmetry_score=symmetry_score,metrics=metrics,variation_hints=sorted(set(hints)),))aggregate_metrics = {"avg_rom_score": (round(mean(item.range_of_motion_score for item in items), 2) if items else 0.0),"avg_stability_score": (round(mean(item.stability_score for item in items), 2) if items else 0.0),"avg_symmetry_score": (round(mean(item.symmetry_score for item in items), 2) if items else 0.0),"avg_rep_duration_sec": (round(mean(item.duration_sec for item in items), 2) if items else 0.0),"avg_tempo_consistency_score": _aggregate_numeric(items, "tempo_consistency_score") or 0.0,"avg_landmark_confidence": (_aggregate_numeric(items, "landmark_confidence") or sequence.pose_valid_ratio),"fatigue_trend_rom_delta": _fatigue_trend(items),"pose_valid_ratio": sequence.pose_valid_ratio,}for metric_name in ("hand_width_ratio","stance_width_ratio","bottom_pause_sec","lockout_quality","wrist_height_asymmetry","wrist_travel","knee_support_score",):aggregate_value = _aggregate_numeric(items, metric_name)if aggregate_value is not None:aggregate_metrics[f"avg_{metric_name}"] = aggregate_valuereturn RepAnalysis(exercise=classification.exercise,items=items,
3 unmodified lines4567891011121314151617181920212223242526272829303132333 unmodified linesfrom pozify.exercise_catalog import get_exercise_specdef run(classification: ExerciseClassification,analysis: RepAnalysis,profile: UserProfile,) -> Variation:exercise_spec = get_exercise_spec(classification.exercise)if profile.intended_variation:variation = profile.intended_variationconfidence = 0.95else:variation = exercise_spec.default_variationconfidence = exercise_spec.default_variation_confidencenot_issues = (list(exercise_spec.default_variation_not_issues)if variation == exercise_spec.default_variationelse [])if analysis.aggregate_metrics.get("avg_rom_score", 1.0) < 0.7:not_issues.append("mock_low_rom_requires_user_intent_check")return Variation(exercise=classification.exercise,detected_variation=variation,variation_confidence=confidence,not_issues=not_issues,)3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361373 unmodified linesfrom pozify.exercise_catalog import get_exercise_specdef _metric(analysis: RepAnalysis, name: str) -> float | None:value = analysis.aggregate_metrics.get(name)if isinstance(value, (int, float)):return float(value)return Nonedef _confidence(base: float, analysis: RepAnalysis, supporting_metric: float | None) -> float:rep_bonus = min(0.12, len(analysis.items) * 0.03)metric_bonus = 0.0 if supporting_metric is None else min(0.1, abs(supporting_metric) * 0.03)pose_bonus = min(0.08, float(analysis.aggregate_metrics.get("pose_valid_ratio", 0.0)) * 0.08)return round(min(0.95, base + rep_bonus + metric_bonus + pose_bonus), 2)def _push_up_variation(analysis: RepAnalysis) -> tuple[str, float, list[str]]:hand_width = _metric(analysis, "avg_hand_width_ratio")knee_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"]if hand_width is not None and hand_width <= 0.95:return ("close_grip_push_up",_confidence(0.72, analysis, 1.0 - hand_width),["close_hand_placement"],)if hand_width is None:not_issues.append("hand_width_unverified")return "standard_push_up", _confidence(0.62, analysis, hand_width), not_issuesdef _squat_variation(analysis: RepAnalysis) -> tuple[str, float, list[str]]:stance_width = _metric(analysis, "avg_stance_width_ratio")bottom_pause = _metric(analysis, "avg_bottom_pause_sec")if bottom_pause is not None and bottom_pause >= 0.4:return "pause_squat", _confidence(0.76, analysis, bottom_pause), ["bottom_pause"]if stance_width is not None and stance_width >= 1.35:return "wide_squat_stance", _confidence(0.72, analysis, stance_width), ["wide_stance"]if stance_width is not None and stance_width <= 0.85:return ("narrow_squat_stance",_confidence(0.72, analysis, 1.0 - stance_width),["narrow_stance"],)not_issues = ["stance_width_unverified"] if stance_width is None else []return "normal_squat_stance", _confidence(0.62, analysis, stance_width), not_issuesdef _shoulder_press_variation(analysis: RepAnalysis) -> tuple[str, float, list[str]]:lockout_quality = _metric(analysis, "avg_lockout_quality")wrist_travel = _metric(analysis, "avg_wrist_travel")wrist_asymmetry = _metric(analysis, "avg_wrist_height_asymmetry")if wrist_asymmetry is not None and wrist_asymmetry >= 0.12:return ("asymmetric_press",_confidence(0.76, analysis, wrist_asymmetry),["intentional_asymmetry_check"],)if (lockout_quality is not None and lockout_quality <= 0.65) or (wrist_travel is not None and wrist_travel < 0.24):support = 1.0 - lockout_quality if lockout_quality is not None else wrist_travelreturn "partial_press", _confidence(0.72, analysis, support), ["partial_range_of_motion"]not_issues = ["lockout_unverified"] if lockout_quality is None else []return "standing_shoulder_press", _confidence(0.62, analysis, lockout_quality), not_issuesdef _detected_variation(classification: ExerciseClassification,analysis: RepAnalysis,) -> tuple[str, float, list[str]]:if classification.exercise == "push_up":return _push_up_variation(analysis)if classification.exercise == "squat":return _squat_variation(analysis)if classification.exercise == "shoulder_press":return _shoulder_press_variation(analysis)exercise_spec = get_exercise_spec(classification.exercise)return (exercise_spec.default_variation,exercise_spec.default_variation_confidence,list(exercise_spec.default_variation_not_issues),)def _profile_not_issues(variation: str) -> list[str]:mapping: dict[str, list[str]] = {"wide_grip_push_up": ["wide_hand_placement"],"close_grip_push_up": ["close_hand_placement"],"knee_push_up": ["knee_contact"],"wide_squat_stance": ["wide_stance"],"narrow_squat_stance": ["narrow_stance"],"pause_squat": ["bottom_pause"],"partial_press": ["partial_range_of_motion"],"asymmetric_press": ["intentional_asymmetry_check"],}return list(mapping.get(variation, []))def run(classification: ExerciseClassification,analysis: RepAnalysis,profile: UserProfile,) -> Variation:if profile.intended_variation:variation = profile.intended_variationconfidence = 0.95not_issues = _profile_not_issues(variation)else:variation, confidence, not_issues = _detected_variation(classification, analysis)if analysis.aggregate_metrics.get("avg_rom_score", 1.0) < 0.7:not_issues.append("low_rom_requires_user_intent_check")if analysis.aggregate_metrics.get("pose_valid_ratio", 1.0) < 0.8:not_issues.append("low_pose_confidence_limits_variation_call")return Variation(exercise=classification.exercise,detected_variation=variation,variation_confidence=confidence,not_issues=sorted(set(not_issues)),)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196from __future__ import annotations
from pathlib import Pathimport mathimport sysimport unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from pozify.contracts import ( ExerciseClassification, PoseFrame, PoseSequence, Rep, Reps, UserProfile,)from pozify.steps import rep_analysis, variation_detector
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) -> float: return (1.0 - math.cos(2.0 * math.pi * (frame_index / cycle_frames))) / 2.0
def _push_up_landmarks(depth: float, *, hand_ratio: float = 1.7) -> 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 shoulder_width = 0.4 hand_width = shoulder_width * hand_ratio return { "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_ankle": {"x": 0.44, "y": ankle_y}, "right_ankle": {"x": 0.56, "y": ankle_y}, }
def _squat_landmarks(depth: float, *, stance_ratio: float = 1.5) -> dict[str, dict[str, float]]: shoulder_width = 0.2 stance_width = shoulder_width * stance_ratio hip_y = 0.52 + depth * 0.22 shoulder_y = 0.28 + depth * 0.06 knee_y = 0.7 return { "left_shoulder": {"x": 0.4, "y": shoulder_y}, "right_shoulder": {"x": 0.6, "y": shoulder_y}, "left_hip": {"x": 0.43, "y": hip_y}, "right_hip": {"x": 0.57, "y": hip_y}, "left_knee": {"x": 0.43 + depth * 0.05, "y": knee_y}, "right_knee": {"x": 0.57 - depth * 0.05, "y": knee_y}, "left_ankle": {"x": 0.5 - stance_width / 2, "y": 0.92}, "right_ankle": {"x": 0.5 + stance_width / 2, "y": 0.92}, }
def _shoulder_press_landmarks(lift: float, *, partial: bool = True) -> dict[str, dict[str, float]]: wrist_top = 0.56 if partial else 0.42 wrist_y = 0.76 - lift * (0.76 - wrist_top) elbow_y = 0.6 - lift * 0.06 return { "left_shoulder": {"x": 0.42, "y": 0.42}, "right_shoulder": {"x": 0.58, "y": 0.42}, "left_elbow": {"x": 0.4 - lift * 0.02, "y": elbow_y}, "right_elbow": {"x": 0.6 + lift * 0.02, "y": elbow_y}, "left_wrist": {"x": 0.4, "y": wrist_y}, "right_wrist": {"x": 0.6, "y": wrist_y}, "left_hip": {"x": 0.44, "y": 0.74}, "right_hip": {"x": 0.56, "y": 0.74}, }
def _sequence(exercise: str) -> PoseSequence: frames = [] for frame_index in range(25): wave = _wave(frame_index, 24) if exercise == "push_up": landmarks = _push_up_landmarks(wave) elif exercise == "shoulder_press": landmarks = _shoulder_press_landmarks(wave) else: landmarks = _squat_landmarks(wave) frames.append(_frame(frame_index, landmarks)) return PoseSequence( frames=frames, normalized=True, smoothing_method="none", pose_valid_ratio=1.0, )
def _classification(exercise: str) -> ExerciseClassification: return ExerciseClassification( exercise=exercise, confidence=0.95, window_predictions=[], fallback_required=False, )
def _reps(exercise: str) -> Reps: return Reps( exercise=exercise, reps=[Rep(1, 0, 12, 24, 0.0, 0.4, 0.8)], partial_reps=[], )
def _profile() -> UserProfile: return UserProfile( goal="beginner_practice", experience_level="beginner", intended_exercise="auto", intended_variation=None, known_limitations=[], equipment="bodyweight", )
class RepAnalysisVariationTests(unittest.TestCase): def test_push_up_metrics_detect_wide_grip_variation(self) -> None: analysis = rep_analysis.run( _classification("push_up"), _reps("push_up"), _sequence("push_up"), ) variation = variation_detector.run(_classification("push_up"), analysis, _profile())
self.assertEqual(variation.detected_variation, "wide_grip_push_up") self.assertIn("wide_hand_placement", variation.not_issues) self.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())
self.assertEqual(variation.detected_variation, "wide_squat_stance") self.assertIn("wide_stance", variation.not_issues) self.assertGreater(analysis.items[0].metrics["stance_width_ratio"], 1.35) self.assertIn("min_knee_angle_deg", analysis.items[0].metrics)
def test_shoulder_press_metrics_detect_partial_press_variation(self) -> None: analysis = rep_analysis.run( _classification("shoulder_press"), _reps("shoulder_press"), _sequence("shoulder_press"), ) variation = variation_detector.run(_classification("shoulder_press"), analysis, _profile())
self.assertEqual(variation.detected_variation, "partial_press") self.assertIn("partial_range_of_motion", variation.not_issues) self.assertIn("lockout_quality", analysis.items[0].metrics) self.assertLess(analysis.aggregate_metrics["avg_wrist_travel"], 0.24)
def test_profile_intended_variation_overrides_metric_rule(self) -> None: profile = UserProfile( goal="beginner_practice", experience_level="beginner", intended_exercise="push_up", intended_variation="close_grip_push_up", known_limitations=[], equipment="bodyweight", ) analysis = rep_analysis.run( _classification("push_up"), _reps("push_up"), _sequence("push_up"), ) variation = variation_detector.run(_classification("push_up"), analysis, profile)
self.assertEqual(variation.detected_variation, "close_grip_push_up") self.assertEqual(variation.variation_confidence, 0.95) self.assertIn("close_hand_placement", variation.not_issues)
if __name__ == "__main__": unittest.main()README.md+5-5
app.py+16-139
src/pozify/pipeline.py-2
src/pozify/steps/rep_analysis.py+601-20
src/pozify/steps/variation_detector.py+114-10
tests/test_rep_analysis_variation.pyAdded+196