yxma commited on
Commit
5711283
·
verified ·
1 Parent(s): 93065ec

examples/play_react_pt.py: interactive .pt viewer (same key bindings as twm.visualize, adapted to the downsampled .pt content). Supports both mode1_v1 episodes and mode2_v1 segments. Self-contained (numpy + torch + cv2). Headless MP4 export via --save_video.

Browse files
Files changed (2) hide show
  1. examples/README.md +21 -0
  2. examples/play_react_pt.py +351 -0
examples/README.md CHANGED
@@ -117,3 +117,24 @@ pre-trim timeline.
117
  trim_offset = ep["_contact_meta"]["trim_offset"]
118
  h5_index = pt_index + trim_offset # only needed when reading raw H5
119
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  trim_offset = ep["_contact_meta"]["trim_offset"]
118
  h5_index = pt_index + trim_offset # only needed when reading raw H5
119
  ```
120
+
121
+
122
+ ## Visualizing a single .pt file
123
+
124
+ If you want to scrub through one recording or segment frame-by-frame (the
125
+ same way `python -m twm.visualize` plays the original H5 archive), use:
126
+
127
+ ```bash
128
+ # Interactive cv2 window (space / arrows / 1..6 / r / q)
129
+ python examples/play_react_pt.py processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
130
+
131
+ # Headless MP4 export (no display required)
132
+ python examples/play_react_pt.py <pt_path> --save_video out.mp4
133
+ ```
134
+
135
+ The viewer shows: cam0 view | tactile_L raw + diff | tactile_R raw + diff
136
+ on the top row, and OptiTrack pose text + a sliding contact-intensity
137
+ trail plot + the controls cheatsheet on the bottom row. The GelSight diff
138
+ is computed against the `_contact_meta.ref_p01_*` baseline (the
139
+ quietest moment of the recording), so it reads as 'what is currently
140
+ pressing on the gel' rather than 'change since the start of the clip.'
examples/play_react_pt.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive playback for a React `.pt` file — same key bindings as
2
+ `twm.visualize`, but operates on the downsampled, single-camera, cam-aligned
3
+ content that's actually inside the `.pt`. Works for both `mode1_v1/` whole
4
+ recordings and `mode2_v1/` clean segments.
5
+
6
+ Usage
7
+ -----
8
+ Interactive (cv2 window):
9
+ python examples/play_react_pt.py \\
10
+ processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
11
+
12
+ Headless export to MP4:
13
+ python examples/play_react_pt.py <pt_path> --save_video out.mp4
14
+
15
+ Controls
16
+ --------
17
+ space — pause / resume
18
+ → / d — next frame (works while paused)
19
+ ← / a — previous frame
20
+ 1 / 2 / 3 / 4 / 5 / 6 — playback speed 1× / 2× / 5× / 10× / 25× / 50×
21
+ r — reset GelSight diff reference to current frame
22
+ q — quit
23
+
24
+ Panel layout (1280 × 480)
25
+ -------------------------
26
+ Row 1 (240 tall): view | tactile_L_raw | tactile_L_diff | tactile_R_raw | tactile_R_diff
27
+ Row 2 (240 tall): OT pose panel | contact-intensity trail plot | controls cheatsheet
28
+ Status bar at top: episode / segment, frame index, wall-clock t, playback speed
29
+
30
+ The diff is computed against the per-episode `ref_p01_{left,right}` image
31
+ stored in `_contact_meta` (the "quietest moment of the recording" — the
32
+ same baseline `twm.contact_index` uses), so it reads as "what is *currently*
33
+ pressing on the gel" rather than "what changed since this clip started."
34
+ """
35
+ import argparse
36
+ import collections
37
+ import sys
38
+ import time
39
+ from pathlib import Path
40
+
41
+ import cv2
42
+ import numpy as np
43
+ import torch
44
+
45
+ # ─── color conventions ──────────────────────────────────────────────────────
46
+ # OT pose-text colors (BGR for cv2 calls)
47
+ TRACKER_COLORS = {
48
+ "sensor_left": ( 0, 255, 120),
49
+ "sensor_right": ( 0, 180, 255),
50
+ }
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
+
60
+ def _to_hwc(t):
61
+ return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()
62
+
63
+
64
+ def _view_to_bgr(view_chw):
65
+ """`view` is BGR (rs.format.bgr8 → contact_index keeps byte order).
66
+ cv2.imshow expects BGR, so just permute to HWC."""
67
+ return view_chw.permute(1, 2, 0).numpy()
68
+
69
+
70
+ def _tactile_to_bgr(tac_chw):
71
+ """`tactile_*` is RGB. Convert to BGR for cv2.imshow."""
72
+ rgb = tac_chw.permute(1, 2, 0).numpy()
73
+ return rgb[..., ::-1]
74
+
75
+
76
+ def _diff_thumb(frame_bgr, ref_bgr, size):
77
+ diff = np.clip(frame_bgr.astype(np.int16) - ref_bgr.astype(np.int16) + 128, 0, 255).astype(np.uint8)
78
+ return cv2.resize(diff, size, interpolation=cv2.INTER_NEAREST)
79
+
80
+
81
+ def _make_ot_panel(pose_L, pose_R, t_idx, t_sec, w, h):
82
+ panel = np.zeros((h, w, 3), np.uint8)
83
+ cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
84
+ cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
85
+ cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
86
+ y = 56
87
+ for name, p, color in [("sensor_left", pose_L, TRACKER_COLORS["sensor_left"]),
88
+ ("sensor_right", pose_R, TRACKER_COLORS["sensor_right"])]:
89
+ cv2.putText(panel, name, (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1, cv2.LINE_AA)
90
+ y += 18
91
+ if p is None or all(v == 0 for v in p):
92
+ cv2.putText(panel, " no data", (8, y),
93
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, (100, 100, 100), 1, cv2.LINE_AA)
94
+ y += 36
95
+ continue
96
+ x, yv, z, qx, qy, qz, qw = p
97
+ cv2.putText(panel, f" x={x:+.3f} y={yv:+.3f} z={z:+.3f}", (8, y),
98
+ cv2.FONT_HERSHEY_SIMPLEX, 0.38, (220, 220, 220), 1, cv2.LINE_AA)
99
+ y += 16
100
+ cv2.putText(panel, f" qx={qx:+.2f} qy={qy:+.2f}", (8, y),
101
+ cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
102
+ y += 16
103
+ cv2.putText(panel, f" qz={qz:+.2f} qw={qw:+.2f}", (8, y),
104
+ cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
105
+ y += 24
106
+ cv2.putText(panel, f"t = {t_sec:.2f} s (frame {t_idx})",
107
+ (8, h - 14), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1, cv2.LINE_AA)
108
+ return panel
109
+
110
+
111
+ def _make_trail_panel(iL_trail, iR_trail, w, h, threshold=0.4):
112
+ """Plot the last ~N frames of tactile_*_mixed as a paired waveform."""
113
+ panel = np.zeros((h, w, 3), np.uint8)
114
+ cv2.putText(panel, "Contact intensity (tactile_*_mixed) — orange=L blue=R",
115
+ (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), 1, cv2.LINE_AA)
116
+ cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
117
+
118
+ # Bipolar plot: L above mid, R below mid
119
+ mid_y = h - 26
120
+ max_y = 50
121
+ plot_top = mid_y - max_y
122
+ plot_bot = mid_y + max_y
123
+ cv2.line(panel, (8, mid_y), (w - 8, mid_y), (80, 80, 80), 1)
124
+
125
+ if not iL_trail:
126
+ return panel
127
+ N = len(iL_trail)
128
+ # Auto-scale by combined max so both stay visible
129
+ smax = max(max(iL_trail), max(iR_trail), float(threshold) * 1.5, 1e-3)
130
+ x_scale = (w - 16) / max(N - 1, 1)
131
+ for i in range(N - 1):
132
+ x0 = int(8 + i * x_scale)
133
+ x1 = int(8 + (i + 1) * x_scale)
134
+ # left = orange #E69F00 in BGR
135
+ y0L = mid_y - int(min(iL_trail[i], smax) / smax * max_y)
136
+ y1L = mid_y - int(min(iL_trail[i + 1], smax) / smax * max_y)
137
+ cv2.line(panel, (x0, y0L), (x1, y1L), (0, 159, 230), 1, cv2.LINE_AA)
138
+ # right = blue #0072B2 in BGR
139
+ y0R = mid_y + int(min(iR_trail[i], smax) / smax * max_y)
140
+ y1R = mid_y + int(min(iR_trail[i + 1], smax) / smax * max_y)
141
+ cv2.line(panel, (x0, y0R), (x1, y1R), (178, 114, 0), 1, cv2.LINE_AA)
142
+ # Threshold lines
143
+ yT_up = mid_y - int(min(threshold, smax) / smax * max_y)
144
+ yT_dn = mid_y + int(min(threshold, smax) / smax * max_y)
145
+ cv2.line(panel, (8, yT_up), (w - 8, yT_up), (60, 60, 60), 1, cv2.LINE_AA)
146
+ cv2.line(panel, (8, yT_dn), (w - 8, yT_dn), (60, 60, 60), 1, cv2.LINE_AA)
147
+ # Current values readout
148
+ cv2.putText(panel, f"L = {iL_trail[-1]:.2f}", (10, plot_top + 10),
149
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 159, 230), 1, cv2.LINE_AA)
150
+ cv2.putText(panel, f"R = {iR_trail[-1]:.2f}", (10, plot_bot + 18),
151
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (178, 114, 0), 1, cv2.LINE_AA)
152
+ cv2.putText(panel, f"window: last {N} frames (threshold = {threshold:.2f})",
153
+ (w - 280, h - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (140, 140, 140), 1, cv2.LINE_AA)
154
+ return panel
155
+
156
+
157
+ def _make_controls_panel(w, h, paused, speed):
158
+ panel = np.zeros((h, w, 3), np.uint8)
159
+ cv2.putText(panel, "Controls", (10, 22),
160
+ cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
161
+ cv2.line(panel, (10, 30), (w - 10, 30), (60, 60, 60), 1)
162
+ keys = [
163
+ ("SPACE", "pause / resume"),
164
+ ("← / a", "previous frame"),
165
+ ("→ / d", "next frame"),
166
+ ("1..6", "speed 1x/2x/5x/10x/25x/50x"),
167
+ ("r", "reset gel-diff ref"),
168
+ ("q", "quit"),
169
+ ]
170
+ y = 52
171
+ for k, v in keys:
172
+ cv2.putText(panel, f"[{k}]", (10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (140, 200, 140), 1, cv2.LINE_AA)
173
+ cv2.putText(panel, v, (110, y), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (200, 200, 200), 1, cv2.LINE_AA)
174
+ y += 22
175
+ # State indicator
176
+ state = "|| PAUSED" if paused else "> PLAYING"
177
+ state_col = (0, 140, 255) if paused else (0, 220, 80)
178
+ cv2.putText(panel, state, (10, h - 26),
179
+ cv2.FONT_HERSHEY_SIMPLEX, 0.55, state_col, 2, cv2.LINE_AA)
180
+ cv2.putText(panel, f"speed: {speed}x", (10, h - 8),
181
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
182
+ return panel
183
+
184
+
185
+ def _episode_label(meta: dict, fallback: str) -> str:
186
+ """Pretty label for header. mode2_v1 segments expose source_episode; older mode1_v1 doesn't."""
187
+ src = meta.get("source_episode")
188
+ seg = meta.get("source_segment_idx")
189
+ if src and seg is not None:
190
+ return f"{src} / seg{int(seg):02d}"
191
+ return fallback
192
+
193
+
194
+ def build_panel(ep, frame_idx, ref_L_bgr, ref_R_bgr, iL_trail, iR_trail,
195
+ ep_label, paused, speed, n_frames):
196
+ view_bgr = _view_to_bgr(ep["view"][frame_idx])
197
+ tac_L_bgr = _tactile_to_bgr(ep["tactile_left"][frame_idx])
198
+ tac_R_bgr = _tactile_to_bgr(ep["tactile_right"][frame_idx])
199
+
200
+ view_thumb = cv2.resize(view_bgr, VIEW_THUMB, interpolation=cv2.INTER_NEAREST)
201
+ tac_L_thumb = cv2.resize(tac_L_bgr, TAC_THUMB, interpolation=cv2.INTER_NEAREST)
202
+ tac_R_thumb = cv2.resize(tac_R_bgr, TAC_THUMB, interpolation=cv2.INTER_NEAREST)
203
+ tac_L_diff = _diff_thumb(tac_L_bgr, ref_L_bgr, TAC_THUMB)
204
+ tac_R_diff = _diff_thumb(tac_R_bgr, ref_R_bgr, TAC_THUMB)
205
+
206
+ # Tile-label headers
207
+ for img, label in [(view_thumb, "cam0 / view"),
208
+ (tac_L_thumb, "tactile_left"),
209
+ (tac_L_diff, "tac_L diff (vs p01)"),
210
+ (tac_R_thumb, "tactile_right"),
211
+ (tac_R_diff, "tac_R diff (vs p01)")]:
212
+ cv2.putText(img, label, (6, 14),
213
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, (220, 220, 220), 1, cv2.LINE_AA)
214
+
215
+ row1 = np.hstack([view_thumb, tac_L_thumb, tac_L_diff, tac_R_thumb, tac_R_diff])
216
+
217
+ pose_L = ep["sensor_left_pose"][frame_idx].tolist()
218
+ pose_R = ep["sensor_right_pose"][frame_idx].tolist()
219
+ t_sec = float(ep["timestamps"][frame_idx] - ep["timestamps"][0])
220
+ ot_panel = _make_ot_panel(pose_L, pose_R, frame_idx, t_sec, *OT_PANEL)
221
+ trail_panel = _make_trail_panel(list(iL_trail), list(iR_trail), *TRAIL_PANEL)
222
+ controls_panel = _make_controls_panel(*CONTROLS_PANEL, paused=paused, speed=speed)
223
+
224
+ row2 = np.hstack([ot_panel, trail_panel, controls_panel])
225
+ panel = np.vstack([row1, row2])
226
+
227
+ # Top status bar (orange, on a dark band so it's legible over the cams)
228
+ cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
229
+ state = "PAUSED" if paused else "PLAYING"
230
+ status = (f"[{state}] {ep_label} · frame {frame_idx + 1}/{n_frames} "
231
+ f"· t = {t_sec:.2f}s · {speed}x")
232
+ cv2.putText(panel, status, (10, 16),
233
+ cv2.FONT_HERSHEY_SIMPLEX, 0.48, (0, 200, 255), 1, cv2.LINE_AA)
234
+ return panel
235
+
236
+
237
+ def main():
238
+ ap = argparse.ArgumentParser(description="Interactive playback of a React .pt file.")
239
+ ap.add_argument("pt_path", help="path to a .pt under processed/mode{1,2}_v1/.../")
240
+ ap.add_argument("--save_video", default=None,
241
+ help="Path to write an MP4 instead of opening a window (headless mode).")
242
+ ap.add_argument("--fps", type=float, default=30.0, help="Playback / output fps.")
243
+ ap.add_argument("--trail_frames", type=int, default=120,
244
+ help="How many recent frames to plot in the contact-intensity trail (default 120 = 4s).")
245
+ args = ap.parse_args()
246
+
247
+ pt_path = Path(args.pt_path)
248
+ if not pt_path.is_file():
249
+ print(f"Not a file: {pt_path}", file=sys.stderr); sys.exit(1)
250
+
251
+ print(f"Loading {pt_path}...")
252
+ ep = torch.load(pt_path, weights_only=False, map_location="cpu")
253
+ n_frames = ep["view"].shape[0]
254
+ meta = ep.get("_contact_meta", {})
255
+ ep_label = _episode_label(meta, fallback=pt_path.stem)
256
+ print(f" {ep_label}: {n_frames} frames ({n_frames / args.fps:.1f}s @ {args.fps:.0f} fps)")
257
+
258
+ # Initial GelSight diff reference — use the per-episode p01 frame stored
259
+ # in _contact_meta (cleanest "no contact" baseline). Fall back to frame 0
260
+ # if the .pt was produced before that field existed.
261
+ def _ref_from_meta_or_first(side):
262
+ key = f"ref_p01_{side}"
263
+ if key in meta and meta[key] is not None:
264
+ ref = meta[key]
265
+ if hasattr(ref, "permute"):
266
+ return _tactile_to_bgr(ref)
267
+ return _tactile_to_bgr(ep[f"tactile_{side}"][0])
268
+ ref_L = _ref_from_meta_or_first("left")
269
+ ref_R = _ref_from_meta_or_first("right")
270
+
271
+ iL = ep["tactile_left_mixed"].numpy()
272
+ iR = ep["tactile_right_mixed"].numpy()
273
+
274
+ paused, speed, frame_idx = False, 1, 0
275
+ SPEEDS = {ord('1'): 1, ord('2'): 2, ord('3'): 5,
276
+ ord('4'): 10, ord('5'): 25, ord('6'): 50}
277
+
278
+ headless = args.save_video is not None
279
+ if headless:
280
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
281
+ writer = cv2.VideoWriter(args.save_video, fourcc, args.fps, (PANEL_W, PANEL_H))
282
+ if not writer.isOpened():
283
+ print(f"Could not open {args.save_video} for writing.", file=sys.stderr); sys.exit(1)
284
+ print(f"Headless: writing {args.save_video} ({n_frames} frames at {args.fps} fps)")
285
+ else:
286
+ cv2.namedWindow(ep_label, cv2.WINDOW_AUTOSIZE)
287
+ cv2.createTrackbar("Frame", ep_label, 0, max(1, n_frames - 1), lambda v: None)
288
+ print("Controls: space / ←→ / 1..6 / r / q")
289
+
290
+ iL_trail = collections.deque(maxlen=args.trail_frames)
291
+ iR_trail = collections.deque(maxlen=args.trail_frames)
292
+ last_drawn = -1
293
+
294
+ try:
295
+ while True:
296
+ frame_idx = max(0, min(frame_idx, n_frames - 1))
297
+ if not headless:
298
+ pos = cv2.getTrackbarPos("Frame", ep_label)
299
+ if pos != frame_idx and pos != last_drawn:
300
+ frame_idx = pos
301
+ paused = True
302
+
303
+ iL_trail.append(float(iL[frame_idx]))
304
+ iR_trail.append(float(iR[frame_idx]))
305
+
306
+ panel = build_panel(ep, frame_idx, ref_L, ref_R,
307
+ iL_trail, iR_trail, ep_label, paused, speed, n_frames)
308
+
309
+ if headless:
310
+ writer.write(panel)
311
+ if frame_idx % 30 == 0:
312
+ print(f" wrote frame {frame_idx + 1}/{n_frames}")
313
+ if frame_idx >= n_frames - 1:
314
+ break
315
+ frame_idx += 1
316
+ continue
317
+
318
+ cv2.imshow(ep_label, panel)
319
+ if cv2.getTrackbarPos("Frame", ep_label) != frame_idx:
320
+ cv2.setTrackbarPos("Frame", ep_label, frame_idx)
321
+ last_drawn = frame_idx
322
+
323
+ key = cv2.waitKey(1) & 0xFF
324
+ if key == ord('q'): break
325
+ elif key == ord(' '): paused = not paused
326
+ elif key in (81, ord('a')): paused = True; frame_idx -= 1
327
+ elif key in (83, ord('d')): paused = True; frame_idx += 1
328
+ elif key in SPEEDS: speed = SPEEDS[key]
329
+ elif key == ord('r'):
330
+ ref_L = _tactile_to_bgr(ep["tactile_left"][frame_idx])
331
+ ref_R = _tactile_to_bgr(ep["tactile_right"][frame_idx])
332
+ print(f" diff ref reset to frame {frame_idx}")
333
+
334
+ if not paused:
335
+ frame_idx += speed
336
+ if frame_idx >= n_frames:
337
+ frame_idx = n_frames - 1
338
+ paused = True
339
+ print("End of file.")
340
+ time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))
341
+
342
+ finally:
343
+ if headless:
344
+ writer.release()
345
+ print(f"Wrote {args.save_video}")
346
+ else:
347
+ cv2.destroyAllWindows()
348
+
349
+
350
+ if __name__ == "__main__":
351
+ main()