"""Check a pose-track JSON against docs/POSE_DATA_SPEC.md. Standalone: no dependency on any pipeline code. python tools/check_pose_json.py path/to/pose_track.json [--strict] Errors mean downstream cannot trust the file; warnings mean it will be used but results get weaker. """ from __future__ import annotations import argparse import itertools import json import math import statistics import sys from dataclasses import dataclass from pathlib import Path import jsonschema DOCS = Path(__file__).resolve().parents[1] / "docs" sys.path.insert(0, str(Path(__file__).resolve().parent)) from build_pose_spec import COCO17, HITTING_EVENTS, PITCHING_EVENTS # noqa: E402 REQUIRED_JOINTS = [ "nose", "left_shoulder", "right_shoulder", "left_wrist", "right_wrist", "left_hip", "right_hip", "left_knee", "right_knee", "left_ankle", "right_ankle", ] MIN_JOINT_COVERAGE = 0.60 # share of frames where a required joint has conf >= CONF_FLOOR CONF_FLOOR = 0.30 OUT_OF_FRAME_MARGIN = 0.05 # fraction of width/height a point may lie outside the image FROZEN_FRAME_SHARE = 0.20 # more identical consecutive frames than this means stale/copied data FPS_TOLERANCE = 0.15 MIN_ATHLETE_HEIGHT_FRACTION = 1 / 3 MIN_REPS = 3 MIN_REP_GAP_S = 1.5 @dataclass(frozen=True) class Issue: level: str code: str detail: str def __str__(self) -> str: return f"[{self.level}] {self.code}: {self.detail}" def _reject_constant(name: str): raise ValueError(f"{name} is not valid JSON; send null for unknown values") def load(path: Path) -> dict: return json.loads(path.read_text(encoding="utf-8"), parse_constant=_reject_constant) def check(data: dict) -> list[Issue]: issues: list[Issue] = [] error = lambda code, detail: issues.append(Issue("error", code, detail)) # noqa: E731 warn = lambda code, detail: issues.append(Issue("warning", code, detail)) # noqa: E731 schema = json.loads((DOCS / "pose_track.schema.json").read_text(encoding="utf-8")) for e in sorted(jsonschema.Draft7Validator(schema).iter_errors(data), key=lambda e: list(e.path))[:10]: error("schema", f"{'/'.join(str(p) for p in list(e.path)[:4]) or ''}: {e.message[:140]}") if any(i.code == "schema" for i in issues): return issues # structure is wrong: semantic checks would only add noise video, frames = data["video"], data["frames"] n, w, h = video["frame_count"], video["width"], video["height"] for key in ("t_s", "kp", "conf", "box", "people_count", "blur", "brightness", "kp_extra", "conf_extra", "track_id"): if key in frames and len(frames[key]) != n: error("length", f"frames.{key} has {len(frames[key])} entries, video.frame_count is {n}") if ("kp_extra" in frames) != ("conf_extra" in frames): error("extra_keypoints", "kp_extra and conf_extra must be sent together") if any(i.code == "length" for i in issues): return issues _check_time(frames["t_s"], video, error, warn) _check_points(frames, w, h, error, warn) _check_quality(frames, data, h, warn) _check_reps(data, n, frames["t_s"], error, warn) for key in ("kp3d", "objects"): if key in data: warn("unused_optional", f"{key} is accepted but not used in v1") return issues def _check_time(t, video, error, warn): if any(b <= a for a, b in itertools.pairwise(t)): error("time_order", "t_s must be strictly increasing") return if t[0] > 0.5: warn("time_origin", f"t_s starts at {t[0]:.2f}s; send seconds from the first frame") if len(t) < 3: return dt = statistics.median(b - a for a, b in itertools.pairwise(t)) capture, playback = video["capture_fps"], video["playback_fps"] if capture >= 2 * playback and abs(dt - 1 / playback) < abs(dt - 1 / capture): error( "slowmo_timebase", f"t_s step {dt * 1000:.1f} ms matches playback ({playback:g} fps), not capture " f"({capture:g} fps): send real capture time, otherwise every timing metric is wrong", ) elif abs(dt - 1 / capture) / (1 / capture) > FPS_TOLERANCE: warn( "fps_mismatch", f"median t_s step is {dt * 1000:.2f} ms but capture_fps={capture:g} implies {1000 / capture:.2f} ms", ) if video["time_source"] == "assumed_constant": warn( "assumed_time", "timestamps are assumed constant, not read from the file; variable frame rates will skew timing", ) def _check_points(frames, w, h, error, warn): kp, conf = frames["kp"], frames["conf"] n = len(kp) nonnull_zero_conf = null_with_conf = outside = zeros = frozen = 0 for i in range(n): for j in range(17): p, c = kp[i][j], conf[i][j] if p is None: null_with_conf += c > 0 continue nonnull_zero_conf += c == 0 x, y = p if not (math.isfinite(x) and math.isfinite(y)): error("non_finite", f"frame {i} joint {j}") elif not ( -OUT_OF_FRAME_MARGIN * w <= x <= (1 + OUT_OF_FRAME_MARGIN) * w and -OUT_OF_FRAME_MARGIN * h <= y <= (1 + OUT_OF_FRAME_MARGIN) * h ): outside += 1 zeros += x == 0 and y == 0 if i and kp[i] == kp[i - 1] and any(p is not None for p in kp[i]): frozen += 1 if null_with_conf: error( "null_with_confidence", f"{null_with_conf} points are null but have confidence > 0 (unknown must be null AND 0)", ) if outside: error("out_of_frame", f"{outside} points lie outside the image; check rotation, scale and the coordinate origin") if nonnull_zero_conf: warn("zero_confidence_point", f"{nonnull_zero_conf} points have a position but confidence 0; send null instead") if zeros > 0.01 * n * 17: warn("placeholder_zeros", f"{zeros} points are exactly (0,0): missing joints must be null, never zero") if n > 1 and frozen / (n - 1) > FROZEN_FRAME_SHARE: warn( "frozen_frames", f"{frozen} of {n - 1} frames repeat the previous frame exactly (stale or copied detections?)", ) detected = [any(c >= CONF_FLOOR for c in row) for row in conf] if not any(detected): error("no_detections", "no frame has a joint with confidence >= 0.3") return for name in REQUIRED_JOINTS: j = COCO17.index(name) share = sum(row[j] >= CONF_FLOOR for row in conf) / n if share < MIN_JOINT_COVERAGE: warn( "low_joint_coverage", f"{name} is confident in only {share:.0%} of frames (needs {MIN_JOINT_COVERAGE:.0%})", ) flat = [c for row in conf for c in row if c > 0] if len(flat) > 50 and statistics.pstdev(flat) < 1e-6: warn("constant_confidence", "every confidence is identical: confidence must reflect real uncertainty") def _check_quality(frames, data, h, warn): boxes = [b for b in frames["box"] if b is not None] for b in boxes: if not (b[0] < b[2] and b[1] < b[3]): warn("bad_box", "a box has x1>=x2 or y1>=y2 (expected [x1,y1,x2,y2])") break if boxes: height = statistics.median((b[3] - b[1]) / h for b in boxes) if height < MIN_ATHLETE_HEIGHT_FRACTION: warn("athlete_small", f"athlete box is {height:.0%} of frame height (capture spec asks for at least a third)") elif frames["box"]: warn("no_boxes", "no person box in any frame") multi = sum(c >= 2 for c in frames["people_count"]) if multi: warn("multiple_people", f"{multi} frames have 2 or more people in view") ids = [i for i in frames.get("track_id", []) if i is not None] switches = sum(a != b for a, b in itertools.pairwise(ids)) if switches: warn("track_switches", f"athlete track id changes {switches} time(s)") if data["model"]["processing"]: warn( "processed_points", f"points are post-processed ({data['model']['processing']}); downstream also smooths, so raw points are preferred", ) def _check_reps(data, n, t, error, warn): reps = data.get("reps") if reps is None: return allowed = HITTING_EVENTS if data["discipline"] == "hitting" else PITCHING_EVENTS if len(reps) < MIN_REPS: warn("few_reps", f"{len(reps)} rep(s); results are unstable below {MIN_REPS}") last_end = None for rep in reps: rid, a, b = rep["rep"], rep["start_frame"], rep["end_frame"] if not (0 <= a <= b < n): error("rep_range", f"rep {rid}: start/end {a}..{b} outside 0..{n - 1}") continue if last_end is not None and t[a] - t[last_end] < MIN_REP_GAP_S: warn("rep_gap", f"rep {rid} starts {t[a] - t[last_end]:.2f}s after the previous rep ended") last_end = b events = rep["events"] for name, ev in events.items(): if name not in allowed: error("event_name", f"rep {rid}: {name!r} is not a {data['discipline']} event") if not a <= ev["frame"] <= b: error("event_range", f"rep {rid}: {name} at frame {ev['frame']} is outside the rep {a}..{b}") if ( ev["frame"] < n and "t_s" in ev and abs(ev["t_s"] - t[ev["frame"]]) > 1.5 * statistics.median(y - x for x, y in itertools.pairwise(t)) ): warn("event_time", f"rep {rid}: {name} t_s does not match t_s[frame]") frames_in_order = [events[e]["frame"] for e in allowed if e in events] if frames_in_order != sorted(frames_in_order): error( "event_order", f"rep {rid}: events are out of order {[(e, events[e]['frame']) for e in allowed if e in events]}", ) for name in rep.get("missing_events", {}): if name in events: error("event_conflict", f"rep {rid}: {name} is both found and listed as missing") if "contact" in events and not events["contact"].get("estimated", True): warn( "contact_certain", f"rep {rid}: contact is flagged as not estimated; confirm a ball or sensor really supports it", ) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Check a pose-track JSON against docs/POSE_DATA_SPEC.md") parser.add_argument("file", type=Path) parser.add_argument("--strict", action="store_true", help="treat warnings as failures") args = parser.parse_args(argv) try: data = load(args.file) except (ValueError, OSError) as exc: print(f"[error] cannot read file: {exc}") return 1 issues = check(data) for issue in issues: print(issue) errors = sum(i.level == "error" for i in issues) print(f"{errors} error(s), {len(issues) - errors} warning(s)", file=sys.stderr) return 1 if errors or (args.strict and len(issues) > errors) else 0 if __name__ == "__main__": raise SystemExit(main())