github-actions[bot] commited on
Commit
6686c0f
·
1 Parent(s): 3249fe4

Automated Deploy: eee53c8cd123595b689e2ad05bf8c9bae3a82c9a

Browse files
AI-coach-agent/src/ai_coach/video_review.py CHANGED
@@ -12,15 +12,16 @@ import time
12
  import uuid
13
  from typing import Literal
14
 
15
- from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
16
 
17
  from .config import Settings
18
  from .cost import UsageLedger, compute_cost
19
  from .knowledge import all_drills
20
  from .schemas import Usage
21
- from .visual_scoring import VisualRating, RUBRIC_PROMPT, build_video_score, unavailable_score, rating_reason
22
 
23
  FEATURES = ("load_timing", "hip_shoulder_separation", "bat_path_contact")
 
24
  FAILURE_MESSAGES = {
25
  "provider_timeout": "Google did not finish the video review in time. Try the video feedback again.",
26
  "provider_rate_limited": "Google's quota or rate limit for this model was reached. Check its quota in Google AI Studio.",
@@ -48,6 +49,20 @@ Describe visible movement in simple words, not measured diagnoses. Return all
48
  three features: load_timing (hands preparing then swinging); hip_shoulder_separation
49
  (visible order of hip and shoulder turning, NOT a true 3D separation angle);
50
  bat_path_contact (VISIBLE bat route and ball interaction).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  For each feature cite at least two provided frame IDs from ONE rep in chronological
52
  order. Use unclear when occlusion, blur, viewpoint, missing bat/ball or gaps prevent
53
  a supported observation. Never infer contact from an extended arm. For bat path
@@ -78,6 +93,22 @@ class FeatureReview(BaseModel):
78
  ball_interaction_visible: bool = False
79
  rating: VisualRating | None = None
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  class Priority(BaseModel):
83
  model_config = ConfigDict(extra="forbid")
@@ -112,6 +143,11 @@ def unavailable(reason: str) -> dict:
112
  "features": [], "priority": None, "drill": None, "score": unavailable_score()}
113
 
114
 
 
 
 
 
 
115
  def provider_failure(error: Exception) -> dict:
116
  """Report allowlisted error categories, never provider messages or credentials."""
117
  import httpx
@@ -312,6 +348,7 @@ def review_video(frames: list[dict], facts: dict, settings: Settings,
312
  d = next(d for d in all_drills() if d["id"] == note.priority.drill_id)
313
  drill = {k: d[k] for k in ("id", "name", "instructions", "cue")}
314
  return {"status": "completed", "source": "poc_video_review", "model": settings.video_review_model,
 
315
  "accuracy_validated": False, "judgment_eligible": False,
316
  "notice": "Experimental video observations, visual rubric ratings and a practice suggestion; accuracy has not been validated.",
317
  **public, "drill": drill, "score": score, "guardrail_warnings": guardrail_warnings,
 
12
  import uuid
13
  from typing import Literal
14
 
15
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
16
 
17
  from .config import Settings
18
  from .cost import UsageLedger, compute_cost
19
  from .knowledge import all_drills
20
  from .schemas import Usage
21
+ from .visual_scoring import VisualRating, RUBRIC_PROMPT, build_video_score, unavailable_score, rating_reason, score_is_current
22
 
23
  FEATURES = ("load_timing", "hip_shoulder_separation", "bat_path_contact")
24
+ TEXT_STYLE_VERSION = "concise-observations-v1"
25
  FAILURE_MESSAGES = {
26
  "provider_timeout": "Google did not finish the video review in time. Try the video feedback again.",
27
  "provider_rate_limited": "Google's quota or rate limit for this model was reached. Check its quota in Google AI Studio.",
 
49
  three features: load_timing (hands preparing then swinging); hip_shoulder_separation
50
  (visible order of hip and shoulder turning, NOT a true 3D separation angle);
51
  bat_path_contact (VISIBLE bat route and ball interaction).
52
+ Write each observation as one or two short, complete sentences, at most thirty-five
53
+ words. Use correct capitalization and punctuation. Split separate ideas with a
54
+ full stop; avoid long sentences joined by repeated commas or "and". Return plain
55
+ paragraph text, without bullets or headings inside observation.
56
+ Explain the visible detail: name the body part or bat, its direction of movement,
57
+ and the order relative to another visible movement when supported. Prefer simple
58
+ words such as hips, chest, front foot and hands. Describe what changes between
59
+ the cited images, rather than offering a broad impression of the swing.
60
+ Keep the observation neutral and factual. Do not call the swing good, bad, smooth,
61
+ powerful, efficient, ideal or rushed. Avoid unsupported size or quality judgments
62
+ such as "wide stance" or "excellent separation". If evidence is missing, name the
63
+ specific hidden movement or unseen ball briefly. Do not claim that the absence of
64
+ a visible ball proves a miss. Keep any requested rubric grade in rating, separate
65
+ from the observation paragraph.
66
  For each feature cite at least two provided frame IDs from ONE rep in chronological
67
  order. Use unclear when occlusion, blur, viewpoint, missing bat/ball or gaps prevent
68
  a supported observation. Never infer contact from an extended arm. For bat path
 
93
  ball_interaction_visible: bool = False
94
  rating: VisualRating | None = None
95
 
96
+ @field_validator("observation", mode="before")
97
+ @classmethod
98
+ def tidy_observation(cls, value):
99
+ """Normalize presentation without shortening or rewriting evidence."""
100
+ if not isinstance(value, str):
101
+ return value
102
+ value = " ".join(value.split())
103
+ value = re.sub(r"\s+([,.;:!?])", r"\1", value)
104
+ value = re.sub(r"([,;:!?])(?=[A-Za-z])", r"\1 ", value)
105
+ if not value:
106
+ raise ValueError("An observation must contain text")
107
+ value = value[0].upper() + value[1:]
108
+ if value[-1] not in ".!?":
109
+ value += "."
110
+ return value
111
+
112
 
113
  class Priority(BaseModel):
114
  model_config = ConfigDict(extra="forbid")
 
143
  "features": [], "priority": None, "drill": None, "score": unavailable_score()}
144
 
145
 
146
+ def review_is_current(review):
147
+ """Allow an older completed review to refresh its wording exactly once."""
148
+ return score_is_current(review) and review.get("text_style_version") == TEXT_STYLE_VERSION
149
+
150
+
151
  def provider_failure(error: Exception) -> dict:
152
  """Report allowlisted error categories, never provider messages or credentials."""
153
  import httpx
 
348
  d = next(d for d in all_drills() if d["id"] == note.priority.drill_id)
349
  drill = {k: d[k] for k in ("id", "name", "instructions", "cue")}
350
  return {"status": "completed", "source": "poc_video_review", "model": settings.video_review_model,
351
+ "text_style_version": TEXT_STYLE_VERSION,
352
  "accuracy_validated": False, "judgment_eligible": False,
353
  "notice": "Experimental video observations, visual rubric ratings and a practice suggestion; accuracy has not been validated.",
354
  **public, "drill": drill, "score": score, "guardrail_warnings": guardrail_warnings,
baseball_batting/api.py CHANGED
@@ -76,7 +76,7 @@ def create_app(settings=None, service=None):
76
  service.start()
77
  try: yield
78
  finally: service.stop()
79
- app = FastAPI(title="Baseball Swing Engine and Coach", version="1.7.1", lifespan=lifespan,
80
  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.")
81
  app.state.service = service
82
  app.add_middleware(UploadGuard, settings=settings, service=service)
@@ -325,8 +325,8 @@ def create_app(settings=None, service=None):
325
  try:
326
  with service.mutation_lock:
327
  directory, payload = stored_product(job_id)
328
- from ai_coach.visual_scoring import score_is_current
329
- if score_is_current(payload['visual_review']):
330
  return JSONResponse(payload, headers={'Cache-Control': 'no-store'})
331
  if not payload['evidence']['frames']:
332
  raise HTTPException(409, 'No retained video frames; upload again with video feedback enabled')
 
76
  service.start()
77
  try: yield
78
  finally: service.stop()
79
+ app = FastAPI(title="Baseball Swing Engine and Coach", version="1.7.2", lifespan=lifespan,
80
  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.")
81
  app.state.service = service
82
  app.add_middleware(UploadGuard, settings=settings, service=service)
 
325
  try:
326
  with service.mutation_lock:
327
  directory, payload = stored_product(job_id)
328
+ from ai_coach.video_review import review_is_current
329
+ if review_is_current(payload['visual_review']):
330
  return JSONResponse(payload, headers={'Cache-Control': 'no-store'})
331
  if not payload['evidence']['frames']:
332
  raise HTTPException(409, 'No retained video frames; upload again with video feedback enabled')
baseball_batting/product.html CHANGED
@@ -33,7 +33,7 @@ function show(product){payload=product;$('results').hidden=false;for(const id of
33
  for(const [key,name] of Object.entries(names)){const card=text('article','',$('features'));card.className='card';text('h2',name,card);const f=product.visual_review.features.find(x=>x.key===key);text('span',f?('Experimental · '+f.status):'Video review unavailable',card).className='tag';text('p',f?f.observation:fallback[key],card);if(f)text('small','Swing '+f.rep+' · frames '+f.evidence_frame_ids.join(', '),card)}
34
  text('h2','Timing estimates',$('timing'));const t=product.coaching.timing;if(t){text('p',t.summary,$('timing'));for(const o of t.observations)text('p',o.text,$('timing'));for(const u of t.unavailable)text('p',u.label+': '+u.text,$('timing'))}else text('p','No supported timing values. Check the recording settings.',$('timing'));
35
  text('h2','Practice suggestion',$('advice'));const v=product.visual_review;if(v.priority&&v.drill){text('p',v.priority.reason,$('advice'));text('h3',v.drill.name,$('advice'));text('p',v.drill.instructions,$('advice'));text('p','Cue: '+v.drill.cue,$('advice'));text('small','Experimental suggestion from visible movement; not a validated fault.',$('advice'))}else if(product.coaching.drill){text('p',product.coaching.summary,$('advice'));text('h3',product.coaching.drill.name,$('advice'));text('p',product.coaching.drill.how,$('advice'))}else{text('p','No supported practice priority from this recording.',$('advice'));if(v.status==='unavailable')text('p',v.message||('Video review: '+v.reason_code),$('advice'))}
36
- const oldScore=!product.visual_review.score||product.visual_review.score.rubric_version!=='visual-swing-v1';$('retry').hidden=(product.visual_review.status!=='unavailable'&&!oldScore)||!product.evidence.frames.length;$('retry').textContent=oldScore&&product.visual_review.status==='completed'?'Update video feedback and score':'Retry video feedback only'; $('json').textContent=JSON.stringify(product,null,2);text('p','Only sampled frames were reviewed.',$('frames'));for(const f of product.evidence.frames){const b=text('button','Show frame '+f.frame,$('frames'));b.style.width='auto';b.onclick=async()=>{b.disabled=true;try{const blob=await(await api(f.url)).blob();const url=URL.createObjectURL(blob);images.push(url);const image=document.createElement('img');image.src=url;image.alt='Swing evidence frame '+f.frame;b.replaceWith(image)}catch(e){b.disabled=false;$('state').textContent=e.message}}}}
37
  async function watch(url){active=url;$('cancel').hidden=false;while(active){const s=await(await api(active)).json();$('state').textContent=s.status+' · job '+s.job_id+(s.progress?' · '+s.progress.stage+(s.progress.total_frames?' · '+s.progress.completed_frames+'/'+s.progress.total_frames+' frames':''):'');if(s.status==='completed'){if(!s.product_url)throw Error('This analysis has measurements only. Upload again with coaching enabled.');show(await(await api(s.product_url)).json());break}if(['failed','cancelled'].includes(s.status))throw Error(s.error||s.status);await new Promise(r=>setTimeout(r,2000))}}
38
  function reset(){active=null;busy=false;$('cancel').hidden=true;$('run').disabled=false;$('load').disabled=false}
39
  $('upload').onsubmit=async e=>{e.preventDefault();if(busy)return;busy=true;$('run').disabled=true;$('load').disabled=true;$('results').hidden=true;$('state').textContent='Uploading…';const options={coaching_mode:$('visual').checked?'poc_video':'measurements_only',view:$('face').checked?'face_on':'unknown',handedness:$('hand').value||null,pitcher_direction:$('direction').value||null,practice_type:$('practice').value,camera_stability:$('fixed').checked?'fixed_verified':'unknown',single_swing:$('single').checked,timing:$('original').checked?{kind:'unretimed',source:'Uploader confirms original recording; no speed changes'}:{kind:'unknown'}};const form=new FormData;form.append('video',$('video').files[0]);form.append('options',JSON.stringify(options));try{const job=await(await api('/v1/swing-coach/analyses',{method:'POST',body:form})).json();$('jobId').value=job.job_id;await watch(job.status_url)}catch(e){$('state').textContent=e.message}finally{reset()}};
 
33
  for(const [key,name] of Object.entries(names)){const card=text('article','',$('features'));card.className='card';text('h2',name,card);const f=product.visual_review.features.find(x=>x.key===key);text('span',f?('Experimental · '+f.status):'Video review unavailable',card).className='tag';text('p',f?f.observation:fallback[key],card);if(f)text('small','Swing '+f.rep+' · frames '+f.evidence_frame_ids.join(', '),card)}
34
  text('h2','Timing estimates',$('timing'));const t=product.coaching.timing;if(t){text('p',t.summary,$('timing'));for(const o of t.observations)text('p',o.text,$('timing'));for(const u of t.unavailable)text('p',u.label+': '+u.text,$('timing'))}else text('p','No supported timing values. Check the recording settings.',$('timing'));
35
  text('h2','Practice suggestion',$('advice'));const v=product.visual_review;if(v.priority&&v.drill){text('p',v.priority.reason,$('advice'));text('h3',v.drill.name,$('advice'));text('p',v.drill.instructions,$('advice'));text('p','Cue: '+v.drill.cue,$('advice'));text('small','Experimental suggestion from visible movement; not a validated fault.',$('advice'))}else if(product.coaching.drill){text('p',product.coaching.summary,$('advice'));text('h3',product.coaching.drill.name,$('advice'));text('p',product.coaching.drill.how,$('advice'))}else{text('p','No supported practice priority from this recording.',$('advice'));if(v.status==='unavailable')text('p',v.message||('Video review: '+v.reason_code),$('advice'))}
36
+ const oldReview=!product.visual_review.score||product.visual_review.score.rubric_version!=='visual-swing-v1'||product.visual_review.text_style_version!=='concise-observations-v1';$('retry').hidden=(product.visual_review.status!=='unavailable'&&!oldReview)||!product.evidence.frames.length;$('retry').textContent=oldReview&&product.visual_review.status==='completed'?'Update video feedback':'Retry video feedback only'; $('json').textContent=JSON.stringify(product,null,2);text('p','Only sampled frames were reviewed.',$('frames'));for(const f of product.evidence.frames){const b=text('button','Show frame '+f.frame,$('frames'));b.style.width='auto';b.onclick=async()=>{b.disabled=true;try{const blob=await(await api(f.url)).blob();const url=URL.createObjectURL(blob);images.push(url);const image=document.createElement('img');image.src=url;image.alt='Swing evidence frame '+f.frame;b.replaceWith(image)}catch(e){b.disabled=false;$('state').textContent=e.message}}}}
37
  async function watch(url){active=url;$('cancel').hidden=false;while(active){const s=await(await api(active)).json();$('state').textContent=s.status+' · job '+s.job_id+(s.progress?' · '+s.progress.stage+(s.progress.total_frames?' · '+s.progress.completed_frames+'/'+s.progress.total_frames+' frames':''):'');if(s.status==='completed'){if(!s.product_url)throw Error('This analysis has measurements only. Upload again with coaching enabled.');show(await(await api(s.product_url)).json());break}if(['failed','cancelled'].includes(s.status))throw Error(s.error||s.status);await new Promise(r=>setTimeout(r,2000))}}
38
  function reset(){active=null;busy=false;$('cancel').hidden=true;$('run').disabled=false;$('load').disabled=false}
39
  $('upload').onsubmit=async e=>{e.preventDefault();if(busy)return;busy=true;$('run').disabled=true;$('load').disabled=true;$('results').hidden=true;$('state').textContent='Uploading…';const options={coaching_mode:$('visual').checked?'poc_video':'measurements_only',view:$('face').checked?'face_on':'unknown',handedness:$('hand').value||null,pitcher_direction:$('direction').value||null,practice_type:$('practice').value,camera_stability:$('fixed').checked?'fixed_verified':'unknown',single_swing:$('single').checked,timing:$('original').checked?{kind:'unretimed',source:'Uploader confirms original recording; no speed changes'}:{kind:'unknown'}};const form=new FormData;form.append('video',$('video').files[0]);form.append('options',JSON.stringify(options));try{const job=await(await api('/v1/swing-coach/analyses',{method:'POST',body:form})).json();$('jobId').value=job.job_id;await watch(job.status_url)}catch(e){$('state').textContent=e.message}finally{reset()}};
docs/APP_API_INTEGRATION.md CHANGED
@@ -341,6 +341,12 @@ When `visual_review.status` is `"completed"`, render its features:
341
  | `hip_shoulder_separation` | Hips and shoulders | `feature.observation` |
342
  | `bat_path_contact` | Bat path and contact | `feature.observation` |
343
 
 
 
 
 
 
 
344
  Each feature also contains `status` (`"observed"` or `"unclear"`), `rep`,
345
  `evidence_frame_ids`, and `ball_interaction_visible`. Show unclear observations
346
  as uncertainty, not as a diagnosed problem. Label this section “Experimental
@@ -514,7 +520,7 @@ player uses it. Forward authenticated JSON error responses for failed requests.
514
 
515
  This returns the updated whole product. It reuses retained images and keeps
516
  the measurements and swing clips. It does not repeat pose inference. A completed
517
- review with the current visual-scoring rubric is returned unchanged, without
518
  another Gemini call. An older completed review with retained frames can be
519
  explicitly upgraded once using this route. An unavailable review
520
  can be retried; a genuine retry consumes Gemini quota. Allow a longer request
 
341
  | `hip_shoulder_separation` | Hips and shoulders | `feature.observation` |
342
  | `bat_path_contact` | Bat path and contact | `feature.observation` |
343
 
344
+ New reviews include `visual_review.text_style_version: "concise-observations-v1"`.
345
+ The prompt asks for one or two complete sentences, at most thirty-five words per
346
+ observation. Text describes the visible body part, movement direction and order,
347
+ with a brief specific limitation when necessary. Render `observation` as returned;
348
+ do not cut it mid-sentence. The numerical measurements and score rules are unchanged.
349
+
350
  Each feature also contains `status` (`"observed"` or `"unclear"`), `rep`,
351
  `evidence_frame_ids`, and `ball_interaction_visible`. Show unclear observations
352
  as uncertainty, not as a diagnosed problem. Label this section “Experimental
 
520
 
521
  This returns the updated whole product. It reuses retained images and keeps
522
  the measurements and swing clips. It does not repeat pose inference. A completed
523
+ review with the current visual-scoring rubric and wording style is returned unchanged, without
524
  another Gemini call. An older completed review with retained frames can be
525
  explicitly upgraded once using this route. An unavailable review
526
  can be retried; a genuine retry consumes Gemini quota. Allow a longer request
docs/SWING_COACH_PRODUCT.md CHANGED
@@ -65,9 +65,10 @@ Use Bearer authorization with the **engine** API key for these endpoints:
65
  6. `DELETE /v1/analyses/{job_id}`: cancel and delete results and evidence.
66
  7. `POST /v1/analyses/{job_id}/video-review`: retry unavailable video feedback
67
  using retained, checksum-verified original images. It preserves measurements
68
- and returns the updated product. A completed current-rubric review is returned
69
- without a further model call; older completed reviews can upgrade their video
70
- score using the retained images. Only one retry runs at a time. No retained images means
 
71
  a new upload is required. The upload screen provides this retry button.
72
 
73
  Recording options example; replace the values to match the recording:
 
65
  6. `DELETE /v1/analyses/{job_id}`: cancel and delete results and evidence.
66
  7. `POST /v1/analyses/{job_id}/video-review`: retry unavailable video feedback
67
  using retained, checksum-verified original images. It preserves measurements
68
+ and returns the updated product. A completed review with the current rubric and
69
+ wording style is returned without a further model call; older completed reviews
70
+ can refresh their feedback using the retained images. New reviews include
71
+ `text_style_version: "concise-observations-v1"`. Only one retry runs at a time. No retained images means
72
  a new upload is required. The upload screen provides this retry button.
73
 
74
  Recording options example; replace the values to match the recording:
tests/test_product.py CHANGED
@@ -153,6 +153,23 @@ def test_visual_review_success_uses_library_drill_and_no_measurement_upgrade(tmp
153
  assert result['accuracy_validated'] is False and result['judgment_eligible'] is False
154
 
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  @pytest.mark.parametrize('bad',['invented_frame','wrong_rep','duplicate','reversed','one_frame','angle','numeric_priority','wrong_drill','unclear_priority','duplicate_feature'])
157
  def test_visual_review_rejects_unsupported_responses(tmp_path,bad):
158
  raw=note(); f=raw['features'][0]
@@ -332,7 +349,8 @@ def test_retry_review_preserves_measurements_auth_and_checksums(tmp_path,monkeyp
332
  calls.append(frames)
333
  assert frames[0]['jpeg']==b'original-image'
334
  from ai_coach.visual_scoring import unavailable_score
335
- return {'status':'completed','features':[],'score':unavailable_score('insufficient_visible_features')}
 
336
  monkeypatch.setattr(review,'review_video',fake_review)
337
  # Exercise the actual retained-frame loader, not a replacement retry handler.
338
  assert retry_video_review(job,product,AnalysisInput())['visual_review']['status']=='completed'
 
153
  assert result['accuracy_validated'] is False and result['judgment_eligible'] is False
154
 
155
 
156
+ def test_observation_presentation_keeps_evidence_and_handles_spacing(tmp_path):
157
+ data = note()
158
+ data['features'][0]['observation'] = ' the hands move back , then forward\n'
159
+ original = deepcopy(data)
160
+ result = review_video(frames(), {}, coach_settings(tmp_path),
161
+ generator=lambda *a: (json.dumps(data), Usage()))
162
+ assert result['status'] == 'completed'
163
+ assert result['features'][0]['observation'] == 'The hands move back, then forward.'
164
+ assert result['features'][0]['evidence_frame_ids'] == [0, 1]
165
+ assert data == original
166
+ from ai_coach.video_review import review_is_current
167
+ assert review_is_current(result)
168
+ legacy = deepcopy(result)
169
+ legacy.pop('text_style_version')
170
+ assert not review_is_current(legacy)
171
+
172
+
173
  @pytest.mark.parametrize('bad',['invented_frame','wrong_rep','duplicate','reversed','one_frame','angle','numeric_priority','wrong_drill','unclear_priority','duplicate_feature'])
174
  def test_visual_review_rejects_unsupported_responses(tmp_path,bad):
175
  raw=note(); f=raw['features'][0]
 
349
  calls.append(frames)
350
  assert frames[0]['jpeg']==b'original-image'
351
  from ai_coach.visual_scoring import unavailable_score
352
+ return {'status':'completed','features':[], 'text_style_version':review.TEXT_STYLE_VERSION,
353
+ 'score':unavailable_score('insufficient_visible_features')}
354
  monkeypatch.setattr(review,'review_video',fake_review)
355
  # Exercise the actual retained-frame loader, not a replacement retry handler.
356
  assert retry_video_review(job,product,AnalysisInput())['visual_review']['status']=='completed'
tests/test_visual_scoring.py CHANGED
@@ -169,7 +169,8 @@ def test_product_adds_visual_score_without_upgrading_mechanics_or_timing(tmp_pat
169
  assert product['timing']==timing==original
170
 
171
 
172
- def test_old_completed_review_can_upgrade_once_without_repeating_gpu_or_losing_clips(tmp_path,monkeypatch):
 
173
  from fastapi.testclient import TestClient
174
  from baseball_batting.api import create_app
175
  from baseball_batting.storage import atomic_json,sha256_file
@@ -177,12 +178,15 @@ def test_old_completed_review_can_upgrade_once_without_repeating_gpu_or_losing_c
177
  import ai_coach.video_review as module
178
  service,identifier,job,product=retained_review_job(tmp_path)
179
  product['visual_review']={'status':'completed','features':[]}
 
 
180
  atomic_json(job/'product.json',product)
181
  service.store.update_product(identifier,sha256_file(job/'product.json'))
182
  calls=[]
183
  def upgraded(*args,**kwargs):
184
  calls.append(True)
185
- return {'status':'completed','features':[],'score':unavailable_score('insufficient_visible_features')}
 
186
  monkeypatch.setattr(module,'review_video',upgraded)
187
  with TestClient(create_app(service.settings,service)) as client:
188
  wait_until(lambda:service.ready)
 
169
  assert product['timing']==timing==original
170
 
171
 
172
+ @pytest.mark.parametrize('legacy', ['missing_score', 'old_wording'])
173
+ def test_old_completed_review_can_upgrade_once_without_repeating_gpu_or_losing_clips(tmp_path,monkeypatch,legacy):
174
  from fastapi.testclient import TestClient
175
  from baseball_batting.api import create_app
176
  from baseball_batting.storage import atomic_json,sha256_file
 
178
  import ai_coach.video_review as module
179
  service,identifier,job,product=retained_review_job(tmp_path)
180
  product['visual_review']={'status':'completed','features':[]}
181
+ if legacy == 'old_wording':
182
+ product['visual_review']['score'] = unavailable_score('insufficient_visible_features')
183
  atomic_json(job/'product.json',product)
184
  service.store.update_product(identifier,sha256_file(job/'product.json'))
185
  calls=[]
186
  def upgraded(*args,**kwargs):
187
  calls.append(True)
188
+ return {'status':'completed','features':[], 'text_style_version':module.TEXT_STYLE_VERSION,
189
+ 'score':unavailable_score('insufficient_visible_features')}
190
  monkeypatch.setattr(module,'review_video',upgraded)
191
  with TestClient(create_app(service.settings,service)) as client:
192
  wait_until(lambda:service.ready)