| """End-to-end usage example for `ReactWindowDataset`. |
| |
| Run this against a local checkout of the React HF dataset: |
| |
| python examples/demo_react_window.py \\ |
| --data_root processed/mode1_v1/motherboard \\ |
| --bad_frames bad_frames.json \\ |
| --tasks_json tasks.json \\ |
| --n_samples 4 \\ |
| --out_dir /tmp/react_demo_out |
| |
| What this script does |
| --------------------- |
| 1. Builds `ReactWindowDataset` with all four quality filters on (see the |
| module docstring of `react_window_dataset.py` for what each catches). |
| 2. Prints how many windows survived and the shape of one sample. |
| 3. Renders a static grid of `--n_samples` random windows as a PNG. Each |
| row = one window; each cell = `view | tactile_left | tactile_right` |
| for a single frame inside that window. |
| 4. For each picked window also writes a small MP4 clip showing the actual |
| per-frame motion (replaces the GIF outputs the old demo used to ship — |
| MP4 is ~10× smaller and renders inline on HF). |
| |
| Self-contained: numpy + torch + Pillow + cv2. `ffmpeg` is used to encode |
| the MP4 clips; if it isn't on `$PATH` the script falls back to |
| `cv2.VideoWriter`. No recording-machine code needed. |
| """ |
| 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_window_dataset import ReactWindowDataset |
|
|
|
|
| def _to_hwc(t): |
| """(3, H, W) torch uint8 → (H, W, 3) numpy uint8.""" |
| return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy() |
|
|
|
|
| def _view_to_rgb(view_chw_uint8): |
| """`view` was extracted from RealSense cam0 which records BGR |
| (`rs.format.bgr8`); convert to RGB for PIL.""" |
| 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: |
| """One row per window, `n_cols` evenly-spaced frames per window. Each |
| cell is `view | tactile_left | tactile_right`.""" |
| 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"ReactWindowDataset — {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()) |
| cv2.putText( |
| canvas, |
| (f"sample #{idx} · {s['episode_key']} · frames {s['frame_start']}-{s['frame_end']} " |
| f"({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)} (frame {s['frame_start'] + 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: |
| """Pipe raw RGB frames to ffmpeg → H.264 MP4. Falls back to |
| cv2.VideoWriter(mp4v) if ffmpeg isn't on PATH.""" |
| 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: |
| """Render one ReactWindowDataset window as a [view | tac_L | tac_R] MP4 |
| at native source FPS (15 by default; sample_rate / playback). Each |
| composite frame is `(128*scale × 384*scale × 3)`.""" |
| s = ds[sample_idx] |
| T = s["view"].shape[0] |
| 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['episode_key']} frame {s['frame_start']+t}/{s['frame_end']} " |
| f"({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("--data_root", required=True, |
| help="processed/mode1_v1/motherboard (relative to dataset root)") |
| ap.add_argument("--bad_frames", default="bad_frames.json") |
| 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_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, |
| help="Playback fps for the per-window MP4 clips.") |
| ap.add_argument("--no_mp4", action="store_true", |
| help="Skip the MP4 clip rendering (only write the static PNG grid).") |
| ap.add_argument("--no_motion_filter", action="store_true", |
| help="Disable the motion filter (useful if you want stationary " |
| "contact windows for studying static tactile patterns).") |
| args = ap.parse_args() |
|
|
| print("=== Building dataset (all four quality filters on) ===") |
| ds = ReactWindowDataset( |
| data_root = args.data_root, |
| bad_frames_path = args.bad_frames, |
| 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 = "any", |
| skip_bad_frames = True, |
| 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. Try lowering `min_contact_fraction` " |
| "or disabling `require_motion`.") |
| 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}") |
|
|
| print(f"\n=== Static grid of {len(pick)} random windows ===") |
| out_dir = Path(args.out_dir) |
| 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() |
|
|