"""End-to-end usage example for `ReactSegmentDataset` (the mode2_v1 schema). Run against a local checkout of the React HF dataset: python examples/demo_react_segment.py \\ --segments_root processed/mode2_v1/motherboard \\ --tasks_json tasks.json \\ --n_samples 4 \\ --out_dir /tmp/react_segment_demo_out What this does -------------- 1. Builds `ReactSegmentDataset` — same window-enumeration / filtering API as `ReactWindowDataset` but operates over pre-sliced clean segments (no `bad_frames.json` lookup; data is clean by construction). 2. Prints how many contact-rich windows were sampled + how many were rejected by the contact / motion filters. 3. Renders a static PNG grid of `--n_samples` random windows. 4. For each picked window also writes an H.264 MP4 clip (`sample_window_NN.mp4`) so you can visually inspect motion. Self-contained: numpy + torch + Pillow + cv2 (ffmpeg if available, falls back to cv2.VideoWriter otherwise). """ import argparse import shutil import subprocess import sys from pathlib import Path import cv2 import numpy as np import torch from PIL import Image sys.path.insert(0, str(Path(__file__).parent)) from react_segment_dataset import ReactSegmentDataset def _to_hwc(t): return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy() def _view_to_rgb(view_chw_uint8): return view_chw_uint8.permute(1, 2, 0).numpy()[..., ::-1].copy() def make_static_grid(ds, sample_indices, out_path: Path, *, n_cols: int = 6, cell_scale: int = 3) -> None: rows = [] for idx in sample_indices: s = ds[idx] T = s["view"].shape[0] pick = np.linspace(0, T - 1, n_cols).astype(int) cells = [] for t in pick: view = _view_to_rgb(s["view"][t]).astype(np.uint8) tac_L = _to_hwc(s["tactile_left"][t]).astype(np.uint8) tac_R = _to_hwc(s["tactile_right"][t]).astype(np.uint8) triplet = np.concatenate([view, tac_L, tac_R], axis=1) triplet = cv2.resize( triplet, (triplet.shape[1] * cell_scale, triplet.shape[0] * cell_scale), interpolation=cv2.INTER_NEAREST, ) cells.append(triplet) rows.append(np.concatenate(cells, axis=1)) H_row = rows[0].shape[0] W_row = rows[0].shape[1] label_h = 88 pad_y = 16 canvas_h = 60 + len(rows) * (H_row + label_h + pad_y) canvas = np.full((canvas_h, W_row + 20, 3), 245, np.uint8) cv2.putText(canvas, f"ReactSegmentDataset — {n_cols} evenly-spaced frames per sample (time runs left → right)", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 50, 50), 2, cv2.LINE_AA) cell_w = W_row // n_cols for r, idx in enumerate(sample_indices): s = ds[idx] y0 = 60 + r * (H_row + label_h + pad_y) dur_s = float(s["timestamps"][-1] - s["timestamps"][0]) mL = float(s["tactile_left_mixed"].max()) mR = float(s["tactile_right_mixed"].max()) h5a = s.get("h5_frame_start", "—") cv2.putText( canvas, (f"sample #{idx} · {s['source_episode']}/seg{int(s['source_segment_idx']):02d} · " f"H5 frame {h5a} · ({dur_s:.2f}s) · active: {','.join(s['active_sensors'])} · " f"peak mixed L={mL:.2f} R={mR:.2f}"), (10, y0 + 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA, ) T = s["view"].shape[0] pick = np.linspace(0, T - 1, n_cols).astype(int) for c, t in enumerate(pick): cv2.putText(canvas, f"t = {int(t)}", (10 + c * cell_w + 8, y0 + 56), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (90, 90, 90), 1, cv2.LINE_AA) cv2.putText(canvas, "view | tactile_left | tactile_right", (10, y0 + 76), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (130, 130, 130), 1, cv2.LINE_AA) canvas[y0 + label_h:y0 + label_h + H_row, 10:10 + W_row] = rows[r] out_path.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(canvas).save(out_path) print(f" grid -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)") def _write_mp4_h264(frames_rgb, out_path: Path, fps: float = 15.0) -> None: H, W = frames_rgb[0].shape[:2] out_path.parent.mkdir(parents=True, exist_ok=True) if shutil.which("ffmpeg") is not None: cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}", "-r", f"{fps:.3f}", "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "medium", "-crf", "20", "-movflags", "+faststart", "-an", str(out_path)] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) for f in frames_rgb: assert f.shape == (H, W, 3) and f.dtype == np.uint8 proc.stdin.write(f.tobytes()) proc.stdin.close() if proc.wait() != 0: raise RuntimeError("ffmpeg failed") return vw = cv2.VideoWriter(str(out_path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (W, H)) for f in frames_rgb: vw.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR)) vw.release() def make_window_mp4(ds, sample_idx: int, out_path: Path, *, scale: int = 3, fps: float = 15.0) -> None: s = ds[sample_idx] T = s["view"].shape[0] h5a = s.get("h5_frame_start", "—") frames = [] for t in range(T): view = _view_to_rgb(s["view"][t]).astype(np.uint8) tac_L = _to_hwc(s["tactile_left"][t]).astype(np.uint8) tac_R = _to_hwc(s["tactile_right"][t]).astype(np.uint8) triplet = np.concatenate([view, tac_L, tac_R], axis=1) triplet = cv2.resize(triplet, (triplet.shape[1] * scale, triplet.shape[0] * scale), interpolation=cv2.INTER_NEAREST) H, W, _ = triplet.shape header = np.full((28, W, 3), 235, np.uint8) cv2.putText( header, f"#{sample_idx} {s['source_episode']}/seg{int(s['source_segment_idx']):02d} " f"H5 frame {h5a}+{t} ({t+1}/{T}) view | tactile_L | tactile_R", (8, 19), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (40, 40, 40), 1, cv2.LINE_AA, ) frames.append(np.concatenate([header, triplet], axis=0)) _write_mp4_h264(frames, out_path, fps=fps) print(f" mp4 -> {out_path.name} ({out_path.stat().st_size / 1024:.1f} KB)") def main(): ap = argparse.ArgumentParser() ap.add_argument("--segments_root", required=True, help="processed/mode2_v1/motherboard") ap.add_argument("--tasks_json", default="tasks.json") ap.add_argument("--n_samples", type=int, default=4) ap.add_argument("--out_dir", default="/tmp/react_segment_demo_out") ap.add_argument("--window_length", type=int, default=16) ap.add_argument("--seed", type=int, default=42) ap.add_argument("--mp4_fps", type=float, default=15.0) ap.add_argument("--no_mp4", action="store_true") ap.add_argument("--no_motion_filter", action="store_true") args = ap.parse_args() print("=== Building dataset (segments are clean by construction) ===") ds = ReactSegmentDataset( segments_root = args.segments_root, tasks_json_path= args.tasks_json, window_length = args.window_length, stride = 1, window_step = max(1, args.window_length // 2), contact_metric = "mixed", tactile_threshold = 0.4, min_contact_fraction = 0.5, which_sensors = "both", respect_active_sensors= True, require_motion = not args.no_motion_filter, min_motion_mps = 0.01, min_motion_fraction = 0.25, which_sensors_must_move = "all_active", ) if len(ds) == 0: print("No windows passed the filters. Lower thresholds or disable a filter.") return rng = np.random.default_rng(args.seed) pick = rng.choice(len(ds), min(args.n_samples, len(ds)), replace=False) print(f"\n=== One sample's structure (#{int(pick[0])}) ===") s0 = ds[int(pick[0])] for k, v in s0.items(): if isinstance(v, torch.Tensor): print(f" {k:30s} {tuple(v.shape)} {v.dtype}") else: print(f" {k:30s} {v!r}") out_dir = Path(args.out_dir) print(f"\n=== Static grid of {len(pick)} random windows ===") make_static_grid(ds, pick, out_dir / "sample_grid.png") if not args.no_mp4: print(f"\n=== Per-window MP4 clips ({len(pick)} files, H.264) ===") for i, idx in enumerate(pick): make_window_mp4(ds, int(idx), out_dir / f"sample_window_{i:02d}.mp4", fps=args.mp4_fps) if __name__ == "__main__": main()