"""Convert tracked human poses into retargetable dance/contact annotations. The source clip contains two deliberate foot close-ups. Those frames remain useful as footwork evidence, but are excluded from full-body imitation. This script keeps both facts explicit instead of silently treating a cropped body as a valid pose. """ from __future__ import annotations import argparse import csv from dataclasses import dataclass import json import math from pathlib import Path import cv2 import numpy as np from scipy.signal import find_peaks, savgol_filter COCO = { "nose": 0, "left_shoulder": 5, "right_shoulder": 6, "left_elbow": 7, "right_elbow": 8, "left_wrist": 9, "right_wrist": 10, "left_hip": 11, "right_hip": 12, "left_knee": 13, "right_knee": 14, "left_ankle": 15, "right_ankle": 16, } SKELETON = ( (5, 6), (5, 7), (7, 9), (6, 8), (8, 10), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16), ) COLORS = ((40, 220, 250), (238, 82, 170)) SHOT_CUT_SECONDS = (9.718, 12.054, 14.264, 15.849) TARGET_BPM = 111.0 @dataclass(frozen=True) class Section: start: float end: float name: str view: str full_body: bool note: str SECTIONS = ( Section(0.000, 9.718, "front_travel_and_groove", "front", True, "wide full-body shot"), Section(9.718, 12.054, "footwork_closeup_a", "cropped", False, "feet retained; hidden body interpolated"), Section(12.054, 14.264, "front_reset", "front", True, "wide full-body shot"), Section(14.264, 15.849, "footwork_closeup_b", "cropped", False, "feet retained; hidden body interpolated"), Section(15.849, 18.500, "turn_away", "turning_away", True, "wide shot; orientation transition"), Section(18.500, 27.500, "back_facing_phrase", "back", True, "wide shot"), Section(27.500, 29.000, "turn_to_front", "turning_to_front", True, "wide shot; orientation transition"), Section(29.000, 34.500, "front_groove_and_stride", "front", True, "wide shot"), Section(34.500, 37.250, "low_lunge_kneel", "front", True, "intentional low body level, not a tracking failure"), Section(37.250, 39.039, "recovery_finish", "front", True, "rise and finish"), ) def section_at(time_seconds: float) -> Section: for section in SECTIONS: if section.start <= time_seconds < section.end: return section return SECTIONS[-1] def odd_window(fps: float, seconds: float, size: int) -> int: value = min(size if size % 2 else size - 1, max(5, int(round(fps * seconds)) | 1)) return value if value % 2 else value - 1 def interpolate_smooth( values: np.ndarray, valid: np.ndarray, fps: float, seconds: float = 0.25, ) -> np.ndarray: """Interpolate invalid observations, then apply zero-phase smoothing.""" result = np.empty_like(values, dtype=np.float64) x = np.arange(len(values), dtype=np.float64) for column in range(values.shape[1]): usable = valid & np.isfinite(values[:, column]) if usable.sum() < 2: result[:, column] = np.nan_to_num(values[:, column], nan=0.0) continue filled = np.interp(x, x[usable], values[usable, column]) window = odd_window(fps, seconds, len(filled)) result[:, column] = savgol_filter( filled, window_length=window, polyorder=min(3, window - 2), mode="interp", ) return result.astype(np.float32) def midpoint(points: np.ndarray, a: int, b: int) -> np.ndarray: return (points[:, :, a] + points[:, :, b]) * 0.5 def angle_at(a: np.ndarray, b: np.ndarray, c: np.ndarray) -> np.ndarray: first = a - b second = c - b dot = np.sum(first * second, axis=-1) norm = np.linalg.norm(first, axis=-1) * np.linalg.norm(second, axis=-1) return np.arccos(np.clip(dot / np.maximum(norm, 1e-7), -1.0, 1.0)).astype(np.float32) def finite_diff(values: np.ndarray, fps: float) -> np.ndarray: return np.gradient(values, 1.0 / fps, axis=0).astype(np.float32) def make_full_body_mask( keypoints: np.ndarray, boxes: np.ndarray, fps: float, height: int, ) -> tuple[np.ndarray, np.ndarray]: times = np.arange(len(keypoints), dtype=np.float32) / fps camera_crop = np.zeros(len(keypoints), dtype=bool) camera_crop |= (times >= SHOT_CUT_SECONDS[0]) & (times < SHOT_CUT_SECONDS[1]) camera_crop |= (times >= SHOT_CUT_SECONDS[2]) & (times < SHOT_CUT_SECONDS[3]) required = [5, 6, 11, 12, 13, 14, 15, 16] confidence_ok = np.min(keypoints[:, :, required, 2], axis=2) >= 0.20 torso_ok = np.mean(keypoints[:, :, [5, 6, 11, 12], 2], axis=2) >= 0.45 box_ok = ((boxes[:, :, 3] - boxes[:, :, 1]) / float(height)) >= 0.48 full_body = confidence_ok & torso_ok & box_ok & ~camera_crop[:, None] return full_body, camera_crop def contact_annotations( ankle_xy: np.ndarray, fps: float, camera_crop: np.ndarray, ) -> tuple[np.ndarray, np.ndarray, list[dict]]: """Estimate planted feet from image-plane height and velocity. These are pseudo-labels for review/retargeting, not force-plate ground truth. """ frame_count, dancers, feet, _ = ankle_xy.shape velocity = finite_diff(ankle_xy, fps) speed = np.linalg.norm(velocity, axis=-1) lower_y = np.max(ankle_xy[..., 1], axis=2, keepdims=True) y_gap = np.maximum(0.0, lower_y - ankle_xy[..., 1]) height_score = np.exp(-np.square(y_gap / 0.045)) speed_score = np.exp(-np.square(speed / 0.28)) probability = 0.68 * height_score + 0.32 * speed_score for dancer in range(dancers): for foot in range(feet): window = odd_window(fps, 0.21, frame_count) probability[:, dancer, foot] = savgol_filter( probability[:, dancer, foot], window, 2, mode="interp", ) probability = np.clip(probability, 0.0, 1.0).astype(np.float32) state = probability >= 0.66 events: list[dict] = [] for dancer in range(dancers): for foot, foot_name in enumerate(("left", "right")): peaks, props = find_peaks( probability[:, dancer, foot], height=0.72, prominence=0.06, distance=max(1, int(round(fps * 0.65))), ) for frame, peak_height in zip(peaks, props["peak_heights"], strict=True): events.append({ "frame_index": int(frame), "time_seconds": round(float(frame / fps), 6), "dancer_index": dancer, "foot": foot_name, "event": "plant_candidate", "confidence": round(float(peak_height), 6), "evidence": "foot_closeup" if camera_crop[frame] else "full_body", }) events.sort(key=lambda item: (item["frame_index"], item["dancer_index"], item["foot"])) return probability, state, events def draw_pose( canvas: np.ndarray, points: np.ndarray, center: tuple[int, int], scale: float, color: tuple[int, int, int], contacts: np.ndarray, ) -> None: pelvis = (points[11] + points[12]) * 0.5 torso = max(1e-5, float(np.linalg.norm((points[5] + points[6]) * 0.5 - pelvis))) display = (points - pelvis) * (scale / torso) display[:, 1] *= -1.0 display += np.asarray(center, dtype=np.float32) for a, b in SKELETON: pa = tuple(np.round(display[a]).astype(int)) pb = tuple(np.round(display[b]).astype(int)) cv2.line(canvas, pa, pb, color, 4, cv2.LINE_AA) for joint in (5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16): point = tuple(np.round(display[joint]).astype(int)) cv2.circle(canvas, point, 5, (255, 255, 255), -1, cv2.LINE_AA) cv2.circle(canvas, point, 3, color, -1, cv2.LINE_AA) for foot, joint in enumerate((15, 16)): if contacts[foot]: point = tuple(np.round(display[joint]).astype(int)) cv2.circle(canvas, point, 13, (60, 205, 90), 3, cv2.LINE_AA) def write_visualization( path: Path, points: np.ndarray, contact_state: np.ndarray, camera_crop: np.ndarray, fps: float, ) -> list[str]: width, height = 960, 540 writer = cv2.VideoWriter( str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height), ) if not writer.isOpened(): raise RuntimeError(f"Could not write {path}") example_dir = path.parent example_frames = sorted(set( int(round(value * fps)) for value in (1, 5, 10.5, 13, 15, 19, 24, 29, 33, 35.5, 38) )) examples: list[str] = [] for frame in range(len(points)): time_seconds = frame / fps section = section_at(time_seconds) canvas = np.full((height, width, 3), (248, 249, 252), dtype=np.uint8) cv2.line(canvas, (80, 465), (880, 465), (196, 201, 211), 2, cv2.LINE_AA) draw_pose(canvas, points[frame, 0], (285, 280), 105.0, COLORS[0], contact_state[frame, 0]) draw_pose(canvas, points[frame, 1], (675, 280), 105.0, COLORS[1], contact_state[frame, 1]) title = ( f"t={time_seconds:05.2f}s | beat@111={time_seconds * TARGET_BPM / 60.0:05.2f} " f"| {section.name}" ) cv2.putText( canvas, title, (24, 36), cv2.FONT_HERSHEY_SIMPLEX, 0.68, (37, 42, 54), 2, cv2.LINE_AA, ) cv2.putText( canvas, "green rings = estimated foot contact", (24, 515), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (72, 79, 94), 1, cv2.LINE_AA, ) if camera_crop[frame]: cv2.rectangle(canvas, (12, 54), (948, 92), (225, 239, 255), -1) cv2.putText( canvas, "CAMERA CROP: feet observed; hidden body interpolated; full-body loss disabled", (28, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.59, (20, 86, 150), 2, cv2.LINE_AA, ) writer.write(canvas) if frame in example_frames: filename = f"annotated_{frame:04d}_{section.name}.png" cv2.imwrite(str(example_dir / filename), canvas) examples.append(filename) writer.release() return examples def run(args: argparse.Namespace) -> dict: pose_path = args.pose.resolve() output_dir = args.output.resolve() examples_dir = output_dir / "examples" / "annotated" examples_dir.mkdir(parents=True, exist_ok=True) data = np.load(pose_path, allow_pickle=True) raw = data["keypoints_xyc"].astype(np.float32) boxes = data["bbox_xyxy"].astype(np.float32) fps = float(data["fps"]) width = int(data["frame_width"]) height = int(data["frame_height"]) track_names = [str(value) for value in data["track_names"]] frame_count = len(raw) times = np.arange(frame_count, dtype=np.float32) / fps full_body_valid, camera_crop = make_full_body_mask(raw, boxes, fps, height) smooth = np.empty_like(raw[..., :2]) for dancer in range(2): for joint in range(17): usable = (raw[:, dancer, joint, 2] >= 0.20) & full_body_valid[:, dancer] smooth[:, dancer, joint] = interpolate_smooth( raw[:, dancer, joint, :2], usable, fps, ) pelvis = midpoint(smooth, 11, 12) shoulders = midpoint(smooth, 5, 6) torso_length = np.linalg.norm(shoulders - pelvis, axis=-1) torso_scale = np.empty_like(torso_length) for dancer in range(2): torso_scale[:, dancer] = interpolate_smooth( torso_length[:, dancer, None], full_body_valid[:, dancer], fps, 0.35, )[:, 0] centered = ( (smooth - pelvis[:, :, None, :]) / np.maximum(torso_scale[:, :, None, None], 1e-4) ) knee_flexion = np.stack(( math.pi - angle_at(smooth[:, :, 11], smooth[:, :, 13], smooth[:, :, 15]), math.pi - angle_at(smooth[:, :, 12], smooth[:, :, 14], smooth[:, :, 16]), ), axis=2) hip_angle = np.stack(( angle_at(shoulders, smooth[:, :, 11], smooth[:, :, 13]), angle_at(shoulders, smooth[:, :, 12], smooth[:, :, 14]), ), axis=2) shoulder_vector = smooth[:, :, 6] - smooth[:, :, 5] torso_vector = shoulders - pelvis body_roll = np.arctan2(torso_vector[..., 0], -torso_vector[..., 1]).astype(np.float32) shoulder_slope = np.arctan2( shoulder_vector[..., 1], shoulder_vector[..., 0], ).astype(np.float32) pelvis_velocity = finite_diff( pelvis / np.array((width, height), dtype=np.float32), fps, ) body_level = ( (np.max(smooth[:, :, [15, 16], 1], axis=2) - pelvis[..., 1]) / np.maximum(torso_scale, 1e-4) ).astype(np.float32) ankles_norm = ( smooth[:, :, [15, 16]] / np.array((width, height), dtype=np.float32) ) contact_probability, contact_state, events = contact_annotations( ankles_norm, fps, camera_crop, ) for event in events: event["track"] = track_names[event["dancer_index"]] event["section"] = section_at(event["time_seconds"]).name event["target_beat_111bpm"] = round( event["time_seconds"] * TARGET_BPM / 60.0, 6, ) np.savez_compressed( output_dir / "motion_features.npz", time_seconds=times, smoothed_keypoints_xy=smooth, pelvis_center_xy=pelvis, pelvis_velocity_norm=pelvis_velocity, pelvis_centered_keypoints=centered, torso_scale_px=torso_scale, knee_flexion_rad=knee_flexion, hip_angle_rad=hip_angle, body_roll_proxy_rad=body_roll, shoulder_slope_rad=shoulder_slope, body_level_torso_units=body_level, foot_contact_probability=contact_probability, foot_contact_state=contact_state, full_body_valid=full_body_valid, camera_crop=camera_crop, target_beat_111bpm=times * (TARGET_BPM / 60.0), track_names=np.asarray(track_names), fps=np.asarray(fps), ) with (output_dir / "motion_features.jsonl").open("w", encoding="utf-8") as stream: for frame in range(frame_count): section = section_at(float(times[frame])) record = { "frame_index": frame, "time_seconds": round(float(times[frame]), 7), "target_beat_111bpm": round(float(times[frame] * TARGET_BPM / 60.0), 7), "section": section.name, "view": section.view, "camera_crop": bool(camera_crop[frame]), "tracks": {}, } for dancer, name in enumerate(track_names): record["tracks"][name] = { "full_body_valid": bool(full_body_valid[frame, dancer]), "body_roll_proxy_rad": round(float(body_roll[frame, dancer]), 6), "shoulder_slope_rad": round(float(shoulder_slope[frame, dancer]), 6), "body_level_torso_units": round(float(body_level[frame, dancer]), 6), "pelvis_velocity_norm_per_s": [ round(float(value), 7) for value in pelvis_velocity[frame, dancer] ], "knee_flexion_rad": [ round(float(value), 6) for value in knee_flexion[frame, dancer] ], "hip_angle_rad": [ round(float(value), 6) for value in hip_angle[frame, dancer] ], "foot_contact_probability": [ round(float(value), 6) for value in contact_probability[frame, dancer] ], "foot_contact_state": [ bool(value) for value in contact_state[frame, dancer] ], } stream.write(json.dumps(record, separators=(",", ":")) + "\n") with (output_dir / "step_events.csv").open("w", newline="", encoding="utf-8") as stream: fields = ( "frame_index", "time_seconds", "dancer_index", "track", "foot", "event", "confidence", "evidence", "section", "target_beat_111bpm", ) writer = csv.DictWriter(stream, fieldnames=fields) writer.writeheader() writer.writerows(events) sections_payload = [section.__dict__ for section in SECTIONS] (output_dir / "motion_sections.json").write_text( json.dumps(sections_payload, indent=2), encoding="utf-8", ) schema = { "schema_version": "1.0", "coordinate_convention": { "image_xy": "pixels, +x right, +y down", "angles": "radians", "normalized_pelvis_velocity": "image fraction per second", }, "joint_schema": "COCO-17", "contact_semantics": "image-derived pseudo-label; not force-plate ground truth", "full_body_valid_semantics": "false frames must not contribute to full-body imitation loss", "camera_crop_semantics": "foot observations may remain useful; hidden body landmarks are interpolated", "target_music_grid": { "song": "Candy", "artist": "Cameo", "bpm": TARGET_BPM, "audio_included": False, "note": "tempo grid only; copyrighted recording is not redistributed", }, } (output_dir / "annotation_schema.json").write_text( json.dumps(schema, indent=2), encoding="utf-8", ) examples = write_visualization( examples_dir / "annotated_skeleton_contacts.mp4", smooth, contact_state, camera_crop, fps, ) event_counts = { name: { foot: sum( 1 for item in events if item["track"] == name and item["foot"] == foot ) for foot in ("left", "right") } for name in track_names } summary = { "schema_version": "1.0", "frames": frame_count, "fps": fps, "duration_seconds": frame_count / fps, "camera_cut_seconds": list(SHOT_CUT_SECONDS), "camera_crop_frame_count": int(camera_crop.sum()), "full_body_valid_fraction": { name: round(float(full_body_valid[:, dancer].mean()), 6) for dancer, name in enumerate(track_names) }, "step_event_counts": event_counts, "target_music_grid_bpm": TARGET_BPM, "example_images": examples, "limitations": [ "2D monocular pose has depth and front/back ambiguity.", "Foot contacts are pseudo-labels inferred from height and image velocity.", "Camera-crop body landmarks are interpolated and excluded from full-body loss.", "Music metadata is a tempo grid; no copyrighted song audio is included.", ], } (output_dir / "annotation_summary.json").write_text( json.dumps(summary, indent=2), encoding="utf-8", ) print(json.dumps(summary, indent=2)) return summary def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--pose", type=Path, required=True, help="human_pose_coco17.npz") parser.add_argument("--output", type=Path, required=True, help="Derived annotation directory") run(parser.parse_args()) if __name__ == "__main__": main()