yxma commited on
Commit
496dc3e
·
verified ·
1 Parent(s): 54a3d1d

scripts: import bootstrap

Browse files
Files changed (1) hide show
  1. scripts/play_react_pt.py +955 -0
scripts/play_react_pt.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import sys as _sys
71
+ from pathlib import Path as _Path
72
+ # repo root, so `force_recovery` / `twm` / `react_toolbox` import however
73
+ # this file is invoked. Six scripts lacked this and failed at import; all
74
+ # six sat in validate_all's "slow" skip list, so nothing ran them.
75
+ _sys.path.insert(0, str(_Path(__file__).resolve().parents[1]))
76
+
77
+ try:
78
+ from twm.viz import (
79
+ load_optitrack as _viz_load_optitrack,
80
+ optitrack_at as _viz_optitrack_at,
81
+ DISPLAY_ORDER,
82
+ draw_projection_overlay as _viz_draw_projection_overlay,
83
+ load_calibrations as _viz_load_calibrations,
84
+ )
85
+ except Exception:
86
+ _viz_load_optitrack = None
87
+ _viz_optitrack_at = None
88
+ _viz_draw_projection_overlay = None
89
+ _viz_load_calibrations = None
90
+ DISPLAY_ORDER = [1, 2, 0] # H5 cam_idx order for [left, middle, right]
91
+
92
+ try:
93
+ from twm.data_collection import REALSENSE_SERIALS
94
+ except Exception:
95
+ REALSENSE_SERIALS = ["143322063538", "104122062574", "217222066989"]
96
+
97
+
98
+ # ──────────────────────────────────────────────────────────────────────────────
99
+ # Layout constants (matches twm.viz.build_preview_panel)
100
+ # ──────────────────────────────────────────────────────────────────────────────
101
+ PANEL_W, PANEL_H = 1280, 480
102
+ RS_THUMB_W, RS_THUMB_H = 320, 240 # RealSense cam cell
103
+ GS_THUMB_W, GS_THUMB_H = 240, 240 # GelSight raw/diff cell
104
+ CONTROLS_W, CONTROLS_H = 320, 240 # Controls panel (replaces blank in row 2)
105
+
106
+ TRACKER_COLORS = {
107
+ "sensor_left": ( 0, 255, 120),
108
+ "sensor_right": ( 0, 180, 255),
109
+ }
110
+
111
+ SEGMENT_FNAME_RE = re.compile(r"^(episode_\d+)\.segment_(\d+)\.pt$")
112
+ PLAIN_EPISODE_RE = re.compile(r"^(episode_\d+)\.pt$")
113
+ DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
114
+
115
+ # The calibration epoch is PER TASK (May-12 for motherboard, June-26 for
116
+ # pushT); it is resolved from the input path at parse time via calib_epoch.
117
+ # The old module constant here defaulted every task to June-26.
118
+
119
+
120
+ # ──────────────────────────────────────────────────────────────────────────────
121
+ def _tactile_to_bgr(tac_chw):
122
+ rgb = tac_chw.permute(1, 2, 0).numpy()
123
+ return rgb[..., ::-1]
124
+
125
+
126
+ def _missing_cell(w, h, label):
127
+ panel = np.full((h, w, 3), 32, np.uint8)
128
+ cv2.putText(panel, label, (10, h // 2),
129
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, (140, 140, 140), 1, cv2.LINE_AA)
130
+ return panel
131
+
132
+
133
+ # ──────────────────────────────────────────────────────────────────────────────
134
+ # H5 source resolution
135
+ # ──────────────────────────────────────────────────────────────────────────────
136
+
137
+ def infer_h5_root(pt_path: Path) -> Optional[Path]:
138
+ """Map a .pt path to its source-H5 root by replacing the
139
+ `processed/<mode>/` prefix with `data/`.
140
+
141
+ Examples:
142
+ .../twm/processed/mode2_v1/motherboard/2026-05-11/ep.pt
143
+ -> .../twm/data/motherboard
144
+ .../twm/processed/mode2_v1/motherboard
145
+ -> .../twm/data/motherboard
146
+ """
147
+ parts = list(pt_path.parts)
148
+ try:
149
+ i = parts.index("processed")
150
+ except ValueError:
151
+ return None
152
+ if i + 1 >= len(parts):
153
+ return None
154
+ base = parts[:i]
155
+ tail = []
156
+ for p in parts[i + 2:]:
157
+ if DATE_RE.match(p) or p.endswith(".pt"):
158
+ break
159
+ tail.append(p)
160
+ return Path(*base, "data", *tail)
161
+
162
+
163
+ def resolve_h5_path(h5_root: Optional[Path], source_episode: Optional[str]) -> Optional[Path]:
164
+ """`source_episode` is '<date>/<episode_stem>'. Returns
165
+ <h5_root>/<source_episode>.h5 if it exists, else None.
166
+ """
167
+ if not h5_root or not source_episode:
168
+ return None
169
+ candidate = h5_root / f"{source_episode}.h5"
170
+ return candidate if candidate.exists() else None
171
+
172
+
173
+ class H5Source:
174
+ """Lazy read-only access to a source H5: cams, gelsight frames, OT poses.
175
+
176
+ Reads are served from an in-RAM chunk cache (default 32 frames). When the
177
+ requested frame falls outside the current chunk, the next chunk for all
178
+ 5 image streams is read in a single batched slab read -- ~30x faster than
179
+ per-frame H5 fancy-indexing.
180
+ """
181
+
182
+ CHUNK = 32
183
+
184
+ def __init__(self, h5_path: Optional[Path]):
185
+ self.path = h5_path
186
+ self.f = None
187
+ self.n_frames = 0
188
+ self.timestamps = None
189
+ self.gs_left_n = 0
190
+ self.gs_right_n = 0
191
+ self.optitrack = None
192
+ self._chunk_start = -1 # inclusive
193
+ self._chunk_end = -1 # exclusive (for cams)
194
+ self._chunk_cache: dict = {}
195
+ if h5_path is None:
196
+ return
197
+ try:
198
+ self.f = h5py.File(str(h5_path), "r")
199
+ self.n_frames = int(self.f["timestamps"].shape[0])
200
+ self.timestamps = self.f["timestamps"][:]
201
+ self.gs_left_n = int(self.f["gelsight/left/frames"].shape[0])
202
+ self.gs_right_n = int(self.f["gelsight/right/frames"].shape[0])
203
+ if _viz_load_optitrack is not None:
204
+ self.optitrack = _viz_load_optitrack(self.f)
205
+ except Exception as e:
206
+ print(f"[player] ! failed to open H5 {h5_path}: {e}")
207
+ self.close()
208
+
209
+ @property
210
+ def ok(self) -> bool:
211
+ return self.f is not None
212
+
213
+ def _ensure_chunk(self, h5_frame: int):
214
+ """Load the chunk containing h5_frame into RAM if not already there."""
215
+ if h5_frame < 0 or h5_frame >= self.n_frames:
216
+ return
217
+ cs = (h5_frame // self.CHUNK) * self.CHUNK
218
+ if cs == self._chunk_start:
219
+ return
220
+ ce = min(cs + self.CHUNK, self.n_frames)
221
+ cache = {
222
+ "cam0": self.f["realsense/cam0/color"][cs:ce],
223
+ "cam1": self.f["realsense/cam1/color"][cs:ce],
224
+ "cam2": self.f["realsense/cam2/color"][cs:ce],
225
+ }
226
+ if self.gs_left_n > 0:
227
+ ge = min(ce, self.gs_left_n)
228
+ cache["gs_left"] = self.f["gelsight/left/frames"][cs:ge] if cs < self.gs_left_n else None
229
+ if self.gs_right_n > 0:
230
+ ge = min(ce, self.gs_right_n)
231
+ cache["gs_right"] = self.f["gelsight/right/frames"][cs:ge] if cs < self.gs_right_n else None
232
+ self._chunk_start = cs
233
+ self._chunk_end = ce
234
+ self._chunk_cache = cache
235
+
236
+ def cam(self, idx: int, h5_frame: int) -> Optional[np.ndarray]:
237
+ if not self.ok or h5_frame < 0 or h5_frame >= self.n_frames:
238
+ return None
239
+ self._ensure_chunk(h5_frame)
240
+ slab = self._chunk_cache.get(f"cam{idx}")
241
+ if slab is None:
242
+ return None
243
+ return slab[h5_frame - self._chunk_start]
244
+
245
+ def gelsight(self, side: str, h5_frame: int) -> Optional[np.ndarray]:
246
+ if not self.ok:
247
+ return None
248
+ n = self.gs_left_n if side == "left" else self.gs_right_n
249
+ if n == 0:
250
+ return None
251
+ clamped = min(max(h5_frame, 0), n - 1)
252
+ self._ensure_chunk(clamped)
253
+ slab = self._chunk_cache.get(f"gs_{side}")
254
+ if slab is None:
255
+ return None
256
+ local = clamped - self._chunk_start
257
+ if local < 0 or local >= len(slab):
258
+ return None
259
+ return slab[local]
260
+
261
+ def ot_at(self, h5_frame: int) -> dict:
262
+ if not self.ok or self.optitrack is None or _viz_optitrack_at is None:
263
+ return {}
264
+ idx = min(max(h5_frame, 0), self.n_frames - 1)
265
+ return _viz_optitrack_at(self.optitrack, float(self.timestamps[idx]))
266
+
267
+ def close(self):
268
+ self._chunk_cache = {}
269
+ self._chunk_start = -1
270
+ if self.f is not None:
271
+ try: self.f.close()
272
+ except Exception: pass
273
+ self.f = None
274
+
275
+
276
+ # ──────────────────────────────────────────────────────────────────────────────
277
+ # Episode discovery
278
+ # ──────────────────────────────────────────────────────────────────────────────
279
+
280
+ def discover_episodes(root: Path) -> list[dict]:
281
+ """Walk `root`, group .pt files by source episode key '<date>/episode_NNN',
282
+ and return one entry per episode with its segment paths sorted.
283
+
284
+ Handles both:
285
+ - mode2_v1: `<root>/<date>/episode_NNN.segment_MM.pt`
286
+ - mode1_v1: `<root>/<date>/episode_NNN.pt`
287
+ """
288
+ pts = sorted(root.rglob("*.pt"))
289
+ if not pts:
290
+ raise SystemExit(f"No .pt files under {root}")
291
+
292
+ episodes: dict[str, dict] = {}
293
+ for p in pts:
294
+ m_seg = SEGMENT_FNAME_RE.match(p.name)
295
+ m_plain = PLAIN_EPISODE_RE.match(p.name)
296
+ if m_seg:
297
+ ep_stem, seg_idx = m_seg.group(1), int(m_seg.group(2))
298
+ elif m_plain:
299
+ ep_stem, seg_idx = m_plain.group(1), 0
300
+ else:
301
+ continue
302
+ date = p.parent.name
303
+ key = f"{date}/{ep_stem}"
304
+ episodes.setdefault(key, {"date": date, "ep_stem": ep_stem, "segs": []})
305
+ episodes[key]["segs"].append((seg_idx, p))
306
+
307
+ out = []
308
+ for key in sorted(episodes):
309
+ ep = episodes[key]
310
+ ep["segs"].sort(key=lambda x: x[0])
311
+ out.append({"key": key, **ep})
312
+ return out
313
+
314
+
315
+ # ──────────────────────────────────────────────────────────────────────────────
316
+ # Episode-load
317
+ # ──────────────────────────────────────────────────────────────────────────────
318
+
319
+ class LoadedEpisode:
320
+ """One source episode, with all its segments concatenated for playback.
321
+
322
+ The concat timeline only carries .pt scalar/pose tensors; image cells are
323
+ served on-demand from the bound source H5 file.
324
+ """
325
+ PER_FRAME_KEYS = (
326
+ "timestamps",
327
+ "sensor_left_pose", "sensor_right_pose",
328
+ "tactile_left_intensity", "tactile_right_intensity",
329
+ "tactile_left_mixed", "tactile_right_mixed",
330
+ )
331
+
332
+ def __init__(self, ep_meta: dict, h5_root: Optional[Path] = None,
333
+ tactile_latency: int = 0, source: str = "pt"):
334
+ self.tactile_latency = int(tactile_latency)
335
+ self.source = source
336
+ self.key = ep_meta["key"]
337
+ self.date = ep_meta["date"]
338
+ self.ep_stem = ep_meta["ep_stem"]
339
+ self.segment_paths = [p for _, p in ep_meta["segs"]]
340
+ _t_load = time.time()
341
+ n_segs = len(self.segment_paths)
342
+ print(f"[player] loading episode {self.key} "
343
+ f"({n_segs} segment{'s' if n_segs > 1 else ''})...", flush=True)
344
+
345
+ # mmap=True memory-maps the .pt without copying tensors into RAM.
346
+ # We only touch the small scalar/pose fields below; the large
347
+ # image tensors (view, tactile_*) are never read.
348
+ def _load(p):
349
+ try:
350
+ return torch.load(str(p), weights_only=False, map_location="cpu", mmap=True)
351
+ except (TypeError, ValueError, RuntimeError):
352
+ return torch.load(p, weights_only=False, map_location="cpu")
353
+ per_seg = []
354
+ for i, p in enumerate(self.segment_paths):
355
+ _ts = time.time()
356
+ per_seg.append(_load(p))
357
+ print(f"[player] [{i + 1}/{n_segs}] {p.name} "
358
+ f"({p.stat().st_size / 1e6:.0f} MB, {time.time() - _ts:.2f}s)", flush=True)
359
+
360
+ # Clone small tensors out of the mmap so they don't keep the file open
361
+ # any longer than necessary. When source="pt" we *do* keep the mmap'd
362
+ # per-segment dicts alive so `view` / `tactile_*` can be served from
363
+ # the .pt on demand.
364
+ cat = {}
365
+ for k in self.PER_FRAME_KEYS:
366
+ if k in per_seg[0]:
367
+ cat[k] = torch.cat([s[k].clone() for s in per_seg], dim=0)
368
+ self.per_seg_data = per_seg if source == "pt" else None
369
+
370
+ bounds = []
371
+ cursor = 0
372
+ source_ep = None
373
+ for i, s in enumerate(per_seg):
374
+ # Use shape[0] of any per-frame tensor instead of "view" to avoid
375
+ # paging in the giant image tensor under mmap.
376
+ n = int(s["timestamps"].shape[0])
377
+ meta = s.get("_contact_meta", {})
378
+ if source_ep is None:
379
+ source_ep = meta.get("source_episode")
380
+ bounds.append({
381
+ "start_in_concat": cursor,
382
+ "end_in_concat": cursor + n - 1,
383
+ "seg_idx": int(meta.get("source_segment_idx", i)),
384
+ "source_h5_range": meta.get("source_h5_frame_range"),
385
+ "n_frames": n,
386
+ })
387
+ cursor += n
388
+ self.data = cat
389
+ self.bounds = bounds
390
+ self.n_frames = cursor
391
+ self.source_episode = source_ep
392
+
393
+ # Bind source H5
394
+ h5_path = resolve_h5_path(h5_root, source_ep) if source_ep else None
395
+ self.h5 = H5Source(h5_path)
396
+ if self.h5.ok:
397
+ print(f"[player] H5 source: {h5_path} ({self.h5.n_frames} frames)", flush=True)
398
+ else:
399
+ print(f"[player] H5 source not available "
400
+ f"(source_episode={source_ep!r}, h5_root={h5_root}) -- "
401
+ f"cam/gelsight cells will be blank", flush=True)
402
+
403
+ # GelSight diff references = gelsight frame at concat-frame 0 + latency
404
+ # (shifted so the reference matches what build_panel will display).
405
+ self.gs_ref_L = None
406
+ self.gs_ref_R = None
407
+ ref_idx = max(0, min(self.n_frames - 1, self.tactile_latency))
408
+ if source == "pt":
409
+ self.gs_ref_L = self.pt_tactile("left", ref_idx)
410
+ self.gs_ref_R = self.pt_tactile("right", ref_idx)
411
+ elif self.h5.ok:
412
+ r0 = bounds[0]["source_h5_range"]
413
+ ref_h5_frame = (r0[0] if r0 else 0) + self.tactile_latency
414
+ self.gs_ref_L = self.h5.gelsight("left", ref_h5_frame)
415
+ self.gs_ref_R = self.h5.gelsight("right", ref_h5_frame)
416
+
417
+ print(f"[player] total {self.n_frames} frames ({self.n_frames / 30.0:.1f}s) "
418
+ f"[ready in {time.time() - _t_load:.2f}s]", flush=True)
419
+
420
+ def segment_at(self, frame_idx: int) -> dict:
421
+ for b in self.bounds:
422
+ if b["start_in_concat"] <= frame_idx <= b["end_in_concat"]:
423
+ return b
424
+ return self.bounds[-1]
425
+
426
+ def is_segment_start(self, frame_idx: int) -> bool:
427
+ return any(frame_idx == b["start_in_concat"] for b in self.bounds[1:])
428
+
429
+ def h5_frame_for(self, frame_idx: int) -> Optional[int]:
430
+ seg = self.segment_at(frame_idx)
431
+ r = seg["source_h5_range"]
432
+ if r is None:
433
+ return None
434
+ return r[0] + (frame_idx - seg["start_in_concat"])
435
+
436
+ def _seg_local(self, frame_idx: int):
437
+ """Map concat frame_idx -> (segment index, local index inside segment)."""
438
+ for i, b in enumerate(self.bounds):
439
+ if b["start_in_concat"] <= frame_idx <= b["end_in_concat"]:
440
+ return i, frame_idx - b["start_in_concat"]
441
+ last = len(self.bounds) - 1
442
+ return last, frame_idx - self.bounds[last]["start_in_concat"]
443
+
444
+ def _pt_image(self, key: str, frame_idx: int) -> Optional[np.ndarray]:
445
+ """Read an image tensor (shape (T, 3, H, W) uint8) from the per-segment
446
+ .pt mmap'd dicts, return BGR HxWx3 uint8 or None.
447
+ """
448
+ if self.per_seg_data is None or frame_idx < 0 or frame_idx >= self.n_frames:
449
+ return None
450
+ seg_i, local = self._seg_local(frame_idx)
451
+ d = self.per_seg_data[seg_i]
452
+ if key not in d:
453
+ return None
454
+ chw = d[key][local]
455
+ rgb = chw.permute(1, 2, 0).numpy()
456
+ return np.ascontiguousarray(rgb[..., ::-1]) # BGR for OpenCV
457
+
458
+ def pt_view(self, frame_idx: int) -> Optional[np.ndarray]:
459
+ return self._pt_image("view", frame_idx)
460
+
461
+ def pt_tactile(self, side: str, frame_idx: int) -> Optional[np.ndarray]:
462
+ return self._pt_image(f"tactile_{side}", frame_idx)
463
+
464
+ def close(self):
465
+ self.h5.close()
466
+
467
+
468
+ # ──────────────────────────────────────────────────────────────────────────────
469
+ # Panel renderer (visualize.py-style 1280x480 grid)
470
+ # ──────────────────────────────────────────────────────────────────────────────
471
+
472
+ def _make_ot_panel(ot_poses, t_idx, t_sec, w, h):
473
+ panel = np.zeros((h, w, 3), np.uint8)
474
+ cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
475
+ cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
476
+ cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
477
+ y = 56
478
+ for name in ("sensor_left", "sensor_right"):
479
+ color = TRACKER_COLORS[name]
480
+ cv2.putText(panel, name, (8, y),
481
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1, cv2.LINE_AA)
482
+ y += 18
483
+ pose = ot_poses.get(name) if isinstance(ot_poses, dict) else None
484
+ if pose is None:
485
+ cv2.putText(panel, " no data", (8, y),
486
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, (100, 100, 100), 1, cv2.LINE_AA)
487
+ y += 36
488
+ continue
489
+ _, xyz_quat = pose
490
+ x_m, y_m, z_m = xyz_quat[:3]
491
+ qx, qy, qz, qw = xyz_quat[3:]
492
+ cv2.putText(panel, f" x={x_m:+.3f} y={y_m:+.3f} z={z_m:+.3f}", (8, y),
493
+ cv2.FONT_HERSHEY_SIMPLEX, 0.38, (220, 220, 220), 1, cv2.LINE_AA)
494
+ y += 16
495
+ cv2.putText(panel, f" qx={qx:+.2f} qy={qy:+.2f}", (8, y),
496
+ cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
497
+ y += 16
498
+ cv2.putText(panel, f" qz={qz:+.2f} qw={qw:+.2f}", (8, y),
499
+ cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
500
+ y += 24
501
+ cv2.putText(panel, f"t = {t_sec:.2f} s (concat frame {t_idx})",
502
+ (8, h - 14), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1, cv2.LINE_AA)
503
+ return panel
504
+
505
+
506
+ def _make_controls_panel(w, h, paused, speed, ep_idx, n_eps, tactile_latency=0):
507
+ panel = np.zeros((h, w, 3), np.uint8)
508
+ cv2.putText(panel, "Controls", (10, 20),
509
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1, cv2.LINE_AA)
510
+ cv2.line(panel, (10, 26), (w - 10, 26), (80, 80, 80), 1)
511
+ keys = [
512
+ ("SPACE", "pause / resume"),
513
+ ("-> / d", "next frame"),
514
+ ("<- / a", "prev frame"),
515
+ ("1..6", "speed 1x/2x/5x/10x/25x/50x"),
516
+ ("n / p", "next / prev episode"),
517
+ ("r", "reset gel-diff ref"),
518
+ ("[ / ]", "tactile lat -/+ 1"),
519
+ ("q", "quit"),
520
+ ]
521
+ y = 44
522
+ for key, desc in keys:
523
+ highlight = (key == "SPACE")
524
+ key_color = (0, 220, 255) if highlight else (140, 200, 140)
525
+ desc_color = (220, 220, 220) if highlight else (160, 160, 160)
526
+ cv2.putText(panel, f"[{key}]", (10, y),
527
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, key_color, 1, cv2.LINE_AA)
528
+ cv2.putText(panel, desc, (105, y),
529
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, desc_color, 1, cv2.LINE_AA)
530
+ y += 18
531
+ state_text = "|| PAUSED" if paused else "> PLAYING"
532
+ state_color = (0, 140, 255) if paused else (0, 220, 80)
533
+ cv2.putText(panel, state_text, (10, h - 44),
534
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, state_color, 2, cv2.LINE_AA)
535
+ cv2.putText(panel, f"speed: {speed}x ep {ep_idx + 1}/{n_eps}",
536
+ (10, h - 26),
537
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, (180, 180, 180), 1, cv2.LINE_AA)
538
+ cv2.putText(panel, f"tactile_latency: {tactile_latency:+d}",
539
+ (10, h - 8),
540
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 220, 255), 1, cv2.LINE_AA)
541
+ return panel
542
+
543
+
544
+ def _rs_thumb(img, label=None):
545
+ out = cv2.resize(img, (RS_THUMB_W, RS_THUMB_H))
546
+ if label:
547
+ cv2.putText(out, label, (6, 16),
548
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, (220, 220, 220), 1, cv2.LINE_AA)
549
+ return out
550
+
551
+
552
+ def _gs_thumb(img, label=None):
553
+ out = cv2.resize(img, (GS_THUMB_W, GS_THUMB_H))
554
+ if label:
555
+ cv2.putText(out, label, (6, 16),
556
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (220, 220, 220), 1, cv2.LINE_AA)
557
+ return out
558
+
559
+
560
+ def _gs_diff_thumb(frame_bgr, ref_bgr, label=None):
561
+ diff = np.clip(frame_bgr.astype(np.int16) - ref_bgr.astype(np.int16) + 128, 0, 255).astype(np.uint8)
562
+ out = cv2.resize(diff, (GS_THUMB_W, GS_THUMB_H))
563
+ if label:
564
+ cv2.putText(out, label, (6, 16),
565
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (220, 220, 220), 1, cv2.LINE_AA)
566
+ return out
567
+
568
+
569
+ def build_panel(ep: LoadedEpisode, frame_idx: int,
570
+ gs_ref_L, gs_ref_R,
571
+ paused: bool, speed: int,
572
+ ep_idx: int, n_eps: int,
573
+ project_cams: Optional[list] = None,
574
+ gel_center_left: Optional[np.ndarray] = None,
575
+ gel_center_right: Optional[np.ndarray] = None,
576
+ tactile_latency: int = 0):
577
+ source = ep.source
578
+ h5_frame = ep.h5_frame_for(frame_idx)
579
+ gs_h5_frame = (h5_frame + tactile_latency) if h5_frame is not None else None
580
+ pt_tac_frame = frame_idx + tactile_latency
581
+ if pt_tac_frame < 0 or pt_tac_frame >= ep.n_frames:
582
+ pt_tac_frame = None
583
+ t_sec = float(ep.data["timestamps"][frame_idx] - ep.data["timestamps"][0])
584
+
585
+ # Row 1: 3 RealSense cams (left, middle, right) + OptiTrack
586
+ cam_thumbs = []
587
+ cam_labels = ["left cam", "middle cam", "right cam"]
588
+ pt_view_bgr = ep.pt_view(frame_idx) if source == "pt" else None
589
+ for slot, label in zip(DISPLAY_ORDER, cam_labels):
590
+ if source == "pt":
591
+ # Only cam0 lives in the .pt; fill its slot (DISPLAY_ORDER maps it
592
+ # to "right cam"), placeholder the others.
593
+ if slot == 0 and pt_view_bgr is not None:
594
+ cam_thumbs.append(_rs_thumb(pt_view_bgr, f"{label} (pt:view)"))
595
+ else:
596
+ cam_thumbs.append(_missing_cell(RS_THUMB_W, RS_THUMB_H,
597
+ f"{label}: pt has cam0 only"))
598
+ else:
599
+ img = ep.h5.cam(slot, h5_frame) if h5_frame is not None else None
600
+ if img is None:
601
+ cam_thumbs.append(_missing_cell(RS_THUMB_W, RS_THUMB_H, f"{label}: no H5"))
602
+ else:
603
+ cam_thumbs.append(_rs_thumb(img, label))
604
+ # OT poses always come from H5 if available, regardless of image source.
605
+ ot_poses = ep.h5.ot_at(h5_frame) if h5_frame is not None else {}
606
+ ot_panel = _make_ot_panel(ot_poses, frame_idx, t_sec, RS_THUMB_W, RS_THUMB_H)
607
+ row1 = np.hstack(cam_thumbs + [ot_panel])
608
+
609
+ # Row 2: GelSight raw + diff (L, R) + Controls. Gelsight reads use
610
+ # `frame + tactile_latency` so a measured capture lag is compensated.
611
+ if source == "pt":
612
+ gs_L = ep.pt_tactile("left", pt_tac_frame) if pt_tac_frame is not None else None
613
+ gs_R = ep.pt_tactile("right", pt_tac_frame) if pt_tac_frame is not None else None
614
+ miss_tag = "no pt"
615
+ else:
616
+ gs_L = ep.h5.gelsight("left", gs_h5_frame) if gs_h5_frame is not None else None
617
+ gs_R = ep.h5.gelsight("right", gs_h5_frame) if gs_h5_frame is not None else None
618
+ miss_tag = "no H5"
619
+ if gs_L is None:
620
+ gs_L_raw = _missing_cell(GS_THUMB_W, GS_THUMB_H, f"tac_L: {miss_tag}")
621
+ gs_L_dif = _missing_cell(GS_THUMB_W, GS_THUMB_H, f"tac_L diff: {miss_tag}")
622
+ else:
623
+ gs_L_raw = _gs_thumb(gs_L, "tactile_left")
624
+ ref_L = gs_ref_L if gs_ref_L is not None else gs_L
625
+ gs_L_dif = _gs_diff_thumb(gs_L, ref_L, "tac_L diff")
626
+ if gs_R is None:
627
+ gs_R_raw = _missing_cell(GS_THUMB_W, GS_THUMB_H, f"tac_R: {miss_tag}")
628
+ gs_R_dif = _missing_cell(GS_THUMB_W, GS_THUMB_H, f"tac_R diff: {miss_tag}")
629
+ else:
630
+ gs_R_raw = _gs_thumb(gs_R, "tactile_right")
631
+ ref_R = gs_ref_R if gs_ref_R is not None else gs_R
632
+ gs_R_dif = _gs_diff_thumb(gs_R, ref_R, "tac_R diff")
633
+ controls = _make_controls_panel(CONTROLS_W, CONTROLS_H, paused, speed, ep_idx, n_eps,
634
+ tactile_latency=tactile_latency)
635
+ row2 = np.hstack([gs_L_raw, gs_L_dif, gs_R_raw, gs_R_dif, controls])
636
+
637
+ panel = np.vstack([row1, row2])
638
+
639
+ # GelSight-center + axes projection on every cam thumb (matches visualize.py)
640
+ if (project_cams and gel_center_left is not None and gel_center_right is not None
641
+ and ot_poses and _viz_draw_projection_overlay is not None):
642
+ _viz_draw_projection_overlay(
643
+ panel, ot_poses, project_cams, gel_center_left, gel_center_right,
644
+ )
645
+
646
+ # Top status bar (visualize.py style: thicker cyan text)
647
+ cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
648
+ state = "PAUSED" if paused else "PLAYING"
649
+ seg = ep.segment_at(frame_idx)
650
+ h5r = seg["source_h5_range"]
651
+ seg_label = f"seg {seg['seg_idx']:02d}"
652
+ if h5r:
653
+ seg_label += f" H5[{h5r[0]}..{h5r[1]}]"
654
+ if h5_frame is not None:
655
+ seg_label += f" @{h5_frame}"
656
+ status = (f"[{state}] ep {ep_idx + 1}/{n_eps} {ep.key} | "
657
+ f"frame {frame_idx + 1}/{ep.n_frames} | t={t_sec:.2f}s | "
658
+ f"{seg_label} | {speed}x | tac_lat={tactile_latency:+d} | src={source}")
659
+ cv2.putText(panel, status, (10, 16),
660
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 255), 1, cv2.LINE_AA)
661
+
662
+ # Segment-cut flash: red border for the first 2 frames of a non-first segment
663
+ if ep.is_segment_start(frame_idx):
664
+ cv2.rectangle(panel, (0, 22), (PANEL_W - 1, PANEL_H - 1), (0, 0, 220), 3)
665
+
666
+ return panel
667
+
668
+
669
+ # ──────────────────────────────────────────────────────────────────────────────
670
+ # Main
671
+ # ──────────────────────────────────────────────────────────────────────────────
672
+
673
+ def main():
674
+ ap = argparse.ArgumentParser(description="Interactive React .pt player (visualize.py-style layout).")
675
+ ap.add_argument("path", help="A single .pt file OR a directory of episodes/segments.")
676
+ ap.add_argument("--save_video", default=None,
677
+ help="When `path` is a single .pt: write that one episode as MP4 here.")
678
+ ap.add_argument("--save_video_dir", default=None,
679
+ help="When `path` is a directory: write one MP4 per episode into this dir.")
680
+ ap.add_argument("--fps", type=float, default=30.0)
681
+ ap.add_argument("--h5_root", default=None,
682
+ help="Root directory of source H5 files (e.g. <twm>/data/<task>). "
683
+ "If omitted, inferred by replacing `processed/<mode>` with `data` in `path`.")
684
+ ap.add_argument("--source", choices=("pt", "h5"), default="pt",
685
+ help="Where to read image cells from. 'pt' = read view/tactile_* from "
686
+ "the .pt segment files (default, ~1000x faster, but the .pt only "
687
+ "carries cam0 + both gelsights at 128x128). 'h5' = read full-res "
688
+ "480x640 frames from the source H5 (original behavior).")
689
+ # ── GelSight-center projection overlay (mirrors visualize.py) ────────────
690
+ ap.add_argument("--cam_calib", type=str, nargs="+", default=None,
691
+ help="Path(s) to T_mocap_to_cam_<name>.json (one per "
692
+ "camera); default: the input's task epoch via calib_epoch.")
693
+ ap.add_argument("--gel_left", type=str, default=None,
694
+ help="Path to T_gel_to_rigid_left.json (default: task epoch).")
695
+ ap.add_argument("--gel_right", type=str, default=None,
696
+ help="Path to T_gel_to_rigid_right.json (default: task epoch).")
697
+ ap.add_argument("--no_projection", action="store_true",
698
+ help="Skip the GelSight-center projection overlay "
699
+ "(and calibration loading). Default: overlay ON.")
700
+ ap.add_argument("--tactile_latency", type=int, default=3,
701
+ help="Frames to advance gelsight reads (h5_frame + N) to "
702
+ "compensate for tactile capture lag. Default: 3.")
703
+ args = ap.parse_args()
704
+
705
+ if not args.no_projection and None in (args.gel_left, args.gel_right,
706
+ args.cam_calib):
707
+ from twm.calib_epoch import calib_dir_for_path
708
+ cdir = calib_dir_for_path(args.path) # raises rather than guessing
709
+ print(f"calibration epoch: {cdir.name} (from input path)")
710
+ if args.cam_calib is None:
711
+ args.cam_calib = [str(cdir / f"T_mocap_to_cam_{n}.json")
712
+ for n in ("middle", "left", "right")]
713
+ args.gel_left = args.gel_left or str(cdir / "T_gel_to_rigid_left.json")
714
+ args.gel_right = args.gel_right or str(cdir / "T_gel_to_rigid_right.json")
715
+
716
+ in_path = Path(args.path)
717
+
718
+ # Path-stem expansion: if the user typed an incomplete path like
719
+ # `.../2026-05-11/episode_005` (no .pt suffix, possibly no .segment_NN),
720
+ # treat it as an episode-stem filter. We load the parent date folder so
721
+ # N/P navigation still works, then start playback at the matching episode.
722
+ start_episode_key: Optional[str] = None
723
+ if not in_path.exists():
724
+ parent = in_path.parent
725
+ stem = in_path.name
726
+ if parent.is_dir() and stem:
727
+ matches = sorted(parent.glob(f"{stem}*.pt"))
728
+ # Require either an exact-name match or segment_NN siblings
729
+ matches = [p for p in matches
730
+ if PLAIN_EPISODE_RE.match(p.name) and p.stem == stem
731
+ or (SEGMENT_FNAME_RE.match(p.name)
732
+ and SEGMENT_FNAME_RE.match(p.name).group(1) == stem)]
733
+ if matches:
734
+ start_episode_key = f"{parent.name}/{stem}"
735
+ in_path = parent # discover the whole date folder
736
+ print(f"[player] interpreting '{args.path}' as episode-stem; "
737
+ f"will start at {start_episode_key}")
738
+ if not in_path.exists():
739
+ print(f"Not found: {args.path}", file=sys.stderr); sys.exit(1)
740
+
741
+ if in_path.is_file():
742
+ parent_root = in_path.parent.parent
743
+ episodes = discover_episodes(parent_root)
744
+ target_path = in_path.resolve()
745
+ start_idx = 0
746
+ for i, ep_meta in enumerate(episodes):
747
+ if any(p.resolve() == target_path for _, p in ep_meta["segs"]):
748
+ start_idx = i; break
749
+ else:
750
+ episodes = discover_episodes(in_path)
751
+ start_idx = 0
752
+ if start_episode_key is not None:
753
+ for i, ep_meta in enumerate(episodes):
754
+ if ep_meta["key"] == start_episode_key:
755
+ start_idx = i; break
756
+ else:
757
+ print(f"[player] WARN: stem '{start_episode_key}' not found in discovered "
758
+ f"episodes; starting at the first one")
759
+ print(f"[player] discovered {len(episodes)} episode(s) under {in_path}")
760
+
761
+ # Resolve H5 root
762
+ h5_root: Optional[Path] = None
763
+ if args.h5_root:
764
+ h5_root = Path(args.h5_root)
765
+ else:
766
+ h5_root = infer_h5_root(in_path)
767
+ if h5_root:
768
+ ok = "ok" if h5_root.exists() else "missing"
769
+ print(f"[player] H5 source root: {h5_root} ({ok})")
770
+ else:
771
+ print("[player] H5 source root not specified and could not be inferred -- "
772
+ "RealSense + GelSight cells will be blank")
773
+
774
+ # ── Load projection calibrations (mirrors visualize.py) ──────��───────────
775
+ project_cams: list = []
776
+ gel_center_left = None
777
+ gel_center_right = None
778
+ if args.no_projection or _viz_load_calibrations is None:
779
+ if args.no_projection:
780
+ print("[player] Projection overlay: OFF (--no_projection)")
781
+ else:
782
+ print("[player] Projection overlay: OFF (twm.viz unavailable)")
783
+ else:
784
+ try:
785
+ cam_calibs, gel_center_left, gel_center_right = \
786
+ _viz_load_calibrations(args.cam_calib, args.gel_left, args.gel_right)
787
+ for calib in cam_calibs:
788
+ serial = calib["camera_serial"]
789
+ try:
790
+ c_idx = REALSENSE_SERIALS.index(serial)
791
+ except ValueError:
792
+ print(f"[player] WARN: camera serial {serial} not in REALSENSE_SERIALS, skipping")
793
+ continue
794
+ project_cams.append({
795
+ "index": c_idx,
796
+ "T_mocap_to_cam": calib["T_mocap_to_cam"],
797
+ "intrinsics": calib["intrinsics"],
798
+ "serial": serial,
799
+ "rmse": calib["rmse_mm"],
800
+ })
801
+ if not project_cams:
802
+ print("[player] Projection overlay: OFF (no usable camera calibrations found -- "
803
+ "check --cam_calib paths)")
804
+ else:
805
+ print(f"[player] Projection overlay: ON ({len(project_cams)} camera(s))")
806
+ for pc in project_cams:
807
+ print(f" cam{pc['index']} serial={pc['serial']} RMSE={pc['rmse']:.2f} mm")
808
+ if gel_center_left is not None and gel_center_right is not None:
809
+ print(f" gel_L center (rigid): "
810
+ f"[{gel_center_left[0]:.2f}, {gel_center_left[1]:.2f}, {gel_center_left[2]:.2f}] mm")
811
+ print(f" gel_R center (rigid): "
812
+ f"[{gel_center_right[0]:.2f}, {gel_center_right[1]:.2f}, {gel_center_right[2]:.2f}] mm")
813
+ except Exception as e:
814
+ print(f"[player] WARN: calibration loading failed -- projection overlay disabled ({e})")
815
+ project_cams = []
816
+ gel_center_left = None
817
+ gel_center_right = None
818
+
819
+ headless_dir = Path(args.save_video_dir) if args.save_video_dir else None
820
+ headless_single = args.save_video
821
+ if headless_single and len(episodes) > 1 and in_path.is_dir():
822
+ print("--save_video accepts a single output path; for a directory pass --save_video_dir instead.",
823
+ file=sys.stderr)
824
+ sys.exit(1)
825
+ headless = headless_single is not None or headless_dir is not None
826
+
827
+ if headless:
828
+ if headless_dir:
829
+ headless_dir.mkdir(parents=True, exist_ok=True)
830
+ for ep_idx in range(start_idx, len(episodes)):
831
+ ep = LoadedEpisode(episodes[ep_idx], h5_root=h5_root,
832
+ tactile_latency=args.tactile_latency,
833
+ source=args.source)
834
+ try:
835
+ out_path = (Path(headless_single)
836
+ if headless_single else
837
+ (headless_dir / f"{ep.date}_{ep.ep_stem}.mp4"))
838
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
839
+ writer = cv2.VideoWriter(str(out_path), fourcc, args.fps, (PANEL_W, PANEL_H))
840
+ print(f" -> {out_path}")
841
+ for f in range(ep.n_frames):
842
+ panel = build_panel(ep, f, ep.gs_ref_L, ep.gs_ref_R,
843
+ paused=False, speed=1,
844
+ ep_idx=ep_idx, n_eps=len(episodes),
845
+ project_cams=project_cams,
846
+ gel_center_left=gel_center_left,
847
+ gel_center_right=gel_center_right,
848
+ tactile_latency=args.tactile_latency)
849
+ writer.write(panel)
850
+ writer.release()
851
+ finally:
852
+ ep.close()
853
+ if headless_single:
854
+ break
855
+ return
856
+
857
+ # Interactive
858
+ paused, speed = False, 1
859
+ SPEEDS = {ord('1'): 1, ord('2'): 2, ord('3'): 5,
860
+ ord('4'): 10, ord('5'): 25, ord('6'): 50}
861
+ tactile_latency = int(args.tactile_latency) # mutable; adjustable via [ / ]
862
+
863
+ ep_idx = start_idx
864
+ while 0 <= ep_idx < len(episodes):
865
+ ep = LoadedEpisode(episodes[ep_idx], h5_root=h5_root,
866
+ tactile_latency=tactile_latency,
867
+ source=args.source)
868
+ action = "stay"
869
+ try:
870
+ WIN = "React .pt player"
871
+ cv2.namedWindow(WIN, cv2.WINDOW_AUTOSIZE)
872
+ cv2.createTrackbar("Frame", WIN, 0, max(1, ep.n_frames - 1), lambda v: None)
873
+ gs_ref_L, gs_ref_R = ep.gs_ref_L, ep.gs_ref_R
874
+ frame_idx = 0
875
+ last_drawn = -1
876
+
877
+ while True:
878
+ frame_idx = max(0, min(frame_idx, ep.n_frames - 1))
879
+ pos = cv2.getTrackbarPos("Frame", WIN)
880
+ if pos != frame_idx and pos != last_drawn:
881
+ frame_idx = pos; paused = True
882
+
883
+ panel = build_panel(ep, frame_idx,
884
+ gs_ref_L, gs_ref_R,
885
+ paused=paused, speed=speed,
886
+ ep_idx=ep_idx, n_eps=len(episodes),
887
+ project_cams=project_cams,
888
+ gel_center_left=gel_center_left,
889
+ gel_center_right=gel_center_right,
890
+ tactile_latency=tactile_latency)
891
+ cv2.imshow(WIN, panel)
892
+ if cv2.getTrackbarPos("Frame", WIN) != frame_idx:
893
+ cv2.setTrackbarPos("Frame", WIN, frame_idx)
894
+ last_drawn = frame_idx
895
+
896
+ key = cv2.waitKey(1) & 0xFF
897
+ if key == ord('q'): action = "quit"; break
898
+ elif key == ord(' '): paused = not paused
899
+ elif key in (81, ord('a')): paused = True; frame_idx -= 1
900
+ elif key in (83, ord('d')): paused = True; frame_idx += 1
901
+ elif key in SPEEDS: speed = SPEEDS[key]
902
+ elif key == ord('r'):
903
+ if ep.source == "pt":
904
+ shifted = max(0, min(ep.n_frames - 1, frame_idx + tactile_latency))
905
+ new_L = ep.pt_tactile("left", shifted)
906
+ new_R = ep.pt_tactile("right", shifted)
907
+ if new_L is not None: gs_ref_L = new_L
908
+ if new_R is not None: gs_ref_R = new_R
909
+ print(f" gel-diff ref reset to concat frame {frame_idx} "
910
+ f"(pt idx {shifted}, latency {tactile_latency:+d})")
911
+ else:
912
+ h5_frame = ep.h5_frame_for(frame_idx)
913
+ if h5_frame is not None and ep.h5.ok:
914
+ shifted = h5_frame + tactile_latency
915
+ gs_ref_L = ep.h5.gelsight("left", shifted)
916
+ gs_ref_R = ep.h5.gelsight("right", shifted)
917
+ print(f" gel-diff ref reset to concat frame {frame_idx} "
918
+ f"(H5 frame {h5_frame}, gs idx {shifted})")
919
+ elif key == ord('['):
920
+ tactile_latency -= 1
921
+ print(f" tactile_latency = {tactile_latency:+d}")
922
+ elif key == ord(']'):
923
+ tactile_latency += 1
924
+ print(f" tactile_latency = {tactile_latency:+d}")
925
+ elif key == ord('n'): action = "next"; break
926
+ elif key == ord('p'): action = "prev"; break
927
+
928
+ if not paused:
929
+ frame_idx += speed
930
+ if frame_idx >= ep.n_frames:
931
+ print(f"End of episode {ep.key}.")
932
+ paused = True
933
+ frame_idx = ep.n_frames - 1
934
+ time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))
935
+
936
+ cv2.destroyAllWindows()
937
+ finally:
938
+ ep.close()
939
+ if action == "quit": return
940
+ if action == "next":
941
+ new_idx = min(ep_idx + 1, len(episodes) - 1)
942
+ if new_idx == ep_idx:
943
+ print("Already at last episode.")
944
+ ep_idx = new_idx
945
+ elif action == "prev":
946
+ new_idx = max(ep_idx - 1, 0)
947
+ if new_idx == ep_idx:
948
+ print("Already at first episode.")
949
+ ep_idx = new_idx
950
+ else:
951
+ paused = True
952
+
953
+
954
+ if __name__ == "__main__":
955
+ main()