Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
64a7cee
1
Parent(s): 314c3d8
Automated Deploy: 4cf3b4dd244510362bb7b19a95f99598e0446a20
Browse files- baseball_batting/contact_vision.py +2 -1
- baseball_batting/contact_worker.py +13 -4
- docs/CONTACT_API.md +5 -0
- tests/test_contact_api.py +12 -0
baseball_batting/contact_vision.py
CHANGED
|
@@ -74,12 +74,13 @@ def collect(video, capture, models, progress=lambda *a:None, device='cuda'):
|
|
| 74 |
roi=image[a[1]:b[1],a[0]:b[0]]
|
| 75 |
row['bat']=deduplicate(row['bat']+bat(roi,a))
|
| 76 |
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
|
| 77 |
-
matrix=background_transform(previous,gray,old_boxes+boxes) if previous is not None else np.eye(3)
|
| 78 |
if matrix is None:
|
| 79 |
segment+=1;transform=np.eye(3)
|
| 80 |
else:
|
| 81 |
transform=transform@np.linalg.inv(matrix)
|
| 82 |
row.update(source_frame_index=i,segment_id=segment,
|
|
|
|
| 83 |
video_time_s=float(record['playback_s']-capture['frames'][0]['playback_s']),
|
| 84 |
camera_motion_status='unresolved' if matrix is None else 'background_affine_estimated')
|
| 85 |
original.append(row)
|
|
|
|
| 74 |
roi=image[a[1]:b[1],a[0]:b[0]]
|
| 75 |
row['bat']=deduplicate(row['bat']+bat(roi,a))
|
| 76 |
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
|
| 77 |
+
matrix=(background_transform(previous,gray,old_boxes+boxes) if previous.shape==gray.shape else None) if previous is not None else np.eye(3)
|
| 78 |
if matrix is None:
|
| 79 |
segment+=1;transform=np.eye(3)
|
| 80 |
else:
|
| 81 |
transform=transform@np.linalg.inv(matrix)
|
| 82 |
row.update(source_frame_index=i,segment_id=segment,
|
| 83 |
+
image_width=image.shape[1],image_height=image.shape[0],
|
| 84 |
video_time_s=float(record['playback_s']-capture['frames'][0]['playback_s']),
|
| 85 |
camera_motion_status='unresolved' if matrix is None else 'background_affine_estimated')
|
| 86 |
original.append(row)
|
baseball_batting/contact_worker.py
CHANGED
|
@@ -16,6 +16,7 @@ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retenti
|
|
| 16 |
from .contact_vision import collect
|
| 17 |
from .contact_audio import inspect
|
| 18 |
from .contact_videos import export
|
|
|
|
| 19 |
job=Path(job);options=ContactInput.model_validate(read_json(job/'request.json'));started=time.monotonic()
|
| 20 |
def progress(stage,done=0,total=None):
|
| 21 |
atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
|
|
@@ -35,7 +36,13 @@ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retenti
|
|
| 35 |
'confidence_meaning':'object detector scores; not contact correctness'},allow_nan=False)+'\n')
|
| 36 |
duration=float(playback[-1]-playback[0])
|
| 37 |
audio=inspect(video,float(playback[0]),duration,contact,options.use_audio)
|
| 38 |
-
clips=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
source=job/('source'+video.suffix)
|
| 40 |
if source.exists():
|
| 41 |
if sha256_file(source)!=capture['input_sha256']:raise ValueError('Source differs from retained input')
|
|
@@ -51,7 +58,8 @@ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retenti
|
|
| 51 |
for key in ('annotated','evidence'):
|
| 52 |
artifacts[key]=asset(key,job/(key+'.mp4'),'mp4','video/mp4') if key in clips else {
|
| 53 |
'status':'unavailable','format':'mp4','media_type':'video/mp4','expires_at':expiry,
|
| 54 |
-
'reason_code':'not_requested' if not options.annotated_video else
|
|
|
|
| 55 |
result=ContactResult(job_id=job.name,contact=contact,audio=audio,expires_at=expiry,
|
| 56 |
source_video={'sha256':capture['input_sha256'],'frame_count':len(original),
|
| 57 |
'display_width':capture['frames'][0]['width'],'display_height':capture['frames'][0]['height'],
|
|
@@ -64,10 +72,11 @@ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retenti
|
|
| 64 |
'notice':'Fitted subframe time is an estimate. Frame spacing and transition interval limit timing resolution.'},
|
| 65 |
pipeline={'version':VERSION,'device':device,'models':model,'options':options.model_dump(mode='json'),
|
| 66 |
'implementation_sha256':{name:sha256_file(Path(__file__).with_name(name)) for name in
|
| 67 |
-
('
|
|
|
|
| 68 |
'requires_pose':False,'requires_3d':False,'requires_manual_events':False,
|
| 69 |
'object_gap_filling':False,'contact_verification':'visual_estimate_only; independent_accuracy_validation_pending',
|
| 70 |
-
'clips':clips},artifacts=artifacts)
|
| 71 |
atomic_json(job/'result.json',result.model_dump(mode='json'));progress('complete',len(original),len(original))
|
| 72 |
return result
|
| 73 |
|
|
|
|
| 16 |
from .contact_vision import collect
|
| 17 |
from .contact_audio import inspect
|
| 18 |
from .contact_videos import export
|
| 19 |
+
from .swing_clips import ClipError
|
| 20 |
job=Path(job);options=ContactInput.model_validate(read_json(job/'request.json'));started=time.monotonic()
|
| 21 |
def progress(stage,done=0,total=None):
|
| 22 |
atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
|
|
|
|
| 36 |
'confidence_meaning':'object detector scores; not contact correctness'},allow_nan=False)+'\n')
|
| 37 |
duration=float(playback[-1]-playback[0])
|
| 38 |
audio=inspect(video,float(playback[0]),duration,contact,options.use_audio)
|
| 39 |
+
clips={};video_export_reason=None
|
| 40 |
+
if options.annotated_video:
|
| 41 |
+
try:clips=export(video,capture,original,contact,job,progress)
|
| 42 |
+
except ClipError as error:
|
| 43 |
+
# Some valid containers omit final sample duration. Do not invent
|
| 44 |
+
# FPS/durations or discard an otherwise usable contact result.
|
| 45 |
+
video_export_reason=str(error)
|
| 46 |
source=job/('source'+video.suffix)
|
| 47 |
if source.exists():
|
| 48 |
if sha256_file(source)!=capture['input_sha256']:raise ValueError('Source differs from retained input')
|
|
|
|
| 58 |
for key in ('annotated','evidence'):
|
| 59 |
artifacts[key]=asset(key,job/(key+'.mp4'),'mp4','video/mp4') if key in clips else {
|
| 60 |
'status':'unavailable','format':'mp4','media_type':'video/mp4','expires_at':expiry,
|
| 61 |
+
'reason_code':('not_requested' if not options.annotated_video else
|
| 62 |
+
video_export_reason or 'contact_not_located')}
|
| 63 |
result=ContactResult(job_id=job.name,contact=contact,audio=audio,expires_at=expiry,
|
| 64 |
source_video={'sha256':capture['input_sha256'],'frame_count':len(original),
|
| 65 |
'display_width':capture['frames'][0]['width'],'display_height':capture['frames'][0]['height'],
|
|
|
|
| 72 |
'notice':'Fitted subframe time is an estimate. Frame spacing and transition interval limit timing resolution.'},
|
| 73 |
pipeline={'version':VERSION,'device':device,'models':model,'options':options.model_dump(mode='json'),
|
| 74 |
'implementation_sha256':{name:sha256_file(Path(__file__).with_name(name)) for name in
|
| 75 |
+
('contact_worker.py','contact_contract.py','contact_detection.py','contact_vision.py',
|
| 76 |
+
'contact_audio.py','contact_videos.py','bat_ball_timing.py','tracking_vision.py','detection.py','ingest.py')},
|
| 77 |
'requires_pose':False,'requires_3d':False,'requires_manual_events':False,
|
| 78 |
'object_gap_filling':False,'contact_verification':'visual_estimate_only; independent_accuracy_validation_pending',
|
| 79 |
+
'clips':clips,'video_export_reason':video_export_reason},artifacts=artifacts)
|
| 80 |
atomic_json(job/'result.json',result.model_dump(mode='json'));progress('complete',len(original),len(original))
|
| 81 |
return result
|
| 82 |
|
docs/CONTACT_API.md
CHANGED
|
@@ -61,6 +61,8 @@ The bat and ball models must pass CUDA preflight. Defaults are 512 MiB upload,
|
|
| 61 |
120 seconds, 7,200 decoded frames and 24-hour retention; consult capabilities and
|
| 62 |
server settings. A high-frame-rate clip can reach the frame cap sooner; there is
|
| 63 |
no minimum-FPS rule and no resampling or intentionally skipped source frames.
|
|
|
|
|
|
|
| 64 |
|
| 65 |
## Response and timing
|
| 66 |
|
|
@@ -144,6 +146,9 @@ Common unavailable reasons:
|
|
| 144 |
- `multiple_contact_candidates`
|
| 145 |
|
| 146 |
A job completes successfully with unavailable contact when detection is uncertain.
|
|
|
|
|
|
|
|
|
|
| 147 |
Invalid media/timestamps or a worker/model failure instead fail the job. Model
|
| 148 |
availability is checked before upload allocation. Limits and readiness are not
|
| 149 |
claims that the pretrained models detect every phone recording reliably.
|
|
|
|
| 61 |
120 seconds, 7,200 decoded frames and 24-hour retention; consult capabilities and
|
| 62 |
server settings. A high-frame-rate clip can reach the frame cap sooner; there is
|
| 63 |
no minimum-FPS rule and no resampling or intentionally skipped source frames.
|
| 64 |
+
Retention depends on the server's storage: an ephemeral Space rebuild can remove
|
| 65 |
+
jobs earlier. Your app should retain completed report assets in its own storage.
|
| 66 |
|
| 67 |
## Response and timing
|
| 68 |
|
|
|
|
| 146 |
- `multiple_contact_candidates`
|
| 147 |
|
| 148 |
A job completes successfully with unavailable contact when detection is uncertain.
|
| 149 |
+
If source timing cannot support a faithful annotation export (for example, a
|
| 150 |
+
missing final-sample duration), the contact JSON and source/observations remain
|
| 151 |
+
available; video artifacts carry the export reason. Playback FPS is not invented.
|
| 152 |
Invalid media/timestamps or a worker/model failure instead fail the job. Model
|
| 153 |
availability is checked before upload allocation. Limits and readiness are not
|
| 154 |
claims that the pretrained models detect every phone recording reliably.
|
tests/test_contact_api.py
CHANGED
|
@@ -133,3 +133,15 @@ def test_optional_audio_never_creates_contact_or_changes_video_time(tmp_path):
|
|
| 133 |
assert audio['status']=='analyzed' and audio['transient_video_times_s']
|
| 134 |
assert audio['used_for_contact_timestamp'] is False and unknown.status=='unavailable'
|
| 135 |
assert inspect(path,0,1,unknown,False)['status']=='not_requested'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
assert audio['status']=='analyzed' and audio['transient_video_times_s']
|
| 134 |
assert audio['used_for_contact_timestamp'] is False and unknown.status=='unavailable'
|
| 135 |
assert inspect(path,0,1,unknown,False)['status']=='not_requested'
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_unavailable_annotation_timing_preserves_contact_json(video,tmp_path,monkeypatch):
|
| 139 |
+
from baseball_batting.swing_clips import ClipError
|
| 140 |
+
def failed_export(*a,**k):raise ClipError('last_frame_duration_unavailable')
|
| 141 |
+
monkeypatch.setattr('baseball_batting.contact_videos.export',failed_export)
|
| 142 |
+
service=fake_service(settings(tmp_path));job,result=stored(service,video,monkeypatch)
|
| 143 |
+
assert result.contact.status=='estimated'
|
| 144 |
+
assert result.artifacts['source'].status=='available'
|
| 145 |
+
assert result.artifacts['observations'].status=='available'
|
| 146 |
+
assert result.artifacts['annotated'].status=='unavailable'
|
| 147 |
+
assert result.artifacts['annotated'].reason_code=='last_frame_duration_unavailable'
|