Spaces:
Running on T4
Running on T4
File size: 10,755 Bytes
e798a49 413b142 e798a49 413b142 e798a49 3249fe4 e798a49 3249fe4 e798a49 6686c0f e798a49 6686c0f e798a49 6686c0f e798a49 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | """Rubric arithmetic/evidence guard tests. Fixture grades are not accuracy evidence."""
from copy import deepcopy
import json
from pathlib import Path
import pytest
pytest.importorskip('ai_coach')
from ai_coach.schemas import Usage
from ai_coach.video_review import review_video, visual_response_schema
from ai_coach.visual_scoring import VideoScore, unavailable_score, RUBRIC_VERSION
from test_product import coach_settings, note, frames, retained_review_job
def graded_note(grades=('clear','mixed',None)):
data = note()
for feature, grade in zip(data['features'],grades):
feature['status'] = 'observed' if grade is not None else 'unclear'
feature['evidence_frame_ids'] = [0,1] if grade is not None else []
feature['observation'] = 'Visible movement follows the described sequence.'
feature['ball_interaction_visible'] = feature['key']=='bat_path_contact' and grade is not None
feature['rating'] = {'grade':grade,'explanation':'The visible sequence matches this rubric category.'} if grade else None
data['priority'] = None
return data
def review(data,tmp_path,source=None):
return review_video(source or frames(),{},coach_settings(tmp_path),
generator=lambda *a:(json.dumps(data),Usage()))
@pytest.mark.parametrize('grades,expected',[
(('clear','mixed',None),75),
(('clear','mixed','needs_practice'),50),
(('needs_practice','needs_practice',None),0),
(('clear','clear','clear'),100),
(('clear','mixed','clear'),83),
])
def test_score_is_deterministic_server_arithmetic_and_unknown_is_not_zero(tmp_path,grades,expected):
result=review(graded_note(grades),tmp_path)
assert result['status']=='completed'
score=VideoScore.model_validate(result['score'])
assert score.status=='available' and score.value==expected
assert score.scored_reps==[1] and score.rubric_version==RUBRIC_VERSION
assert score.rep_scores[0].features_scored==sum(g is not None for g in grades)
assert score.accuracy_validated is False and score.judgment_eligible is False
assert result['accuracy_validated'] is False and result['judgment_eligible'] is False
if grades[2] is None:
row=score.rep_scores[0].breakdown[2]
assert row.points is None and row.status=='unavailable'
def test_cannot_combine_different_swings_or_claim_unreviewed_swings_scored(tmp_path):
data=graded_note();data['features'][1]['rep']=2
source=[{**f,'reps':[1,2,3]} for f in frames()]
result=review(data,tmp_path,source)
assert result['status']=='completed'
score=result['score']
assert score['status']=='unavailable' and score['value'] is None
assert score['reviewed_reps']==[1,2,3] and score['scored_reps']==[]
assert [r['features_scored'] for r in score['rep_scores']]==[1,1,0]
assert all(r['value'] is None for r in score['rep_scores'])
def test_partial_coverage_is_explicit_without_copying_grades_to_other_reps(tmp_path):
result=review(graded_note(),tmp_path,[{**f,'reps':[1,2]} for f in frames()])
score=result['score']
assert score['value']==75 and score['scored_reps']==[1]
assert score['rep_scores'][1]['value'] is None
assert all(b['reason_code']=='feature_not_reviewed' for b in score['rep_scores'][1]['breakdown'])
def test_unclear_feature_and_unseen_ball_cannot_receive_a_grade(tmp_path):
data=graded_note(('clear','clear','clear'))
data['features'][1]['status']='unclear'
data['features'][2]['ball_interaction_visible']=False
original=deepcopy(data)
result=review(data,tmp_path)
assert data==original
assert result['status']=='completed' and result['score']['value'] is None
assert result['score']['rep_scores'][0]['features_scored']==1
assert result['features'][1]['rating'] is None and result['features'][2]['rating'] is None
assert result['score']['rep_scores'][0]['breakdown'][2]['reason_code']=='ball_interaction_not_visible'
def test_legacy_notes_remain_readable_but_do_not_gain_invented_ratings(tmp_path):
result=review(note(),tmp_path)
assert result['status']=='completed' and result['score']['value'] is None
assert result['score']['rep_scores'][0]['breakdown'][0]['reason_code']=='rating_not_supplied'
schema=visual_response_schema()
assert 'rating' in schema['$defs']['FeatureReview']['required']
assert 'ball_interaction_visible' in schema['$defs']['FeatureReview']['required']
def test_positive_visibility_flag_cannot_override_explicitly_unclear_interaction(tmp_path):
data=graded_note(('clear','mixed','clear'))
data['features'][2]['observation']='The bat moves forward but direct contact cannot be verified.'
result=review(data,tmp_path)
assert result['score']['value']==75
assert result['features'][2]['rating'] is None
assert result['score']['rep_scores'][0]['breakdown'][2]['reason_code']=='ball_interaction_unclear'
@pytest.mark.parametrize('priority_on_contact', [False, True])
def test_unverified_contact_is_removed_without_discarding_valid_body_feedback(tmp_path,priority_on_contact):
data=graded_note(('clear','mixed','clear'))
data['features'][2].update(observation='The bat hits the ball.',ball_interaction_visible=False)
data['priority']={'feature':'bat_path_contact' if priority_on_contact else 'load_timing',
'reason':'Practice the visible movement sequence.',
'drill_id':'hit_08' if priority_on_contact else 'hit_04'}
original=deepcopy(data)
result=review(data,tmp_path)
assert data==original
assert result['status']=='completed' and result['score']['value']==75
assert result['score']['rep_scores'][0]['features_scored']==2
contact=result['features'][2]
assert contact['status']=='unclear' and contact['rating'] is None
assert 'contact cannot be confirmed' in contact['observation']
assert result['guardrail_warnings']==[{'feature':'bat_path_contact','reason_code':'unverified_contact_statement'}]
if priority_on_contact:
assert result['priority'] is None and result['drill'] is None
else:
assert result['priority']['feature']=='load_timing' and result['drill']
def test_contact_downgrade_does_not_hide_invalid_evidence(tmp_path):
data=graded_note(('clear','mixed','clear'))
data['features'][2].update(observation='The bat hits the ball.',
ball_interaction_visible=False,evidence_frame_ids=[0,999])
result=review(data,tmp_path)
assert result['status']=='unavailable' and result['validation_reason']=='evidence_reference'
@pytest.mark.parametrize('bad', ['numeric_score','invented_frame','rating_measurement','invalid_grade'])
def test_model_cannot_choose_a_numeric_score_or_bypass_evidence_guards(tmp_path,bad):
data=graded_note()
if bad=='numeric_score':data['score']={'value':100}
if bad=='invented_frame':data['features'][0]['evidence_frame_ids']=[0,999]
if bad=='rating_measurement':data['features'][0]['rating']['explanation']='Your load took 100 ms.'
if bad=='invalid_grade':data['features'][0]['rating']['grade']='excellent'
result=review(data,tmp_path)
assert result['status']=='unavailable' and result['score']['value'] is None
assert result['reason_code']=='invalid_visual_response'
if bad=='rating_measurement':assert result['validation_reason']=='unsupported_rating_claim'
def test_failed_review_has_no_placeholder_score(tmp_path):
result=review_video([],{},coach_settings(tmp_path))
assert result['score']['status']=='unavailable' and result['score']['value'] is None
assert result['score']['rep_scores']==[]
def test_product_adds_visual_score_without_upgrading_mechanics_or_timing(tmp_path,monkeypatch):
from ai_coach.service import CoachService
from baseball_batting.api_contract import AnalysisInput
from baseball_batting.product import build_product
from test_product import combined_fixture
import baseball_batting.product as module
result,timing=combined_fixture()
original=deepcopy(timing)
monkeypatch.setattr(module,'sample_review_frames',lambda *a,**kw:frames())
service=CoachService(settings=coach_settings(tmp_path))
product=build_product(tmp_path,Path('unused-video.mp4'),result,timing,
AnalysisInput(coaching_mode='poc_video'),service=service,
generator=lambda *a:(json.dumps(graded_note()),Usage()))
assert product['visual_review']['score']['value']==75
assert product['coaching']['score']['value'] is None
assert product['coaching']['score']['checked']==0
assert product['coaching']['timing']['observations']
assert product['timing']==timing==original
@pytest.mark.parametrize('legacy', ['missing_score', 'old_wording'])
def test_old_completed_review_can_upgrade_once_without_repeating_gpu_or_losing_clips(tmp_path,monkeypatch,legacy):
from fastapi.testclient import TestClient
from baseball_batting.api import create_app
from baseball_batting.storage import atomic_json,sha256_file
from test_api import AUTH,wait_until
import ai_coach.video_review as module
service,identifier,job,product=retained_review_job(tmp_path)
product['visual_review']={'status':'completed','features':[]}
if legacy == 'old_wording':
product['visual_review']['score'] = unavailable_score('insufficient_visible_features')
atomic_json(job/'product.json',product)
service.store.update_product(identifier,sha256_file(job/'product.json'))
calls=[]
def upgraded(*args,**kwargs):
calls.append(True)
return {'status':'completed','features':[], 'text_style_version':module.TEXT_STYLE_VERSION,
'score':unavailable_score('insufficient_visible_features')}
monkeypatch.setattr(module,'review_video',upgraded)
with TestClient(create_app(service.settings,service)) as client:
wait_until(lambda:service.ready)
url=f'/v1/analyses/{identifier}/video-review'
result=client.post(url,headers=AUTH)
assert result.status_code==200
assert result.json()['visual_review']['score']['rubric_version']==RUBRIC_VERSION
assert result.json()['coaching']==product['coaching'] and result.json()['swings']==product['swings']
assert client.post(url,headers=AUTH).status_code==200
assert len(calls)==1
assert service.store.get(identifier)['result_sha256']=='original-result-hash'
assert service.store.get(identifier)['swings_sha256']=='original-swings-hash'
assert client.get('/v1/video-score-schema',headers=AUTH).json()==VideoScore.model_json_schema()
def test_score_schema_matches_published_contract():
root=Path(__file__).resolve().parents[1]
assert json.loads((root/'docs/video-score.schema.json').read_text())==VideoScore.model_json_schema()
|