File size: 5,745 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
from pathlib import Path
import json
import numpy as np
import pytest
from baseball_batting.pipeline import run_engine
from baseball_batting.config import EngineConfig
from baseball_batting.storage import sha256_file, atomic_json
from baseball_batting.ingest import iter_frames

def reviewed_labels(video, tmp_path):
    frames = {}
    for i in range(8):
        frames[str(i)] = {"landmarks": {"left_shoulder":[30,40], "left_elbow":[40,40], "left_wrist":[50+i,40],
                           "right_shoulder":[70,40], "right_elbow":[80,40], "right_wrist":[90+i,40],
                           "left_hip":[40,60], "left_knee":[40,80], "left_ankle":[40,100],
                           "right_hip":[80,60], "right_knee":[80,80], "right_ankle":[80,100]},
                          "knob":[60+i,40], "barrel":[100+i,30]}
    path = tmp_path / "reviewed.json"
    atomic_json(path, {"schema_version":"1.0", "input_sha256":sha256_file(video), "annotator":"fixture_operator",
                      "frames":frames, "events":[{"type":"dry_swing","state":"confirmed","frame_interval":[0,7],
                                                  "evidence_frames":[0,1,2,3,4,5,6,7],"evidence_description":"Synthetic fixture has no ball"}]})
    return path

def test_no_models_returns_honest_partial(video,tmp_path):
    root = tmp_path / "out"
    result = run_engine(video,root,EngineConfig(chunk_size=3))
    assert result["status"] == "partial"
    assert all(m["value"] is None for m in result["metrics"])
    assert result["stages"]["body_pose"]["status"] == "unavailable"
    assert next(e for e in result["events"] if e["type"] == "contact")["state"] == "unknown"
    assert not result["findings"]
    assert (root/"report.html").exists()
    assert result["stages"]["video_export"]["status"] == "complete", result["stages"]["video_export"]
    src = [(pts*tb) for _,pts,tb,_ in iter_frames(video)]
    dst = [(pts*tb) for _,pts,tb,_ in iter_frames(root/"annotated.mp4")]
    np.testing.assert_allclose([float(x) for x in src],[float(x) for x in dst],atol=.001)

def test_reviewed_metrics_and_unknown_physical_speed(video,tmp_path):
    labels = reviewed_labels(video,tmp_path)
    result = run_engine(video,tmp_path/"out",EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=3),
                        {"camera_stability":"fixed_verified", "player_id":"generated_fixture"})
    assert result["provenance"] == "human_assisted"
    metrics = {m["metric_id"]:m for m in result["metrics"]}
    assert metrics["left_elbow_projected_flexion_deg_median"]["value"] == pytest.approx(0)
    assert metrics["left_hand_projected_path_length"]["value"] == pytest.approx(7)
    assert metrics["left_hand_projected_path_length"]["provenance"] == ["manual"]
    assert metrics["left_hand_peak_projected_speed"]["value"] is None
    assert metrics["bat_sweet_spot_speed_at_contact"]["value"] is None
    assert next(e for e in result["events"] if e["type"] == "dry_swing")["state"] == "confirmed"
    assert all(f["expert_review"] == "not_reviewed" and f["research_exercise"] is None for f in result["findings"])

def test_resume_verifies_chunks_and_annotation_invalidates(video,tmp_path):
    labels = reviewed_labels(video,tmp_path)
    root = tmp_path/"out"
    cfg = EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=3,export_video=False)
    first = run_engine(video,root,cfg)
    chunks = sorted((root/"stages"/"observations").rglob("chunk_*.json"))
    before = {str(p):p.stat().st_mtime_ns for p in chunks}
    second = run_engine(video,root,cfg)
    assert first["metrics"] == second["metrics"]
    assert before == {str(p):p.stat().st_mtime_ns for p in chunks}
    # An incomplete/corrupt chunk is rerun instead of trusted.
    record = next(p for p in chunks if p.name.endswith("000001.json"))
    record.write_text("corrupt")
    run_engine(video,root,cfg)
    assert json.loads(record.read_text())["frames"][0]["frame_id"] == 3
    labels_data = json.loads(labels.read_text())
    labels_data["frames"]["0"]["landmarks"]["left_elbow"] = [40,50]
    atomic_json(labels,labels_data)
    run_engine(video,root,cfg)
    assert len(list((root/"stages"/"observations").iterdir())) == 2

def test_chunk_equivalence(video,tmp_path):
    labels = reviewed_labels(video,tmp_path)
    a = run_engine(video,tmp_path/"a",EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=2,export_video=False))
    b = run_engine(video,tmp_path/"b",EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=99,export_video=False))
    assert a["metrics"] == b["metrics"]
    assert a["events"] == b["events"]

def test_missing_gpu_does_not_block_2d(video,tmp_path):
    result = run_engine(video,tmp_path/"out",EngineConfig(body3d_enabled=True,export_video=False))
    assert result["stages"]["body3d"]["status"] == "unavailable"
    assert result["stages"]["observations"]["status"] == "empty"

def test_untrained_and_unsupported_branches_return_partial(video,tmp_path):
    result = run_engine(video,tmp_path/"out",EngineConfig(learned_events_enabled=True,
                        bat_3d_mode="requested",export_video=False))
    assert result["stages"]["learned_events"]["status"] == "unavailable"
    assert result["stages"]["learned_events"]["reason"] == "no_qualified_checkpoint"
    assert result["stages"]["bat3d"]["status"] == "unavailable"
    assert result["stages"]["observations"]["status"] == "empty"

def test_html_escapes_context(video,tmp_path):
    root = tmp_path/"out"
    run_engine(video,root,EngineConfig(export_video=False),{"timing":{"kind":"unretimed","source":"<script>alert(1)</script>"}})
    assert "<script>" not in (root/"report.html").read_text()