React / examples /demo_react_window.py
yxma's picture
examples/: upgraded ReactWindowDataset (adds motion filter to catch operator-paused windows the bad_frames check cant); canonical self-contained demo_react_window.py (no twm dependency); new examples/README.md with four-filter explanation and recipes per use case
cc62065 verified
raw
history blame
6.84 kB
"""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.
Self-contained: only depends on numpy, torch, Pillow, and `cv2`. No
recording-machine code is needed — everything required to read the
published .pt files is shipped here.
"""
import argparse
import sys
from pathlib import Path
import cv2
import numpy as np
import torch
from PIL import Image
# Same-directory import.
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) # (128, 384, 3)
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 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("--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.03,
min_motion_fraction = 0.5,
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 __name__ == "__main__":
main()