Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
3ee736f
1
Parent(s): 4b1e064
Automated Deploy: 3cef450938b366a5739995a2288af2ec45e2cf94
Browse files- AI-coach-agent/src/ai_coach/knowledge/swing_metrics.yaml +24 -0
- AI-coach-agent/src/ai_coach/swing_report/repository.py +8 -0
- AI-coach-agent/src/ai_coach/swing_report/schemas.py +6 -2
- AI-coach-agent/src/ai_coach/swing_report/service.py +51 -22
- AI-coach-agent/src/ai_coach/swing_report/text.py +8 -5
- AI-coach-agent/tests/test_swing_report_report.py +50 -11
- backend/app/main.py +46 -0
- backend/app/modules/sessions/summary.py +5 -3
- backend/docs/FRONTEND_INTEGRATION.md +278 -0
- backend/docs/openapi.json +0 -0
- backend/e2e/qa_sessions_reports.py +52 -24
- backend/tests/integration/test_health.py +10 -0
- backend/tests/integration/test_swing_reports.py +6 -4
AI-coach-agent/src/ai_coach/knowledge/swing_metrics.yaml
CHANGED
|
@@ -65,6 +65,11 @@ metrics:
|
|
| 65 |
practice_feel: Coil your shoulders just enough to feel ready, then let your hips start the turn.
|
| 66 |
drill_id: hit_09
|
| 67 |
drill_review: needs_coach_review
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
- metric_id: stride_relative_length
|
| 70 |
display_name: Stride Length
|
|
@@ -99,6 +104,11 @@ metrics:
|
|
| 99 |
practice_feel: Load back first, then let your front foot step toward the pitcher.
|
| 100 |
drill_id: hit_04
|
| 101 |
drill_review: needs_coach_review
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
- metric_id: hip_shoulder_separation_at_contact
|
| 104 |
display_name: Hip Shoulder Separation at Contact
|
|
@@ -132,6 +142,19 @@ metrics:
|
|
| 132 |
practice_feel: Stride, then press into the ground with your front leg as you turn.
|
| 133 |
drill_id: hit_12
|
| 134 |
drill_review: needs_coach_review
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
# Plain-language text per contract reason code: `limitation` on a measurement, `report` in data_quality.
|
| 137 |
reasons:
|
|
@@ -208,3 +231,4 @@ text:
|
|
| 208 |
headline_focus: "{subject} is the area to work on."
|
| 209 |
headline_all_on_target: Everything we could rate in this swing is in the typical range.
|
| 210 |
headline_nothing_rated: We could not rate this swing yet, but you can see what we measured below.
|
|
|
|
|
|
| 65 |
practice_feel: Coil your shoulders just enough to feel ready, then let your hips start the turn.
|
| 66 |
drill_id: hit_09
|
| 67 |
drill_review: needs_coach_review
|
| 68 |
+
maintain:
|
| 69 |
+
coach_message: Your hips and shoulders were set the way most hitters are when your front foot landed. Keep that timing by letting your hips start the turn while your shoulders stay closed.
|
| 70 |
+
practice_feel: Land with your front shoulder still pointed at the pitcher, then let your hips start the turn.
|
| 71 |
+
drill_id: hit_14
|
| 72 |
+
drill_review: needs_coach_review
|
| 73 |
|
| 74 |
- metric_id: stride_relative_length
|
| 75 |
display_name: Stride Length
|
|
|
|
| 104 |
practice_feel: Load back first, then let your front foot step toward the pitcher.
|
| 105 |
drill_id: hit_04
|
| 106 |
drill_review: needs_coach_review
|
| 107 |
+
maintain:
|
| 108 |
+
coach_message: Your step length matches what most hitters do. Keep the same easy step and land under control every swing.
|
| 109 |
+
practice_feel: Take the same short, quiet step and land softly on your front foot.
|
| 110 |
+
drill_id: hit_05
|
| 111 |
+
drill_review: needs_coach_review
|
| 112 |
|
| 113 |
- metric_id: hip_shoulder_separation_at_contact
|
| 114 |
display_name: Hip Shoulder Separation at Contact
|
|
|
|
| 142 |
practice_feel: Stride, then press into the ground with your front leg as you turn.
|
| 143 |
drill_id: hit_12
|
| 144 |
drill_review: needs_coach_review
|
| 145 |
+
maintain: # every rated result is on target and this is the area to keep sharp
|
| 146 |
+
coach_message: Your hips and shoulders lined up the way most hitters do when the bat met the ball. Keep that order by letting your hips lead the turn every swing.
|
| 147 |
+
practice_feel: Turn your back hip first and feel your chest follow a moment later.
|
| 148 |
+
drill_id: hit_08
|
| 149 |
+
drill_review: needs_coach_review
|
| 150 |
+
|
| 151 |
+
# The practice suggestion when nothing in the swing could be rated, so the player always has a drill.
|
| 152 |
+
general_focus:
|
| 153 |
+
display_name: General practice
|
| 154 |
+
coach_message: We could not rate this swing yet. Keep building a smooth, balanced swing with this drill, and film again from the side with your whole body in view.
|
| 155 |
+
practice_feel: Load slowly, step softly, and feel your hips start the turn.
|
| 156 |
+
drill_id: hit_04
|
| 157 |
+
drill_review: needs_coach_review
|
| 158 |
|
| 159 |
# Plain-language text per contract reason code: `limitation` on a measurement, `report` in data_quality.
|
| 160 |
reasons:
|
|
|
|
| 231 |
headline_focus: "{subject} is the area to work on."
|
| 232 |
headline_all_on_target: Everything we could rate in this swing is in the typical range.
|
| 233 |
headline_nothing_rated: We could not rate this swing yet, but you can see what we measured below.
|
| 234 |
+
headline_tentative: These results are close estimates from your video.
|
AI-coach-agent/src/ai_coach/swing_report/repository.py
CHANGED
|
@@ -125,9 +125,17 @@ def metric_registry() -> dict:
|
|
| 125 |
for side in ("above", "below"):
|
| 126 |
if m["directions"][side]["drill_id"] not in library:
|
| 127 |
raise ValueError(f"{m['metric_id']} {side}: drill not in drills.yaml")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
return data
|
| 129 |
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def coaching_rules_version() -> str:
|
| 132 |
return str(metric_registry()["version"])
|
| 133 |
|
|
|
|
| 125 |
for side in ("above", "below"):
|
| 126 |
if m["directions"][side]["drill_id"] not in library:
|
| 127 |
raise ValueError(f"{m['metric_id']} {side}: drill not in drills.yaml")
|
| 128 |
+
if m["maintain"]["drill_id"] not in library:
|
| 129 |
+
raise ValueError(f"{m['metric_id']} maintain: drill not in drills.yaml")
|
| 130 |
+
if data["general_focus"]["drill_id"] not in library:
|
| 131 |
+
raise ValueError("general_focus: drill not in drills.yaml")
|
| 132 |
return data
|
| 133 |
|
| 134 |
|
| 135 |
+
def general_focus() -> dict[str, Any]:
|
| 136 |
+
return metric_registry()["general_focus"]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
def coaching_rules_version() -> str:
|
| 140 |
return str(metric_registry()["version"])
|
| 141 |
|
AI-coach-agent/src/ai_coach/swing_report/schemas.py
CHANGED
|
@@ -131,6 +131,7 @@ class GroupReport(_Output):
|
|
| 131 |
group: MeasurementGroup
|
| 132 |
display_name: str
|
| 133 |
score: int | None
|
|
|
|
| 134 |
rating: Rating
|
| 135 |
rating_label: str
|
| 136 |
not_rated_reason: NotRatedReason | None
|
|
@@ -147,8 +148,10 @@ class Drill(_Output):
|
|
| 147 |
|
| 148 |
|
| 149 |
class FocusArea(_Output):
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
| 152 |
display_name: str
|
| 153 |
rating: Rating
|
| 154 |
rating_label: str
|
|
@@ -223,6 +226,7 @@ class SwingReport(_Output):
|
|
| 223 |
analysis_id: str
|
| 224 |
analysis_revision: int
|
| 225 |
overall_score: int | None
|
|
|
|
| 226 |
overview: Overview
|
| 227 |
groups: list[GroupReport]
|
| 228 |
focus_area: FocusArea | None
|
|
|
|
| 131 |
group: MeasurementGroup
|
| 132 |
display_name: str
|
| 133 |
score: int | None
|
| 134 |
+
score_is_tentative: bool
|
| 135 |
rating: Rating
|
| 136 |
rating_label: str
|
| 137 |
not_rated_reason: NotRatedReason | None
|
|
|
|
| 148 |
|
| 149 |
|
| 150 |
class FocusArea(_Output):
|
| 151 |
+
kind: Literal["fix", "maintain", "general"]
|
| 152 |
+
is_tentative: bool
|
| 153 |
+
metric_id: str | None
|
| 154 |
+
group: MeasurementGroup | None
|
| 155 |
display_name: str
|
| 156 |
rating: Rating
|
| 157 |
rating_label: str
|
|
|
|
| 226 |
analysis_id: str
|
| 227 |
analysis_revision: int
|
| 228 |
overall_score: int | None
|
| 229 |
+
overall_score_is_tentative: bool
|
| 230 |
overview: Overview
|
| 231 |
groups: list[GroupReport]
|
| 232 |
focus_area: FocusArea | None
|
AI-coach-agent/src/ai_coach/swing_report/service.py
CHANGED
|
@@ -128,7 +128,9 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 128 |
groups: list[dict] = []
|
| 129 |
for info in repo.groups():
|
| 130 |
members = [m for m in measurements if m["group"] == info["group"]]
|
| 131 |
-
|
|
|
|
|
|
|
| 132 |
reason = None
|
| 133 |
if group_score is None:
|
| 134 |
if not members:
|
|
@@ -139,24 +141,14 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 139 |
reason = "no_rated_measurements"
|
| 140 |
rating = rating_for(group_score)
|
| 141 |
groups.append({
|
| 142 |
-
"group": info["group"], "display_name": info["display_name"], "score": group_score,
|
|
|
|
| 143 |
"rating_label": RATING_LABELS.get(rating) or NOT_RATED_LABELS[reason], "not_rated_reason": reason,
|
| 144 |
"summary": "", "metric_ids": [m["metric_id"] for m in members],
|
| 145 |
})
|
| 146 |
overall = mean_score(g["score"] for g in groups)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
if m["status"] == "available" and m["rating"] in ("satisfactory", "off_target")]
|
| 150 |
-
focus = None
|
| 151 |
-
if candidates:
|
| 152 |
-
_, _, fm = min(candidates, key=lambda c: (c[0], c[1]))
|
| 153 |
-
direction = repo.metric_info(fm["metric_id"])["directions"][sides[fm["metric_id"]]]
|
| 154 |
-
focus = {
|
| 155 |
-
"metric_id": fm["metric_id"], "group": fm["group"], "display_name": fm["display_name"],
|
| 156 |
-
"rating": fm["rating"], "rating_label": fm["rating_label"], "coach_message": direction["coach_message"],
|
| 157 |
-
"practice_feel": direction["practice_feel"], "drill": repo.drill(direction["drill_id"]),
|
| 158 |
-
"evidence_metric_ids": [fm["metric_id"]],
|
| 159 |
-
}
|
| 160 |
|
| 161 |
# Rules text for every field, then the subset the model may reword.
|
| 162 |
rules: dict[str, str | None] = {}
|
|
@@ -178,18 +170,21 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 178 |
rules[f"group:{g['group']}"] = g["summary"]
|
| 179 |
groups_wanted.append(g["group"])
|
| 180 |
subjects = {info["group"]: info["subject"] for info in repo.groups()}
|
| 181 |
-
if focus
|
| 182 |
headline = (repo.text("headline_focus").format(subject=subjects[focus["group"]]) + " "
|
| 183 |
+ repo.metric_info(focus["metric_id"])["directions"][sides[focus["metric_id"]]]["headline"])
|
| 184 |
-
|
| 185 |
-
elif any(m["status"] == "available" and m["rating"] != NOT_RATED for m in measurements):
|
| 186 |
headline = repo.text("headline_all_on_target")
|
| 187 |
else:
|
| 188 |
headline = repo.text("headline_nothing_rated")
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
report: dict[str, Any] = {
|
| 191 |
"schema_version": REPORT_SCHEMA_VERSION, "analysis_id": parsed.analysis_id,
|
| 192 |
-
"analysis_revision": parsed.analysis_revision, "overall_score": overall,
|
|
|
|
| 193 |
"groups": groups, "focus_area": focus, "measurements": measurements,
|
| 194 |
"data_quality": _data_quality(parsed, measurements, notes, hand, hand_inferred),
|
| 195 |
}
|
|
@@ -200,8 +195,7 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 200 |
result = write_texts(facts, rules, settings, generator=generator, request_id=request_id)
|
| 201 |
texts = result.texts
|
| 202 |
report["overview"]["headline"] = texts["headline"]
|
| 203 |
-
|
| 204 |
-
focus["coach_message"] = texts["coach_message"]
|
| 205 |
for g in groups:
|
| 206 |
g["summary"] = texts.get(f"group:{g['group']}", g["summary"])
|
| 207 |
for m in measurements:
|
|
@@ -222,6 +216,41 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 222 |
return SwingReport.model_validate(report).model_dump(mode="json")
|
| 223 |
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
def _rules_group_summary(g: dict, by_id: dict[str, dict]) -> str:
|
| 226 |
reason = g["not_rated_reason"]
|
| 227 |
members = [by_id[k] for k in g["metric_ids"]]
|
|
@@ -235,7 +264,7 @@ def _rules_group_summary(g: dict, by_id: dict[str, dict]) -> str:
|
|
| 235 |
return repo.text("group_not_rated")
|
| 236 |
if g["rating"] == ON_TARGET:
|
| 237 |
return repo.text("group_on_target")
|
| 238 |
-
rated = [m for m in members if m["
|
| 239 |
worst = min(rated, key=lambda m: m["score"])
|
| 240 |
return worst["result_text"] or repo.text("group_on_target")
|
| 241 |
|
|
|
|
| 128 |
groups: list[dict] = []
|
| 129 |
for info in repo.groups():
|
| 130 |
members = [m for m in measurements if m["group"] == info["group"]]
|
| 131 |
+
# Limited (estimated) results count, but the score is then marked tentative so the app shows it as approximate.
|
| 132 |
+
rated = [m for m in members if m["score"] is not None]
|
| 133 |
+
group_score = mean_score(m["score"] for m in rated)
|
| 134 |
reason = None
|
| 135 |
if group_score is None:
|
| 136 |
if not members:
|
|
|
|
| 141 |
reason = "no_rated_measurements"
|
| 142 |
rating = rating_for(group_score)
|
| 143 |
groups.append({
|
| 144 |
+
"group": info["group"], "display_name": info["display_name"], "score": group_score,
|
| 145 |
+
"score_is_tentative": any(m["rating_is_tentative"] for m in rated), "rating": rating,
|
| 146 |
"rating_label": RATING_LABELS.get(rating) or NOT_RATED_LABELS[reason], "not_rated_reason": reason,
|
| 147 |
"summary": "", "metric_ids": [m["metric_id"] for m in members],
|
| 148 |
})
|
| 149 |
overall = mean_score(g["score"] for g in groups)
|
| 150 |
+
overall_tentative = any(g["score_is_tentative"] for g in groups if g["score"] is not None)
|
| 151 |
+
focus = _choose_focus(measurements, sides)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# Rules text for every field, then the subset the model may reword.
|
| 154 |
rules: dict[str, str | None] = {}
|
|
|
|
| 170 |
rules[f"group:{g['group']}"] = g["summary"]
|
| 171 |
groups_wanted.append(g["group"])
|
| 172 |
subjects = {info["group"]: info["subject"] for info in repo.groups()}
|
| 173 |
+
if focus["kind"] == "fix":
|
| 174 |
headline = (repo.text("headline_focus").format(subject=subjects[focus["group"]]) + " "
|
| 175 |
+ repo.metric_info(focus["metric_id"])["directions"][sides[focus["metric_id"]]]["headline"])
|
| 176 |
+
elif focus["kind"] == "maintain":
|
|
|
|
| 177 |
headline = repo.text("headline_all_on_target")
|
| 178 |
else:
|
| 179 |
headline = repo.text("headline_nothing_rated")
|
| 180 |
+
if overall_tentative and focus["kind"] != "general":
|
| 181 |
+
headline = f"{headline} {repo.text('headline_tentative')}"
|
| 182 |
+
rules["coach_message"] = focus["coach_message"]
|
| 183 |
|
| 184 |
report: dict[str, Any] = {
|
| 185 |
"schema_version": REPORT_SCHEMA_VERSION, "analysis_id": parsed.analysis_id,
|
| 186 |
+
"analysis_revision": parsed.analysis_revision, "overall_score": overall,
|
| 187 |
+
"overall_score_is_tentative": overall_tentative, "overview": {"headline": headline},
|
| 188 |
"groups": groups, "focus_area": focus, "measurements": measurements,
|
| 189 |
"data_quality": _data_quality(parsed, measurements, notes, hand, hand_inferred),
|
| 190 |
}
|
|
|
|
| 195 |
result = write_texts(facts, rules, settings, generator=generator, request_id=request_id)
|
| 196 |
texts = result.texts
|
| 197 |
report["overview"]["headline"] = texts["headline"]
|
| 198 |
+
focus["coach_message"] = texts["coach_message"]
|
|
|
|
| 199 |
for g in groups:
|
| 200 |
g["summary"] = texts.get(f"group:{g['group']}", g["summary"])
|
| 201 |
for m in measurements:
|
|
|
|
| 216 |
return SwingReport.model_validate(report).model_dump(mode="json")
|
| 217 |
|
| 218 |
|
| 219 |
+
def _choose_focus(measurements: list[dict], sides: dict[str, str | None]) -> dict:
|
| 220 |
+
"""Always one practice focus with a drill.
|
| 221 |
+
|
| 222 |
+
fix: the lowest-scoring result that is not on target. Exact (available) results come first; estimated (limited)
|
| 223 |
+
results are used only when no exact one needs work, and the focus is then marked tentative.
|
| 224 |
+
maintain: everything rated is on target; keep the first rated area sharp (exact results first).
|
| 225 |
+
general: nothing could be rated; a general practice drill.
|
| 226 |
+
"""
|
| 227 |
+
def pick(rows: list[tuple[int, dict]]) -> dict | None:
|
| 228 |
+
rows = sorted(rows, key=lambda r: (r[1]["rating_is_tentative"], r[1]["score"], r[0]))
|
| 229 |
+
return rows[0][1] if rows else None
|
| 230 |
+
|
| 231 |
+
indexed = list(enumerate(measurements))
|
| 232 |
+
needs_work = pick([(i, m) for i, m in indexed if m["rating"] in ("satisfactory", "off_target")])
|
| 233 |
+
if needs_work is not None:
|
| 234 |
+
direction = repo.metric_info(needs_work["metric_id"])["directions"][sides[needs_work["metric_id"]]]
|
| 235 |
+
return _focus("fix", needs_work, direction)
|
| 236 |
+
on_target = sorted((m for _, m in indexed if m["rating"] == ON_TARGET), key=lambda m: m["rating_is_tentative"])
|
| 237 |
+
if on_target:
|
| 238 |
+
return _focus("maintain", on_target[0], repo.metric_info(on_target[0]["metric_id"])["maintain"])
|
| 239 |
+
general = repo.general_focus()
|
| 240 |
+
return {"kind": "general", "is_tentative": False, "metric_id": None, "group": None,
|
| 241 |
+
"display_name": general["display_name"], "rating": NOT_RATED,
|
| 242 |
+
"rating_label": NOT_RATED_LABELS["no_rated_measurements"],
|
| 243 |
+
"coach_message": general["coach_message"], "practice_feel": general["practice_feel"],
|
| 244 |
+
"drill": repo.drill(general["drill_id"]), "evidence_metric_ids": []}
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _focus(kind: str, m: dict, advice: dict) -> dict:
|
| 248 |
+
return {"kind": kind, "is_tentative": m["rating_is_tentative"], "metric_id": m["metric_id"], "group": m["group"],
|
| 249 |
+
"display_name": m["display_name"], "rating": m["rating"], "rating_label": m["rating_label"],
|
| 250 |
+
"coach_message": advice["coach_message"], "practice_feel": advice["practice_feel"],
|
| 251 |
+
"drill": repo.drill(advice["drill_id"]), "evidence_metric_ids": [m["metric_id"]]}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
def _rules_group_summary(g: dict, by_id: dict[str, dict]) -> str:
|
| 255 |
reason = g["not_rated_reason"]
|
| 256 |
members = [by_id[k] for k in g["metric_ids"]]
|
|
|
|
| 264 |
return repo.text("group_not_rated")
|
| 265 |
if g["rating"] == ON_TARGET:
|
| 266 |
return repo.text("group_on_target")
|
| 267 |
+
rated = [m for m in members if m["score"] is not None]
|
| 268 |
worst = min(rated, key=lambda m: m["score"])
|
| 269 |
return worst["result_text"] or repo.text("group_on_target")
|
| 270 |
|
AI-coach-agent/src/ai_coach/swing_report/text.py
CHANGED
|
@@ -42,10 +42,12 @@ Rules for every string you write:
|
|
| 42 |
- Keep each finding's meaning exactly. For on_target results say the movement is in the typical range.
|
| 43 |
|
| 44 |
Fields:
|
| 45 |
-
- headline: at most twenty-five words. If
|
| 46 |
-
the finding is. If
|
|
|
|
| 47 |
- group_summaries: one sentence per listed group describing its measured results together.
|
| 48 |
-
- coach_message: two sentences about the focus
|
|
|
|
| 49 |
- measurements: for each listed metric, result_text (one sentence on what was seen) and coach_tip (one short
|
| 50 |
practice tip, or an empty string when tip_wanted is false).
|
| 51 |
|
|
@@ -305,8 +307,9 @@ def model_facts(report: dict[str, Any], findings: dict[str, str | None], subject
|
|
| 305 |
]
|
| 306 |
focus = report.get("focus_area")
|
| 307 |
return {
|
| 308 |
-
"focus": None if focus
|
| 309 |
-
"
|
|
|
|
| 310 |
"finding": findings.get(focus["metric_id"]), "practice_feel": focus["practice_feel"]},
|
| 311 |
"groups": groups,
|
| 312 |
"measurements": measurements,
|
|
|
|
| 42 |
- Keep each finding's meaning exactly. For on_target results say the movement is in the typical range.
|
| 43 |
|
| 44 |
Fields:
|
| 45 |
+
- headline: at most twenty-five words. If the focus kind is "fix", name the focus group as the area to work on and say
|
| 46 |
+
what the finding is. If it is "maintain", say everything rated is in the typical range. If any rated result is
|
| 47 |
+
approximate, say the results are approximate.
|
| 48 |
- group_summaries: one sentence per listed group describing its measured results together.
|
| 49 |
+
- coach_message: two sentences about the focus. For "fix": what happens and why changing it helps. For "maintain":
|
| 50 |
+
the movement is in the typical range and how the drill keeps it there. If the focus is approximate, say so gently.
|
| 51 |
- measurements: for each listed metric, result_text (one sentence on what was seen) and coach_tip (one short
|
| 52 |
practice tip, or an empty string when tip_wanted is false).
|
| 53 |
|
|
|
|
| 307 |
]
|
| 308 |
focus = report.get("focus_area")
|
| 309 |
return {
|
| 310 |
+
"focus": None if not focus or focus["kind"] == "general" else {
|
| 311 |
+
"kind": focus["kind"], "group": subjects[focus["group"]], "metric_id": focus["metric_id"],
|
| 312 |
+
"rating": focus["rating"], "approximate": focus["is_tentative"],
|
| 313 |
"finding": findings.get(focus["metric_id"]), "practice_feel": focus["practice_feel"]},
|
| 314 |
"groups": groups,
|
| 315 |
"measurements": measurements,
|
AI-coach-agent/tests/test_swing_report_report.py
CHANGED
|
@@ -58,7 +58,8 @@ def by_group(report: dict) -> dict[str, dict]:
|
|
| 58 |
def test_spec_example():
|
| 59 |
r = build(request_id="req_1")
|
| 60 |
assert r["schema_version"] == "1.0" and r["analysis_id"] == "analysis_001" and r["analysis_revision"] == 1
|
| 61 |
-
|
|
|
|
| 62 |
sep = by_metric(r)["hip_shoulder_separation_at_foot_down"]
|
| 63 |
assert (sep["score"], sep["rating"], sep["rating_label"], sep["display_value"]) == (55, "off_target", "Off Target", "3°")
|
| 64 |
assert sep["benchmark"] == {
|
|
@@ -75,12 +76,14 @@ def test_spec_example():
|
|
| 75 |
contact["benchmark"], contact["result_text"], contact["display_value"]) == (
|
| 76 |
"unavailable", None, "not_rated", "Not measured", "measurement_unavailable", None, None, None)
|
| 77 |
groups = by_group(r)
|
| 78 |
-
assert groups["stride"]["score"]
|
|
|
|
| 79 |
assert groups["balance_load"]["not_rated_reason"] == "no_measurements_available"
|
| 80 |
assert groups["balance_load"]["rating_label"] == "Not measured yet"
|
| 81 |
assert groups["contact_follow_through"]["not_rated_reason"] == "measurements_unavailable"
|
| 82 |
assert groups["contact_follow_through"]["rating_label"] == "Not measured"
|
| 83 |
focus = r["focus_area"]
|
|
|
|
| 84 |
assert focus["metric_id"] == "hip_shoulder_separation_at_foot_down"
|
| 85 |
assert focus["drill"] == {"drill_id": "hit_13", "name": "Front Shoulder In Tee",
|
| 86 |
"how": "Set the tee on the outer half. Keep your front shoulder pointed at the pitcher until "
|
|
@@ -111,27 +114,55 @@ def test_invalid_payload_raises_with_paths():
|
|
| 111 |
assert exc.value.problems == {"measurements[1].reasons": "A limited result needs at least one reason code."}
|
| 112 |
|
| 113 |
|
| 114 |
-
def
|
| 115 |
p = payload()
|
| 116 |
-
p["measurements"][0]["value"] = -15.0 # on target
|
| 117 |
p["measurements"][1]["value"] = 70.0 # limited and far off target
|
| 118 |
r = build(p)
|
| 119 |
stride = by_metric(r)["stride_relative_length"]
|
| 120 |
assert stride["rating"] == "off_target" and stride["rating_is_tentative"] is True
|
| 121 |
-
|
| 122 |
-
assert
|
| 123 |
-
assert r["
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
-
def
|
| 127 |
p = payload()
|
| 128 |
p["events"]["front_foot_down"].update(status="limited", reasons=["event_timing_uncertain"])
|
| 129 |
p["measurements"][0].update(status="limited", reasons=["required_event_limited"])
|
| 130 |
r = build(p)
|
| 131 |
stride = by_group(r)["stride"]
|
| 132 |
-
assert
|
| 133 |
-
|
| 134 |
-
assert r["
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
assert r["overview"]["headline"] == repo.text("headline_nothing_rated")
|
| 136 |
assert r["meta"]["text_source"] == "rules"
|
| 137 |
|
|
@@ -253,6 +284,14 @@ def test_registry_text_passes_guardrails():
|
|
| 253 |
for t in [*d["result_text"].values(), d["coach_tip"], d["practice_feel"]]:
|
| 254 |
assert check_text(t, "result") == [], t
|
| 255 |
assert check_text(d["coach_message"], "coach_message") == [], d["coach_message"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
for code in repo.metric_registry()["reasons"]:
|
| 257 |
for t in repo.reason_text(code).values():
|
| 258 |
assert set(check_text(t, "result")) <= set(SPEC_WORDING_OK.get(t, ())), t
|
|
|
|
| 58 |
def test_spec_example():
|
| 59 |
r = build(request_id="req_1")
|
| 60 |
assert r["schema_version"] == "1.0" and r["analysis_id"] == "analysis_001" and r["analysis_revision"] == 1
|
| 61 |
+
# Stride group = mean(separation 55, stride length 100, limited) = 78, marked approximate.
|
| 62 |
+
assert r["overall_score"] == 78 and r["overall_score_is_tentative"] is True
|
| 63 |
sep = by_metric(r)["hip_shoulder_separation_at_foot_down"]
|
| 64 |
assert (sep["score"], sep["rating"], sep["rating_label"], sep["display_value"]) == (55, "off_target", "Off Target", "3°")
|
| 65 |
assert sep["benchmark"] == {
|
|
|
|
| 76 |
contact["benchmark"], contact["result_text"], contact["display_value"]) == (
|
| 77 |
"unavailable", None, "not_rated", "Not measured", "measurement_unavailable", None, None, None)
|
| 78 |
groups = by_group(r)
|
| 79 |
+
assert (groups["stride"]["score"], groups["stride"]["rating"], groups["stride"]["score_is_tentative"]) == (
|
| 80 |
+
78, "satisfactory", True)
|
| 81 |
assert groups["balance_load"]["not_rated_reason"] == "no_measurements_available"
|
| 82 |
assert groups["balance_load"]["rating_label"] == "Not measured yet"
|
| 83 |
assert groups["contact_follow_through"]["not_rated_reason"] == "measurements_unavailable"
|
| 84 |
assert groups["contact_follow_through"]["rating_label"] == "Not measured"
|
| 85 |
focus = r["focus_area"]
|
| 86 |
+
assert (focus["kind"], focus["is_tentative"]) == ("fix", False)
|
| 87 |
assert focus["metric_id"] == "hip_shoulder_separation_at_foot_down"
|
| 88 |
assert focus["drill"] == {"drill_id": "hit_13", "name": "Front Shoulder In Tee",
|
| 89 |
"how": "Set the tee on the outer half. Keep your front shoulder pointed at the pitcher until "
|
|
|
|
| 114 |
assert exc.value.problems == {"measurements[1].reasons": "A limited result needs at least one reason code."}
|
| 115 |
|
| 116 |
|
| 117 |
+
def test_limited_counts_as_tentative_but_exact_results_lead_the_focus():
|
| 118 |
p = payload()
|
| 119 |
+
p["measurements"][0]["value"] = -15.0 # exact and on target
|
| 120 |
p["measurements"][1]["value"] = 70.0 # limited and far off target
|
| 121 |
r = build(p)
|
| 122 |
stride = by_metric(r)["stride_relative_length"]
|
| 123 |
assert stride["rating"] == "off_target" and stride["rating_is_tentative"] is True
|
| 124 |
+
group = by_group(r)["stride"]
|
| 125 |
+
assert group["score"] < 100 and group["score_is_tentative"] is True
|
| 126 |
+
assert r["overall_score_is_tentative"] is True
|
| 127 |
+
focus = r["focus_area"] # the only result needing work is an estimate, so it becomes a tentative focus
|
| 128 |
+
assert (focus["kind"], focus["metric_id"], focus["is_tentative"]) == ("fix", "stride_relative_length", True)
|
| 129 |
+
assert focus["drill"]["drill_id"]
|
| 130 |
|
| 131 |
|
| 132 |
+
def test_only_limited_values_still_score_tentatively():
|
| 133 |
p = payload()
|
| 134 |
p["events"]["front_foot_down"].update(status="limited", reasons=["event_timing_uncertain"])
|
| 135 |
p["measurements"][0].update(status="limited", reasons=["required_event_limited"])
|
| 136 |
r = build(p)
|
| 137 |
stride = by_group(r)["stride"]
|
| 138 |
+
assert stride["score"] is not None and stride["score_is_tentative"] is True and stride["not_rated_reason"] is None
|
| 139 |
+
assert r["overall_score"] == stride["score"] and r["overall_score_is_tentative"] is True
|
| 140 |
+
assert r["focus_area"]["kind"] == "fix" and r["focus_area"]["is_tentative"] is True
|
| 141 |
+
assert repo.text("headline_tentative") in r["overview"]["headline"]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_maintain_focus_when_everything_rated_is_on_target():
|
| 145 |
+
p = payload()
|
| 146 |
+
p["measurements"][0]["value"] = -15.0
|
| 147 |
+
r = build(p)
|
| 148 |
+
focus = r["focus_area"]
|
| 149 |
+
assert (focus["kind"], focus["rating"], focus["metric_id"]) == ("maintain", "on_target",
|
| 150 |
+
"hip_shoulder_separation_at_foot_down")
|
| 151 |
+
assert focus["drill"]["drill_id"] == repo.metric_info(focus["metric_id"])["maintain"]["drill_id"]
|
| 152 |
+
assert r["overview"]["headline"].startswith(repo.text("headline_all_on_target"))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_general_focus_when_nothing_can_be_rated():
|
| 156 |
+
p = payload()
|
| 157 |
+
for m, reason in zip(p["measurements"], ("required_landmarks_unusable", "scale_unknown", "contact_not_verified"),
|
| 158 |
+
strict=True):
|
| 159 |
+
m.update(value=None, status="unavailable", confidence=None, reasons=[reason])
|
| 160 |
+
r = build(p)
|
| 161 |
+
assert r["overall_score"] is None and r["overall_score_is_tentative"] is False
|
| 162 |
+
focus = r["focus_area"]
|
| 163 |
+
assert (focus["kind"], focus["metric_id"], focus["group"], focus["evidence_metric_ids"]) == (
|
| 164 |
+
"general", None, None, [])
|
| 165 |
+
assert focus["drill"]["drill_id"] == repo.general_focus()["drill_id"]
|
| 166 |
assert r["overview"]["headline"] == repo.text("headline_nothing_rated")
|
| 167 |
assert r["meta"]["text_source"] == "rules"
|
| 168 |
|
|
|
|
| 284 |
for t in [*d["result_text"].values(), d["coach_tip"], d["practice_feel"]]:
|
| 285 |
assert check_text(t, "result") == [], t
|
| 286 |
assert check_text(d["coach_message"], "coach_message") == [], d["coach_message"]
|
| 287 |
+
assert check_text(m["maintain"]["coach_message"], "coach_message") == [], m["maintain"]["coach_message"]
|
| 288 |
+
assert check_text(m["maintain"]["practice_feel"], "result") == [], m["maintain"]["practice_feel"]
|
| 289 |
+
general = repo.general_focus()
|
| 290 |
+
assert check_text(general["coach_message"], "coach_message") == []
|
| 291 |
+
assert check_text(general["practice_feel"], "result") == []
|
| 292 |
+
for key in ("headline_all_on_target", "headline_nothing_rated", "headline_tentative"):
|
| 293 |
+
assert check_text(repo.text(key), "headline") == [], key
|
| 294 |
+
assert check_text(repo.text("headline_all_on_target") + " " + repo.text("headline_tentative"), "headline") == []
|
| 295 |
for code in repo.metric_registry()["reasons"]:
|
| 296 |
for t in repo.reason_text(code).values():
|
| 297 |
assert set(check_text(t, "result")) <= set(SPEC_WORDING_OK.get(t, ())), t
|
backend/app/main.py
CHANGED
|
@@ -2,7 +2,10 @@
|
|
| 2 |
|
| 3 |
import uuid
|
| 4 |
|
|
|
|
| 5 |
from fastapi import FastAPI, Request
|
|
|
|
|
|
|
| 6 |
|
| 7 |
from app.core.config import get_settings
|
| 8 |
from app.core.errors import register_error_handlers
|
|
@@ -49,7 +52,50 @@ def create_app() -> FastAPI:
|
|
| 49 |
|
| 50 |
for router in ROUTERS:
|
| 51 |
app.include_router(router)
|
|
|
|
| 52 |
return app
|
| 53 |
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
app = create_app()
|
|
|
|
| 2 |
|
| 3 |
import uuid
|
| 4 |
|
| 5 |
+
from ai_coach.swing_report.schemas import SwingAnalysisPayload, SwingReport
|
| 6 |
from fastapi import FastAPI, Request
|
| 7 |
+
from fastapi.openapi.utils import get_openapi
|
| 8 |
+
from pydantic.json_schema import models_json_schema
|
| 9 |
|
| 10 |
from app.core.config import get_settings
|
| 11 |
from app.core.errors import register_error_handlers
|
|
|
|
| 52 |
|
| 53 |
for router in ROUTERS:
|
| 54 |
app.include_router(router)
|
| 55 |
+
app.openapi = lambda: _openapi(app)
|
| 56 |
return app
|
| 57 |
|
| 58 |
|
| 59 |
+
ERROR_SCHEMA = {
|
| 60 |
+
"type": "object", "required": ["error"],
|
| 61 |
+
"properties": {"error": {"type": "object", "required": ["code", "message"], "properties": {
|
| 62 |
+
"code": {"type": "string", "examples": ["VALIDATION", "NOT_FOUND", "PLAN_LIMIT"]},
|
| 63 |
+
"message": {"type": "string", "description": "Safe to show in the app"},
|
| 64 |
+
"fields": {"type": "object", "additionalProperties": {"type": "string"},
|
| 65 |
+
"description": "Field path -> problem, for validation errors"},
|
| 66 |
+
}}},
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _openapi(app: FastAPI) -> dict:
|
| 71 |
+
"""The generated schema, corrected to match what the API really returns (for client code generation)."""
|
| 72 |
+
if app.openapi_schema:
|
| 73 |
+
return app.openapi_schema
|
| 74 |
+
spec = get_openapi(title=app.title, version=app.version, routes=app.routes)
|
| 75 |
+
schemas = spec.setdefault("components", {}).setdefault("schemas", {})
|
| 76 |
+
schemas.pop("HTTPValidationError", None)
|
| 77 |
+
schemas.pop("ValidationError", None)
|
| 78 |
+
schemas["ErrorResponse"] = ERROR_SCHEMA
|
| 79 |
+
_, contract = models_json_schema([(SwingAnalysisPayload, "validation"), (SwingReport, "serialization")],
|
| 80 |
+
ref_template="#/components/schemas/{model}")
|
| 81 |
+
schemas.update(contract.get("$defs", {}))
|
| 82 |
+
error_ref = {"description": "Error", "content": {"application/json": {
|
| 83 |
+
"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}
|
| 84 |
+
for path, operations in spec["paths"].items():
|
| 85 |
+
for operation in operations.values():
|
| 86 |
+
responses = operation.setdefault("responses", {})
|
| 87 |
+
responses.pop("422", None)
|
| 88 |
+
responses.setdefault("400", error_ref)
|
| 89 |
+
responses.setdefault("default", error_ref)
|
| 90 |
+
if path == "/v1/sessions/{session_id}/swing-report":
|
| 91 |
+
operation["requestBody"] = {"required": True, "content": {"application/json": {
|
| 92 |
+
"schema": {"$ref": "#/components/schemas/SwingAnalysisPayload"}}}}
|
| 93 |
+
session_out = schemas.get("SessionOut", {}).get("properties", {})
|
| 94 |
+
if "report" in session_out:
|
| 95 |
+
session_out["report"] = {"anyOf": [{"$ref": "#/components/schemas/SwingReport"}, {"type": "null"}],
|
| 96 |
+
"description": "Null while status is pending"}
|
| 97 |
+
app.openapi_schema = spec
|
| 98 |
+
return spec
|
| 99 |
+
|
| 100 |
+
|
| 101 |
app = create_app()
|
backend/app/modules/sessions/summary.py
CHANGED
|
@@ -17,7 +17,7 @@ from app.modules.uploads.models import Upload
|
|
| 17 |
|
| 18 |
|
| 19 |
class FocusSummary(ResponseModel):
|
| 20 |
-
metric_id: str
|
| 21 |
display_name: str
|
| 22 |
drill_id: str | None
|
| 23 |
|
|
@@ -35,6 +35,7 @@ class SessionSummary(ResponseModel):
|
|
| 35 |
athlete_name: str
|
| 36 |
status: str
|
| 37 |
overall_score: int | None
|
|
|
|
| 38 |
focus: FocusSummary | None
|
| 39 |
review: ReviewSummary | None
|
| 40 |
thumbnail_url: str | None
|
|
@@ -59,7 +60,7 @@ def _focus(report: dict | None) -> FocusSummary | None:
|
|
| 59 |
focus = (report or {}).get("focus_area")
|
| 60 |
if not focus:
|
| 61 |
return None
|
| 62 |
-
return FocusSummary(metric_id=focus
|
| 63 |
drill_id=(focus.get("drill") or {}).get("drill_id"))
|
| 64 |
|
| 65 |
|
|
@@ -68,7 +69,8 @@ async def load_summaries(db: AsyncSession, storage: StorageClient, query: Select
|
|
| 68 |
return [
|
| 69 |
SessionSummary(
|
| 70 |
id=s.id, owner_id=s.owner_id, mode=s.mode, is_self=s.is_self, athlete_name=s.athlete.get("name", ""),
|
| 71 |
-
status=s.status, overall_score=s.overall_score,
|
|
|
|
| 72 |
review=ReviewSummary(coach_name=coach_name or "", at=reviewed_at) if reviewed_at else None,
|
| 73 |
thumbnail_url=storage.presign_get(thumb_key) if thumb_key else None, created_at=s.created_at,
|
| 74 |
)
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
class FocusSummary(ResponseModel):
|
| 20 |
+
metric_id: str | None # null for a general practice focus (nothing could be rated)
|
| 21 |
display_name: str
|
| 22 |
drill_id: str | None
|
| 23 |
|
|
|
|
| 35 |
athlete_name: str
|
| 36 |
status: str
|
| 37 |
overall_score: int | None
|
| 38 |
+
overall_score_is_tentative: bool
|
| 39 |
focus: FocusSummary | None
|
| 40 |
review: ReviewSummary | None
|
| 41 |
thumbnail_url: str | None
|
|
|
|
| 60 |
focus = (report or {}).get("focus_area")
|
| 61 |
if not focus:
|
| 62 |
return None
|
| 63 |
+
return FocusSummary(metric_id=focus.get("metric_id"), display_name=focus["display_name"],
|
| 64 |
drill_id=(focus.get("drill") or {}).get("drill_id"))
|
| 65 |
|
| 66 |
|
|
|
|
| 69 |
return [
|
| 70 |
SessionSummary(
|
| 71 |
id=s.id, owner_id=s.owner_id, mode=s.mode, is_self=s.is_self, athlete_name=s.athlete.get("name", ""),
|
| 72 |
+
status=s.status, overall_score=s.overall_score,
|
| 73 |
+
overall_score_is_tentative=bool((s.report or {}).get("overall_score_is_tentative")), focus=_focus(s.report),
|
| 74 |
review=ReviewSummary(coach_name=coach_name or "", at=reviewed_at) if reviewed_at else None,
|
| 75 |
thumbnail_url=storage.presign_get(thumb_key) if thumb_key else None, created_at=s.created_at,
|
| 76 |
)
|
backend/docs/FRONTEND_INTEGRATION.md
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Frontend integration guide (React Native app → Cognivision backend)
|
| 2 |
+
|
| 3 |
+
**Audience:** the frontend engineer or coding agent connecting the app to the backend.
|
| 4 |
+
|
| 5 |
+
**Goal:** replace the local AsyncStorage store (`src/store`, `AppContext`) with API calls. Every screen keeps calling the same context actions; only the store layer changes.
|
| 6 |
+
|
| 7 |
+
**Status:** all 4 milestones are implemented. They are verified end to end against the real Supabase database and DigitalOcean Spaces bucket (713 QA checks, `backend/e2e/`).
|
| 8 |
+
|
| 9 |
+
## 0. Sources of truth (read in this order)
|
| 10 |
+
|
| 11 |
+
| What | Where | Use it for |
|
| 12 |
+
|---|---|---|
|
| 13 |
+
| Machine-readable API | `backend/docs/openapi.json` (also served at `GET /openapi.json` in dev) | Generate TypeScript types. It reflects the real API: errors use the envelope in §3, and the swing report request and response are fully typed. |
|
| 14 |
+
| Swing report (the analysis result) | `AI-coach-agent/docs/SWING_REPORT_API.md` | How to render scores, ratings, groups, focus area and measurements |
|
| 15 |
+
| ML payload the app forwards | `backend/docs/reference/ml_contract_v1.md` | What the ML API returns and the app posts to us, unchanged |
|
| 16 |
+
| This guide | `backend/docs/FRONTEND_INTEGRATION.md` | Flows, mapping from the old store, rules, edge cases |
|
| 17 |
+
|
| 18 |
+
When this guide and `openapi.json` disagree, `openapi.json` wins. Please report the mismatch.
|
| 19 |
+
|
| 20 |
+
## 1. Conventions
|
| 21 |
+
|
| 22 |
+
- **Base URL:** `https://<api host>/v1/...` (deployment owns the host). Local development: `http://127.0.0.1:8000`.
|
| 23 |
+
- **JSON keys are `snake_case`** in requests and responses. Map them to camelCase in your API adapter if the app wants camelCase, and never send camelCase: unknown fields are rejected with 400.
|
| 24 |
+
- **Ids** are UUID strings. **Times** are ISO 8601 UTC; convert to local time for display.
|
| 25 |
+
- **Body measurements are metric** (`height_cm`, `weight_kg`). The account's `unit` only affects display.
|
| 26 |
+
- **Enums:**
|
| 27 |
+
- `role`: `player` | `coach`
|
| 28 |
+
- `focus`: `h` | `p` | `both`
|
| 29 |
+
- `mode`: `h` | `p`
|
| 30 |
+
- `bats`: `L` | `R` | `S`
|
| 31 |
+
- `throws`: `L` | `R`
|
| 32 |
+
- `level`: `youth` | `high_school` | `college` | `adult`. The old app used "High school" and similar labels; map them in the adapter.
|
| 33 |
+
- `unit`: `imperial` | `metric`
|
| 34 |
+
- **Lists** return `{ "items": [...], "next_cursor": "..." | null }`. Ask for the next page with `?cursor=<next_cursor>&limit=<1..200>` (default 50).
|
| 35 |
+
- **Retries:** `POST /v1/sessions` and `POST /v1/drill-logs` accept an `Idempotency-Key: <uuid>` header. Retrying with the same key and body returns the original response. The same key with a different body returns 409 `IDEMPOTENCY_KEY_REUSED`. Generate one key per user action and reuse it only for retries of that action.
|
| 36 |
+
- **Request id:** every response has an `X-Request-Id` header. Attach it to bug reports. You may send your own `X-Request-Id`.
|
| 37 |
+
|
| 38 |
+
## 2. Authentication and session restore
|
| 39 |
+
|
| 40 |
+
```
|
| 41 |
+
Authorization: Bearer <access_token>
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
All endpoints except `/v1/auth/*` (other than logout) need it.
|
| 45 |
+
|
| 46 |
+
| Step | Call | Notes |
|
| 47 |
+
|---|---|---|
|
| 48 |
+
| Sign up | `POST /v1/auth/register` `{email, password, role}` | 201 `{user, tokens}`. The password must be 8 to 128 characters. 409 `EMAIL_TAKEN`: show its message inline. |
|
| 49 |
+
| Sign in | `POST /v1/auth/login` `{email, password}` | 200 `{user, tokens}`. 401 `INVALID_CREDENTIALS`: show the message verbatim. 429 `RATE_LIMITED` after 10 failures a minute from one network. |
|
| 50 |
+
| Apple / Google | `POST /v1/auth/social` `{provider, id_token, role}` | 200 `{user, tokens, is_new}`. If `is_new` is true, route to the Role screen. 401 `INVALID_TOKEN`. |
|
| 51 |
+
| Restore on launch | `GET /v1/me` | Returns `{user, team, entitlement}`, which seeds Home, Profile, Roster and Team in one call. |
|
| 52 |
+
| Token expired | `POST /v1/auth/refresh` `{refresh_token}` | Returns new `{access_token, refresh_token, expires_in}`. **Store the new refresh token.** Refresh tokens rotate, and reusing an old one revokes the whole sign-in. |
|
| 53 |
+
| Sign out | `POST /v1/auth/logout` `{refresh_token}` and `DELETE /v1/devices/{push_token}` | Then clear the keychain and the local cache. |
|
| 54 |
+
| Forgot password | `POST /v1/auth/password/forgot` `{email}` | Always 202. Show "check your email". |
|
| 55 |
+
| Delete account | `DELETE /v1/me` | 204. Removes the account, its sessions and its media. Required by the app stores. |
|
| 56 |
+
|
| 57 |
+
**Token rules for the HTTP client:**
|
| 58 |
+
1. Keep `access_token` (valid about 30 minutes) in memory and `refresh_token` in the keychain, not AsyncStorage.
|
| 59 |
+
2. When a call fails with 401 `UNAUTHENTICATED`, call refresh **once** and retry the original request.
|
| 60 |
+
3. If refresh fails with 401 `TOKEN_REVOKED`, sign the user out to Welcome.
|
| 61 |
+
4. Allow only one refresh in flight: queue other requests behind it. Two parallel refreshes with the same token count as reuse and revoke the sign-in.
|
| 62 |
+
|
| 63 |
+
## 3. Errors (one shape everywhere)
|
| 64 |
+
|
| 65 |
+
```json
|
| 66 |
+
{ "error": { "code": "VALIDATION", "message": "Some fields are not valid.", "fields": { "profile.age": "Input should be less than or equal to 70" } } }
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
`message` is always safe to show. `fields` appears on validation errors, with keys as dotted paths (`marks.contact_frame`, `measurements[1].reasons`).
|
| 70 |
+
|
| 71 |
+
| HTTP | `code` | Where | What the app should do |
|
| 72 |
+
|---|---|---|---|
|
| 73 |
+
| 400 | `VALIDATION` | Any write | Show `fields` inline under the inputs |
|
| 74 |
+
| 400 | `TOKEN_INVALID` | Password reset | "This link has expired" |
|
| 75 |
+
| 401 | `UNAUTHENTICATED` | Any | Refresh once, then sign out |
|
| 76 |
+
| 401 | `INVALID_CREDENTIALS` | Login | Show the message |
|
| 77 |
+
| 401 | `TOKEN_REVOKED` | Refresh | Sign out |
|
| 78 |
+
| 401 | `INVALID_TOKEN` | Social sign-in | "Sign-in failed, try again" |
|
| 79 |
+
| 402 | `PLAN_LIMIT` | Create session, swing report | Show the upgrade alert. The message is "The free plan includes 3 analyses a week." |
|
| 80 |
+
| 403 | `FORBIDDEN` | Any | Not allowed. Coach endpoints called by a player, someone else's session, and so on. |
|
| 81 |
+
| 404 | `NOT_FOUND` | Any | "This session is gone" and similar |
|
| 82 |
+
| 404 | `TEAM_NOT_FOUND` | Lookup, join | Show the message |
|
| 83 |
+
| 404 | `PLAYER_NOT_ON_TEAM` | Coach player page | "Player not on your team" |
|
| 84 |
+
| 405 | `METHOD_NOT_ALLOWED` | Any | Bug in the client |
|
| 85 |
+
| 409 | `EMAIL_TAKEN`, `ROLE_LOCKED`, `STALE_REVISION`, `ANALYSIS_MISMATCH`, `IDEMPOTENCY_KEY_REUSED`, `RECEIPT_IN_USE` | See the flows | See the flows |
|
| 86 |
+
| 413 | `TOO_LARGE` | Uploads, swing report | "Clip too large" |
|
| 87 |
+
| 422 | `UPLOAD_MISSING`, `UPLOAD_INVALID` | Create session | Upload again, or record again |
|
| 88 |
+
| 422 | `INVALID_PAYLOAD` | Swing report | The ML payload broke the contract. Log `fields` and show "analysis failed, please re-film". |
|
| 89 |
+
| 422 | `MODE_NOT_SUPPORTED` | Swing report on pitching | "Pitching analysis is coming soon" |
|
| 90 |
+
| 422 | `RECEIPT_INVALID` | Billing | "Purchase could not be verified" |
|
| 91 |
+
| 429 | `RATE_LIMITED` | Login, forgot password, team lookup | "Too many attempts. Wait a minute." |
|
| 92 |
+
| 5xx | `INTERNAL` / `UNAVAILABLE` | Any | Generic retry message |
|
| 93 |
+
|
| 94 |
+
## 4. Store action → endpoint map
|
| 95 |
+
|
| 96 |
+
This replaces the local store behind `AppContext`; screens don't change.
|
| 97 |
+
|
| 98 |
+
| AppContext action (today) | Endpoint | Notes |
|
| 99 |
+
|---|---|---|
|
| 100 |
+
| `signUp(email, password, role)` | `POST /v1/auth/register` | |
|
| 101 |
+
| `signIn(email, password)` | `POST /v1/auth/login`, then `GET /v1/me` | |
|
| 102 |
+
| `signOut()` | `POST /v1/auth/logout` + `DELETE /v1/devices/{token}` | |
|
| 103 |
+
| `setRole(role)` | `PATCH /v1/me {role}` | 409 `ROLE_LOCKED` once the account has a team or a session |
|
| 104 |
+
| `setFocus(focus)` | `PATCH /v1/me {focus}` | |
|
| 105 |
+
| `updateProfile(patch)`, `setUnit(unit)` | `PATCH /v1/me {profile: {...}, unit}` | Inside `profile`, `null` clears a value. At the top level, `null` is rejected. |
|
| 106 |
+
| `setPrivateVideos(bool)` | `PATCH /v1/me {private_videos}` | It never blocks the coach (see §8) |
|
| 107 |
+
| `createTeam(name, coachName, coaching)` | `POST /v1/teams {name, coach_name, coaching}` | 201 the first time. A second call updates the team (200) and keeps the code and the members. |
|
| 108 |
+
| `findTeam(code)` | `GET /v1/teams/lookup?code=` | Debounce while typing. Matching ignores case and spaces. |
|
| 109 |
+
| `joinTeam(code)` | `POST /v1/teams/{code}/join` | Players only. Joining another team moves the player. |
|
| 110 |
+
| `leaveTeam()` | `DELETE /v1/me/team` | |
|
| 111 |
+
| `addSession(args)` | §5 flow: uploads, session, ML API, swing report | |
|
| 112 |
+
| `getSession(id)` | `GET /v1/sessions/{id}` | |
|
| 113 |
+
| `mySessions(mode)` | `GET /v1/sessions?mode=h&self=true` | Newest first |
|
| 114 |
+
| `deleteSession(id)` | `DELETE /v1/sessions/{id}` | The media is deleted immediately |
|
| 115 |
+
| `logSet(session, drill, reps)` | `POST /v1/drill-logs {session_id, drill_id, reps, day}` | `day` is the device's local date (YYYY-MM-DD) |
|
| 116 |
+
| `setsToday(drill)` / the 7-day dots | `GET /v1/drill-logs?from=&to=` | Count logs for the drill and today's date on the client. Range at most 90 days. |
|
| 117 |
+
| `roster` | `GET /v1/coach/roster` | |
|
| 118 |
+
| `sessionsOf(playerId)` | `GET /v1/coach/players/{id}/sessions?mode=` | |
|
| 119 |
+
| `queue` | `GET /v1/coach/queue?since=<local midnight as UTC ISO>` | Send `since` so "Reviewed today" matches the coach's day |
|
| 120 |
+
| `sendReview(sessionId, {cue, drill, verdicts})` | `POST /v1/sessions/{id}/review {cue, drill_id, verdicts}` | |
|
| 121 |
+
| `analysesLeft`, `setPlan` | `GET /v1/me/entitlement`, `POST /v1/billing/receipts` | |
|
| 122 |
+
| `loadSample()`, `resetAll()` | none | Dev only. Keep them local or remove them. |
|
| 123 |
+
|
| 124 |
+
Values the client computed before now come from the server:
|
| 125 |
+
- `team` comes from `GET /v1/me`.
|
| 126 |
+
- `roster`, `queue` and `analysesLeft` (`entitlement.left`) come from their endpoints.
|
| 127 |
+
- The session title number comes from `ordinal`, and the delta comes from `previous.overall_score`.
|
| 128 |
+
|
| 129 |
+
## 5. Recording a swing (the core flow)
|
| 130 |
+
|
| 131 |
+
The app calls the ML API itself. Our backend never calls the ML API: the app forwards the ML result to us.
|
| 132 |
+
|
| 133 |
+
```
|
| 134 |
+
1. POST /v1/uploads {kind:"video", content_type:"video/mp4"|"video/quicktime", size_bytes, duration_sec}
|
| 135 |
+
→ {upload_id, url, headers, expires_at}
|
| 136 |
+
PUT <url> with the file bytes and EXACTLY the returned headers (Content-Type) ← straight to storage
|
| 137 |
+
2. Same for the thumbnail: {kind:"thumbnail", content_type:"image/jpeg", size_bytes} (optional, recommended)
|
| 138 |
+
3. POST /v1/sessions (Idempotency-Key header)
|
| 139 |
+
{video_upload_id, thumbnail_upload_id, mode:"h", is_self:true, athlete:null, duration_sec, fps,
|
| 140 |
+
marks:{contact_frame, contact_offset, contact_source:"detected"|"suggested"|"manual",
|
| 141 |
+
stride_start_frame, stride_end_frame, pitcher_direction:{from:[x,y], to:[x,y]}}}
|
| 142 |
+
→ 201 {session} with status "pending", report null
|
| 143 |
+
4. Call the ML API (not ours) → contract 1.0 payload
|
| 144 |
+
5. POST /v1/sessions/{session.id}/swing-report with the ML payload, unchanged
|
| 145 |
+
→ 200 swing report (also saved on the session)
|
| 146 |
+
6. Show Result from the step 5 response (or GET /v1/sessions/{id}: report is the same object)
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
**Limits and rules:**
|
| 150 |
+
- **Video:** `video/mp4` or `video/quicktime`, at most 250 MB and 60 s. **Thumbnail:** `image/jpeg`, at most 5 MB. Presigned URLs expire after 15 minutes, so upload right away.
|
| 151 |
+
- **Uploaded files must match their type.** A JPEG sent as a video is rejected at step 3 with 422 `UPLOAD_INVALID`. If step 3 says `UPLOAD_MISSING`, the PUT never finished: retry the upload.
|
| 152 |
+
- **Marks:**
|
| 153 |
+
- `stride_start_frame < stride_end_frame < contact_frame`, all within `0 .. round(duration_sec*fps)-1`.
|
| 154 |
+
- `pitcher_direction` points are fractions of the frame, from 0 to 1, and at least 0.08 apart.
|
| 155 |
+
- Pitching labels map like this: leg lift is `stride_start_frame`, foot strike is `stride_end_frame`.
|
| 156 |
+
- **Athlete:**
|
| 157 |
+
- For `is_self: true`, send `athlete: null`; the server snapshots the profile.
|
| 158 |
+
- For someone else's swing, send `{name, age, height_cm, weight_kg, bats, throws, level}`; all are required.
|
| 159 |
+
- **Plan:** the free plan allows 3 analysed swings in a rolling 7 days, counting swings filmed for someone else. Step 3 returns 402 `PLAN_LIMIT` before anything is stored. Pending sessions that never get a report don't count, and are deleted with their media after 24 h.
|
| 160 |
+
- **No polling:** the Analyzing screen waits on steps 4 and 5. There is no `queued` or `processing` status: a session is `pending` until its report exists, then `done`.
|
| 161 |
+
- **Pitching:** step 5 returns 422 `MODE_NOT_SUPPORTED` until pitching measurements exist. Keep the pitching UI behind a "coming soon" state.
|
| 162 |
+
- **Re-analysis:** post a payload with a higher `analysis_revision` and the same `analysis_id`.
|
| 163 |
+
- Re-posting the same id and revision is safe: it returns the stored report.
|
| 164 |
+
- A lower revision returns 409 `STALE_REVISION`.
|
| 165 |
+
- A different `analysis_id` on the same session returns 409 `ANALYSIS_MISMATCH`.
|
| 166 |
+
- **Batting side:** the report uses the payload's `athlete.batting_hand`. When that is missing, it falls back to the session athlete's `bats`.
|
| 167 |
+
|
| 168 |
+
## 6. Rendering the swing report (Result, Phase and Recap screens)
|
| 169 |
+
|
| 170 |
+
The full field list is in `SWING_REPORT_API.md`. The app renders; it never computes scores or ratings.
|
| 171 |
+
|
| 172 |
+
### The old Session shape and the new one
|
| 173 |
+
|
| 174 |
+
| Old local shape | New field | Notes |
|
| 175 |
+
|---|---|---|
|
| 176 |
+
| `score` | `report.overall_score` (0–100 or null) | Null when nothing could be rated. Show "Not rated" and never 0. |
|
| 177 |
+
| `phases: [name, score][]` | `report.groups[]` | Always 4, in a fixed order: `balance_load`, `stride`, `power_move`, `contact_follow_through`. Each has `{display_name, score, rating, rating_label, summary}`. |
|
| 178 |
+
| `weak` | The lowest-scoring rated group, or `report.focus_area.group` | |
|
| 179 |
+
| `metrics[]` | `report.measurements[]` | `{metric_id, display_name, group, value, unit, display_value, score, rating, rating_label, rating_is_tentative, benchmark, what_it_means, result_text, coach_tip, limitations[]}` |
|
| 180 |
+
| `metric.grade` (`g`, `b`, `o`) | `rating`: `on_target`, `satisfactory`, `off_target`, `not_rated` | Colors: green, yellow, red, grey |
|
| 181 |
+
| `metric.band` / `target` | `benchmark.on_target {lower, upper}` and `benchmark.satisfactory` | Use them for a range bar. `value` sits on the same axis. |
|
| 182 |
+
| `metric.why` | `what_it_means` (meaning) and `result_text` (what we saw) | |
|
| 183 |
+
| `fixOrder[0]`, cue, drill | `report.focus_area {display_name, rating, coach_message, practice_feel, drill {drill_id, name, how, cue, reps}}` | Null when nothing needs work: show `overview.headline` instead |
|
| 184 |
+
| (none) | `report.overview.headline` | Show it as the coach bubble |
|
| 185 |
+
| (none) | `report.data_quality[] {code, severity, text}` | Always show, as a "Keep in mind" list |
|
| 186 |
+
| drill name as key | `drill_id` (for example `hit_13`) | Look up names with `GET /v1/catalog/metrics?mode=h`, or use `focus_area.drill` |
|
| 187 |
+
|
| 188 |
+
**Rendering rules:**
|
| 189 |
+
- **`not_rated`:** the group or measurement shows `rating_label` ("Not measured yet", "Not measured" or "Not rated") in grey. Never show a score.
|
| 190 |
+
- **`rating_is_tentative: true`:** the value was a model estimate. Show the rating with a "≈" or "approximate" hint, and always show `limitations[].text` under it.
|
| 191 |
+
- **Text fields are plain text with no numbers.** Numbers appear only in `value`, `display_value` and `benchmark`. Don't reword the text.
|
| 192 |
+
- **No video highlighting:** the report doesn't point at the video. For Recap timing, use the session's own `marks`.
|
| 193 |
+
- **`meta`** is for logs and support only. Don't show it.
|
| 194 |
+
|
| 195 |
+
## 7. Practice and history
|
| 196 |
+
|
| 197 |
+
- **History:** `GET /v1/sessions?mode=h&self=true&since=<ISO>` gives summaries with `{overall_score, focus {metric_id, display_name, drill_id}, review {coach_name, at}, thumbnail_url, status}`. Compute the trend, best, average and streak on the client from `overall_score` and `created_at`.
|
| 198 |
+
- **Title and delta:** `GET /v1/sessions/{id}` gives `ordinal` ("Swing 4"; only analysed swings are numbered) and `previous {id, overall_score, created_at}`. If `previous` is null, show the "First rep" badge.
|
| 199 |
+
- **Drill of the day:** use the latest session's `report.focus_area.drill`, or the coach's `review.drill_id` when the session was reviewed.
|
| 200 |
+
- **Logging a set:** `POST /v1/drill-logs`. `reps` is 1 to 8, and the 3-sets-a-day rule stays on the client.
|
| 201 |
+
- **Media URLs** (`media.video_url`, `thumbnail_url`) expire after `media.expires_at` (1 hour). If playback fails, fetch `GET /v1/sessions/{id}` again.
|
| 202 |
+
|
| 203 |
+
## 8. Coach
|
| 204 |
+
|
| 205 |
+
| Screen | Call | Notes |
|
| 206 |
+
|---|---|---|
|
| 207 |
+
| Roster | `GET /v1/coach/roster` | `{items: [{id, name, email, focus, level, pending_count, last: {h, p}, recent: {h: [scores], p: [...]}}]}`. `last.h` is `{session_id, overall_score, delta, created_at, focus_name}` or null ("Not filmed yet"). Compute the "Stuck" flag from `recent.h`. There is never any body data. |
|
| 208 |
+
| Queue | `GET /v1/coach/queue?since=` | `{open: [...oldest first], reviewed_today: [...]}`. Items are session summaries plus `owner_name`. |
|
| 209 |
+
| Player page | `GET /v1/coach/players/{id}/sessions?mode=` | Only analysed own swings |
|
| 210 |
+
| Review | `GET /v1/sessions/{id}` then `POST /v1/sessions/{id}/review` | See below |
|
| 211 |
+
|
| 212 |
+
**Review rules:**
|
| 213 |
+
- **Request body:** `{cue (1–200 characters), drill_id, verdicts: {metric_id: "agree"|"change"|"later"}}`.
|
| 214 |
+
- Verdict keys must be the report's `measurements[].metric_id`.
|
| 215 |
+
- `drill_id` must be a hitting drill for a hitting session.
|
| 216 |
+
- The first send returns 201. Sending again overwrites and returns 200.
|
| 217 |
+
- The player gets a push.
|
| 218 |
+
- **What the coach can see:** only the team's players' own swings, and only once analysed. Someone-else swings and pending swings return 403.
|
| 219 |
+
- **Body data is hidden:** in coach views of a session, `athlete` has no `age`, `height_cm` or `weight_kg`.
|
| 220 |
+
- **`private_videos`:** stored on the account, but it does not block the coach. The UI copy says "Only you and your coaches".
|
| 221 |
+
- **Leaving the team:** when a player leaves, their sessions disappear from the coach's views immediately.
|
| 222 |
+
|
| 223 |
+
## 9. Push notifications
|
| 224 |
+
|
| 225 |
+
- **Register:** after the user grants permission and after each sign-in, call `POST /v1/devices {platform: "ios"|"android", push_token}` with the FCM token (201, or 200 if already registered). Calling it again is safe. A token registered by another account moves to the current one.
|
| 226 |
+
- **Unregister:** on sign-out, `DELETE /v1/devices/{push_token}`.
|
| 227 |
+
- **Payload:** `data: {type: "review.received", session_id}` → open Result for `session_id`. It also carries a title and body notification. There is no `analysis.done` push, because the analysis is synchronous (§5).
|
| 228 |
+
|
| 229 |
+
## 10. Plan and billing
|
| 230 |
+
|
| 231 |
+
- **Entitlement:** `GET /v1/me/entitlement` (also inside `GET /v1/me`) returns `{plan: "free"|"pro", weekly_limit, used_this_week, left, window_days}`. `weekly_limit` and `left` are null on pro.
|
| 232 |
+
- **iOS (StoreKit 2):** after a purchase, `POST /v1/billing/receipts {platform:"ios", product_id:"pro_monthly", signed_transaction:<jwsRepresentation>}` returns `{entitlement}`.
|
| 233 |
+
- **Android:** `POST /v1/billing/receipts {platform:"android", product_id:"pro_monthly", purchase_token}`. The server acknowledges the purchase.
|
| 234 |
+
- **Errors:** 400 for a product that isn't allowed, 422 `RECEIPT_INVALID`, 409 `RECEIPT_IN_USE` (the purchase belongs to another account). Re-posting the same purchase is safe; use it for "Restore purchases".
|
| 235 |
+
- **Renewals, cancellations and refunds** come from store webhooks to the server. Refresh entitlement on app foreground.
|
| 236 |
+
|
| 237 |
+
## 11. Catalog
|
| 238 |
+
|
| 239 |
+
`GET /v1/catalog/metrics?mode=h` returns:
|
| 240 |
+
- `groups[] {group, display_name}`
|
| 241 |
+
- `metrics[] {metric_id, display_name, group, unit, what_it_means}`
|
| 242 |
+
- `drills[] {drill_id, name, how, cue, reps}`
|
| 243 |
+
|
| 244 |
+
Use it for drill names and the review drill picker. `mode=p` returns pitching drills only for now.
|
| 245 |
+
|
| 246 |
+
## 12. Differences from the original frontend spec
|
| 247 |
+
|
| 248 |
+
| Spec said | Backend does | Why |
|
| 249 |
+
|---|---|---|
|
| 250 |
+
| camelCase keys | snake_case | Backend convention; map in the adapter |
|
| 251 |
+
| `user.plan` | `entitlement.plan` | The plan comes from subscriptions, not from a field on the user |
|
| 252 |
+
| Session `status` queued, processing, done, failed; poll D3 | `pending` → `done`; synchronous swing report | The app runs the ML step itself |
|
| 253 |
+
| 10 metrics, 5 phases, grades `g/b/o` | 4 groups, the registered measurements, ratings | Matches the ML contract and the report spec |
|
| 254 |
+
| Drill names as keys | `drill_id` | Stable ids; names come from the catalog |
|
| 255 |
+
| Roster `joinedAt` | Not provided | Join time is not stored; show `email` when `name` is empty |
|
| 256 |
+
| D5 deletes after a lifecycle period | D5 deletes the media immediately | Privacy |
|
| 257 |
+
| `level` "High school" and similar labels | `high_school` and similar enum values | Map in the adapter |
|
| 258 |
+
| `pitcherDir` | `marks.pitcher_direction {from, to}` | |
|
| 259 |
+
| `contactSec`, `strideStartSec`, etc. | Not stored | Compute them as `frame / fps` |
|
| 260 |
+
|
| 261 |
+
## 13. Checklist per milestone
|
| 262 |
+
|
| 263 |
+
1. **Accounts and teams:**
|
| 264 |
+
- A1 register, A2 login, A4 refresh, A5 logout, B1 `GET /me`, B2 `PATCH /me`, and team create, lookup, join and leave all wired.
|
| 265 |
+
- Errors are shown inline.
|
| 266 |
+
- Tokens are in the keychain, with a single-flight refresh.
|
| 267 |
+
2. **Sessions:**
|
| 268 |
+
- Upload, PUT, session and swing-report flow wired, with an Idempotency-Key.
|
| 269 |
+
- Result renders from `report`.
|
| 270 |
+
- History, delete, drill logs and the plan alert on 402.
|
| 271 |
+
3. **Coach:**
|
| 272 |
+
- Roster, queue, player page and review wired.
|
| 273 |
+
- Device registration and the `review.received` deep link.
|
| 274 |
+
4. **Growth:**
|
| 275 |
+
- Social sign-in, forgot password, account deletion in Profile.
|
| 276 |
+
- StoreKit and Play purchases posted to `/billing/receipts`; catalog used for drill names.
|
| 277 |
+
|
| 278 |
+
To check the backend at any time: `cd backend && .venv/bin/python e2e/qa_sessions_reports.py` against a running API (see `backend/e2e/README.md`).
|
backend/docs/openapi.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/e2e/qa_sessions_reports.py
CHANGED
|
@@ -242,8 +242,8 @@ def post_report(acct, sid, body, **kw) -> httpx.Response:
|
|
| 242 |
return call("POST", f"/v1/sessions/{sid}/swing-report", acct["token"], json=body, **kw)
|
| 243 |
|
| 244 |
|
| 245 |
-
TOP_KEYS = {"schema_version", "analysis_id", "analysis_revision", "overall_score", "
|
| 246 |
-
"focus_area", "measurements", "data_quality", "meta"}
|
| 247 |
GROUP_ORDER = ["balance_load", "stride", "power_move", "contact_follow_through"]
|
| 248 |
|
| 249 |
|
|
@@ -307,32 +307,55 @@ def check_report_shape(name: str, r: httpx.Response) -> dict | None:
|
|
| 307 |
b = m.get("benchmark") or {}
|
| 308 |
check(f"{name}: rated {m['metric_id']} has benchmark population",
|
| 309 |
bool(b.get("population")) and "on_target" in b and "satisfactory" in b, r, json.dumps(b))
|
| 310 |
-
# group score = mean of
|
| 311 |
-
group_scores = []
|
| 312 |
for g in groups:
|
| 313 |
members = [by_id[mid] for mid in g.get("metric_ids", []) if mid in by_id]
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
|
|
|
| 317 |
expected = 99
|
| 318 |
-
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
| 320 |
check(f"{name}: group {g['group']} rating matches score", g.get("rating") == rating_for(g.get("score")), r)
|
| 321 |
if g.get("score") is not None:
|
| 322 |
group_scores.append(g["score"])
|
|
|
|
| 323 |
exp_overall = None if not group_scores else int(sum(group_scores) / len(group_scores) + 0.5)
|
| 324 |
-
if exp_overall == 100 and any(
|
| 325 |
exp_overall = 99
|
| 326 |
check(f"{name}: overall_score = mean of group scores ({exp_overall})", rep.get("overall_score") == exp_overall,
|
| 327 |
r, f"got {rep.get('overall_score')}")
|
|
|
|
| 328 |
fa = rep.get("focus_area")
|
|
|
|
| 329 |
if fa:
|
|
|
|
| 330 |
fm = by_id.get(fa.get("metric_id"), {})
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
bad = [(p, t) for p, t in text_fields(rep) if isinstance(t, str) and re.search(r"\d", t)]
|
| 337 |
check(f"{name}: no digits in text fields", not bad, r, f"digits in {bad}")
|
| 338 |
return rep
|
|
@@ -500,18 +523,20 @@ def run():
|
|
| 500 |
stride["score"] == 100 and stride["rating"] == "on_target" and stride["rating_is_tentative"] is True,
|
| 501 |
r, json.dumps({k: stride.get(k) for k in ("score", "rating", "rating_is_tentative")}))
|
| 502 |
check("spec: contact unavailable -> not_rated", contact["rating"] == "not_rated", r)
|
| 503 |
-
check("spec: overall_score
|
|
|
|
|
|
|
| 504 |
g = {x["group"]: x for x in rep1["groups"]}
|
| 505 |
-
check("spec: stride group
|
| 506 |
-
g["stride"]["rating"] == "
|
| 507 |
check("spec: balance_load not_rated no_measurements_available",
|
| 508 |
g["balance_load"]["not_rated_reason"] == "no_measurements_available"
|
| 509 |
and g["balance_load"]["metric_ids"] == [], r)
|
| 510 |
check("spec: contact group not_rated measurements_unavailable",
|
| 511 |
g["contact_follow_through"]["not_rated_reason"] == "measurements_unavailable", r)
|
| 512 |
fa = rep1.get("focus_area") or {}
|
| 513 |
-
check("spec: focus hip_shoulder_separation_at_foot_down with drill hit_13",
|
| 514 |
-
fa.get("metric_id") == "hip_shoulder_separation_at_foot_down"
|
| 515 |
and (fa.get("drill") or {}).get("drill_id") == "hit_13", r, json.dumps(fa)[:300])
|
| 516 |
check("spec: analysis_id/revision echoed", rep1["analysis_id"] == p1["analysis_id"]
|
| 517 |
and rep1["analysis_revision"] == 1, r)
|
|
@@ -544,8 +569,9 @@ def run():
|
|
| 544 |
check("revision 2 rebuilt (revision 2, new generated_at, separation now on_target)",
|
| 545 |
rep1v2["analysis_revision"] == 2 and rep1v2["meta"]["generated_at"] != rep1["meta"]["generated_at"]
|
| 546 |
and rep1v2["measurements"][0]["rating"] == "on_target", r)
|
| 547 |
-
check("all on
|
| 548 |
-
rep1v2["focus_area"]
|
|
|
|
| 549 |
rep1 = rep1v2
|
| 550 |
expect_error("revision 1 after 2 -> 409 STALE_REVISION", post_report(A, S1["id"], p1), 409, "STALE_REVISION")
|
| 551 |
p_other = copy.deepcopy(p2)
|
|
@@ -746,8 +772,10 @@ def run():
|
|
| 746 |
check("summary thumbnail_url downloads", g.status_code == 200 and g.content == JPEG_BYTES, None,
|
| 747 |
str(g.status_code))
|
| 748 |
if it1:
|
| 749 |
-
check("summary of S1 (all on target):
|
| 750 |
-
it1["focus"] is None and it1["
|
|
|
|
|
|
|
| 751 |
check("list ordered newest first", ids == [i["id"] for i in sorted(items, key=lambda x: (x["created_at"],
|
| 752 |
x["id"]), reverse=True)],
|
| 753 |
r)
|
|
|
|
| 242 |
return call("POST", f"/v1/sessions/{sid}/swing-report", acct["token"], json=body, **kw)
|
| 243 |
|
| 244 |
|
| 245 |
+
TOP_KEYS = {"schema_version", "analysis_id", "analysis_revision", "overall_score", "overall_score_is_tentative",
|
| 246 |
+
"overview", "groups", "focus_area", "measurements", "data_quality", "meta"}
|
| 247 |
GROUP_ORDER = ["balance_load", "stride", "power_move", "contact_follow_through"]
|
| 248 |
|
| 249 |
|
|
|
|
| 307 |
b = m.get("benchmark") or {}
|
| 308 |
check(f"{name}: rated {m['metric_id']} has benchmark population",
|
| 309 |
bool(b.get("population")) and "on_target" in b and "satisfactory" in b, r, json.dumps(b))
|
| 310 |
+
# group score = mean of every rated measurement score; limited ones count but mark the score tentative
|
| 311 |
+
group_scores, tentative_groups = [], []
|
| 312 |
for g in groups:
|
| 313 |
members = [by_id[mid] for mid in g.get("metric_ids", []) if mid in by_id]
|
| 314 |
+
rated = [m for m in members if m["score"] is not None]
|
| 315 |
+
scores = [m["score"] for m in rated]
|
| 316 |
+
expected = None if not scores else int(sum(scores) / len(scores) + 0.5)
|
| 317 |
+
if expected is not None and expected == 100 and any(x < 100 for x in scores):
|
| 318 |
expected = 99
|
| 319 |
+
label = f"{name}: group {g['group']} score = mean of rated (expected {expected}, got {g.get('score')})"
|
| 320 |
+
check(label, g.get("score") == expected, r)
|
| 321 |
+
tentative = any(m.get("rating_is_tentative") for m in rated)
|
| 322 |
+
check(f"{name}: group {g['group']} score_is_tentative = {tentative}",
|
| 323 |
+
g.get("score_is_tentative") is tentative, r)
|
| 324 |
check(f"{name}: group {g['group']} rating matches score", g.get("rating") == rating_for(g.get("score")), r)
|
| 325 |
if g.get("score") is not None:
|
| 326 |
group_scores.append(g["score"])
|
| 327 |
+
tentative_groups.append(tentative)
|
| 328 |
exp_overall = None if not group_scores else int(sum(group_scores) / len(group_scores) + 0.5)
|
| 329 |
+
if exp_overall == 100 and any(x < 100 for x in group_scores):
|
| 330 |
exp_overall = 99
|
| 331 |
check(f"{name}: overall_score = mean of group scores ({exp_overall})", rep.get("overall_score") == exp_overall,
|
| 332 |
r, f"got {rep.get('overall_score')}")
|
| 333 |
+
check(f"{name}: overall_score_is_tentative", rep.get("overall_score_is_tentative") is any(tentative_groups), r)
|
| 334 |
fa = rep.get("focus_area")
|
| 335 |
+
check(f"{name}: focus area always present with a drill", bool(fa and (fa.get("drill") or {}).get("drill_id")), r)
|
| 336 |
if fa:
|
| 337 |
+
kind = fa.get("kind")
|
| 338 |
fm = by_id.get(fa.get("metric_id"), {})
|
| 339 |
+
if kind == "fix":
|
| 340 |
+
needs_work = [m for m in ms if m.get("rating") in ("off_target", "satisfactory")]
|
| 341 |
+
exact_needs_work = [m for m in needs_work if not m.get("rating_is_tentative")]
|
| 342 |
+
check(f"{name}: fix focus is a non-on-target measurement, exact results first",
|
| 343 |
+
fm.get("rating") in ("off_target", "satisfactory")
|
| 344 |
+
and (not exact_needs_work or not fm.get("rating_is_tentative")), r,
|
| 345 |
+
f"focus={fa.get('metric_id')} rating={fm.get('rating')} tentative={fm.get('rating_is_tentative')}")
|
| 346 |
+
elif kind == "maintain":
|
| 347 |
+
check(f"{name}: maintain focus only when every rated result is on target",
|
| 348 |
+
fm.get("rating") == "on_target" and all(m.get("rating") in ("on_target", "not_rated") for m in ms), r)
|
| 349 |
+
elif kind == "general":
|
| 350 |
+
check(f"{name}: general focus only when nothing is rated",
|
| 351 |
+
fa.get("metric_id") is None and all(m.get("rating") == "not_rated" for m in ms), r)
|
| 352 |
+
else:
|
| 353 |
+
check(f"{name}: focus kind is fix, maintain or general", False, r, f"kind={kind}")
|
| 354 |
+
check(f"{name}: focus is_tentative matches its measurement",
|
| 355 |
+
fa.get("is_tentative") is bool(fm.get("rating_is_tentative")), r)
|
| 356 |
+
if fa.get("metric_id"):
|
| 357 |
+
check(f"{name}: focus evidence cites its metric",
|
| 358 |
+
fa.get("metric_id") in (fa.get("evidence_metric_ids") or []), r)
|
| 359 |
bad = [(p, t) for p, t in text_fields(rep) if isinstance(t, str) and re.search(r"\d", t)]
|
| 360 |
check(f"{name}: no digits in text fields", not bad, r, f"digits in {bad}")
|
| 361 |
return rep
|
|
|
|
| 523 |
stride["score"] == 100 and stride["rating"] == "on_target" and stride["rating_is_tentative"] is True,
|
| 524 |
r, json.dumps({k: stride.get(k) for k in ("score", "rating", "rating_is_tentative")}))
|
| 525 |
check("spec: contact unavailable -> not_rated", contact["rating"] == "not_rated", r)
|
| 526 |
+
check("spec: overall_score 78 tentative (stride length is an estimate)",
|
| 527 |
+
rep1["overall_score"] == 78 and rep1["overall_score_is_tentative"] is True, r,
|
| 528 |
+
str(rep1["overall_score"]))
|
| 529 |
g = {x["group"]: x for x in rep1["groups"]}
|
| 530 |
+
check("spec: stride group 78 satisfactory tentative", g["stride"]["score"] == 78 and
|
| 531 |
+
g["stride"]["rating"] == "satisfactory" and g["stride"]["score_is_tentative"] is True, r)
|
| 532 |
check("spec: balance_load not_rated no_measurements_available",
|
| 533 |
g["balance_load"]["not_rated_reason"] == "no_measurements_available"
|
| 534 |
and g["balance_load"]["metric_ids"] == [], r)
|
| 535 |
check("spec: contact group not_rated measurements_unavailable",
|
| 536 |
g["contact_follow_through"]["not_rated_reason"] == "measurements_unavailable", r)
|
| 537 |
fa = rep1.get("focus_area") or {}
|
| 538 |
+
check("spec: fix focus hip_shoulder_separation_at_foot_down with drill hit_13",
|
| 539 |
+
fa.get("kind") == "fix" and fa.get("metric_id") == "hip_shoulder_separation_at_foot_down"
|
| 540 |
and (fa.get("drill") or {}).get("drill_id") == "hit_13", r, json.dumps(fa)[:300])
|
| 541 |
check("spec: analysis_id/revision echoed", rep1["analysis_id"] == p1["analysis_id"]
|
| 542 |
and rep1["analysis_revision"] == 1, r)
|
|
|
|
| 569 |
check("revision 2 rebuilt (revision 2, new generated_at, separation now on_target)",
|
| 570 |
rep1v2["analysis_revision"] == 2 and rep1v2["meta"]["generated_at"] != rep1["meta"]["generated_at"]
|
| 571 |
and rep1v2["measurements"][0]["rating"] == "on_target", r)
|
| 572 |
+
check("all rated on target -> maintain focus with a drill and a headline",
|
| 573 |
+
(rep1v2["focus_area"] or {}).get("kind") == "maintain"
|
| 574 |
+
and bool(rep1v2["focus_area"]["drill"]["drill_id"]) and bool(rep1v2["overview"]["headline"]), r)
|
| 575 |
rep1 = rep1v2
|
| 576 |
expect_error("revision 1 after 2 -> 409 STALE_REVISION", post_report(A, S1["id"], p1), 409, "STALE_REVISION")
|
| 577 |
p_other = copy.deepcopy(p2)
|
|
|
|
| 772 |
check("summary thumbnail_url downloads", g.status_code == 200 and g.content == JPEG_BYTES, None,
|
| 773 |
str(g.status_code))
|
| 774 |
if it1:
|
| 775 |
+
check("summary of S1 (all on target): maintain focus, score from latest revision",
|
| 776 |
+
it1["focus"] is not None and it1["focus"]["drill_id"] == rep1["focus_area"]["drill"]["drill_id"]
|
| 777 |
+
and it1["overall_score"] == rep1["overall_score"]
|
| 778 |
+
and it1["overall_score_is_tentative"] is rep1["overall_score_is_tentative"], r, json.dumps(it1)[:300])
|
| 779 |
check("list ordered newest first", ids == [i["id"] for i in sorted(items, key=lambda x: (x["created_at"],
|
| 780 |
x["id"]), reverse=True)],
|
| 781 |
r)
|
backend/tests/integration/test_health.py
CHANGED
|
@@ -16,3 +16,13 @@ async def test_routing_errors_use_the_error_envelope(client):
|
|
| 16 |
response = await client.delete("/v1/auth/register")
|
| 17 |
assert response.status_code == 405
|
| 18 |
assert response.json()["error"]["code"] == "METHOD_NOT_ALLOWED"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
response = await client.delete("/v1/auth/register")
|
| 17 |
assert response.status_code == 405
|
| 18 |
assert response.json()["error"]["code"] == "METHOD_NOT_ALLOWED"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
async def test_openapi_documents_the_real_error_envelope_and_report(client):
|
| 22 |
+
spec = (await client.get("/openapi.json")).json()
|
| 23 |
+
schemas = spec["components"]["schemas"]
|
| 24 |
+
assert "HTTPValidationError" not in schemas and "ErrorResponse" in schemas
|
| 25 |
+
assert all("422" not in op["responses"] for ops in spec["paths"].values() for op in ops.values())
|
| 26 |
+
report_op = spec["paths"]["/v1/sessions/{session_id}/swing-report"]["post"]
|
| 27 |
+
assert report_op["requestBody"]["content"]["application/json"]["schema"]["$ref"].endswith("SwingAnalysisPayload")
|
| 28 |
+
assert schemas["SessionOut"]["properties"]["report"]["anyOf"][0]["$ref"].endswith("SwingReport")
|
backend/tests/integration/test_swing_reports.py
CHANGED
|
@@ -104,18 +104,20 @@ async def test_report_success_and_saved(client):
|
|
| 104 |
response = await client.post(url(sid), json=PAYLOAD, headers={**headers, "X-Request-Id": "req_test"})
|
| 105 |
assert response.status_code == 200, response.text
|
| 106 |
report = response.json()
|
| 107 |
-
|
|
|
|
| 108 |
assert [g["group"] for g in report["groups"]] == ["balance_load", "stride", "power_move", "contact_follow_through"]
|
| 109 |
assert report["focus_area"]["drill"]["drill_id"] == "hit_13"
|
| 110 |
assert report["measurements"][0]["benchmark"]["benchmark_id"] == (
|
| 111 |
"obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college")
|
| 112 |
assert report["meta"]["text_source"] == "rules" and report["meta"]["request_id"] == "req_test"
|
| 113 |
-
assert set(report) == {"schema_version", "analysis_id", "analysis_revision", "overall_score",
|
| 114 |
-
"
|
|
|
|
| 115 |
|
| 116 |
row = await load_session(sid)
|
| 117 |
assert row.report == report and row.measurement_payload == PAYLOAD
|
| 118 |
-
assert (row.analysis_id, row.analysis_revision, row.overall_score) == ("analysis_001", 1,
|
| 119 |
assert row.analyzed_at is not None
|
| 120 |
|
| 121 |
|
|
|
|
| 104 |
response = await client.post(url(sid), json=PAYLOAD, headers={**headers, "X-Request-Id": "req_test"})
|
| 105 |
assert response.status_code == 200, response.text
|
| 106 |
report = response.json()
|
| 107 |
+
# Stride length is an estimate, so it counts toward the score and marks it tentative.
|
| 108 |
+
assert report["overall_score"] == 78 and report["overall_score_is_tentative"] is True
|
| 109 |
assert [g["group"] for g in report["groups"]] == ["balance_load", "stride", "power_move", "contact_follow_through"]
|
| 110 |
assert report["focus_area"]["drill"]["drill_id"] == "hit_13"
|
| 111 |
assert report["measurements"][0]["benchmark"]["benchmark_id"] == (
|
| 112 |
"obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college")
|
| 113 |
assert report["meta"]["text_source"] == "rules" and report["meta"]["request_id"] == "req_test"
|
| 114 |
+
assert set(report) == {"schema_version", "analysis_id", "analysis_revision", "overall_score",
|
| 115 |
+
"overall_score_is_tentative", "overview", "groups", "focus_area", "measurements",
|
| 116 |
+
"data_quality", "meta"}
|
| 117 |
|
| 118 |
row = await load_session(sid)
|
| 119 |
assert row.report == report and row.measurement_payload == PAYLOAD
|
| 120 |
+
assert (row.analysis_id, row.analysis_revision, row.overall_score) == ("analysis_001", 1, 78)
|
| 121 |
assert row.analyzed_at is not None
|
| 122 |
|
| 123 |
|