github-actions[bot] commited on
Commit
f9655f6
·
1 Parent(s): cf86ef2

Automated Deploy: f8d0a1c175bd44875ba46fbe487133af20eb459b

Browse files
AI-coach-agent/src/ai_coach/pitch_report/v1_1/coaching.py CHANGED
@@ -75,6 +75,8 @@ these headings. Do not warn of over-rotation, early opening, or prescribe keepin
75
  Do not prescribe or grade moving smoothly, naturally, without rushing, or without an intentional stretch.
76
  Those cues are not established by these estimates. For an uncertain movement, ask the player to inspect the
77
  specific visible action without implying which outcome is correct.
 
 
78
  Unknown capture timing does NOT hide the visible chronological order of phases. It hides physical durations
79
  and speed-based peak ordering. Variable frame rates are supported using actual capture timestamps; constant FPS
80
  is NOT required. Advise preserving the original recording and documenting capture/export speed, not relying on
@@ -279,7 +281,7 @@ def generate_coaching(p, rubric, *, settings=None, generator=None, request_id=No
279
  review_status="automated_evidence_check",
280
  evidence_mode=(
281
  "visual_observations_and_motion"
282
- if p.visual_evidence and p.visual_evidence.observations
283
  else "video_derived_measurements_and_motion"
284
  ),
285
  ).model_dump(mode="json"), meta
 
75
  Do not prescribe or grade moving smoothly, naturally, without rushing, or without an intentional stretch.
76
  Those cues are not established by these estimates. For an uncertain movement, ask the player to inspect the
77
  specific visible action without implying which outcome is correct.
78
+ Do not describe physical acceleration, deceleration, or arm speed from visual observations. The visual facts
79
+ describe body movement; they do not measure its physical rate. Never turn an unclear visual topic into confirmation.
80
  Unknown capture timing does NOT hide the visible chronological order of phases. It hides physical durations
81
  and speed-based peak ordering. Variable frame rates are supported using actual capture timestamps; constant FPS
82
  is NOT required. Advise preserving the original recording and documenting capture/export speed, not relying on
 
281
  review_status="automated_evidence_check",
282
  evidence_mode=(
283
  "visual_observations_and_motion"
284
+ if p.visual_evidence and any(o.status == "observed" for o in p.visual_evidence.observations)
285
  else "video_derived_measurements_and_motion"
286
  ),
287
  ).model_dump(mode="json"), meta
AI-coach-agent/src/ai_coach/pitch_report/v1_1/evidence.py CHANGED
@@ -19,6 +19,8 @@ def visual_claim_issues(description: str) -> list[str]:
19
  issues.append("Anatomical/screen side ambiguity: use front/back leg and throwing/glove arm, not left/right.")
20
  if re.search(r"\b(?:target|catcher|plate)\b", description, re.I):
21
  issues.append("Target direction was not established; describe relative visible body movement.")
 
 
22
  if re.search(
23
  r"\b(?:weight|balance|balanced|momentum|layback|deceleration|efficient|effective|smooth(?:ly)?|correct|incorrect|good|bad|excessive|deficient|rushed)\b",
24
  description,
@@ -34,6 +36,12 @@ class VisualObservation(Strict):
34
  description: str = Field(min_length=1, max_length=600)
35
  evidence_frames: list[int] = Field(min_length=2, max_length=8)
36
 
 
 
 
 
 
 
37
 
38
  class VisualEvidence(Strict):
39
  status: Literal["provisional", "unavailable"]
 
19
  issues.append("Anatomical/screen side ambiguity: use front/back leg and throwing/glove arm, not left/right.")
20
  if re.search(r"\b(?:target|catcher|plate)\b", description, re.I):
21
  issues.append("Target direction was not established; describe relative visible body movement.")
22
+ if re.search(r"\b(?:accelerat\w*|decelerat\w*|speed\w*|faster|slower|quickly|rapidly)\b", description, re.I):
23
+ issues.append("Physical speed or acceleration was not measured; describe movement without a rate claim.")
24
  if re.search(
25
  r"\b(?:weight|balance|balanced|momentum|layback|deceleration|efficient|effective|smooth(?:ly)?|correct|incorrect|good|bad|excessive|deficient|rushed)\b",
26
  description,
 
36
  description: str = Field(min_length=1, max_length=600)
37
  evidence_frames: list[int] = Field(min_length=2, max_length=8)
38
 
39
+ @model_validator(mode="after")
40
+ def unclear_is_not_an_assertion(self):
41
+ if self.status == "unclear":
42
+ self.description = "This movement could not be confirmed from the sampled frames."
43
+ return self
44
+
45
 
46
  class VisualEvidence(Strict):
47
  status: Literal["provisional", "unavailable"]
AI-coach-agent/tests/test_pitching_coaching.py CHANGED
@@ -166,3 +166,16 @@ def test_older_visual_side_claim_is_withheld_without_rewriting_saved_input(tmp_p
166
  finish = next(o for o in r["visual_evidence"]["observations"] if o["topic"] == "finish")
167
  assert finish["status"] == "unclear" and "right" not in finish["description"]
168
  assert json.dumps(p, sort_keys=True) == original
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  finish = next(o for o in r["visual_evidence"]["observations"] if o["topic"] == "finish")
167
  assert finish["status"] == "unclear" and "right" not in finish["description"]
168
  assert json.dumps(p, sort_keys=True) == original
169
+
170
+
171
+ def test_unclear_visual_topic_cannot_supply_a_categorical_claim():
172
+ from ai_coach.pitch_report.v1_1.evidence import VisualObservation
173
+
174
+ observation = VisualObservation(
175
+ topic="plant",
176
+ status="unclear",
177
+ evidence_frames=[0, 1],
178
+ description="The front foot remains planted throughout the throw.",
179
+ )
180
+ assert "remains planted" not in observation.description
181
+ assert "could not be confirmed" in observation.description
backend/app/modules/swing_reports/controller.py CHANGED
@@ -30,9 +30,10 @@ def get_swing_report_service(db: Db) -> SwingReportService:
30
  async def retry_pitch_coaching(
31
  session_id: UUID, request: Request, account: CurrentAccount,
32
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
 
33
  ) -> dict:
34
  request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
35
- return await service.retry_pitch_coaching(account, session_id, request_id)
36
 
37
 
38
  async def payload_size_ok(request: Request) -> None:
 
30
  async def retry_pitch_coaching(
31
  session_id: UUID, request: Request, account: CurrentAccount,
32
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
33
+ refresh: bool = False,
34
  ) -> dict:
35
  request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
36
+ return await service.retry_pitch_coaching(account, session_id, request_id, refresh=refresh)
37
 
38
 
39
  async def payload_size_ok(request: Request) -> None:
backend/app/modules/swing_reports/service.py CHANGED
@@ -115,8 +115,9 @@ class SwingReportService:
115
  async def create_pitch(self, account: Account, session_id: UUID, payload: Any, request_id: str | None) -> dict:
116
  return await self._create(PITCH, self.pitch_builder, account, session_id, payload, request_id)
117
 
118
- async def retry_pitch_coaching(self, account: Account, session_id: UUID, request_id: str | None) -> dict:
119
- """Retry unavailable AI text from saved evidence, without rerunning ML or consuming another analysis."""
 
120
  session = await self.sessions.get_for_update(session_id)
121
  if session is None:
122
  raise NotFound("We couldn't find that session.")
@@ -128,7 +129,7 @@ class SwingReportService:
128
  raise Conflict("Complete the motion analysis first.", code="REPORT_NOT_READY")
129
  if session.measurement_payload.get("schema_version") != "pitch-1.1":
130
  raise Unprocessable("This saved report does not support coaching retry.", code="MODE_NOT_SUPPORTED")
131
- if (session.report.get("coaching") or {}).get("status") == "generated":
132
  return session.report
133
  if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent):
134
  raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
 
115
  async def create_pitch(self, account: Account, session_id: UUID, payload: Any, request_id: str | None) -> dict:
116
  return await self._create(PITCH, self.pitch_builder, account, session_id, payload, request_id)
117
 
118
+ async def retry_pitch_coaching(self, account: Account, session_id: UUID, request_id: str | None,
119
+ *, refresh: bool = False) -> dict:
120
+ """Retry unavailable text, or explicitly refresh it, without rerunning ML or consuming another analysis."""
121
  session = await self.sessions.get_for_update(session_id)
122
  if session is None:
123
  raise NotFound("We couldn't find that session.")
 
129
  raise Conflict("Complete the motion analysis first.", code="REPORT_NOT_READY")
130
  if session.measurement_payload.get("schema_version") != "pitch-1.1":
131
  raise Unprocessable("This saved report does not support coaching retry.", code="MODE_NOT_SUPPORTED")
132
+ if (session.report.get("coaching") or {}).get("status") == "generated" and not refresh:
133
  return session.report
134
  if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent):
135
  raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
backend/docs/openapi.json CHANGED
@@ -1335,6 +1335,16 @@
1335
  "title": "Session Id"
1336
  }
1337
  },
 
 
 
 
 
 
 
 
 
 
1338
  {
1339
  "name": "authorization",
1340
  "in": "header",
 
1335
  "title": "Session Id"
1336
  }
1337
  },
1338
+ {
1339
+ "name": "refresh",
1340
+ "in": "query",
1341
+ "required": false,
1342
+ "schema": {
1343
+ "type": "boolean",
1344
+ "default": false,
1345
+ "title": "Refresh"
1346
+ }
1347
+ },
1348
  {
1349
  "name": "authorization",
1350
  "in": "header",
backend/tests/integration/test_pitching_flow.py CHANGED
@@ -55,6 +55,11 @@ async def test_retry_unavailable_ai_preserves_evidence_usage_and_is_idempotent(c
55
  assert (await client.get("/v1/me/entitlement", headers=player["headers"])).json() == entitlement
56
  again = await client.post(url(sid) + "/retry-coaching", headers=player["headers"])
57
  assert again.json() == retry.json() and len(calls) == 1
 
 
 
 
 
58
 
59
 
60
  async def test_retry_coaching_requires_owner_pitch_and_existing_report(client):
 
55
  assert (await client.get("/v1/me/entitlement", headers=player["headers"])).json() == entitlement
56
  again = await client.post(url(sid) + "/retry-coaching", headers=player["headers"])
57
  assert again.json() == retry.json() and len(calls) == 1
58
+ refreshed = await client.post(url(sid) + "/retry-coaching?refresh=true", headers=player["headers"])
59
+ assert refreshed.status_code == 200 and len(calls) == 2
60
+ latest = await load_session(sid)
61
+ assert latest.measurement_payload == p and latest.analyzed_at == analyzed_at
62
+ assert (await client.get("/v1/me/entitlement", headers=player["headers"])).json() == entitlement
63
 
64
 
65
  async def test_retry_coaching_requires_owner_pitch_and_existing_report(client):
baseball_batting/api.py CHANGED
@@ -78,7 +78,7 @@ def create_app(settings=None, service=None):
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
- app = FastAPI(title="Baseball Motion Engine and Coach", version="1.21.2", lifespan=lifespan,
82
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
83
  app.state.service = service
84
  app.add_middleware(UploadGuard, settings=settings, service=service)
 
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
+ app = FastAPI(title="Baseball Motion Engine and Coach", version="1.21.3", lifespan=lifespan,
82
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
83
  app.state.service = service
84
  app.add_middleware(UploadGuard, settings=settings, service=service)
baseball_batting/pitching_visual.py CHANGED
@@ -51,6 +51,9 @@ screen direction can be confused with anatomical side. The lead foot is opposite
51
  trailing leg is on the throwing side. Do not infer a target direction from the background or the throw;
52
  describe visible relative body movement without claiming where the target is. A leg rising after the throw
53
  does not prove balance, braking force or a good finish.
 
 
 
54
  """
55
 
56
 
 
51
  trailing leg is on the throwing side. Do not infer a target direction from the background or the throw;
52
  describe visible relative body movement without claiming where the target is. A leg rising after the throw
53
  does not prove balance, braking force or a good finish.
54
+ Describe changing positions, not speed: use moves, raises, lowers, bends, straightens, turns, contacts or lifts.
55
+ Do not describe acceleration, deceleration, speed or energy. Unknown recording speed cannot establish these.
56
+ When status is unclear, do not assert that an action happened or did not happen.
57
  """
58
 
59
 
tests/test_pitching_evidence.py CHANGED
@@ -136,7 +136,7 @@ def test_visual_review_repairs_specific_claims_and_withholds_unconfirmed_topic(v
136
  assert result.reason == "some_visual_observations_withheld"
137
 
138
 
139
- @pytest.mark.parametrize("claim", ["The trailing right leg rises.", "The body turns toward the target.", "The knee bends thirty degrees.", "The pitcher shifts weight forward into layback."])
140
  def test_visual_critic_cannot_override_unsupported_claim_guard(video, tmp_path, claim):
141
  import json
142
  from ai_coach.config import Settings
 
136
  assert result.reason == "some_visual_observations_withheld"
137
 
138
 
139
+ @pytest.mark.parametrize("claim", ["The trailing right leg rises.", "The body turns toward the target.", "The knee bends thirty degrees.", "The pitcher shifts weight forward into layback.", "The throwing arm accelerates forward."])
140
  def test_visual_critic_cannot_override_unsupported_claim_guard(video, tmp_path, claim):
141
  import json
142
  from ai_coach.config import Settings