baseball-engine / AI-coach-agent /tools /build_pose_spec.py
github-actions[bot]
Automated Deploy: f4f01388c7b26e818cffbd64414eac11381a7891
35e80ff
Raw History Blame Contribute Delete
14.3 kB
"""Generate docs/pose_track.schema.json and docs/examples/pose_track_example.json (synthetic, illustrative).
The pose-data contract is defined HERE, from the downstream (metrics/coach) side, independent of how the pose
pipeline is implemented. Run: python tools/build_pose_spec.py
"""
import json
import math
from pathlib import Path
DOCS = Path(__file__).resolve().parents[1] / "docs"
SCHEMA_VERSION = "1.0"
COCO17 = [
"nose",
"left_eye",
"right_eye",
"left_ear",
"right_ear",
"left_shoulder",
"right_shoulder",
"left_elbow",
"right_elbow",
"left_wrist",
"right_wrist",
"left_hip",
"right_hip",
"left_knee",
"right_knee",
"left_ankle",
"right_ankle",
]
FOOT6 = ["left_big_toe", "left_small_toe", "left_heel", "right_big_toe", "right_small_toe", "right_heel"]
HITTING_EVENTS = ["stance_set", "load_start", "stride", "foot_contact", "foot_plant", "swing_start", "contact", "finish"]
PITCHING_EVENTS = ["first_move", "leg_lift", "hand_break", "foot_contact", "foot_plant", "release", "finish"]
def point(n=2):
return {"type": "array", "items": {"type": "number"}, "minItems": n, "maxItems": n}
def nullable(schema):
return {"anyOf": [schema, {"type": "null"}]}
def per_frame(item, **extra):
return {"type": "array", "items": item, **extra}
def build_schema() -> dict:
kp_frame = {"type": "array", "minItems": 17, "maxItems": 17, "items": nullable(point(2))}
return {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Pose track (what the pose pipeline sends downstream)",
"type": "object",
"required": ["schema_version", "discipline", "view", "video", "model", "keypoint_order", "frames"],
"additionalProperties": False,
"properties": {
"schema_version": {"const": SCHEMA_VERSION},
"discipline": {"enum": ["hitting", "pitching"]},
"view": {"enum": ["face_on", "open_side"]},
"video": {
"type": "object",
"required": [
"width",
"height",
"frame_count",
"capture_fps",
"playback_fps",
"rotation_degrees_applied",
"time_source",
],
"additionalProperties": False,
"properties": {
"width": {"type": "integer", "minimum": 1},
"height": {"type": "integer", "minimum": 1},
"frame_count": {"type": "integer", "minimum": 1},
"capture_fps": {"type": "number", "exclusiveMinimum": 0},
"playback_fps": {"type": "number", "exclusiveMinimum": 0},
"rotation_degrees_applied": {"enum": [0, 90, 180, 270]},
"time_source": {"enum": ["pts", "assumed_constant", "slowmo_rescaled"]},
"sha256": {"type": "string"},
},
},
"model": {
"type": "object",
"required": ["name", "processing"],
"additionalProperties": True,
"properties": {
"name": {"type": "string"},
"version": {"type": "string"},
"processing": {
"type": "array",
"items": {"type": "string"},
"description": "Applied after the model, e.g. one_euro or interpolation. Empty = raw.",
},
"people_rule": {"type": "string"},
"blur_definition": {"type": "string"},
},
},
"keypoint_order": {"const": COCO17},
"extra_keypoint_order": {"const": FOOT6},
"frames": {
"type": "object",
"required": ["t_s", "kp", "conf", "box", "people_count", "blur", "brightness"],
"additionalProperties": False,
"properties": {
"t_s": per_frame({"type": "number"}, minItems=1),
"kp": per_frame(kp_frame, minItems=1),
"conf": per_frame(
{
"type": "array",
"minItems": 17,
"maxItems": 17,
"items": {"type": "number", "minimum": 0, "maximum": 1},
},
minItems=1,
),
"kp_extra": per_frame({"type": "array", "minItems": 6, "maxItems": 6, "items": nullable(point(2))}),
"conf_extra": per_frame(
{
"type": "array",
"minItems": 6,
"maxItems": 6,
"items": {"type": "number", "minimum": 0, "maximum": 1},
}
),
"box": per_frame(nullable(point(4)), minItems=1),
"track_id": per_frame(nullable({"type": "integer"})),
"people_count": per_frame({"type": "integer", "minimum": 0}, minItems=1),
"blur": per_frame({"type": "number", "minimum": 0, "maximum": 1}, minItems=1),
"brightness": per_frame({"type": "number", "minimum": 0, "maximum": 255}, minItems=1),
},
},
"reps": {
"type": "array",
"items": {
"type": "object",
"required": ["rep", "start_frame", "end_frame", "events"],
"additionalProperties": False,
"properties": {
"rep": {"type": "integer", "minimum": 1},
"start_frame": {"type": "integer", "minimum": 0},
"end_frame": {"type": "integer", "minimum": 0},
"events": {
"type": "object",
"propertyNames": {"enum": sorted(set(HITTING_EVENTS + PITCHING_EVENTS))},
"additionalProperties": {
"type": "object",
"required": ["frame", "confidence"],
"additionalProperties": False,
"properties": {
"frame": {"type": "integer", "minimum": 0},
"t_s": {"type": "number"},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
"estimated": {"type": "boolean"},
"method": {"type": "string"},
},
},
},
"missing_events": {"type": "object", "additionalProperties": {"type": "string"}},
},
},
},
"kp3d": {
"type": "object",
"description": "OPTIONAL, not used in v1. Per-frame 3D points for the same 17 joints.",
"required": ["frame_of_reference", "unit", "points", "conf"],
"additionalProperties": False,
"properties": {
"frame_of_reference": {"enum": ["camera", "pelvis_relative"]},
"unit": {"const": "m"},
"points": per_frame({"type": "array", "minItems": 17, "maxItems": 17, "items": nullable(point(3))}),
"conf": per_frame(
{
"type": "array",
"minItems": 17,
"maxItems": 17,
"items": {"type": "number", "minimum": 0, "maximum": 1},
}
),
},
},
"objects": {
"type": "object",
"description": "OPTIONAL, not used in v1. Bat and ball per frame (pixels, upright image).",
"additionalProperties": False,
"properties": {
"bat": per_frame(
nullable(
{
"type": "object",
"required": ["knob", "barrel", "conf"],
"additionalProperties": False,
"properties": {
"knob": nullable(point(2)),
"barrel": nullable(point(2)),
"conf": {"type": "number", "minimum": 0, "maximum": 1},
},
}
)
),
"ball": per_frame(
nullable(
{
"type": "object",
"required": ["center", "conf"],
"additionalProperties": False,
"properties": {
"center": point(2),
"radius_px": {"type": "number", "minimum": 0},
"conf": {"type": "number", "minimum": 0, "maximum": 1},
},
}
)
),
},
},
},
}
def build_example(n=120, fps=120.0, width=1080, height=1920) -> dict:
"""A synthetic, physically plausible *shape* (not real motion): a hitter standing face-on with a small stride."""
base = { # x, y in pixels for a 1080x1920 portrait frame, athlete about 1100 px tall
"nose": (540, 760),
"left_eye": (555, 745),
"right_eye": (525, 745),
"left_ear": (575, 755),
"right_ear": (505, 755),
"left_shoulder": (610, 880),
"right_shoulder": (470, 880),
"left_elbow": (640, 1010),
"right_elbow": (440, 1010),
"left_wrist": (610, 1130),
"right_wrist": (470, 1130),
"left_hip": (590, 1140),
"right_hip": (490, 1140),
"left_knee": (600, 1380),
"right_knee": (480, 1380),
"left_ankle": (605, 1620),
"right_ankle": (475, 1620),
}
t_s, kp, conf, box, people, blur, bright, track = [], [], [], [], [], [], [], []
for i in range(n):
phase = i / (n - 1)
sway = 6 * math.sin(2 * math.pi * phase)
step = 90 * max(0.0, min(1.0, (phase - 0.3) / 0.25)) # lead ankle strides toward the pitcher
frame, c = [], []
for name in COCO17:
x, y = base[name]
x += sway
if name == "left_ankle":
x += step
if name == "left_wrist":
c_val = 0.0 if 40 <= i < 43 else 0.86 # a short occlusion: null point, confidence 0
frame.append(None if c_val == 0 else [round(x, 1), round(y, 1)])
c.append(c_val)
continue
frame.append([round(x, 1), round(y, 1)])
c.append(0.93 if "ankle" not in name else 0.9)
t_s.append(round(i / fps, 5))
kp.append(frame)
conf.append(c)
box.append([380.0, 700.0, 740.0, 1700.0])
people.append(1)
blur.append(0.12 if 50 < i < 90 else 0.05)
bright.append(128.0)
track.append(1)
def ev(frame, conf_, est=False, method=""):
return {
"frame": frame,
"t_s": round(frame / fps, 5),
"confidence": conf_,
"estimated": est,
"method": method,
}
return {
"schema_version": SCHEMA_VERSION,
"discipline": "hitting",
"view": "face_on",
"video": {
"width": width,
"height": height,
"frame_count": n,
"capture_fps": fps,
"playback_fps": 30.0,
"rotation_degrees_applied": 90,
"time_source": "slowmo_rescaled",
},
"model": {
"name": "illustrative-example",
"version": "0",
"processing": [],
"people_rule": "score>=0.5 and box height>=15% of frame height",
"blur_definition": "1 - clip(log10(laplacian_var(person_crop_256px)/20)/log10(500/20), 0, 1)",
},
"keypoint_order": COCO17,
"frames": {
"t_s": t_s,
"kp": kp,
"conf": conf,
"box": box,
"track_id": track,
"people_count": people,
"blur": blur,
"brightness": bright,
},
"reps": [
{
"rep": 1,
"start_frame": 0,
"end_frame": n - 1,
"events": {
"stance_set": ev(6, 0.8, method="body speed below threshold for 100 ms"),
"load_start": ev(26, 0.6, method="hands move backward after stance"),
"stride": ev(36, 0.7, method="lead ankle starts moving toward the pitcher"),
"foot_contact": ev(62, 0.7, method="lead foot first touches the ground"),
"foot_plant": ev(66, 0.75, method="lead ankle velocity returns to ~0 after the stride"),
"swing_start": ev(78, 0.6, method="sustained forward hand acceleration"),
"contact": ev(90, 0.5, est=True, method="max lead-arm extension, hands in front"),
"finish": ev(112, 0.6, method="hands settled after follow-through"),
},
"missing_events": {},
}
],
}
if __name__ == "__main__":
DOCS.mkdir(exist_ok=True)
(DOCS / "examples").mkdir(exist_ok=True)
(DOCS / "pose_track.schema.json").write_text(json.dumps(build_schema(), indent=2, sort_keys=True) + "\n")
(DOCS / "examples" / "pose_track_example.json").write_text(json.dumps(build_example(), separators=(",", ":")) + "\n")
print("pose spec files written")