github-actions[bot] commited on
Commit
6f9fccc
·
1 Parent(s): d20de35

Automated Deploy: fcb29d440b3ada848b116394e1125e3309c468e4

Browse files
AI-coach-agent/src/ai_coach/pitch_report/v1_1/coaching.py CHANGED
@@ -72,7 +72,7 @@ opening. Knee straightening is not a measurement of force or an effective block.
72
  The rotation headings use an arbitrary coordinate basis: target/catcher direction and 'open/closed' positions were
73
  NOT measured. Describe relative pelvis/shoulder movement only; never say either turned toward the target from
74
  these headings. Do not warn of over-rotation, early opening, or prescribe keeping the chest/shoulders closed.
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
@@ -81,7 +81,9 @@ Describe the body moving, not weight shift, weight transfer, momentum or energy
81
  measure load distribution. Do not attribute an unclear visual movement to missing capture timing: unknown timing
82
  limits physical durations and speeds; unclear visual evidence means that movement was not confirmed in the frames.
83
  Unknown capture timing does NOT hide the visible chronological order of phases. It hides physical durations
84
- and speed-based peak ordering. Variable frame rates are supported using actual capture timestamps; constant FPS
 
 
85
  is NOT required. Advise preserving the original recording and documenting capture/export speed, not relying on
86
  container FPS or requiring constant timestamps. A speed-ramp export needs its explicit capture-time map.
87
  Peak rotation order is not energy transfer or automatically correct/incorrect. Missing leg lift in a rocker is not a fault.
@@ -164,10 +166,30 @@ def check_draft(draft, facts):
164
  if re.search(r"over[- ]?rotat|under[- ]?rotat|(?:keep|stay|remain).{0,35}(?:shoulders?|chest).{0,15}closed", prose, re.I):
165
  problems.append("unsupported_rotation_correction")
166
  actions = " ".join(c.next_step + " " + c.check for c in draft.cards)
167
- if re.search(r"\b(?:smooth(?:ly)?|naturally|rush(?:ing|ed)?)\b|intentional stretch", actions, re.I):
 
 
 
 
 
168
  problems.append("unsupported_movement_quality_cue")
169
  if re.search(r"\bweight (?:shift\w*|transfer\w*|distribution)\b|\bmomentum\b", prose, re.I):
170
  problems.append("unmeasured_load_or_momentum_claim")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  return problems
172
 
173
 
@@ -252,6 +274,8 @@ def generate_coaching(p, rubric, *, settings=None, generator=None, request_id=No
252
  "There is no calibrated target direction; reject target-direction claims from headings. "
253
  "Video phase order remains observable even when physical timing is unknown. Constant FPS "
254
  "is not required; reject advice asserting it is required or container metadata proves capture speed. "
 
 
255
  "A correct citation does not prove the accompanying claim. Missing or uncertain facts cannot "
256
  "justify mechanics changes. Return supported=true only if EVERY claim is supported. "
257
  "If uncertain, supported=false. Facts:\n" + canonical + "\nDraft:\n" + draft.model_dump_json()
 
72
  The rotation headings use an arbitrary coordinate basis: target/catcher direction and 'open/closed' positions were
73
  NOT measured. Describe relative pelvis/shoulder movement only; never say either turned toward the target from
74
  these headings. Do not warn of over-rotation, early opening, or prescribe keeping the chest/shoulders closed.
75
+ Do not prescribe or grade moving smoothly, naturally, with a steady knee lift, 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
 
81
  measure load distribution. Do not attribute an unclear visual movement to missing capture timing: unknown timing
82
  limits physical durations and speeds; unclear visual evidence means that movement was not confirmed in the frames.
83
  Unknown capture timing does NOT hide the visible chronological order of phases. It hides physical durations
84
+ and speed-based peak ordering. Unknown timing does NOT mean the video was slowed down, edited, or that playback
85
+ speed differs from recording speed. Say the relationship is unknown; never assert that the speeds differ without
86
+ documented retiming. Variable frame rates are supported using actual capture timestamps; constant FPS
87
  is NOT required. Advise preserving the original recording and documenting capture/export speed, not relying on
88
  container FPS or requiring constant timestamps. A speed-ramp export needs its explicit capture-time map.
89
  Peak rotation order is not energy transfer or automatically correct/incorrect. Missing leg lift in a rocker is not a fault.
 
166
  if re.search(r"over[- ]?rotat|under[- ]?rotat|(?:keep|stay|remain).{0,35}(?:shoulders?|chest).{0,15}closed", prose, re.I):
167
  problems.append("unsupported_rotation_correction")
168
  actions = " ".join(c.next_step + " " + c.check for c in draft.cards)
169
+ if re.search(
170
+ r"\b(?:smooth(?:ly)?|naturally|rush(?:ing|ed)?)\b|intentional stretch"
171
+ r"|\bsteady (?:lift|knee|leg|movement|motion|delivery)",
172
+ actions,
173
+ re.I,
174
+ ):
175
  problems.append("unsupported_movement_quality_cue")
176
  if re.search(r"\bweight (?:shift\w*|transfer\w*|distribution)\b|\bmomentum\b", prose, re.I):
177
  problems.append("unmeasured_load_or_momentum_claim")
178
+ clock = facts.get("clock:capture", {})
179
+ unknown_clock = (
180
+ clock.get("kind") == "unknown"
181
+ or clock.get("physical_time_available") is False
182
+ or any(
183
+ "capture_time_unknown" in value.get("reasons", []) for key, value in facts.items() if key.startswith("measurement:")
184
+ )
185
+ )
186
+ if unknown_clock and re.search(
187
+ r"\b(?:playback|export(?:ed)?) (?:speed|rate|fps) (?:differs?\b|is different\b|does not match\b|is (?:slower|faster)\b)"
188
+ r"|\b(?:clip|video|footage|file) (?:is|was|has been) (?:slowed|sped|retimed|in slow[- ]motion)\b",
189
+ prose,
190
+ re.I,
191
+ ):
192
+ problems.append("unknown_clock_does_not_prove_retiming")
193
  return problems
194
 
195
 
 
274
  "There is no calibrated target direction; reject target-direction claims from headings. "
275
  "Video phase order remains observable even when physical timing is unknown. Constant FPS "
276
  "is not required; reject advice asserting it is required or container metadata proves capture speed. "
277
+ "Unknown capture timing does not establish that footage was retimed or that playback and "
278
+ "recording speeds differ. Reject such assertions unless the supplied clock documents retiming. "
279
  "A correct citation does not prove the accompanying claim. Missing or uncertain facts cannot "
280
  "justify mechanics changes. Return supported=true only if EVERY claim is supported. "
281
  "If uncertain, supported=false. Facts:\n" + canonical + "\nDraft:\n" + draft.model_dump_json()
AI-coach-agent/src/ai_coach/pitch_report/v1_1/evidence.py CHANGED
@@ -21,6 +21,13 @@ def visual_claim_issues(description: str) -> list[str]:
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,
 
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(?:stays?|remains?|keeps?)\b.{0,35}\b(?:grounded|planted|on the (?:ground|surface)|in contact)\b"
26
+ r"|\bcontinuous(?:ly)?\b.{0,35}\b(?:contact|grounded|planted)\b",
27
+ description,
28
+ re.I,
29
+ ):
30
+ issues.append("Sparse frames do not establish continuous foot contact; describe visible positions or use unclear.")
31
  if re.search(
32
  r"\b(?:weight|balance|balanced|momentum|layback|deceleration|efficient|effective|smooth(?:ly)?|correct|incorrect|good|bad|excessive|deficient|rushed)\b",
33
  description,
AI-coach-agent/tests/test_pitching_coaching.py CHANGED
@@ -133,6 +133,44 @@ def test_live_review_regressions_target_direction_and_rotation_advice():
133
  d = draft()
134
  d["cards"][0]["next_step"] = "Keep using this initial weight shift setup."
135
  assert "unmeasured_load_or_momentum_claim" in check_draft(Draft.model_validate(d), facts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
 
138
  def test_older_payload_instability_is_not_reintroduced_by_coaching_retry(tmp_path):
@@ -149,7 +187,10 @@ def test_older_payload_instability_is_not_reintroduced_by_coaching_retry(tmp_pat
149
  assert "rocker" not in r["drill_evaluation"]["criteria"][0]["meaning"]
150
 
151
 
152
- def test_older_visual_side_claim_is_withheld_without_rewriting_saved_input(tmp_path):
 
 
 
153
  p = payload()
154
  p["visual_evidence"] = {
155
  "status": "provisional",
@@ -158,7 +199,7 @@ def test_older_visual_side_claim_is_withheld_without_rewriting_saved_input(tmp_p
158
  {
159
  "topic": topic,
160
  "status": "observed",
161
- "description": "The trailing right leg rises." if topic == "finish" else "The chest moves forward.",
162
  "evidence_frames": [0, 1],
163
  }
164
  for topic in ("loading", "plant", "rotation", "finish")
@@ -167,7 +208,7 @@ def test_older_visual_side_claim_is_withheld_without_rewriting_saved_input(tmp_p
167
  original = json.dumps(p, sort_keys=True)
168
  r = build_pitch_report(p, settings=settings(tmp_path))
169
  finish = next(o for o in r["visual_evidence"]["observations"] if o["topic"] == "finish")
170
- assert finish["status"] == "unclear" and "right" not in finish["description"]
171
  assert json.dumps(p, sort_keys=True) == original
172
 
173
 
 
133
  d = draft()
134
  d["cards"][0]["next_step"] = "Keep using this initial weight shift setup."
135
  assert "unmeasured_load_or_momentum_claim" in check_draft(Draft.model_validate(d), facts)
136
+ d = draft()
137
+ d["cards"][0]["next_step"] = "Continue pairing your backward step with a steady lift of the front knee."
138
+ assert "unsupported_movement_quality_cue" in check_draft(Draft.model_validate(d), facts)
139
+
140
+
141
+ @pytest.mark.parametrize(
142
+ "claim",
143
+ [
144
+ "Physical capture timing is unavailable because the file playback speed differs from original capture speed.",
145
+ "Your playback speed does not match the recording speed.",
146
+ "Your video was slowed during export.",
147
+ "Your footage is in slow motion.",
148
+ ],
149
+ )
150
+ def test_unknown_capture_clock_does_not_prove_the_video_was_retimed(claim):
151
+ from ai_coach.pitch_report.v1_1.coaching import Draft, check_draft
152
+
153
+ d = draft()
154
+ d["cards"][0]["observation"] = claim
155
+ facts = {
156
+ "measurement:lead_knee_extension_to_release": {"value": 30},
157
+ "clock:capture": {"kind": "unknown", "physical_time_available": False},
158
+ }
159
+ assert "unknown_clock_does_not_prove_retiming" in check_draft(Draft.model_validate(d), facts)
160
+ d["cards"][0]["observation"] = "The relationship between playback and original recording speed is unknown."
161
+ assert not check_draft(Draft.model_validate(d), facts)
162
+ d["cards"][0]["observation"] = claim
163
+ facts["clock:capture"] = {"kind": "constant_slowdown", "physical_time_available": True}
164
+ assert "unknown_clock_does_not_prove_retiming" not in check_draft(Draft.model_validate(d), facts)
165
+
166
+
167
+ def test_unknown_capture_clock_is_respected_in_older_payloads_without_clock_evidence():
168
+ from ai_coach.pitch_report.v1_1.coaching import Draft, check_draft
169
+
170
+ d = draft()
171
+ d["summary"] = "Your playback speed differs from the original recording speed."
172
+ facts = {"measurement:lead_knee_extension_to_release": {"value": None, "reasons": ["capture_time_unknown"]}}
173
+ assert "unknown_clock_does_not_prove_retiming" in check_draft(Draft.model_validate(d), facts)
174
 
175
 
176
  def test_older_payload_instability_is_not_reintroduced_by_coaching_retry(tmp_path):
 
187
  assert "rocker" not in r["drill_evaluation"]["criteria"][0]["meaning"]
188
 
189
 
190
+ @pytest.mark.parametrize(
191
+ "claim", ["The trailing right leg rises.", "The lead foot stays on the ground while the front leg straightens."]
192
+ )
193
+ def test_older_unsupported_visual_claim_is_withheld_without_rewriting_saved_input(tmp_path, claim):
194
  p = payload()
195
  p["visual_evidence"] = {
196
  "status": "provisional",
 
199
  {
200
  "topic": topic,
201
  "status": "observed",
202
+ "description": claim if topic == "finish" else "The chest moves forward.",
203
  "evidence_frames": [0, 1],
204
  }
205
  for topic in ("loading", "plant", "rotation", "finish")
 
208
  original = json.dumps(p, sort_keys=True)
209
  r = build_pitch_report(p, settings=settings(tmp_path))
210
  finish = next(o for o in r["visual_evidence"]["observations"] if o["topic"] == "finish")
211
+ assert finish["status"] == "unclear" and finish["description"] != claim
212
  assert json.dumps(p, sort_keys=True) == original
213
 
214
 
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.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)
 
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
+ app = FastAPI(title="Baseball Motion Engine and Coach", version="1.21.4", 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
@@ -54,6 +54,10 @@ 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
 
@@ -121,9 +125,11 @@ def _review_pitch_video(
121
  a, b = np.maximum(xy.min(0) - 20, 0).astype(int), (xy.max(0) + 20).astype(int)
122
  cv2.rectangle(frame, tuple(a), tuple(b), (0, 255, 255), 2)
123
  h, w = frame.shape[:2]
124
- if max(h, w) > 768:
 
 
125
  frame = cv2.resize(
126
- frame, (round(w * 768 / max(h, w)), round(h * 768 / max(h, w)))
127
  )
128
  ok, encoded = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 85])
129
  if ok:
@@ -131,12 +137,15 @@ def _review_pitch_video(
131
  if len(frames) < 4:
132
  return unavailable("insufficient_visible_frames")
133
 
 
134
  facts = {
135
  "throwing_hand": options.handedness,
136
  "lead_foot": options.athlete.lead_foot,
137
  "trailing_leg": options.handedness,
138
  "context": options.context.model_dump(mode="json"),
139
  "marked_release_frame": options.release_frame,
 
 
140
  "frame_ids": [i for i, _ in frames],
141
  "marks_are_approximate": True,
142
  "capture_clock_known": capture["physical_clock_known"],
@@ -145,16 +154,13 @@ def _review_pitch_video(
145
  def call(prompt, schema):
146
  if not ledger.within_budget():
147
  raise RuntimeError("daily_budget_exceeded")
 
148
  if generator:
149
  return generator(prompt, frames, schema)
150
  from google import genai
151
  from google.genai import types
152
 
153
- contents = [
154
- types.Part.from_text(
155
- text=prompt + "\nRecording facts: " + json.dumps(facts)
156
- )
157
- ]
158
  for index, jpeg in frames:
159
  contents.extend(
160
  [
 
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
+ Inspect the front foot against the surface in the cited frames: do not assume it remains grounded because this
58
+ is a rocker drill. Sparse samples cannot establish continuous ground contact. Describe visible foot positions
59
+ or the landing transition, and use unclear when the foot/surface boundary is ambiguous. Reviewed lift and foot
60
+ strike marks are approximate checks, not permission to invent what the images show; flag a contradiction.
61
  """
62
 
63
 
 
125
  a, b = np.maximum(xy.min(0) - 20, 0).astype(int), (xy.max(0) + 20).astype(int)
126
  cv2.rectangle(frame, tuple(a), tuple(b), (0, 255, 255), 2)
127
  h, w = frame.shape[:2]
128
+ # Preserve foot/surface detail for contact review; the old 768px whole-frame
129
+ # resize obscured the foot in portrait recordings during real evaluation.
130
+ if max(h, w) > 1280:
131
  frame = cv2.resize(
132
+ frame, (round(w * 1280 / max(h, w)), round(h * 1280 / max(h, w)))
133
  )
134
  ok, encoded = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 85])
135
  if ok:
 
137
  if len(frames) < 4:
138
  return unavailable("insufficient_visible_frames")
139
 
140
+ window = options.windows[0] if options.windows else None
141
  facts = {
142
  "throwing_hand": options.handedness,
143
  "lead_foot": options.athlete.lead_foot,
144
  "trailing_leg": options.handedness,
145
  "context": options.context.model_dump(mode="json"),
146
  "marked_release_frame": options.release_frame,
147
+ "marked_leg_lift_frame": window.leg_lift_frame if window else None,
148
+ "marked_foot_strike_frame": window.foot_strike_frame if window else None,
149
  "frame_ids": [i for i, _ in frames],
150
  "marks_are_approximate": True,
151
  "capture_clock_known": capture["physical_clock_known"],
 
154
  def call(prompt, schema):
155
  if not ledger.within_budget():
156
  raise RuntimeError("daily_budget_exceeded")
157
+ prompt = prompt + "\nRecording facts: " + json.dumps(facts)
158
  if generator:
159
  return generator(prompt, frames, schema)
160
  from google import genai
161
  from google.genai import types
162
 
163
+ contents = [types.Part.from_text(text=prompt)]
 
 
 
 
164
  for index, jpeg in frames:
165
  contents.extend(
166
  [
tests/test_pitching_evidence.py CHANGED
@@ -88,6 +88,8 @@ def test_visual_review_uses_real_frames_citations_and_separate_critique(video, t
88
  def generator(prompt, frames, schema):
89
  calls.append(prompt)
90
  assert all(jpeg[:2] == b'\xff\xd8' for _, jpeg in frames)
 
 
91
  if len(calls) % 2 == 0:
92
  return json.dumps({"reviews": [{"topic": k, "supported": True, "problems": []}
93
  for k in ("loading", "plant", "rotation", "finish")]})
@@ -136,7 +138,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.", "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
 
88
  def generator(prompt, frames, schema):
89
  calls.append(prompt)
90
  assert all(jpeg[:2] == b'\xff\xd8' for _, jpeg in frames)
91
+ assert '"marked_foot_strike_frame": ' + str(options().windows[0].foot_strike_frame) in prompt
92
+ assert '"marked_leg_lift_frame": ' + str(options().windows[0].leg_lift_frame) in prompt
93
  if len(calls) % 2 == 0:
94
  return json.dumps({"reviews": [{"topic": k, "supported": True, "problems": []}
95
  for k in ("loading", "plant", "rotation", "finish")]})
 
138
  assert result.reason == "some_visual_observations_withheld"
139
 
140
 
141
+ @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.", "The lead foot stays on the ground while the front leg straightens."])
142
  def test_visual_critic_cannot_override_unsupported_claim_guard(video, tmp_path, claim):
143
  import json
144
  from ai_coach.config import Settings