yxma commited on
Commit
d78749e
·
verified ·
1 Parent(s): bd2bd59

ReactWindowDataset: prominent contact-rich window count + stats attribute (ds.stats) + per-filter rejection breakdown in the summary print. Demo: write H.264 MP4 per picked window (was just static PNG); --no_mp4 to skip; --mp4_fps to tune.

Browse files
examples/demo_react_window.py CHANGED
@@ -17,12 +17,17 @@ What this script does
17
  3. Renders a static grid of `--n_samples` random windows as a PNG. Each
18
  row = one window; each cell = `view | tactile_left | tactile_right`
19
  for a single frame inside that window.
 
 
 
20
 
21
- Self-contained: only depends on numpy, torch, Pillow, and `cv2`. No
22
- recording-machine code is needed everything required to read the
23
- published .pt files is shipped here.
24
  """
25
  import argparse
 
 
26
  import sys
27
  from pathlib import Path
28
 
@@ -108,6 +113,75 @@ def make_static_grid(ds, sample_indices, out_path: Path, *,
108
  print(f" grid -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
109
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  def main():
112
  ap = argparse.ArgumentParser()
113
  ap.add_argument("--data_root", required=True,
@@ -118,6 +192,10 @@ def main():
118
  ap.add_argument("--out_dir", default="/tmp/react_demo_out")
119
  ap.add_argument("--window_length", type=int, default=16)
120
  ap.add_argument("--seed", type=int, default=42)
 
 
 
 
121
  ap.add_argument("--no_motion_filter", action="store_true",
122
  help="Disable the motion filter (useful if you want stationary "
123
  "contact windows for studying static tactile patterns).")
@@ -163,6 +241,15 @@ def main():
163
  out_dir = Path(args.out_dir)
164
  make_static_grid(ds, pick, out_dir / "sample_grid.png")
165
 
 
 
 
 
 
 
 
 
 
166
 
167
  if __name__ == "__main__":
168
  main()
 
17
  3. Renders a static grid of `--n_samples` random windows as a PNG. Each
18
  row = one window; each cell = `view | tactile_left | tactile_right`
19
  for a single frame inside that window.
20
+ 4. For each picked window also writes a small MP4 clip showing the actual
21
+ per-frame motion (replaces the GIF outputs the old demo used to ship —
22
+ MP4 is ~10× smaller and renders inline on HF).
23
 
24
+ Self-contained: numpy + torch + Pillow + cv2. `ffmpeg` is used to encode
25
+ the MP4 clips; if it isn't on `$PATH` the script falls back to
26
+ `cv2.VideoWriter`. No recording-machine code needed.
27
  """
28
  import argparse
29
+ import shutil
30
+ import subprocess
31
  import sys
32
  from pathlib import Path
33
 
 
113
  print(f" grid -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
114
 
115
 
116
+ def _write_mp4_h264(frames_rgb, out_path: Path, fps: float = 15.0) -> None:
117
+ """Pipe raw RGB frames to ffmpeg → H.264 MP4. Falls back to
118
+ cv2.VideoWriter(mp4v) if ffmpeg isn't on PATH."""
119
+ H, W = frames_rgb[0].shape[:2]
120
+ out_path.parent.mkdir(parents=True, exist_ok=True)
121
+
122
+ if shutil.which("ffmpeg") is not None:
123
+ cmd = [
124
+ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
125
+ "-f", "rawvideo", "-pix_fmt", "rgb24",
126
+ "-s", f"{W}x{H}", "-r", f"{fps:.3f}",
127
+ "-i", "-",
128
+ "-c:v", "libx264", "-pix_fmt", "yuv420p",
129
+ "-preset", "medium", "-crf", "20",
130
+ "-movflags", "+faststart",
131
+ "-an", str(out_path),
132
+ ]
133
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
134
+ for f in frames_rgb:
135
+ assert f.shape == (H, W, 3) and f.dtype == np.uint8
136
+ proc.stdin.write(f.tobytes())
137
+ proc.stdin.close()
138
+ if proc.wait() != 0:
139
+ raise RuntimeError("ffmpeg failed")
140
+ return
141
+
142
+ # Fallback: cv2.VideoWriter with mp4v codec (universally portable but
143
+ # not as widely browser-streamable as H.264).
144
+ vw = cv2.VideoWriter(str(out_path),
145
+ cv2.VideoWriter_fourcc(*"mp4v"),
146
+ fps, (W, H))
147
+ for f in frames_rgb:
148
+ vw.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR))
149
+ vw.release()
150
+
151
+
152
+ def make_window_mp4(ds, sample_idx: int, out_path: Path,
153
+ *, scale: int = 3, fps: float = 15.0) -> None:
154
+ """Render one ReactWindowDataset window as a [view | tac_L | tac_R] MP4
155
+ at native source FPS (15 by default; sample_rate / playback). Each
156
+ composite frame is `(128*scale × 384*scale × 3)`."""
157
+ s = ds[sample_idx]
158
+ T = s["view"].shape[0]
159
+ frames = []
160
+ for t in range(T):
161
+ view = _view_to_rgb(s["view"][t]).astype(np.uint8)
162
+ tac_L = _to_hwc(s["tactile_left"][t]).astype(np.uint8)
163
+ tac_R = _to_hwc(s["tactile_right"][t]).astype(np.uint8)
164
+ triplet = np.concatenate([view, tac_L, tac_R], axis=1) # (128, 384, 3)
165
+ triplet = cv2.resize(
166
+ triplet,
167
+ (triplet.shape[1] * scale, triplet.shape[0] * scale),
168
+ interpolation=cv2.INTER_NEAREST,
169
+ )
170
+ # Header strip with sample metadata so the clip is self-describing
171
+ H, W, _ = triplet.shape
172
+ header = np.full((28, W, 3), 235, np.uint8)
173
+ cv2.putText(
174
+ header,
175
+ f"#{sample_idx} {s['episode_key']} frame {s['frame_start']+t}/{s['frame_end']} "
176
+ f"({t+1}/{T}) view | tactile_L | tactile_R",
177
+ (8, 19), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (40, 40, 40), 1, cv2.LINE_AA,
178
+ )
179
+ frames.append(np.concatenate([header, triplet], axis=0))
180
+
181
+ _write_mp4_h264(frames, out_path, fps=fps)
182
+ print(f" mp4 -> {out_path.name} ({out_path.stat().st_size / 1024:.1f} KB)")
183
+
184
+
185
  def main():
186
  ap = argparse.ArgumentParser()
187
  ap.add_argument("--data_root", required=True,
 
192
  ap.add_argument("--out_dir", default="/tmp/react_demo_out")
193
  ap.add_argument("--window_length", type=int, default=16)
194
  ap.add_argument("--seed", type=int, default=42)
195
+ ap.add_argument("--mp4_fps", type=float, default=15.0,
196
+ help="Playback fps for the per-window MP4 clips.")
197
+ ap.add_argument("--no_mp4", action="store_true",
198
+ help="Skip the MP4 clip rendering (only write the static PNG grid).")
199
  ap.add_argument("--no_motion_filter", action="store_true",
200
  help="Disable the motion filter (useful if you want stationary "
201
  "contact windows for studying static tactile patterns).")
 
241
  out_dir = Path(args.out_dir)
242
  make_static_grid(ds, pick, out_dir / "sample_grid.png")
243
 
244
+ if not args.no_mp4:
245
+ print(f"\n=== Per-window MP4 clips ({len(pick)} files, H.264) ===")
246
+ for i, idx in enumerate(pick):
247
+ make_window_mp4(
248
+ ds, int(idx),
249
+ out_dir / f"sample_window_{i:02d}.mp4",
250
+ fps=args.mp4_fps,
251
+ )
252
+
253
 
254
  if __name__ == "__main__":
255
  main()
examples/react_window_dataset.py CHANGED
@@ -337,11 +337,42 @@ class ReactWindowDataset(Dataset):
337
  kept += 1
338
  print(f"[ReactWindowDataset] {key}: T={T}, active={active}, kept {kept} windows")
339
 
340
- print(f"[ReactWindowDataset] total windows: {len(self.windows)} "
341
- f"(window_length={self.window_length}, stride={self.stride}, "
342
- f"window_step={self.window_step})")
343
- print(f"[ReactWindowDataset] enumerated {n_total_candidates} candidates: "
344
- f"-{n_drop_bad} bad_frames, -{n_drop_contact} contact, -{n_drop_motion} motion")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
 
346
  def __len__(self) -> int:
347
  return len(self.windows)
 
337
  kept += 1
338
  print(f"[ReactWindowDataset] {key}: T={T}, active={active}, kept {kept} windows")
339
 
340
+ # Persist build stats on the instance so callers can inspect / log them
341
+ self.stats = {
342
+ "n_episodes": len(self.episodes),
343
+ "n_candidates": n_total_candidates,
344
+ "n_dropped_bad_frames": n_drop_bad,
345
+ "n_dropped_contact": n_drop_contact,
346
+ "n_dropped_motion": n_drop_motion,
347
+ "n_contact_rich_windows": len(self.windows),
348
+ "window_length": self.window_length,
349
+ "stride": self.stride,
350
+ "window_step": self.window_step,
351
+ "min_contact_fraction": self.min_contact_fraction,
352
+ "tactile_threshold": self.tactile_threshold,
353
+ "contact_metric": self.contact_metric,
354
+ "which_sensors": self.which_sensors,
355
+ "skip_bad_frames": self.skip_bad_frames,
356
+ "require_motion": self.require_motion,
357
+ "min_motion_mps": self.min_motion_mps,
358
+ "min_motion_fraction": self.min_motion_fraction,
359
+ "which_sensors_must_move": self.which_sensors_must_move,
360
+ }
361
+
362
+ # Headline summary — emphasises the contact-rich count, which is the
363
+ # number you'd quote in a paper or a model training log.
364
+ pct = 100.0 * len(self.windows) / max(1, n_total_candidates)
365
+ print()
366
+ print(f"[ReactWindowDataset] =================================")
367
+ print(f"[ReactWindowDataset] Contact-rich windows sampled: {len(self.windows):,}")
368
+ print(f"[ReactWindowDataset] ({pct:.1f}% of {n_total_candidates:,} sliding-window candidates)")
369
+ print(f"[ReactWindowDataset] =================================")
370
+ print(f"[ReactWindowDataset] Window spec: length={self.window_length}, stride={self.stride}, "
371
+ f"step={self.window_step} (≈{self.window_length / 30:.2f}s @ 30 fps)")
372
+ print(f"[ReactWindowDataset] Rejected by filter:")
373
+ print(f"[ReactWindowDataset] bad_frames (intensity_spikes, pose_teleports, ot_loss): {n_drop_bad:,}")
374
+ print(f"[ReactWindowDataset] contact (< {self.min_contact_fraction:.0%} of frames in tactile contact): {n_drop_contact:,}")
375
+ print(f"[ReactWindowDataset] motion ({'enabled' if self.require_motion else 'disabled'}): {n_drop_motion:,}")
376
 
377
  def __len__(self) -> int:
378
  return len(self.windows)