File size: 6,912 Bytes
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""Pose-data contract: schema and example are in sync, the example is valid, the checker catches mistakes."""

import copy
import json
import sys
from pathlib import Path

import pytest

TOOLS = Path(__file__).resolve().parents[1] / "tools"
sys.path.insert(0, str(TOOLS))
import build_pose_spec as spec  # noqa: E402
import check_pose_json as checker  # noqa: E402

DOCS = Path(__file__).resolve().parents[1] / "docs"


@pytest.fixture
def example():
    return json.loads((DOCS / "examples" / "pose_track_example.json").read_text())


def codes(data, level=None):
    return {i.code for i in checker.check(data) if level is None or i.level == level}


def test_published_files_match_the_generator():
    """If this fails run: python tools/build_pose_spec.py  (the ML engineer reads these files)."""
    assert (DOCS / "pose_track.schema.json").read_text() == json.dumps(spec.build_schema(), indent=2, sort_keys=True) + "\n"
    assert (DOCS / "examples" / "pose_track_example.json").read_text() == json.dumps(
        spec.build_example(), separators=(",", ":")
    ) + "\n"


def test_example_has_no_errors_and_only_the_expected_warning(example):
    assert codes(example, "error") == set() and codes(example, "warning") == {"few_reps"}


def test_example_models_a_short_occlusion_correctly(example):
    wrist = spec.COCO17.index("left_wrist")
    assert example["frames"]["kp"][41][wrist] is None and example["frames"]["conf"][41][wrist] == 0


def test_hitting_and_pitching_event_lists_are_the_documented_ones():
    assert spec.HITTING_EVENTS == [
        "stance_set",
        "load_start",
        "stride",
        "foot_contact",
        "foot_plant",
        "swing_start",
        "contact",
        "finish",
    ]
    assert spec.PITCHING_EVENTS == ["first_move", "leg_lift", "hand_break", "foot_contact", "foot_plant", "release", "finish"]
    assert len(spec.COCO17) == 17 and len(spec.FOOT6) == 6


def mutate(example, fn):
    data = copy.deepcopy(example)
    fn(data)
    return data


@pytest.mark.parametrize(
    "name,fn,code,level",
    [
        ("wrong keypoint order", lambda d: d.update(keypoint_order=list(reversed(spec.COCO17))), "schema", "error"),
        ("unknown top-level field", lambda d: d.update(video_url="x"), "schema", "error"),
        ("length mismatch", lambda d: d["frames"]["blur"].pop(), "length", "error"),
        ("time not increasing", lambda d: d["frames"]["t_s"].__setitem__(10, 0.0), "time_order", "error"),
        (
            "slow-mo timebase (playback time sent)",
            lambda d: d["frames"].update(t_s=[i / 30.0 for i in range(d["video"]["frame_count"])]),
            "slowmo_timebase",
            "error",
        ),
        (
            "null point with confidence",
            lambda d: d["frames"]["conf"][41].__setitem__(9, 0.8) if d["frames"]["kp"][41][9] is None else None,
            "null_with_confidence",
            "error",
        ),
        (
            "point far outside the image",
            lambda d: d["frames"]["kp"][5].__setitem__(0, [5000.0, 100.0]),
            "out_of_frame",
            "error",
        ),
        (
            "no detections at all",
            lambda d: d["frames"].update(
                conf=[[0.0] * 17 for _ in d["frames"]["conf"]], kp=[[None] * 17 for _ in d["frames"]["kp"]]
            ),
            "no_detections",
            "error",
        ),
        ("event order", lambda d: d["reps"][0]["events"]["foot_plant"].update(frame=20), "event_order", "error"),
        ("event outside rep", lambda d: d["reps"][0].update(end_frame=50), "event_range", "error"),
        (
            "pitching event in a hitting file",
            lambda d: d["reps"][0]["events"].update(release=d["reps"][0]["events"]["finish"]),
            "event_name",
            "error",
        ),
        (
            "found and missing",
            lambda d: d["reps"][0].update(missing_events={"contact": "no ball"}),
            "event_conflict",
            "error",
        ),
        ("rep range", lambda d: d["reps"][0].update(end_frame=9999), "rep_range", "error"),
        (
            "confidence constant",
            lambda d: d["frames"].update(conf=[[0.9] * 17 for _ in d["frames"]["conf"]]),
            "constant_confidence",
            "warning",
        ),
        (
            "frozen frames",
            lambda d: d["frames"].update(kp=[d["frames"]["kp"][0]] * len(d["frames"]["kp"])),
            "frozen_frames",
            "warning",
        ),
        (
            "placeholder zeros",
            lambda d: d["frames"].update(kp=[[[0.0, 0.0] for _ in range(17)] for _ in d["frames"]["kp"]]),
            "placeholder_zeros",
            "warning",
        ),
        ("two people", lambda d: d["frames"]["people_count"].__setitem__(3, 2), "multiple_people", "warning"),
        (
            "athlete small",
            lambda d: d["frames"].update(box=[[500.0, 800.0, 600.0, 1000.0]] * len(d["frames"]["box"])),
            "athlete_small",
            "warning",
        ),
        ("track switch", lambda d: d["frames"]["track_id"].__setitem__(5, 2), "track_switches", "warning"),
        ("post-processed points", lambda d: d["model"].update(processing=["one_euro"]), "processed_points", "warning"),
        ("assumed time", lambda d: d["video"].update(time_source="assumed_constant"), "assumed_time", "warning"),
        ("fps mismatch", lambda d: d["video"].update(capture_fps=240.0, playback_fps=240.0), "fps_mismatch", "warning"),
        (
            "optional 3d is ignored",
            lambda d: d.update(kp3d={"frame_of_reference": "camera", "unit": "m", "points": [], "conf": []}),
            "unused_optional",
            "warning",
        ),
    ],
)
def test_checker_catches_mistakes(example, name, fn, code, level):
    assert code in codes(mutate(example, fn), level), name


def test_low_joint_coverage_is_reported_per_joint(example):
    ankle = spec.COCO17.index("right_ankle")

    def drop(d):
        for i in range(len(d["frames"]["conf"])):
            d["frames"]["conf"][i][ankle] = 0.0
            d["frames"]["kp"][i][ankle] = None

    issues = [i for i in checker.check(mutate(example, drop)) if i.code == "low_joint_coverage"]
    assert len(issues) == 1 and "right_ankle" in issues[0].detail


def test_nan_and_infinity_tokens_are_rejected_when_loading(tmp_path):
    path = tmp_path / "bad.json"
    path.write_text('{"frames": {"t_s": [NaN]}}')
    with pytest.raises(ValueError, match="not valid JSON"):
        checker.load(path)


def test_cli_exit_codes(tmp_path, capsys):
    good = DOCS / "examples" / "pose_track_example.json"
    assert checker.main([str(good)]) == 0
    assert checker.main([str(good), "--strict"]) == 1  # the example has one warning
    broken = tmp_path / "broken.json"
    broken.write_text("{not json")
    assert checker.main([str(broken)]) == 1
    assert "error" in capsys.readouterr().out