Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
cf86ef2
1
Parent(s): 19d2582
Automated Deploy: c9a20f898e1842345277a36675adc902e0d534fd
Browse files- AI-coach-agent/src/ai_coach/pitch_report/v1_1/coaching.py +6 -0
- AI-coach-agent/src/ai_coach/pitch_report/v1_1/evidence.py +19 -0
- AI-coach-agent/src/ai_coach/pitch_report/v1_1/service.py +21 -0
- AI-coach-agent/tests/test_pitching_coaching.py +25 -0
- baseball_batting/api.py +1 -1
- baseball_batting/pitching_visual.py +15 -10
- tests/test_pitching_evidence.py +23 -0
AI-coach-agent/src/ai_coach/pitch_report/v1_1/coaching.py
CHANGED
|
@@ -72,6 +72,9 @@ 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 |
Unknown capture timing does NOT hide the visible chronological order of phases. It hides physical durations
|
| 76 |
and speed-based peak ordering. Variable frame rates are supported using actual capture timestamps; constant FPS
|
| 77 |
is NOT required. Advise preserving the original recording and documenting capture/export speed, not relying on
|
|
@@ -155,6 +158,9 @@ def check_draft(draft, facts):
|
|
| 155 |
problems.append("target_direction_not_measured")
|
| 156 |
if re.search(r"over[- ]?rotat|under[- ]?rotat|(?:keep|stay|remain).{0,35}(?:shoulders?|chest).{0,15}closed", prose, re.I):
|
| 157 |
problems.append("unsupported_rotation_correction")
|
|
|
|
|
|
|
|
|
|
| 158 |
return problems
|
| 159 |
|
| 160 |
|
|
|
|
| 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 |
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
|
|
|
|
| 158 |
problems.append("target_direction_not_measured")
|
| 159 |
if re.search(r"over[- ]?rotat|under[- ]?rotat|(?:keep|stay|remain).{0,35}(?:shoulders?|chest).{0,15}closed", prose, re.I):
|
| 160 |
problems.append("unsupported_rotation_correction")
|
| 161 |
+
actions = " ".join(c.next_step + " " + c.check for c in draft.cards)
|
| 162 |
+
if re.search(r"\b(?:smooth(?:ly)?|naturally|rush(?:ing|ed)?)\b|intentional stretch", actions, re.I):
|
| 163 |
+
problems.append("unsupported_movement_quality_cue")
|
| 164 |
return problems
|
| 165 |
|
| 166 |
|
AI-coach-agent/src/ai_coach/pitch_report/v1_1/evidence.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""Optional, versioned whole-delivery evidence; coverage is not model confidence."""
|
| 2 |
|
|
|
|
| 3 |
from typing import Literal
|
| 4 |
|
| 5 |
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
@@ -9,6 +10,24 @@ class Strict(BaseModel):
|
|
| 9 |
model_config = ConfigDict(extra="forbid", allow_inf_nan=False, strict=True)
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
class VisualObservation(Strict):
|
| 13 |
topic: Literal["loading", "plant", "rotation", "finish"]
|
| 14 |
status: Literal["observed", "unclear"]
|
|
|
|
| 1 |
"""Optional, versioned whole-delivery evidence; coverage is not model confidence."""
|
| 2 |
|
| 3 |
+
import re
|
| 4 |
from typing import Literal
|
| 5 |
|
| 6 |
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
|
|
| 10 |
model_config = ConfigDict(extra="forbid", allow_inf_nan=False, strict=True)
|
| 11 |
|
| 12 |
|
| 13 |
+
def visual_claim_issues(description: str) -> list[str]:
|
| 14 |
+
"""Reject unsupported claim classes even when an automated critique accepts them."""
|
| 15 |
+
issues = []
|
| 16 |
+
if re.search(r"\d|\b(?:degrees?|mph|torque|injury|force|power)\b", description, re.I):
|
| 17 |
+
issues.append("Unsupported numerical or physical claim; describe only visible movement.")
|
| 18 |
+
if re.search(r"\b(?:left|right)\b", description, re.I):
|
| 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,
|
| 25 |
+
re.I,
|
| 26 |
+
):
|
| 27 |
+
issues.append("Unmeasured mechanics or technique judgment; describe the visible body movement only.")
|
| 28 |
+
return issues
|
| 29 |
+
|
| 30 |
+
|
| 31 |
class VisualObservation(Strict):
|
| 32 |
topic: Literal["loading", "plant", "rotation", "finish"]
|
| 33 |
status: Literal["observed", "unclear"]
|
AI-coach-agent/src/ai_coach/pitch_report/v1_1/service.py
CHANGED
|
@@ -12,6 +12,7 @@ from ...swing_report.scoring import mean_score, rating_for, score
|
|
| 12 |
from ...swing_report.service import InvalidPayload
|
| 13 |
from .coaching import generate_coaching
|
| 14 |
from .contract import GROUPS, METRICS, PitchPayload
|
|
|
|
| 15 |
from .rubric import evaluate_drill
|
| 16 |
|
| 17 |
REASONS = {
|
|
@@ -106,6 +107,26 @@ def build_report(payload, athlete=None, *, request_id=None, settings=None, gener
|
|
| 106 |
else m
|
| 107 |
)
|
| 108 |
p = p.model_copy(update={"measurements": safe_measurements})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
athlete = athlete or AthleteContext()
|
| 110 |
registry = references()
|
| 111 |
context = p.context
|
|
|
|
| 12 |
from ...swing_report.service import InvalidPayload
|
| 13 |
from .coaching import generate_coaching
|
| 14 |
from .contract import GROUPS, METRICS, PitchPayload
|
| 15 |
+
from .evidence import visual_claim_issues
|
| 16 |
from .rubric import evaluate_drill
|
| 17 |
|
| 18 |
REASONS = {
|
|
|
|
| 107 |
else m
|
| 108 |
)
|
| 109 |
p = p.model_copy(update={"measurements": safe_measurements})
|
| 110 |
+
if p.visual_evidence and p.visual_evidence.status == "provisional":
|
| 111 |
+
safe_visual = [
|
| 112 |
+
o.model_copy(
|
| 113 |
+
update={"status": "unclear", "description": "This movement could not be confirmed from the sampled frames."}
|
| 114 |
+
)
|
| 115 |
+
if visual_claim_issues(o.description)
|
| 116 |
+
else o
|
| 117 |
+
for o in p.visual_evidence.observations
|
| 118 |
+
]
|
| 119 |
+
if safe_visual != p.visual_evidence.observations:
|
| 120 |
+
p = p.model_copy(
|
| 121 |
+
update={
|
| 122 |
+
"visual_evidence": p.visual_evidence.model_copy(
|
| 123 |
+
update={
|
| 124 |
+
"observations": safe_visual,
|
| 125 |
+
"reason": "some_visual_observations_withheld",
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
}
|
| 129 |
+
)
|
| 130 |
athlete = athlete or AthleteContext()
|
| 131 |
registry = references()
|
| 132 |
context = p.context
|
AI-coach-agent/tests/test_pitching_coaching.py
CHANGED
|
@@ -127,6 +127,9 @@ def test_live_review_regressions_target_direction_and_rotation_advice():
|
|
| 127 |
assert "target_direction_not_measured" in check_draft(Draft.model_validate(d), facts)
|
| 128 |
d["cards"][0]["next_step"] = "Verify you are not over-rotating early."
|
| 129 |
assert "unsupported_rotation_correction" in check_draft(Draft.model_validate(d), facts)
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
|
| 132 |
def test_older_payload_instability_is_not_reintroduced_by_coaching_retry(tmp_path):
|
|
@@ -141,3 +144,25 @@ def test_older_payload_instability_is_not_reintroduced_by_coaching_retry(tmp_pat
|
|
| 141 |
p["context"]["drill_type"] = "step_back"
|
| 142 |
r = build_pitch_report(p, settings=settings(tmp_path))
|
| 143 |
assert "rocker" not in r["drill_evaluation"]["criteria"][0]["meaning"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
assert "target_direction_not_measured" in check_draft(Draft.model_validate(d), facts)
|
| 128 |
d["cards"][0]["next_step"] = "Verify you are not over-rotating early."
|
| 129 |
assert "unsupported_rotation_correction" in check_draft(Draft.model_validate(d), facts)
|
| 130 |
+
d = draft()
|
| 131 |
+
d["cards"][0]["check"] = "Keep moving naturally without rushing into landing."
|
| 132 |
+
assert "unsupported_movement_quality_cue" in check_draft(Draft.model_validate(d), facts)
|
| 133 |
|
| 134 |
|
| 135 |
def test_older_payload_instability_is_not_reintroduced_by_coaching_retry(tmp_path):
|
|
|
|
| 144 |
p["context"]["drill_type"] = "step_back"
|
| 145 |
r = build_pitch_report(p, settings=settings(tmp_path))
|
| 146 |
assert "rocker" not in r["drill_evaluation"]["criteria"][0]["meaning"]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_older_visual_side_claim_is_withheld_without_rewriting_saved_input(tmp_path):
|
| 150 |
+
p = payload()
|
| 151 |
+
p["visual_evidence"] = {
|
| 152 |
+
"status": "provisional",
|
| 153 |
+
"sampled_frames": [0, 1],
|
| 154 |
+
"observations": [
|
| 155 |
+
{
|
| 156 |
+
"topic": topic,
|
| 157 |
+
"status": "observed",
|
| 158 |
+
"description": "The trailing right leg rises." if topic == "finish" else "The chest moves forward.",
|
| 159 |
+
"evidence_frames": [0, 1],
|
| 160 |
+
}
|
| 161 |
+
for topic in ("loading", "plant", "rotation", "finish")
|
| 162 |
+
],
|
| 163 |
+
}
|
| 164 |
+
original = json.dumps(p, sort_keys=True)
|
| 165 |
+
r = build_pitch_report(p, settings=settings(tmp_path))
|
| 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
|
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.
|
| 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.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)
|
baseball_batting/pitching_visual.py
CHANGED
|
@@ -2,7 +2,6 @@
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import logging
|
| 5 |
-
import re
|
| 6 |
import time
|
| 7 |
from typing import Literal
|
| 8 |
|
|
@@ -14,6 +13,7 @@ from ai_coach.pitch_report.v1_1.evidence import (
|
|
| 14 |
Strict,
|
| 15 |
VisualEvidence,
|
| 16 |
VisualObservation,
|
|
|
|
| 17 |
)
|
| 18 |
from ai_coach.schemas import Usage
|
| 19 |
from ai_coach.swing_report.text import _redact
|
|
@@ -46,6 +46,11 @@ ideal mechanics, early/late arm action, or release from an extended arm. No scor
|
|
| 46 |
causal diagnosis or advice. Do not call movement smooth, correct, good, bad, excessive, deficient, or rushed.
|
| 47 |
Describe what changes: body part, visible direction, and sequence. Prefer unclear over filling in missing motion.
|
| 48 |
Use simple complete sentences, no digits in descriptions. These are provisional visual observations.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
"""
|
| 50 |
|
| 51 |
|
|
@@ -125,6 +130,8 @@ def _review_pitch_video(
|
|
| 125 |
|
| 126 |
facts = {
|
| 127 |
"throwing_hand": options.handedness,
|
|
|
|
|
|
|
| 128 |
"context": options.context.model_dump(mode="json"),
|
| 129 |
"marked_release_frame": options.release_frame,
|
| 130 |
"frame_ids": [i for i, _ in frames],
|
|
@@ -210,15 +217,11 @@ def _review_pitch_video(
|
|
| 210 |
sampled_frames=[i for i, _ in frames],
|
| 211 |
observations=draft.observations,
|
| 212 |
)
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
)
|
| 219 |
-
for o in result.observations
|
| 220 |
-
):
|
| 221 |
-
return partial or unavailable("unsupported_visual_claim")
|
| 222 |
review = VisualCritique.model_validate_json(
|
| 223 |
call(
|
| 224 |
PROMPT
|
|
@@ -240,6 +243,8 @@ def _review_pitch_video(
|
|
| 240 |
for r in review.reviews
|
| 241 |
if not r.supported or r.problems
|
| 242 |
}
|
|
|
|
|
|
|
| 243 |
if not rejected:
|
| 244 |
return result
|
| 245 |
logging.getLogger(__name__).warning(
|
|
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import logging
|
|
|
|
| 5 |
import time
|
| 6 |
from typing import Literal
|
| 7 |
|
|
|
|
| 13 |
Strict,
|
| 14 |
VisualEvidence,
|
| 15 |
VisualObservation,
|
| 16 |
+
visual_claim_issues,
|
| 17 |
)
|
| 18 |
from ai_coach.schemas import Usage
|
| 19 |
from ai_coach.swing_report.text import _redact
|
|
|
|
| 46 |
causal diagnosis or advice. Do not call movement smooth, correct, good, bad, excessive, deficient, or rushed.
|
| 47 |
Describe what changes: body part, visible direction, and sequence. Prefer unclear over filling in missing motion.
|
| 48 |
Use simple complete sentences, no digits in descriptions. These are provisional visual observations.
|
| 49 |
+
Describe body roles as front leg, back leg, throwing arm, and glove arm. Do not use the words left or right:
|
| 50 |
+
screen direction can be confused with anatomical side. The lead foot is opposite the throwing side, and the
|
| 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 |
|
|
|
|
| 130 |
|
| 131 |
facts = {
|
| 132 |
"throwing_hand": options.handedness,
|
| 133 |
+
"lead_foot": options.athlete.lead_foot,
|
| 134 |
+
"trailing_leg": options.handedness,
|
| 135 |
"context": options.context.model_dump(mode="json"),
|
| 136 |
"marked_release_frame": options.release_frame,
|
| 137 |
"frame_ids": [i for i, _ in frames],
|
|
|
|
| 217 |
sampled_frames=[i for i, _ in frames],
|
| 218 |
observations=draft.observations,
|
| 219 |
)
|
| 220 |
+
guarded = {}
|
| 221 |
+
for o in result.observations:
|
| 222 |
+
issues = visual_claim_issues(o.description)
|
| 223 |
+
if issues:
|
| 224 |
+
guarded[o.topic] = issues
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
review = VisualCritique.model_validate_json(
|
| 226 |
call(
|
| 227 |
PROMPT
|
|
|
|
| 243 |
for r in review.reviews
|
| 244 |
if not r.supported or r.problems
|
| 245 |
}
|
| 246 |
+
for topic, issues in guarded.items():
|
| 247 |
+
rejected[topic] = rejected.get(topic, []) + issues
|
| 248 |
if not rejected:
|
| 249 |
return result
|
| 250 |
logging.getLogger(__name__).warning(
|
tests/test_pitching_evidence.py
CHANGED
|
@@ -134,3 +134,26 @@ def test_visual_review_repairs_specific_claims_and_withholds_unconfirmed_topic(v
|
|
| 134 |
else:
|
| 135 |
assert plant.status == "unclear" and "lands" not in plant.description
|
| 136 |
assert result.reason == "some_visual_observations_withheld"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
else:
|
| 135 |
assert plant.status == "unclear" and "lands" not in plant.description
|
| 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
|
| 143 |
+
from baseball_batting.pitching_visual import review_pitch_video
|
| 144 |
+
capture = ingest(video, {})
|
| 145 |
+
rows = [{"joints": {str(j): {"pixel": [40 + j, 40 + j], "valid": True, "in_frame": True}
|
| 146 |
+
for j in range(8)}} for _ in range(8)]
|
| 147 |
+
calls = []
|
| 148 |
+
def generator(prompt, frames, schema):
|
| 149 |
+
calls.append(prompt)
|
| 150 |
+
if len(calls) % 2 == 0:
|
| 151 |
+
return json.dumps({"reviews": [{"topic": k, "supported": True, "problems": []}
|
| 152 |
+
for k in ("loading", "plant", "rotation", "finish")]})
|
| 153 |
+
return json.dumps({"observations": [{"topic": k, "status": "observed",
|
| 154 |
+
"description": claim if k == "finish" else "The body moves across the image.",
|
| 155 |
+
"evidence_frames": [frames[0][0], frames[-1][0]]} for k in ("loading", "plant", "rotation", "finish")]})
|
| 156 |
+
result = review_pitch_video(video, capture, options(), rows, generator=generator,
|
| 157 |
+
settings=Settings(_env_file=None, google_api_key=None, cache_path=tmp_path / "cache", repair_attempts=0))
|
| 158 |
+
finish = next(o for o in result.observations if o.topic == "finish")
|
| 159 |
+
assert finish.status == "unclear" and finish.description != claim
|