Spaces:
Running on T4
Running on T4
Download tests/test_visual_scoring.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_visual_scoring.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tests/test_visual_scoring.py
-
curl -L -o test_visual_scoring.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_visual_scoring.py
10.8 kB
| """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())) | |
| 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' | |
| 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' | |
| 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 | |
| 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() | |