Spaces:
Running on T4
Running on T4
File size: 6,038 Bytes
326d3cc | 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 | import json
from pathlib import Path
import numpy as np
import pytest
from baseball_batting.ingest import ingest, physical_time, orientation_matrix, validate_metadata
from baseball_batting.storage import StageCache, atomic_json, digest, read_json
from baseball_batting.contracts import json_safe
from baseball_batting.metrics import flexion_degrees, derivative
from baseball_batting.config import EngineConfig
from baseball_batting.detection import decode_yolox, select_person, verify_cuda_nodes
from baseball_batting.body3d import native_mhr_positions_to_sam_camera, translate_sam_positions
from baseball_batting.annotations import load_annotations
def test_decode_and_clock(video):
c = ingest(video, {})
assert c["frame_count"] == 8
assert not c["physical_clock_known"]
assert all(f["physical_s"] is None for f in c["frames"])
np.testing.assert_allclose([f["playback_s"] for f in c["frames"]], [0,.033,.066,.1,.15,.183,.216,.25], atol=.001)
assert all(f["pts"] is not None for f in c["frames"])
def test_declared_clock(video):
c = ingest(video, {"timing": {"kind": "constant_slowdown", "factor": 4,
"source": "synthetic retained frames", "all_captured_frames_retained": True}})
assert c["physical_clock_known"]
assert c["frames"][-1]["physical_s"] == pytest.approx(.25/4, abs=.001)
@pytest.mark.parametrize("timing", [
{"kind": "constant_slowdown", "factor": 0, "source": "test", "all_captured_frames_retained": True},
{"kind": "constant_slowdown", "factor": 4, "source": "test"},
{"kind": "unretimed"}, {"kind": "explicit", "source": "test", "physical_times_s": [0,0]},
{"kind": "explicit", "source": "test", "physical_times_s": [0,float("nan")]},
])
def test_bad_timing_rejected(timing):
with pytest.raises(ValueError):
validate_metadata({"timing": timing})
def test_explicit_time_map_count(video):
with pytest.raises(ValueError, match="shorter"):
ingest(video, {"timing": {"kind": "explicit", "source": "test", "physical_times_s": [0,1]}})
@pytest.mark.parametrize("angle,expected", [(0,[10,20,1]),(90,[99,10,1]),(180,[149,99,1]),(270,[20,149,1])])
def test_orientation(angle,expected):
np.testing.assert_allclose(orientation_matrix(160,120,angle) @ [10,20,1], expected)
def test_stage_integrity_and_key(tmp_path):
cache = StageCache(tmp_path, "test", digest({"model": "one"}))
p = cache.root / "points.json"
atomic_json(p, [1,2])
cache.commit("chunk_0", [p])
assert cache.valid("chunk_0")
p.write_text("corrupt")
assert cache.valid("chunk_0") is None
assert StageCache(tmp_path, "test", digest({"model": "two"})).valid("chunk_0") is None
def test_json_nulls():
assert json_safe({"value": np.float64(np.nan)}) == {"value": None}
json.dumps(json_safe(np.array([np.nan, np.inf])), allow_nan=False)
@pytest.mark.parametrize("a,b,c,expected", [([-1,0],[0,0],[1,0],0), ([0,1],[0,0],[1,0],90), ([1,0],[0,0],[1,0],180)])
def test_flexion_convention(a,b,c,expected):
assert flexion_degrees(a,b,c) == pytest.approx(expected)
def test_degenerate_joint():
assert np.isnan(flexion_degrees([0,0],[0,0],[1,0]))
def test_derivative_nonuniform_and_gaps():
t = np.array([0,.1,.25,.4,.6,.8,1.0])
values = t**2
np.testing.assert_allclose(derivative(values,t), 2*t, atol=1e-12)
values[3] = np.nan
d = derivative(values,t)
assert np.isnan(d[3])
np.testing.assert_allclose(d[:3], 2*t[:3], atol=1e-12)
np.testing.assert_allclose(d[4:], 2*t[4:], atol=1e-12)
def test_detector_retains_class_scores():
count = sum((640//s)**2 for s in (8,16,32))
raw = np.zeros((1,count,85), np.float32)
raw[0,0,:4] = [10,10,1,1]
raw[0,0,4] = .8
raw[0,0,5+34] = .9
detections = decode_yolox(raw)
assert len(detections) == 1
assert detections[0]["class_id"] == 34
assert detections[0]["score"] == pytest.approx(.72)
def test_person_identity_does_not_jump():
assert select_person([{"class_id":0,"box":[100,100,200,200],"score":.9}], [0,0,20,20]) is None
def test_integrated_nms_person_scores():
raw = np.array([[[10,20,30,40,.8], [0,0,0,0,0]]], np.float32)
detections = decode_yolox(raw, ratio=.5, classes=[0])
assert len(detections) == 1
assert detections[0]["score"] == pytest.approx(.8)
assert detections[0]["box"] == [20,40,60,80]
with pytest.raises(ValueError):
decode_yolox(raw, classes=[0,32,34])
def test_person_only_raw_export_rejected_for_objects():
raw = np.zeros((1,8400,6),np.float32)
with pytest.raises(ValueError,match="Person-only"):
decode_yolox(raw,classes=[0,32,34])
@pytest.mark.parametrize("provider", ["CPUExecutionProvider", "CUDAExecutionProvider"])
def test_cuda_proof_requires_executed_node(tmp_path,provider):
profile = tmp_path/"profile.json"
profile.write_text(json.dumps([{"args":{"provider":provider}}]))
class Session:
def end_profiling(self):
return str(profile)
if provider == "CPUExecutionProvider":
with pytest.raises(RuntimeError,match="No CUDA"):
verify_cuda_nodes(Session())
else:
verify_cuda_nodes(Session())
assert not profile.exists()
def test_mhr_units_and_translation_once():
native = np.array([[100,200,300]])
camera = native_mhr_positions_to_sam_camera(native)
np.testing.assert_allclose(camera, [[1,-2,-3]])
np.testing.assert_allclose(translate_sam_positions(camera,[0,0,5]), [[1,-2,2]])
@pytest.mark.parametrize("cfg", [EngineConfig(learned_events_enabled="yes"), EngineConfig(bat_3d_mode=None),
EngineConfig(chunk_size=0), EngineConfig(annotations_path="x")])
def test_invalid_configuration_rejected(cfg):
with pytest.raises(ValueError):
cfg.validate()
def test_wrong_annotation_video(tmp_path):
p = tmp_path / "a.json"
atomic_json(p, {"schema_version":"1.0", "input_sha256":"wrong", "annotator":"test"})
with pytest.raises(ValueError):
load_annotations(p,"expected",8,160,120)
|