examples/play_react_pt.py: accept episode-stem paths. You can now pass .../2026-05-11/episode_005 (no .pt suffix) and the player resolves all matching segments, loads the parent date folder so N/P navigation still works, and seeks to that episode on start.
Browse files- examples/play_react_pt.py +446 -247
examples/play_react_pt.py
CHANGED
|
@@ -1,78 +1,208 @@
|
|
| 1 |
-
"""Interactive playback for React data
|
| 2 |
directory of segments / episodes, concatenates same-episode segments
|
| 3 |
into one continuous timeline, and lets you switch between source
|
| 4 |
episodes with N / P.
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
Usage
|
| 7 |
-----
|
| 8 |
-
Single file (mode1_v1 episode OR
|
| 9 |
-
python
|
| 10 |
processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
Headless export (one MP4 per episode):
|
| 23 |
-
python
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
Controls
|
| 26 |
--------
|
| 27 |
-
space
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
1..6
|
| 31 |
-
r
|
| 32 |
-
n
|
| 33 |
-
p
|
| 34 |
-
q
|
| 35 |
"""
|
| 36 |
import argparse
|
| 37 |
-
import collections
|
| 38 |
import re
|
| 39 |
import sys
|
| 40 |
import time
|
| 41 |
from pathlib import Path
|
|
|
|
| 42 |
|
| 43 |
import cv2
|
|
|
|
| 44 |
import numpy as np
|
| 45 |
import torch
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# ──────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
TRACKER_COLORS = {
|
| 49 |
"sensor_left": ( 0, 255, 120),
|
| 50 |
"sensor_right": ( 0, 180, 255),
|
| 51 |
}
|
| 52 |
-
PANEL_W, PANEL_H = 1280, 480
|
| 53 |
-
VIEW_THUMB = (320, 240)
|
| 54 |
-
TAC_THUMB = (240, 240)
|
| 55 |
-
OT_PANEL = (320, 240)
|
| 56 |
-
TRAIL_PANEL = (640, 240)
|
| 57 |
-
CONTROLS_PANEL = (320, 240)
|
| 58 |
|
| 59 |
SEGMENT_FNAME_RE = re.compile(r"^(episode_\d+)\.segment_(\d+)\.pt$")
|
| 60 |
PLAIN_EPISODE_RE = re.compile(r"^(episode_\d+)\.pt$")
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
-
|
| 64 |
-
return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()
|
| 65 |
-
|
| 66 |
-
def _view_to_bgr(view_chw):
|
| 67 |
-
return view_chw.permute(1, 2, 0).numpy()
|
| 68 |
-
|
| 69 |
def _tactile_to_bgr(tac_chw):
|
| 70 |
rgb = tac_chw.permute(1, 2, 0).numpy()
|
| 71 |
return rgb[..., ::-1]
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
# ──────────────────────────────────────────────────────────────────────────────
|
|
@@ -91,7 +221,7 @@ def discover_episodes(root: Path) -> list[dict]:
|
|
| 91 |
if not pts:
|
| 92 |
raise SystemExit(f"No .pt files under {root}")
|
| 93 |
|
| 94 |
-
episodes: dict[str, dict] = {}
|
| 95 |
for p in pts:
|
| 96 |
m_seg = SEGMENT_FNAME_RE.match(p.name)
|
| 97 |
m_plain = PLAIN_EPISODE_RE.match(p.name)
|
|
@@ -121,21 +251,17 @@ def discover_episodes(root: Path) -> list[dict]:
|
|
| 121 |
class LoadedEpisode:
|
| 122 |
"""One source episode, with all its segments concatenated for playback.
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
- keys for the 5 per-frame scalar/vector tensors
|
| 127 |
-
- segment_bounds[i] = (start_in_concat, end_in_concat, seg_idx, source_h5_range)
|
| 128 |
-
for the i-th segment
|
| 129 |
-
- p01 reference frames pulled from the *first* segment's _contact_meta
|
| 130 |
"""
|
| 131 |
PER_FRAME_KEYS = (
|
| 132 |
-
"
|
| 133 |
-
"sensor_left_pose", "sensor_right_pose",
|
| 134 |
"tactile_left_intensity", "tactile_right_intensity",
|
| 135 |
"tactile_left_mixed", "tactile_right_mixed",
|
| 136 |
)
|
| 137 |
|
| 138 |
-
def __init__(self, ep_meta: dict):
|
| 139 |
self.key = ep_meta["key"]
|
| 140 |
self.date = ep_meta["date"]
|
| 141 |
self.ep_stem = ep_meta["ep_stem"]
|
|
@@ -144,16 +270,20 @@ class LoadedEpisode:
|
|
| 144 |
f"({len(self.segment_paths)} segment{'s' if len(self.segment_paths) > 1 else ''})...")
|
| 145 |
|
| 146 |
per_seg = [torch.load(p, weights_only=False, map_location="cpu") for p in self.segment_paths]
|
|
|
|
| 147 |
cat = {}
|
| 148 |
for k in self.PER_FRAME_KEYS:
|
| 149 |
if k in per_seg[0]:
|
| 150 |
cat[k] = torch.cat([s[k] for s in per_seg], dim=0)
|
| 151 |
-
|
| 152 |
bounds = []
|
| 153 |
cursor = 0
|
|
|
|
| 154 |
for i, s in enumerate(per_seg):
|
| 155 |
n = s["view"].shape[0]
|
| 156 |
meta = s.get("_contact_meta", {})
|
|
|
|
|
|
|
| 157 |
bounds.append({
|
| 158 |
"start_in_concat": cursor,
|
| 159 |
"end_in_concat": cursor + n - 1,
|
|
@@ -165,10 +295,27 @@ class LoadedEpisode:
|
|
| 165 |
self.data = cat
|
| 166 |
self.bounds = bounds
|
| 167 |
self.n_frames = cursor
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
print(f"[player] total {self.n_frames} frames ({self.n_frames / 30.0:.1f}s)")
|
| 173 |
|
| 174 |
def segment_at(self, frame_idx: int) -> dict:
|
|
@@ -180,134 +327,157 @@ class LoadedEpisode:
|
|
| 180 |
def is_segment_start(self, frame_idx: int) -> bool:
|
| 181 |
return any(frame_idx == b["start_in_concat"] for b in self.bounds[1:])
|
| 182 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 185 |
-
# Panel renderer
|
| 186 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 187 |
|
| 188 |
-
def _make_ot_panel(
|
| 189 |
panel = np.zeros((h, w, 3), np.uint8)
|
| 190 |
cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
|
| 191 |
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
|
| 192 |
cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
|
| 193 |
y = 56
|
| 194 |
-
for name
|
| 195 |
-
|
| 196 |
-
cv2.putText(panel, name, (8, y),
|
|
|
|
| 197 |
y += 18
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
y += 16
|
| 204 |
-
cv2.putText(panel, f" qx={qx:+.2f} qy={qy:+.2f}", (8, y),
|
|
|
|
| 205 |
y += 16
|
| 206 |
-
cv2.putText(panel, f" qz={qz:+.2f} qw={qw:+.2f}", (8, y),
|
|
|
|
| 207 |
y += 24
|
| 208 |
cv2.putText(panel, f"t = {t_sec:.2f} s (concat frame {t_idx})",
|
| 209 |
(8, h - 14), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1, cv2.LINE_AA)
|
| 210 |
return panel
|
| 211 |
|
| 212 |
|
| 213 |
-
def _make_trail_panel(iL_trail, iR_trail, boundary_marks, w, h, threshold=0.4):
|
| 214 |
-
panel = np.zeros((h, w, 3), np.uint8)
|
| 215 |
-
cv2.putText(panel, "Contact intensity (mixed) — orange = L · blue = R · red = segment cut",
|
| 216 |
-
(8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (200, 200, 200), 1, cv2.LINE_AA)
|
| 217 |
-
cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
|
| 218 |
-
mid_y = h - 26
|
| 219 |
-
max_y = 50
|
| 220 |
-
cv2.line(panel, (8, mid_y), (w - 8, mid_y), (80, 80, 80), 1)
|
| 221 |
-
if not iL_trail:
|
| 222 |
-
return panel
|
| 223 |
-
N = len(iL_trail)
|
| 224 |
-
smax = max(max(iL_trail), max(iR_trail), float(threshold) * 1.5, 1e-3)
|
| 225 |
-
x_scale = (w - 16) / max(N - 1, 1)
|
| 226 |
-
for i in range(N - 1):
|
| 227 |
-
x0 = int(8 + i * x_scale); x1 = int(8 + (i + 1) * x_scale)
|
| 228 |
-
y0L = mid_y - int(min(iL_trail[i], smax) / smax * max_y)
|
| 229 |
-
y1L = mid_y - int(min(iL_trail[i + 1], smax) / smax * max_y)
|
| 230 |
-
cv2.line(panel, (x0, y0L), (x1, y1L), (0, 159, 230), 1, cv2.LINE_AA)
|
| 231 |
-
y0R = mid_y + int(min(iR_trail[i], smax) / smax * max_y)
|
| 232 |
-
y1R = mid_y + int(min(iR_trail[i + 1], smax) / smax * max_y)
|
| 233 |
-
cv2.line(panel, (x0, y0R), (x1, y1R), (178, 114, 0), 1, cv2.LINE_AA)
|
| 234 |
-
# Segment-cut markers
|
| 235 |
-
for off in boundary_marks:
|
| 236 |
-
if 0 <= off < N:
|
| 237 |
-
x = int(8 + off * x_scale)
|
| 238 |
-
cv2.line(panel, (x, 35), (x, h - 30), (0, 0, 220), 1, cv2.LINE_AA)
|
| 239 |
-
cv2.putText(panel, f"L = {iL_trail[-1]:.2f}", (10, 50),
|
| 240 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 159, 230), 1, cv2.LINE_AA)
|
| 241 |
-
cv2.putText(panel, f"R = {iR_trail[-1]:.2f}", (10, h - 8),
|
| 242 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (178, 114, 0), 1, cv2.LINE_AA)
|
| 243 |
-
return panel
|
| 244 |
-
|
| 245 |
-
|
| 246 |
def _make_controls_panel(w, h, paused, speed, ep_idx, n_eps):
|
| 247 |
panel = np.zeros((h, w, 3), np.uint8)
|
| 248 |
-
cv2.putText(panel, "Controls", (10,
|
| 249 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.
|
| 250 |
-
cv2.line(panel, (10,
|
| 251 |
keys = [
|
| 252 |
-
("SPACE",
|
| 253 |
-
("
|
| 254 |
-
("
|
| 255 |
-
("
|
| 256 |
-
("
|
| 257 |
-
("
|
|
|
|
| 258 |
]
|
| 259 |
-
y =
|
| 260 |
-
for
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
| 265 |
y += 22
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
cv2.putText(panel,
|
| 269 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.55,
|
| 270 |
-
cv2.putText(panel, f"speed: {speed}x
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
|
| 274 |
return panel
|
| 275 |
|
| 276 |
|
| 277 |
-
def
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
paused: bool, speed: int,
|
| 280 |
ep_idx: int, n_eps: int):
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
panel = np.vstack([row1, row2])
|
| 309 |
|
| 310 |
-
# Top status bar
|
| 311 |
cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
|
| 312 |
state = "PAUSED" if paused else "PLAYING"
|
| 313 |
seg = ep.segment_at(frame_idx)
|
|
@@ -315,11 +485,13 @@ def build_panel(ep: LoadedEpisode, frame_idx: int, ref_L_bgr, ref_R_bgr,
|
|
| 315 |
seg_label = f"seg {seg['seg_idx']:02d}"
|
| 316 |
if h5r:
|
| 317 |
seg_label += f" H5[{h5r[0]}..{h5r[1]}]"
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
| 321 |
cv2.putText(panel, status, (10, 16),
|
| 322 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.
|
| 323 |
|
| 324 |
# Segment-cut flash: red border for the first 2 frames of a non-first segment
|
| 325 |
if ep.is_segment_start(frame_idx):
|
|
@@ -333,25 +505,46 @@ def build_panel(ep: LoadedEpisode, frame_idx: int, ref_L_bgr, ref_R_bgr,
|
|
| 333 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 334 |
|
| 335 |
def main():
|
| 336 |
-
ap = argparse.ArgumentParser(description="Interactive React .pt player.")
|
| 337 |
ap.add_argument("path", help="A single .pt file OR a directory of episodes/segments.")
|
| 338 |
ap.add_argument("--save_video", default=None,
|
| 339 |
help="When `path` is a single .pt: write that one episode as MP4 here.")
|
| 340 |
ap.add_argument("--save_video_dir", default=None,
|
| 341 |
help="When `path` is a directory: write one MP4 per episode into this dir.")
|
| 342 |
ap.add_argument("--fps", type=float, default=30.0)
|
| 343 |
-
ap.add_argument("--
|
|
|
|
|
|
|
| 344 |
args = ap.parse_args()
|
| 345 |
|
| 346 |
in_path = Path(args.path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
if not in_path.exists():
|
| 348 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
if in_path.is_file():
|
| 351 |
-
|
| 352 |
-
parent_root = in_path.parent.parent # <root>/<date>/file.pt → <root>
|
| 353 |
episodes = discover_episodes(parent_root)
|
| 354 |
-
# Find the episode that contains this exact file
|
| 355 |
target_path = in_path.resolve()
|
| 356 |
start_idx = 0
|
| 357 |
for i, ep_meta in enumerate(episodes):
|
|
@@ -360,44 +553,56 @@ def main():
|
|
| 360 |
else:
|
| 361 |
episodes = discover_episodes(in_path)
|
| 362 |
start_idx = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
print(f"[player] discovered {len(episodes)} episode(s) under {in_path}")
|
| 364 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
headless_dir = Path(args.save_video_dir) if args.save_video_dir else None
|
| 366 |
headless_single = args.save_video
|
| 367 |
-
|
| 368 |
if headless_single and len(episodes) > 1 and in_path.is_dir():
|
| 369 |
-
print("--save_video accepts a single output path; for a directory pass --save_video_dir instead.",
|
|
|
|
| 370 |
sys.exit(1)
|
| 371 |
-
|
| 372 |
headless = headless_single is not None or headless_dir is not None
|
| 373 |
|
| 374 |
if headless:
|
| 375 |
if headless_dir:
|
| 376 |
headless_dir.mkdir(parents=True, exist_ok=True)
|
| 377 |
for ep_idx in range(start_idx, len(episodes)):
|
| 378 |
-
ep = LoadedEpisode(episodes[ep_idx])
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
]
|
| 395 |
-
panel = build_panel(ep, f, ep.ref_L, ep.ref_R,
|
| 396 |
-
iL_trail, iR_trail, local_boundary_marks,
|
| 397 |
-
paused=False, speed=1,
|
| 398 |
-
ep_idx=ep_idx, n_eps=len(episodes))
|
| 399 |
-
writer.write(panel)
|
| 400 |
-
writer.release()
|
| 401 |
if headless_single:
|
| 402 |
break
|
| 403 |
return
|
|
@@ -409,75 +614,69 @@ def main():
|
|
| 409 |
|
| 410 |
ep_idx = start_idx
|
| 411 |
while 0 <= ep_idx < len(episodes):
|
| 412 |
-
ep = LoadedEpisode(episodes[ep_idx])
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
if frame_idx >= ep.n_frames:
|
| 464 |
-
print(f"End of episode {ep.key}.")
|
| 465 |
-
paused = True
|
| 466 |
-
frame_idx = ep.n_frames - 1
|
| 467 |
-
time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))
|
| 468 |
-
|
| 469 |
-
cv2.destroyAllWindows()
|
| 470 |
if action == "quit": return
|
| 471 |
if action == "next":
|
| 472 |
-
|
| 473 |
-
if
|
| 474 |
print("Already at last episode.")
|
|
|
|
| 475 |
elif action == "prev":
|
| 476 |
-
|
| 477 |
-
if
|
| 478 |
print("Already at first episode.")
|
|
|
|
| 479 |
else:
|
| 480 |
-
# natural end of an episode — pause; wait for explicit action
|
| 481 |
paused = True
|
| 482 |
|
| 483 |
|
|
|
|
| 1 |
+
"""Interactive playback for React data -- accepts a single `.pt` OR a
|
| 2 |
directory of segments / episodes, concatenates same-episode segments
|
| 3 |
into one continuous timeline, and lets you switch between source
|
| 4 |
episodes with N / P.
|
| 5 |
|
| 6 |
+
The viewer reuses `twm.viz.build_preview_panel`'s 1280x480 grid:
|
| 7 |
+
|
| 8 |
+
Row 1 (y=0..240): [left cam | middle cam | right cam | OptiTrack]
|
| 9 |
+
Row 2 (y=240..480): [gs_L_raw | gs_L_diff | gs_R_raw | gs_R_diff | Controls]
|
| 10 |
+
|
| 11 |
+
The three RealSense thumbnails and both GelSight raw streams are pulled
|
| 12 |
+
from the source HDF5 file (referenced by each .pt segment's
|
| 13 |
+
`_contact_meta.source_episode` + `source_h5_frame_range`). When the
|
| 14 |
+
source H5 cannot be located, those cells are filled with a "no H5"
|
| 15 |
+
placeholder.
|
| 16 |
+
|
| 17 |
Usage
|
| 18 |
-----
|
| 19 |
+
Single .pt file (mode1_v1 episode OR one mode2_v1 segment):
|
| 20 |
+
python scripts/play_react_pt.py \\
|
| 21 |
processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
|
| 22 |
|
| 23 |
+
Episode stem (no .pt suffix) -- loads ALL segments of that episode and
|
| 24 |
+
seeds N/P navigation across the rest of the date folder:
|
| 25 |
+
python scripts/play_react_pt.py \\
|
| 26 |
+
processed/mode2_v1/motherboard/2026-05-11/episode_005
|
| 27 |
|
| 28 |
+
Date folder -- all episodes recorded that day:
|
| 29 |
+
python scripts/play_react_pt.py \\
|
| 30 |
+
processed/mode2_v1/motherboard/2026-05-11
|
| 31 |
|
| 32 |
+
Whole task -- every episode across every date:
|
| 33 |
+
python scripts/play_react_pt.py \\
|
| 34 |
+
processed/mode2_v1/motherboard
|
| 35 |
+
|
| 36 |
+
In all multi-episode modes, same-episode segments are concatenated
|
| 37 |
+
into one playback timeline; N / P jumps to the next / previous
|
| 38 |
+
source episode.
|
| 39 |
|
| 40 |
Headless export (one MP4 per episode):
|
| 41 |
+
python scripts/play_react_pt.py <root> --save_video_dir /tmp/out
|
| 42 |
+
|
| 43 |
+
Override the source-H5 root (otherwise inferred by replacing
|
| 44 |
+
`processed/<mode>` with `data` in the input path):
|
| 45 |
+
python scripts/play_react_pt.py <root> --h5_root /path/to/data/<task>
|
| 46 |
|
| 47 |
Controls
|
| 48 |
--------
|
| 49 |
+
space pause / resume
|
| 50 |
+
-> / d next frame
|
| 51 |
+
<- / a previous frame
|
| 52 |
+
1..6 playback speed 1x / 2x / 5x / 10x / 25x / 50x
|
| 53 |
+
r reset GelSight diff reference to current frame
|
| 54 |
+
n next episode
|
| 55 |
+
p previous episode
|
| 56 |
+
q quit
|
| 57 |
"""
|
| 58 |
import argparse
|
|
|
|
| 59 |
import re
|
| 60 |
import sys
|
| 61 |
import time
|
| 62 |
from pathlib import Path
|
| 63 |
+
from typing import Optional
|
| 64 |
|
| 65 |
import cv2
|
| 66 |
+
import h5py
|
| 67 |
import numpy as np
|
| 68 |
import torch
|
| 69 |
|
| 70 |
+
try:
|
| 71 |
+
from twm.viz import (
|
| 72 |
+
load_optitrack as _viz_load_optitrack,
|
| 73 |
+
optitrack_at as _viz_optitrack_at,
|
| 74 |
+
DISPLAY_ORDER,
|
| 75 |
+
)
|
| 76 |
+
except Exception:
|
| 77 |
+
_viz_load_optitrack = None
|
| 78 |
+
_viz_optitrack_at = None
|
| 79 |
+
DISPLAY_ORDER = [1, 2, 0] # H5 cam_idx order for [left, middle, right]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 83 |
+
# Layout constants (matches twm.viz.build_preview_panel)
|
| 84 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 85 |
+
PANEL_W, PANEL_H = 1280, 480
|
| 86 |
+
RS_THUMB_W, RS_THUMB_H = 320, 240 # RealSense cam cell
|
| 87 |
+
GS_THUMB_W, GS_THUMB_H = 240, 240 # GelSight raw/diff cell
|
| 88 |
+
CONTROLS_W, CONTROLS_H = 320, 240 # Controls panel (replaces blank in row 2)
|
| 89 |
+
|
| 90 |
TRACKER_COLORS = {
|
| 91 |
"sensor_left": ( 0, 255, 120),
|
| 92 |
"sensor_right": ( 0, 180, 255),
|
| 93 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
SEGMENT_FNAME_RE = re.compile(r"^(episode_\d+)\.segment_(\d+)\.pt$")
|
| 96 |
PLAIN_EPISODE_RE = re.compile(r"^(episode_\d+)\.pt$")
|
| 97 |
+
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
| 98 |
|
| 99 |
|
| 100 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def _tactile_to_bgr(tac_chw):
|
| 102 |
rgb = tac_chw.permute(1, 2, 0).numpy()
|
| 103 |
return rgb[..., ::-1]
|
| 104 |
|
| 105 |
+
|
| 106 |
+
def _missing_cell(w, h, label):
|
| 107 |
+
panel = np.full((h, w, 3), 32, np.uint8)
|
| 108 |
+
cv2.putText(panel, label, (10, h // 2),
|
| 109 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (140, 140, 140), 1, cv2.LINE_AA)
|
| 110 |
+
return panel
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 114 |
+
# H5 source resolution
|
| 115 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 116 |
+
|
| 117 |
+
def infer_h5_root(pt_path: Path) -> Optional[Path]:
|
| 118 |
+
"""Map a .pt path to its source-H5 root by replacing the
|
| 119 |
+
`processed/<mode>/` prefix with `data/`.
|
| 120 |
+
|
| 121 |
+
Examples:
|
| 122 |
+
.../twm/processed/mode2_v1/motherboard/2026-05-11/ep.pt
|
| 123 |
+
-> .../twm/data/motherboard
|
| 124 |
+
.../twm/processed/mode2_v1/motherboard
|
| 125 |
+
-> .../twm/data/motherboard
|
| 126 |
+
"""
|
| 127 |
+
parts = list(pt_path.parts)
|
| 128 |
+
try:
|
| 129 |
+
i = parts.index("processed")
|
| 130 |
+
except ValueError:
|
| 131 |
+
return None
|
| 132 |
+
if i + 1 >= len(parts):
|
| 133 |
+
return None
|
| 134 |
+
base = parts[:i]
|
| 135 |
+
tail = []
|
| 136 |
+
for p in parts[i + 2:]:
|
| 137 |
+
if DATE_RE.match(p) or p.endswith(".pt"):
|
| 138 |
+
break
|
| 139 |
+
tail.append(p)
|
| 140 |
+
return Path(*base, "data", *tail)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def resolve_h5_path(h5_root: Optional[Path], source_episode: Optional[str]) -> Optional[Path]:
|
| 144 |
+
"""`source_episode` is '<date>/<episode_stem>'. Returns
|
| 145 |
+
<h5_root>/<source_episode>.h5 if it exists, else None.
|
| 146 |
+
"""
|
| 147 |
+
if not h5_root or not source_episode:
|
| 148 |
+
return None
|
| 149 |
+
candidate = h5_root / f"{source_episode}.h5"
|
| 150 |
+
return candidate if candidate.exists() else None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class H5Source:
|
| 154 |
+
"""Lazy read-only access to a source H5: cams, gelsight frames, OT poses."""
|
| 155 |
+
|
| 156 |
+
def __init__(self, h5_path: Optional[Path]):
|
| 157 |
+
self.path = h5_path
|
| 158 |
+
self.f = None
|
| 159 |
+
self.n_frames = 0
|
| 160 |
+
self.timestamps = None
|
| 161 |
+
self.gs_left_n = 0
|
| 162 |
+
self.gs_right_n = 0
|
| 163 |
+
self.optitrack = None
|
| 164 |
+
if h5_path is None:
|
| 165 |
+
return
|
| 166 |
+
try:
|
| 167 |
+
self.f = h5py.File(str(h5_path), "r")
|
| 168 |
+
self.n_frames = int(self.f["timestamps"].shape[0])
|
| 169 |
+
self.timestamps = self.f["timestamps"][:]
|
| 170 |
+
self.gs_left_n = int(self.f["gelsight/left/frames"].shape[0])
|
| 171 |
+
self.gs_right_n = int(self.f["gelsight/right/frames"].shape[0])
|
| 172 |
+
if _viz_load_optitrack is not None:
|
| 173 |
+
self.optitrack = _viz_load_optitrack(self.f)
|
| 174 |
+
except Exception as e:
|
| 175 |
+
print(f"[player] ! failed to open H5 {h5_path}: {e}")
|
| 176 |
+
self.close()
|
| 177 |
+
|
| 178 |
+
@property
|
| 179 |
+
def ok(self) -> bool:
|
| 180 |
+
return self.f is not None
|
| 181 |
+
|
| 182 |
+
def cam(self, idx: int, h5_frame: int) -> Optional[np.ndarray]:
|
| 183 |
+
if not self.ok or h5_frame < 0 or h5_frame >= self.n_frames:
|
| 184 |
+
return None
|
| 185 |
+
return self.f[f"realsense/cam{idx}/color"][h5_frame]
|
| 186 |
+
|
| 187 |
+
def gelsight(self, side: str, h5_frame: int) -> Optional[np.ndarray]:
|
| 188 |
+
if not self.ok:
|
| 189 |
+
return None
|
| 190 |
+
n = self.gs_left_n if side == "left" else self.gs_right_n
|
| 191 |
+
if n == 0:
|
| 192 |
+
return None
|
| 193 |
+
return self.f[f"gelsight/{side}/frames"][min(max(h5_frame, 0), n - 1)]
|
| 194 |
+
|
| 195 |
+
def ot_at(self, h5_frame: int) -> dict:
|
| 196 |
+
if not self.ok or self.optitrack is None or _viz_optitrack_at is None:
|
| 197 |
+
return {}
|
| 198 |
+
idx = min(max(h5_frame, 0), self.n_frames - 1)
|
| 199 |
+
return _viz_optitrack_at(self.optitrack, float(self.timestamps[idx]))
|
| 200 |
+
|
| 201 |
+
def close(self):
|
| 202 |
+
if self.f is not None:
|
| 203 |
+
try: self.f.close()
|
| 204 |
+
except Exception: pass
|
| 205 |
+
self.f = None
|
| 206 |
|
| 207 |
|
| 208 |
# ──────────────────────────────────────────────────────────────────────────────
|
|
|
|
| 221 |
if not pts:
|
| 222 |
raise SystemExit(f"No .pt files under {root}")
|
| 223 |
|
| 224 |
+
episodes: dict[str, dict] = {}
|
| 225 |
for p in pts:
|
| 226 |
m_seg = SEGMENT_FNAME_RE.match(p.name)
|
| 227 |
m_plain = PLAIN_EPISODE_RE.match(p.name)
|
|
|
|
| 251 |
class LoadedEpisode:
|
| 252 |
"""One source episode, with all its segments concatenated for playback.
|
| 253 |
|
| 254 |
+
The concat timeline only carries .pt scalar/pose tensors; image cells are
|
| 255 |
+
served on-demand from the bound source H5 file.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
"""
|
| 257 |
PER_FRAME_KEYS = (
|
| 258 |
+
"timestamps",
|
| 259 |
+
"sensor_left_pose", "sensor_right_pose",
|
| 260 |
"tactile_left_intensity", "tactile_right_intensity",
|
| 261 |
"tactile_left_mixed", "tactile_right_mixed",
|
| 262 |
)
|
| 263 |
|
| 264 |
+
def __init__(self, ep_meta: dict, h5_root: Optional[Path] = None):
|
| 265 |
self.key = ep_meta["key"]
|
| 266 |
self.date = ep_meta["date"]
|
| 267 |
self.ep_stem = ep_meta["ep_stem"]
|
|
|
|
| 270 |
f"({len(self.segment_paths)} segment{'s' if len(self.segment_paths) > 1 else ''})...")
|
| 271 |
|
| 272 |
per_seg = [torch.load(p, weights_only=False, map_location="cpu") for p in self.segment_paths]
|
| 273 |
+
|
| 274 |
cat = {}
|
| 275 |
for k in self.PER_FRAME_KEYS:
|
| 276 |
if k in per_seg[0]:
|
| 277 |
cat[k] = torch.cat([s[k] for s in per_seg], dim=0)
|
| 278 |
+
|
| 279 |
bounds = []
|
| 280 |
cursor = 0
|
| 281 |
+
source_ep = None
|
| 282 |
for i, s in enumerate(per_seg):
|
| 283 |
n = s["view"].shape[0]
|
| 284 |
meta = s.get("_contact_meta", {})
|
| 285 |
+
if source_ep is None:
|
| 286 |
+
source_ep = meta.get("source_episode")
|
| 287 |
bounds.append({
|
| 288 |
"start_in_concat": cursor,
|
| 289 |
"end_in_concat": cursor + n - 1,
|
|
|
|
| 295 |
self.data = cat
|
| 296 |
self.bounds = bounds
|
| 297 |
self.n_frames = cursor
|
| 298 |
+
self.source_episode = source_ep
|
| 299 |
+
|
| 300 |
+
# Bind source H5
|
| 301 |
+
h5_path = resolve_h5_path(h5_root, source_ep) if source_ep else None
|
| 302 |
+
self.h5 = H5Source(h5_path)
|
| 303 |
+
if self.h5.ok:
|
| 304 |
+
print(f"[player] H5 source: {h5_path} ({self.h5.n_frames} frames)")
|
| 305 |
+
else:
|
| 306 |
+
print(f"[player] H5 source not available "
|
| 307 |
+
f"(source_episode={source_ep!r}, h5_root={h5_root}) -- "
|
| 308 |
+
f"cam/gelsight cells will be blank")
|
| 309 |
+
|
| 310 |
+
# GelSight diff references = H5 gelsight at the first segment's H5 start
|
| 311 |
+
self.gs_ref_L = None
|
| 312 |
+
self.gs_ref_R = None
|
| 313 |
+
if self.h5.ok:
|
| 314 |
+
r0 = bounds[0]["source_h5_range"]
|
| 315 |
+
ref_h5_frame = r0[0] if r0 else 0
|
| 316 |
+
self.gs_ref_L = self.h5.gelsight("left", ref_h5_frame)
|
| 317 |
+
self.gs_ref_R = self.h5.gelsight("right", ref_h5_frame)
|
| 318 |
+
|
| 319 |
print(f"[player] total {self.n_frames} frames ({self.n_frames / 30.0:.1f}s)")
|
| 320 |
|
| 321 |
def segment_at(self, frame_idx: int) -> dict:
|
|
|
|
| 327 |
def is_segment_start(self, frame_idx: int) -> bool:
|
| 328 |
return any(frame_idx == b["start_in_concat"] for b in self.bounds[1:])
|
| 329 |
|
| 330 |
+
def h5_frame_for(self, frame_idx: int) -> Optional[int]:
|
| 331 |
+
seg = self.segment_at(frame_idx)
|
| 332 |
+
r = seg["source_h5_range"]
|
| 333 |
+
if r is None:
|
| 334 |
+
return None
|
| 335 |
+
return r[0] + (frame_idx - seg["start_in_concat"])
|
| 336 |
+
|
| 337 |
+
def close(self):
|
| 338 |
+
self.h5.close()
|
| 339 |
+
|
| 340 |
|
| 341 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 342 |
+
# Panel renderer (visualize.py-style 1280x480 grid)
|
| 343 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 344 |
|
| 345 |
+
def _make_ot_panel(ot_poses, t_idx, t_sec, w, h):
|
| 346 |
panel = np.zeros((h, w, 3), np.uint8)
|
| 347 |
cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
|
| 348 |
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
|
| 349 |
cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
|
| 350 |
y = 56
|
| 351 |
+
for name in ("sensor_left", "sensor_right"):
|
| 352 |
+
color = TRACKER_COLORS[name]
|
| 353 |
+
cv2.putText(panel, name, (8, y),
|
| 354 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1, cv2.LINE_AA)
|
| 355 |
y += 18
|
| 356 |
+
pose = ot_poses.get(name) if isinstance(ot_poses, dict) else None
|
| 357 |
+
if pose is None:
|
| 358 |
+
cv2.putText(panel, " no data", (8, y),
|
| 359 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (100, 100, 100), 1, cv2.LINE_AA)
|
| 360 |
+
y += 36
|
| 361 |
+
continue
|
| 362 |
+
_, xyz_quat = pose
|
| 363 |
+
x_m, y_m, z_m = xyz_quat[:3]
|
| 364 |
+
qx, qy, qz, qw = xyz_quat[3:]
|
| 365 |
+
cv2.putText(panel, f" x={x_m:+.3f} y={y_m:+.3f} z={z_m:+.3f}", (8, y),
|
| 366 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.38, (220, 220, 220), 1, cv2.LINE_AA)
|
| 367 |
y += 16
|
| 368 |
+
cv2.putText(panel, f" qx={qx:+.2f} qy={qy:+.2f}", (8, y),
|
| 369 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
|
| 370 |
y += 16
|
| 371 |
+
cv2.putText(panel, f" qz={qz:+.2f} qw={qw:+.2f}", (8, y),
|
| 372 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
|
| 373 |
y += 24
|
| 374 |
cv2.putText(panel, f"t = {t_sec:.2f} s (concat frame {t_idx})",
|
| 375 |
(8, h - 14), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1, cv2.LINE_AA)
|
| 376 |
return panel
|
| 377 |
|
| 378 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
def _make_controls_panel(w, h, paused, speed, ep_idx, n_eps):
|
| 380 |
panel = np.zeros((h, w, 3), np.uint8)
|
| 381 |
+
cv2.putText(panel, "Controls", (10, 24),
|
| 382 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 1, cv2.LINE_AA)
|
| 383 |
+
cv2.line(panel, (10, 32), (w - 10, 32), (80, 80, 80), 1)
|
| 384 |
keys = [
|
| 385 |
+
("SPACE", "pause / resume"),
|
| 386 |
+
("-> / d", "next frame"),
|
| 387 |
+
("<- / a", "prev frame"),
|
| 388 |
+
("1..6", "speed 1x/2x/5x/10x/25x/50x"),
|
| 389 |
+
("n / p", "next / prev episode"),
|
| 390 |
+
("r", "reset gel-diff ref"),
|
| 391 |
+
("q", "quit"),
|
| 392 |
]
|
| 393 |
+
y = 56
|
| 394 |
+
for key, desc in keys:
|
| 395 |
+
highlight = (key == "SPACE")
|
| 396 |
+
key_color = (0, 220, 255) if highlight else (140, 200, 140)
|
| 397 |
+
desc_color = (220, 220, 220) if highlight else (160, 160, 160)
|
| 398 |
+
cv2.putText(panel, f"[{key}]", (10, y),
|
| 399 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, key_color, 1, cv2.LINE_AA)
|
| 400 |
+
cv2.putText(panel, desc, (110, y),
|
| 401 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, desc_color, 1, cv2.LINE_AA)
|
| 402 |
y += 22
|
| 403 |
+
state_text = "|| PAUSED" if paused else "> PLAYING"
|
| 404 |
+
state_color = (0, 140, 255) if paused else (0, 220, 80)
|
| 405 |
+
cv2.putText(panel, state_text, (10, h - 32),
|
| 406 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.55, state_color, 2, cv2.LINE_AA)
|
| 407 |
+
cv2.putText(panel, f"speed: {speed}x ep {ep_idx + 1}/{n_eps}",
|
| 408 |
+
(10, h - 12),
|
| 409 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (180, 180, 180), 1, cv2.LINE_AA)
|
|
|
|
| 410 |
return panel
|
| 411 |
|
| 412 |
|
| 413 |
+
def _rs_thumb(img, label=None):
|
| 414 |
+
out = cv2.resize(img, (RS_THUMB_W, RS_THUMB_H))
|
| 415 |
+
if label:
|
| 416 |
+
cv2.putText(out, label, (6, 16),
|
| 417 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (220, 220, 220), 1, cv2.LINE_AA)
|
| 418 |
+
return out
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def _gs_thumb(img, label=None):
|
| 422 |
+
out = cv2.resize(img, (GS_THUMB_W, GS_THUMB_H))
|
| 423 |
+
if label:
|
| 424 |
+
cv2.putText(out, label, (6, 16),
|
| 425 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (220, 220, 220), 1, cv2.LINE_AA)
|
| 426 |
+
return out
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def _gs_diff_thumb(frame_bgr, ref_bgr, label=None):
|
| 430 |
+
diff = np.clip(frame_bgr.astype(np.int16) - ref_bgr.astype(np.int16) + 128, 0, 255).astype(np.uint8)
|
| 431 |
+
out = cv2.resize(diff, (GS_THUMB_W, GS_THUMB_H))
|
| 432 |
+
if label:
|
| 433 |
+
cv2.putText(out, label, (6, 16),
|
| 434 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (220, 220, 220), 1, cv2.LINE_AA)
|
| 435 |
+
return out
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def build_panel(ep: LoadedEpisode, frame_idx: int,
|
| 439 |
+
gs_ref_L, gs_ref_R,
|
| 440 |
paused: bool, speed: int,
|
| 441 |
ep_idx: int, n_eps: int):
|
| 442 |
+
h5_frame = ep.h5_frame_for(frame_idx)
|
| 443 |
+
t_sec = float(ep.data["timestamps"][frame_idx] - ep.data["timestamps"][0])
|
| 444 |
+
|
| 445 |
+
# Row 1: 3 RealSense cams (left, middle, right) + OptiTrack
|
| 446 |
+
cam_thumbs = []
|
| 447 |
+
cam_labels = ["left cam", "middle cam", "right cam"]
|
| 448 |
+
for slot, label in zip(DISPLAY_ORDER, cam_labels):
|
| 449 |
+
img = ep.h5.cam(slot, h5_frame) if h5_frame is not None else None
|
| 450 |
+
if img is None:
|
| 451 |
+
cam_thumbs.append(_missing_cell(RS_THUMB_W, RS_THUMB_H, f"{label}: no H5"))
|
| 452 |
+
else:
|
| 453 |
+
cam_thumbs.append(_rs_thumb(img, label))
|
| 454 |
+
ot_poses = ep.h5.ot_at(h5_frame) if h5_frame is not None else {}
|
| 455 |
+
ot_panel = _make_ot_panel(ot_poses, frame_idx, t_sec, RS_THUMB_W, RS_THUMB_H)
|
| 456 |
+
row1 = np.hstack(cam_thumbs + [ot_panel])
|
| 457 |
+
|
| 458 |
+
# Row 2: GelSight raw + diff (L, R) + Controls
|
| 459 |
+
gs_L = ep.h5.gelsight("left", h5_frame) if h5_frame is not None else None
|
| 460 |
+
gs_R = ep.h5.gelsight("right", h5_frame) if h5_frame is not None else None
|
| 461 |
+
if gs_L is None:
|
| 462 |
+
gs_L_raw = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_L: no H5")
|
| 463 |
+
gs_L_dif = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_L diff: no H5")
|
| 464 |
+
else:
|
| 465 |
+
gs_L_raw = _gs_thumb(gs_L, "tactile_left")
|
| 466 |
+
ref_L = gs_ref_L if gs_ref_L is not None else gs_L
|
| 467 |
+
gs_L_dif = _gs_diff_thumb(gs_L, ref_L, "tac_L diff")
|
| 468 |
+
if gs_R is None:
|
| 469 |
+
gs_R_raw = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_R: no H5")
|
| 470 |
+
gs_R_dif = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_R diff: no H5")
|
| 471 |
+
else:
|
| 472 |
+
gs_R_raw = _gs_thumb(gs_R, "tactile_right")
|
| 473 |
+
ref_R = gs_ref_R if gs_ref_R is not None else gs_R
|
| 474 |
+
gs_R_dif = _gs_diff_thumb(gs_R, ref_R, "tac_R diff")
|
| 475 |
+
controls = _make_controls_panel(CONTROLS_W, CONTROLS_H, paused, speed, ep_idx, n_eps)
|
| 476 |
+
row2 = np.hstack([gs_L_raw, gs_L_dif, gs_R_raw, gs_R_dif, controls])
|
| 477 |
+
|
| 478 |
panel = np.vstack([row1, row2])
|
| 479 |
|
| 480 |
+
# Top status bar (visualize.py style: thicker cyan text)
|
| 481 |
cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
|
| 482 |
state = "PAUSED" if paused else "PLAYING"
|
| 483 |
seg = ep.segment_at(frame_idx)
|
|
|
|
| 485 |
seg_label = f"seg {seg['seg_idx']:02d}"
|
| 486 |
if h5r:
|
| 487 |
seg_label += f" H5[{h5r[0]}..{h5r[1]}]"
|
| 488 |
+
if h5_frame is not None:
|
| 489 |
+
seg_label += f" @{h5_frame}"
|
| 490 |
+
status = (f"[{state}] ep {ep_idx + 1}/{n_eps} {ep.key} | "
|
| 491 |
+
f"frame {frame_idx + 1}/{ep.n_frames} | t={t_sec:.2f}s | "
|
| 492 |
+
f"{seg_label} | {speed}x")
|
| 493 |
cv2.putText(panel, status, (10, 16),
|
| 494 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 255), 1, cv2.LINE_AA)
|
| 495 |
|
| 496 |
# Segment-cut flash: red border for the first 2 frames of a non-first segment
|
| 497 |
if ep.is_segment_start(frame_idx):
|
|
|
|
| 505 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 506 |
|
| 507 |
def main():
|
| 508 |
+
ap = argparse.ArgumentParser(description="Interactive React .pt player (visualize.py-style layout).")
|
| 509 |
ap.add_argument("path", help="A single .pt file OR a directory of episodes/segments.")
|
| 510 |
ap.add_argument("--save_video", default=None,
|
| 511 |
help="When `path` is a single .pt: write that one episode as MP4 here.")
|
| 512 |
ap.add_argument("--save_video_dir", default=None,
|
| 513 |
help="When `path` is a directory: write one MP4 per episode into this dir.")
|
| 514 |
ap.add_argument("--fps", type=float, default=30.0)
|
| 515 |
+
ap.add_argument("--h5_root", default=None,
|
| 516 |
+
help="Root directory of source H5 files (e.g. <twm>/data/<task>). "
|
| 517 |
+
"If omitted, inferred by replacing `processed/<mode>` with `data` in `path`.")
|
| 518 |
args = ap.parse_args()
|
| 519 |
|
| 520 |
in_path = Path(args.path)
|
| 521 |
+
|
| 522 |
+
# Path-stem expansion: if the user typed an incomplete path like
|
| 523 |
+
# `.../2026-05-11/episode_005` (no .pt suffix, possibly no .segment_NN),
|
| 524 |
+
# treat it as an episode-stem filter. We load the parent date folder so
|
| 525 |
+
# N/P navigation still works, then start playback at the matching episode.
|
| 526 |
+
start_episode_key: Optional[str] = None
|
| 527 |
if not in_path.exists():
|
| 528 |
+
parent = in_path.parent
|
| 529 |
+
stem = in_path.name
|
| 530 |
+
if parent.is_dir() and stem:
|
| 531 |
+
matches = sorted(parent.glob(f"{stem}*.pt"))
|
| 532 |
+
# Require either an exact-name match or segment_NN siblings
|
| 533 |
+
matches = [p for p in matches
|
| 534 |
+
if PLAIN_EPISODE_RE.match(p.name) and p.stem == stem
|
| 535 |
+
or (SEGMENT_FNAME_RE.match(p.name)
|
| 536 |
+
and SEGMENT_FNAME_RE.match(p.name).group(1) == stem)]
|
| 537 |
+
if matches:
|
| 538 |
+
start_episode_key = f"{parent.name}/{stem}"
|
| 539 |
+
in_path = parent # discover the whole date folder
|
| 540 |
+
print(f"[player] interpreting '{args.path}' as episode-stem; "
|
| 541 |
+
f"will start at {start_episode_key}")
|
| 542 |
+
if not in_path.exists():
|
| 543 |
+
print(f"Not found: {args.path}", file=sys.stderr); sys.exit(1)
|
| 544 |
|
| 545 |
if in_path.is_file():
|
| 546 |
+
parent_root = in_path.parent.parent
|
|
|
|
| 547 |
episodes = discover_episodes(parent_root)
|
|
|
|
| 548 |
target_path = in_path.resolve()
|
| 549 |
start_idx = 0
|
| 550 |
for i, ep_meta in enumerate(episodes):
|
|
|
|
| 553 |
else:
|
| 554 |
episodes = discover_episodes(in_path)
|
| 555 |
start_idx = 0
|
| 556 |
+
if start_episode_key is not None:
|
| 557 |
+
for i, ep_meta in enumerate(episodes):
|
| 558 |
+
if ep_meta["key"] == start_episode_key:
|
| 559 |
+
start_idx = i; break
|
| 560 |
+
else:
|
| 561 |
+
print(f"[player] WARN: stem '{start_episode_key}' not found in discovered "
|
| 562 |
+
f"episodes; starting at the first one")
|
| 563 |
print(f"[player] discovered {len(episodes)} episode(s) under {in_path}")
|
| 564 |
|
| 565 |
+
# Resolve H5 root
|
| 566 |
+
h5_root: Optional[Path] = None
|
| 567 |
+
if args.h5_root:
|
| 568 |
+
h5_root = Path(args.h5_root)
|
| 569 |
+
else:
|
| 570 |
+
h5_root = infer_h5_root(in_path)
|
| 571 |
+
if h5_root:
|
| 572 |
+
ok = "ok" if h5_root.exists() else "missing"
|
| 573 |
+
print(f"[player] H5 source root: {h5_root} ({ok})")
|
| 574 |
+
else:
|
| 575 |
+
print("[player] H5 source root not specified and could not be inferred -- "
|
| 576 |
+
"RealSense + GelSight cells will be blank")
|
| 577 |
+
|
| 578 |
headless_dir = Path(args.save_video_dir) if args.save_video_dir else None
|
| 579 |
headless_single = args.save_video
|
|
|
|
| 580 |
if headless_single and len(episodes) > 1 and in_path.is_dir():
|
| 581 |
+
print("--save_video accepts a single output path; for a directory pass --save_video_dir instead.",
|
| 582 |
+
file=sys.stderr)
|
| 583 |
sys.exit(1)
|
|
|
|
| 584 |
headless = headless_single is not None or headless_dir is not None
|
| 585 |
|
| 586 |
if headless:
|
| 587 |
if headless_dir:
|
| 588 |
headless_dir.mkdir(parents=True, exist_ok=True)
|
| 589 |
for ep_idx in range(start_idx, len(episodes)):
|
| 590 |
+
ep = LoadedEpisode(episodes[ep_idx], h5_root=h5_root)
|
| 591 |
+
try:
|
| 592 |
+
out_path = (Path(headless_single)
|
| 593 |
+
if headless_single else
|
| 594 |
+
(headless_dir / f"{ep.date}_{ep.ep_stem}.mp4"))
|
| 595 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 596 |
+
writer = cv2.VideoWriter(str(out_path), fourcc, args.fps, (PANEL_W, PANEL_H))
|
| 597 |
+
print(f" -> {out_path}")
|
| 598 |
+
for f in range(ep.n_frames):
|
| 599 |
+
panel = build_panel(ep, f, ep.gs_ref_L, ep.gs_ref_R,
|
| 600 |
+
paused=False, speed=1,
|
| 601 |
+
ep_idx=ep_idx, n_eps=len(episodes))
|
| 602 |
+
writer.write(panel)
|
| 603 |
+
writer.release()
|
| 604 |
+
finally:
|
| 605 |
+
ep.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 606 |
if headless_single:
|
| 607 |
break
|
| 608 |
return
|
|
|
|
| 614 |
|
| 615 |
ep_idx = start_idx
|
| 616 |
while 0 <= ep_idx < len(episodes):
|
| 617 |
+
ep = LoadedEpisode(episodes[ep_idx], h5_root=h5_root)
|
| 618 |
+
action = "stay"
|
| 619 |
+
try:
|
| 620 |
+
WIN = "React .pt player"
|
| 621 |
+
cv2.namedWindow(WIN, cv2.WINDOW_AUTOSIZE)
|
| 622 |
+
cv2.createTrackbar("Frame", WIN, 0, max(1, ep.n_frames - 1), lambda v: None)
|
| 623 |
+
gs_ref_L, gs_ref_R = ep.gs_ref_L, ep.gs_ref_R
|
| 624 |
+
frame_idx = 0
|
| 625 |
+
last_drawn = -1
|
| 626 |
+
|
| 627 |
+
while True:
|
| 628 |
+
frame_idx = max(0, min(frame_idx, ep.n_frames - 1))
|
| 629 |
+
pos = cv2.getTrackbarPos("Frame", WIN)
|
| 630 |
+
if pos != frame_idx and pos != last_drawn:
|
| 631 |
+
frame_idx = pos; paused = True
|
| 632 |
+
|
| 633 |
+
panel = build_panel(ep, frame_idx,
|
| 634 |
+
gs_ref_L, gs_ref_R,
|
| 635 |
+
paused=paused, speed=speed,
|
| 636 |
+
ep_idx=ep_idx, n_eps=len(episodes))
|
| 637 |
+
cv2.imshow(WIN, panel)
|
| 638 |
+
if cv2.getTrackbarPos("Frame", WIN) != frame_idx:
|
| 639 |
+
cv2.setTrackbarPos("Frame", WIN, frame_idx)
|
| 640 |
+
last_drawn = frame_idx
|
| 641 |
+
|
| 642 |
+
key = cv2.waitKey(1) & 0xFF
|
| 643 |
+
if key == ord('q'): action = "quit"; break
|
| 644 |
+
elif key == ord(' '): paused = not paused
|
| 645 |
+
elif key in (81, ord('a')): paused = True; frame_idx -= 1
|
| 646 |
+
elif key in (83, ord('d')): paused = True; frame_idx += 1
|
| 647 |
+
elif key in SPEEDS: speed = SPEEDS[key]
|
| 648 |
+
elif key == ord('r'):
|
| 649 |
+
h5_frame = ep.h5_frame_for(frame_idx)
|
| 650 |
+
if h5_frame is not None and ep.h5.ok:
|
| 651 |
+
gs_ref_L = ep.h5.gelsight("left", h5_frame)
|
| 652 |
+
gs_ref_R = ep.h5.gelsight("right", h5_frame)
|
| 653 |
+
print(f" gel-diff ref reset to concat frame {frame_idx} (H5 frame {h5_frame})")
|
| 654 |
+
elif key == ord('n'): action = "next"; break
|
| 655 |
+
elif key == ord('p'): action = "prev"; break
|
| 656 |
+
|
| 657 |
+
if not paused:
|
| 658 |
+
frame_idx += speed
|
| 659 |
+
if frame_idx >= ep.n_frames:
|
| 660 |
+
print(f"End of episode {ep.key}.")
|
| 661 |
+
paused = True
|
| 662 |
+
frame_idx = ep.n_frames - 1
|
| 663 |
+
time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))
|
| 664 |
+
|
| 665 |
+
cv2.destroyAllWindows()
|
| 666 |
+
finally:
|
| 667 |
+
ep.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
if action == "quit": return
|
| 669 |
if action == "next":
|
| 670 |
+
new_idx = min(ep_idx + 1, len(episodes) - 1)
|
| 671 |
+
if new_idx == ep_idx:
|
| 672 |
print("Already at last episode.")
|
| 673 |
+
ep_idx = new_idx
|
| 674 |
elif action == "prev":
|
| 675 |
+
new_idx = max(ep_idx - 1, 0)
|
| 676 |
+
if new_idx == ep_idx:
|
| 677 |
print("Already at first episode.")
|
| 678 |
+
ep_idx = new_idx
|
| 679 |
else:
|
|
|
|
| 680 |
paused = True
|
| 681 |
|
| 682 |
|