examples/play_react_pt.py: episode-aware viewer. Accepts a directory of segments — all same-episode segments concatenate into one playback timeline; N/P switches between episodes. Red border + red trail-plot mark on segment-boundary frames. Also supports --save_video_dir for per-episode batch MP4 export.
Browse files- examples/README.md +32 -15
- examples/play_react_pt.py +325 -191
examples/README.md
CHANGED
|
@@ -117,24 +117,41 @@ 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 |
```
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 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 |
-
#
|
| 129 |
-
python examples/play_react_pt.py
|
|
|
|
| 130 |
|
| 131 |
-
#
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
```
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
trim_offset = ep["_contact_meta"]["trim_offset"]
|
| 118 |
h5_index = pt_index + trim_offset # only needed when reading raw H5
|
| 119 |
```
|
| 120 |
+
## Visualizing a single .pt or a whole task
|
| 121 |
|
| 122 |
+
Use `examples/play_react_pt.py` to scrub through React data interactively
|
| 123 |
+
(same key bindings as `python -m twm.visualize` for H5 archives).
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
```bash
|
| 126 |
+
# Single .pt (mode1_v1 episode or one mode2_v1 segment)
|
| 127 |
+
python examples/play_react_pt.py \
|
| 128 |
+
processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
|
| 129 |
|
| 130 |
+
# Whole task: all 27 episodes are discovered; same-source segments are
|
| 131 |
+
# concatenated into one playback timeline. N / P jumps between episodes.
|
| 132 |
+
python examples/play_react_pt.py processed/mode2_v1/motherboard
|
| 133 |
+
|
| 134 |
+
# Headless: write one MP4 per episode into a directory
|
| 135 |
+
python examples/play_react_pt.py processed/mode2_v1/motherboard \
|
| 136 |
+
--save_video_dir /tmp/react_mp4s
|
| 137 |
```
|
| 138 |
|
| 139 |
+
Controls:
|
| 140 |
+
|
| 141 |
+
| Key | Action |
|
| 142 |
+
|---|---|
|
| 143 |
+
| `space` | pause / resume |
|
| 144 |
+
| `left / a`, `right / d` | prev / next frame |
|
| 145 |
+
| `1..6` | speed 1x / 2x / 5x / 10x / 25x / 50x |
|
| 146 |
+
| `r` | reset GelSight diff reference to current frame |
|
| 147 |
+
| **`n` / `p`** | **next / previous episode** |
|
| 148 |
+
| `q` | quit |
|
| 149 |
+
|
| 150 |
+
Panel layout (1280 x 480):
|
| 151 |
+
|
| 152 |
+
- **Row 1**: cam0 view, tactile_L raw, tactile_L diff, tactile_R raw, tactile_R diff
|
| 153 |
+
- **Row 2**: OT pose text (live x/y/z + quaternion), contact-intensity trail plot, controls cheatsheet
|
| 154 |
+
- **Status bar at top**: episode index, frame index in the concatenated timeline, segment number, source-H5 frame range
|
| 155 |
+
- **Red border for 1 frame** when crossing a segment boundary (visible cue that a bad interval was cut here). Vertical red marks in the trail plot show recent boundaries.
|
| 156 |
+
|
| 157 |
+
The GelSight diff is computed against `_contact_meta.ref_p01_*` (the quietest frame of the episode), so it reads as the absolute contact on the gel rather than change since the start of the clip.
|
examples/play_react_pt.py
CHANGED
|
@@ -1,39 +1,41 @@
|
|
| 1 |
-
"""Interactive playback for a
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
|
| 6 |
Usage
|
| 7 |
-----
|
| 8 |
-
|
| 9 |
python examples/play_react_pt.py \\
|
| 10 |
processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
|
| 11 |
|
| 12 |
-
|
| 13 |
-
python examples/play_react_pt.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
Controls
|
| 16 |
--------
|
| 17 |
-
space
|
| 18 |
-
→ / d
|
| 19 |
-
← / a
|
| 20 |
-
1
|
| 21 |
-
r
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 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
|
|
@@ -42,13 +44,11 @@ import cv2
|
|
| 42 |
import numpy as np
|
| 43 |
import torch
|
| 44 |
|
| 45 |
-
# ───
|
| 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)
|
|
@@ -56,28 +56,135 @@ 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),
|
|
@@ -89,121 +196,97 @@ def _make_ot_panel(pose_L, pose_R, t_idx, t_sec, w, h):
|
|
| 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 |
-
|
| 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 (
|
| 115 |
-
(8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.
|
| 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 |
-
#
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 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,
|
| 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",
|
| 164 |
-
("←
|
| 165 |
-
("
|
| 166 |
-
("
|
| 167 |
-
("r",
|
| 168 |
-
("q",
|
| 169 |
]
|
| 170 |
y = 52
|
| 171 |
for k, v in keys:
|
| 172 |
-
cv2.putText(panel, f"[{k}]", (10, y),
|
| 173 |
-
|
|
|
|
|
|
|
| 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 -
|
| 179 |
cv2.FONT_HERSHEY_SIMPLEX, 0.55, state_col, 2, cv2.LINE_AA)
|
| 180 |
-
cv2.putText(panel, f"speed: {speed}x", (10, h -
|
|
|
|
|
|
|
| 181 |
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
|
| 182 |
return panel
|
| 183 |
|
| 184 |
|
| 185 |
-
def
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 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)"),
|
|
@@ -211,140 +294,191 @@ def build_panel(ep, frame_idx, ref_L_bgr, ref_R_bgr, iL_trail, iR_trail,
|
|
| 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),
|
| 222 |
-
|
| 223 |
-
|
|
|
|
| 224 |
row2 = np.hstack([ot_panel, trail_panel, controls_panel])
|
| 225 |
panel = np.vstack([row1, row2])
|
| 226 |
|
| 227 |
-
# Top status bar
|
| 228 |
cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
|
| 229 |
state = "PAUSED" if paused else "PLAYING"
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
cv2.putText(panel, status, (10, 16),
|
| 233 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
return panel
|
| 235 |
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def main():
|
| 238 |
-
ap = argparse.ArgumentParser(description="Interactive
|
| 239 |
-
ap.add_argument("
|
| 240 |
ap.add_argument("--save_video", default=None,
|
| 241 |
-
help="
|
| 242 |
-
ap.add_argument("--
|
| 243 |
-
|
| 244 |
-
|
|
|
|
| 245 |
args = ap.parse_args()
|
| 246 |
|
| 247 |
-
|
| 248 |
-
if not
|
| 249 |
-
print(f"Not
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 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 |
-
|
| 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 |
panel = build_panel(ep, frame_idx, ref_L, ref_R,
|
| 307 |
-
iL_trail, iR_trail,
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 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 |
-
|
| 338 |
paused = True
|
| 339 |
-
|
| 340 |
time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))
|
| 341 |
|
| 342 |
-
|
| 343 |
-
if
|
| 344 |
-
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
else:
|
| 347 |
-
|
|
|
|
| 348 |
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
|
|
|
| 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 |
Usage
|
| 7 |
-----
|
| 8 |
+
Single file (mode1_v1 episode OR a single mode2_v1 segment):
|
| 9 |
python examples/play_react_pt.py \\
|
| 10 |
processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt
|
| 11 |
|
| 12 |
+
Whole task — episode-by-episode browser:
|
| 13 |
+
python examples/play_react_pt.py \\
|
| 14 |
+
processed/mode2_v1/motherboard
|
| 15 |
+
|
| 16 |
+
All segments of `episode_NNN` are concatenated into one playback
|
| 17 |
+
timeline; N / P jumps to the next / previous source episode.
|
| 18 |
+
|
| 19 |
+
Works with mode1_v1 too (each `.pt` is treated as a one-segment
|
| 20 |
+
episode); N / P then jumps file-to-file.
|
| 21 |
+
|
| 22 |
+
Headless export (one MP4 per episode):
|
| 23 |
+
python examples/play_react_pt.py <root> --save_video_dir /tmp/out
|
| 24 |
|
| 25 |
Controls
|
| 26 |
--------
|
| 27 |
+
space — pause / resume
|
| 28 |
+
→ / d — next frame
|
| 29 |
+
← / a — previous frame
|
| 30 |
+
1..6 — playback speed 1× / 2× / 5× / 10× / 25× / 50×
|
| 31 |
+
r — reset GelSight diff reference to current frame
|
| 32 |
+
n — next episode
|
| 33 |
+
p — previous episode
|
| 34 |
+
q — quit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
"""
|
| 36 |
import argparse
|
| 37 |
import collections
|
| 38 |
+
import re
|
| 39 |
import sys
|
| 40 |
import time
|
| 41 |
from pathlib import Path
|
|
|
|
| 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)
|
|
|
|
| 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 |
def _to_hwc(t):
|
| 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 |
def _diff_thumb(frame_bgr, ref_bgr, size):
|
| 74 |
diff = np.clip(frame_bgr.astype(np.int16) - ref_bgr.astype(np.int16) + 128, 0, 255).astype(np.uint8)
|
| 75 |
return cv2.resize(diff, size, interpolation=cv2.INTER_NEAREST)
|
| 76 |
|
| 77 |
|
| 78 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 79 |
+
# Episode discovery
|
| 80 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 81 |
+
|
| 82 |
+
def discover_episodes(root: Path) -> list[dict]:
|
| 83 |
+
"""Walk `root`, group .pt files by source episode key '<date>/episode_NNN',
|
| 84 |
+
and return one entry per episode with its segment paths sorted.
|
| 85 |
+
|
| 86 |
+
Handles both:
|
| 87 |
+
- mode2_v1: `<root>/<date>/episode_NNN.segment_MM.pt`
|
| 88 |
+
- mode1_v1: `<root>/<date>/episode_NNN.pt`
|
| 89 |
+
"""
|
| 90 |
+
pts = sorted(root.rglob("*.pt"))
|
| 91 |
+
if not pts:
|
| 92 |
+
raise SystemExit(f"No .pt files under {root}")
|
| 93 |
+
|
| 94 |
+
episodes: dict[str, dict] = {} # key: "<date>/<ep>" → {date, ep_stem, segs: [(seg_idx, path)]}
|
| 95 |
+
for p in pts:
|
| 96 |
+
m_seg = SEGMENT_FNAME_RE.match(p.name)
|
| 97 |
+
m_plain = PLAIN_EPISODE_RE.match(p.name)
|
| 98 |
+
if m_seg:
|
| 99 |
+
ep_stem, seg_idx = m_seg.group(1), int(m_seg.group(2))
|
| 100 |
+
elif m_plain:
|
| 101 |
+
ep_stem, seg_idx = m_plain.group(1), 0
|
| 102 |
+
else:
|
| 103 |
+
continue
|
| 104 |
+
date = p.parent.name
|
| 105 |
+
key = f"{date}/{ep_stem}"
|
| 106 |
+
episodes.setdefault(key, {"date": date, "ep_stem": ep_stem, "segs": []})
|
| 107 |
+
episodes[key]["segs"].append((seg_idx, p))
|
| 108 |
+
|
| 109 |
+
out = []
|
| 110 |
+
for key in sorted(episodes):
|
| 111 |
+
ep = episodes[key]
|
| 112 |
+
ep["segs"].sort(key=lambda x: x[0])
|
| 113 |
+
out.append({"key": key, **ep})
|
| 114 |
+
return out
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 118 |
+
# Episode-load
|
| 119 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 120 |
+
|
| 121 |
+
class LoadedEpisode:
|
| 122 |
+
"""One source episode, with all its segments concatenated for playback.
|
| 123 |
+
|
| 124 |
+
Stores:
|
| 125 |
+
- keys for the 5 image-shaped tensors (view, tactile_*) concatenated
|
| 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 |
+
"view", "tactile_left", "tactile_right",
|
| 133 |
+
"sensor_left_pose", "sensor_right_pose", "timestamps",
|
| 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"]
|
| 142 |
+
self.segment_paths = [p for _, p in ep_meta["segs"]]
|
| 143 |
+
print(f"[player] loading episode {self.key} "
|
| 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 |
+
# Boundaries
|
| 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,
|
| 160 |
+
"seg_idx": int(meta.get("source_segment_idx", i)),
|
| 161 |
+
"source_h5_range": meta.get("source_h5_frame_range"),
|
| 162 |
+
"n_frames": n,
|
| 163 |
+
})
|
| 164 |
+
cursor += n
|
| 165 |
+
self.data = cat
|
| 166 |
+
self.bounds = bounds
|
| 167 |
+
self.n_frames = cursor
|
| 168 |
+
meta0 = per_seg[0].get("_contact_meta", {})
|
| 169 |
+
# p01 references from the first segment (same per-source-episode)
|
| 170 |
+
self.ref_L = _tactile_to_bgr(meta0["ref_p01_left"]) if meta0.get("ref_p01_left") is not None else _tactile_to_bgr(per_seg[0]["tactile_left"][0])
|
| 171 |
+
self.ref_R = _tactile_to_bgr(meta0["ref_p01_right"]) if meta0.get("ref_p01_right") is not None else _tactile_to_bgr(per_seg[0]["tactile_right"][0])
|
| 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:
|
| 175 |
+
for b in self.bounds:
|
| 176 |
+
if b["start_in_concat"] <= frame_idx <= b["end_in_concat"]:
|
| 177 |
+
return b
|
| 178 |
+
return self.bounds[-1]
|
| 179 |
+
|
| 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(pose_L, pose_R, t_idx, t_sec, w, h):
|
| 189 |
panel = np.zeros((h, w, 3), np.uint8)
|
| 190 |
cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
|
|
|
|
| 196 |
cv2.putText(panel, name, (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1, cv2.LINE_AA)
|
| 197 |
y += 18
|
| 198 |
if p is None or all(v == 0 for v in p):
|
| 199 |
+
cv2.putText(panel, " no data", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (100, 100, 100), 1, cv2.LINE_AA)
|
| 200 |
+
y += 36; continue
|
|
|
|
|
|
|
| 201 |
x, yv, z, qx, qy, qz, qw = p
|
| 202 |
+
cv2.putText(panel, f" x={x:+.3f} y={yv:+.3f} z={z:+.3f}", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (220, 220, 220), 1, cv2.LINE_AA)
|
|
|
|
| 203 |
y += 16
|
| 204 |
+
cv2.putText(panel, f" qx={qx:+.2f} qy={qy:+.2f}", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
|
|
|
|
| 205 |
y += 16
|
| 206 |
+
cv2.putText(panel, f" qz={qz:+.2f} qw={qw:+.2f}", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
|
|
|
|
| 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, 22),
|
| 249 |
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
|
| 250 |
cv2.line(panel, (10, 30), (w - 10, 30), (60, 60, 60), 1)
|
| 251 |
keys = [
|
| 252 |
+
("SPACE", "pause / resume"),
|
| 253 |
+
("← →", "prev / next frame"),
|
| 254 |
+
("1..6", "speed 1x/2x/5x/10x/25x/50x"),
|
| 255 |
+
("n p", "next / prev episode"),
|
| 256 |
+
("r", "reset gel-diff ref"),
|
| 257 |
+
("q", "quit"),
|
| 258 |
]
|
| 259 |
y = 52
|
| 260 |
for k, v in keys:
|
| 261 |
+
cv2.putText(panel, f"[{k}]", (10, y),
|
| 262 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (140, 200, 140), 1, cv2.LINE_AA)
|
| 263 |
+
cv2.putText(panel, v, (110, y),
|
| 264 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.42, (200, 200, 200), 1, cv2.LINE_AA)
|
| 265 |
y += 22
|
|
|
|
| 266 |
state = "|| PAUSED" if paused else "> PLAYING"
|
| 267 |
state_col = (0, 140, 255) if paused else (0, 220, 80)
|
| 268 |
+
cv2.putText(panel, state, (10, h - 50),
|
| 269 |
cv2.FONT_HERSHEY_SIMPLEX, 0.55, state_col, 2, cv2.LINE_AA)
|
| 270 |
+
cv2.putText(panel, f"speed: {speed}x", (10, h - 30),
|
| 271 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
|
| 272 |
+
cv2.putText(panel, f"episode {ep_idx + 1} / {n_eps}", (10, h - 10),
|
| 273 |
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
|
| 274 |
return panel
|
| 275 |
|
| 276 |
|
| 277 |
+
def build_panel(ep: LoadedEpisode, frame_idx: int, ref_L_bgr, ref_R_bgr,
|
| 278 |
+
iL_trail, iR_trail, boundary_marks_local,
|
| 279 |
+
paused: bool, speed: int,
|
| 280 |
+
ep_idx: int, n_eps: int):
|
| 281 |
+
view_bgr = _view_to_bgr(ep.data["view"][frame_idx])
|
| 282 |
+
tac_L_bgr = _tactile_to_bgr(ep.data["tactile_left"][frame_idx])
|
| 283 |
+
tac_R_bgr = _tactile_to_bgr(ep.data["tactile_right"][frame_idx])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
view_thumb = cv2.resize(view_bgr, VIEW_THUMB, interpolation=cv2.INTER_NEAREST)
|
| 286 |
tac_L_thumb = cv2.resize(tac_L_bgr, TAC_THUMB, interpolation=cv2.INTER_NEAREST)
|
| 287 |
tac_R_thumb = cv2.resize(tac_R_bgr, TAC_THUMB, interpolation=cv2.INTER_NEAREST)
|
| 288 |
tac_L_diff = _diff_thumb(tac_L_bgr, ref_L_bgr, TAC_THUMB)
|
| 289 |
tac_R_diff = _diff_thumb(tac_R_bgr, ref_R_bgr, TAC_THUMB)
|
|
|
|
|
|
|
| 290 |
for img, label in [(view_thumb, "cam0 / view"),
|
| 291 |
(tac_L_thumb, "tactile_left"),
|
| 292 |
(tac_L_diff, "tac_L diff (vs p01)"),
|
|
|
|
| 294 |
(tac_R_diff, "tac_R diff (vs p01)")]:
|
| 295 |
cv2.putText(img, label, (6, 14),
|
| 296 |
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (220, 220, 220), 1, cv2.LINE_AA)
|
|
|
|
| 297 |
row1 = np.hstack([view_thumb, tac_L_thumb, tac_L_diff, tac_R_thumb, tac_R_diff])
|
| 298 |
|
| 299 |
+
pose_L = ep.data["sensor_left_pose"][frame_idx].tolist()
|
| 300 |
+
pose_R = ep.data["sensor_right_pose"][frame_idx].tolist()
|
| 301 |
+
t_sec = float(ep.data["timestamps"][frame_idx] - ep.data["timestamps"][0])
|
| 302 |
ot_panel = _make_ot_panel(pose_L, pose_R, frame_idx, t_sec, *OT_PANEL)
|
| 303 |
+
trail_panel = _make_trail_panel(list(iL_trail), list(iR_trail),
|
| 304 |
+
boundary_marks_local, *TRAIL_PANEL)
|
| 305 |
+
controls_panel = _make_controls_panel(*CONTROLS_PANEL, paused=paused, speed=speed,
|
| 306 |
+
ep_idx=ep_idx, n_eps=n_eps)
|
| 307 |
row2 = np.hstack([ot_panel, trail_panel, controls_panel])
|
| 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)
|
| 314 |
+
h5r = seg["source_h5_range"]
|
| 315 |
+
seg_label = f"seg {seg['seg_idx']:02d}"
|
| 316 |
+
if h5r:
|
| 317 |
+
seg_label += f" H5[{h5r[0]}..{h5r[1]}]"
|
| 318 |
+
status = (f"[{state}] ep {ep_idx + 1}/{n_eps} {ep.key} · "
|
| 319 |
+
f"frame {frame_idx + 1}/{ep.n_frames} · t={t_sec:.2f}s · "
|
| 320 |
+
f"{seg_label} · {speed}x")
|
| 321 |
cv2.putText(panel, status, (10, 16),
|
| 322 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.46, (0, 200, 255), 1, cv2.LINE_AA)
|
| 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):
|
| 326 |
+
cv2.rectangle(panel, (0, 22), (PANEL_W - 1, PANEL_H - 1), (0, 0, 220), 3)
|
| 327 |
+
|
| 328 |
return panel
|
| 329 |
|
| 330 |
|
| 331 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 332 |
+
# Main
|
| 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("--trail_frames", type=int, default=120)
|
| 344 |
args = ap.parse_args()
|
| 345 |
|
| 346 |
+
in_path = Path(args.path)
|
| 347 |
+
if not in_path.exists():
|
| 348 |
+
print(f"Not found: {in_path}", file=sys.stderr); sys.exit(1)
|
| 349 |
+
|
| 350 |
+
if in_path.is_file():
|
| 351 |
+
# Single .pt → one-episode mode (use parent dir for discovery to enable n/p)
|
| 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):
|
| 358 |
+
if any(p.resolve() == target_path for _, p in ep_meta["segs"]):
|
| 359 |
+
start_idx = i; break
|
| 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.", file=sys.stderr)
|
| 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 |
+
out_path = (Path(headless_single)
|
| 380 |
+
if headless_single else
|
| 381 |
+
(headless_dir / f"{ep.date}_{ep.ep_stem}.mp4"))
|
| 382 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 383 |
+
writer = cv2.VideoWriter(str(out_path), fourcc, args.fps, (PANEL_W, PANEL_H))
|
| 384 |
+
iL_trail = collections.deque(maxlen=args.trail_frames)
|
| 385 |
+
iR_trail = collections.deque(maxlen=args.trail_frames)
|
| 386 |
+
print(f" → {out_path}")
|
| 387 |
+
for f in range(ep.n_frames):
|
| 388 |
+
iL_trail.append(float(ep.data["tactile_left_mixed"][f]))
|
| 389 |
+
iR_trail.append(float(ep.data["tactile_right_mixed"][f]))
|
| 390 |
+
local_boundary_marks = [
|
| 391 |
+
args.trail_frames - 1 - (f - b["start_in_concat"])
|
| 392 |
+
for b in ep.bounds[1:]
|
| 393 |
+
if b["start_in_concat"] <= f and (f - b["start_in_concat"]) < args.trail_frames
|
| 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
|
| 404 |
|
| 405 |
+
# Interactive
|
| 406 |
+
paused, speed = False, 1
|
| 407 |
+
SPEEDS = {ord('1'): 1, ord('2'): 2, ord('3'): 5,
|
| 408 |
+
ord('4'): 10, ord('5'): 25, ord('6'): 50}
|
| 409 |
|
| 410 |
+
ep_idx = start_idx
|
| 411 |
+
while 0 <= ep_idx < len(episodes):
|
| 412 |
+
ep = LoadedEpisode(episodes[ep_idx])
|
| 413 |
+
WIN = "React .pt player"
|
| 414 |
+
cv2.namedWindow(WIN, cv2.WINDOW_AUTOSIZE)
|
| 415 |
+
cv2.createTrackbar("Frame", WIN, 0, max(1, ep.n_frames - 1), lambda v: None)
|
| 416 |
+
ref_L, ref_R = ep.ref_L, ep.ref_R
|
| 417 |
+
iL_trail = collections.deque(maxlen=args.trail_frames)
|
| 418 |
+
iR_trail = collections.deque(maxlen=args.trail_frames)
|
| 419 |
+
frame_idx = 0
|
| 420 |
+
last_drawn = -1
|
| 421 |
+
action = "stay" # 'next' | 'prev' | 'quit' | 'stay'
|
| 422 |
|
| 423 |
+
while True:
|
| 424 |
+
frame_idx = max(0, min(frame_idx, ep.n_frames - 1))
|
| 425 |
+
pos = cv2.getTrackbarPos("Frame", WIN)
|
| 426 |
+
if pos != frame_idx and pos != last_drawn:
|
| 427 |
+
frame_idx = pos; paused = True
|
| 428 |
+
|
| 429 |
+
iL_trail.append(float(ep.data["tactile_left_mixed"][frame_idx]))
|
| 430 |
+
iR_trail.append(float(ep.data["tactile_right_mixed"][frame_idx]))
|
| 431 |
+
boundary_marks = [
|
| 432 |
+
args.trail_frames - 1 - (frame_idx - b["start_in_concat"])
|
| 433 |
+
for b in ep.bounds[1:]
|
| 434 |
+
if b["start_in_concat"] <= frame_idx and (frame_idx - b["start_in_concat"]) < args.trail_frames
|
| 435 |
+
]
|
| 436 |
|
| 437 |
panel = build_panel(ep, frame_idx, ref_L, ref_R,
|
| 438 |
+
iL_trail, iR_trail, boundary_marks,
|
| 439 |
+
paused=paused, speed=speed,
|
| 440 |
+
ep_idx=ep_idx, n_eps=len(episodes))
|
| 441 |
+
cv2.imshow(WIN, panel)
|
| 442 |
+
if cv2.getTrackbarPos("Frame", WIN) != frame_idx:
|
| 443 |
+
cv2.setTrackbarPos("Frame", WIN, frame_idx)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
last_drawn = frame_idx
|
| 445 |
|
| 446 |
key = cv2.waitKey(1) & 0xFF
|
| 447 |
+
if key == ord('q'): action = "quit"; break
|
| 448 |
elif key == ord(' '): paused = not paused
|
| 449 |
elif key in (81, ord('a')): paused = True; frame_idx -= 1
|
| 450 |
elif key in (83, ord('d')): paused = True; frame_idx += 1
|
| 451 |
elif key in SPEEDS: speed = SPEEDS[key]
|
| 452 |
elif key == ord('r'):
|
| 453 |
+
ref_L = _tactile_to_bgr(ep.data["tactile_left"][frame_idx])
|
| 454 |
+
ref_R = _tactile_to_bgr(ep.data["tactile_right"][frame_idx])
|
| 455 |
print(f" diff ref reset to frame {frame_idx}")
|
| 456 |
+
elif key == ord('n'):
|
| 457 |
+
action = "next"; break
|
| 458 |
+
elif key == ord('p'):
|
| 459 |
+
action = "prev"; break
|
| 460 |
|
| 461 |
if not paused:
|
| 462 |
frame_idx += speed
|
| 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 |
+
ep_idx = min(ep_idx + 1, len(episodes) - 1)
|
| 473 |
+
if ep_idx == len(episodes) - 1 and episodes[ep_idx]["key"] == ep.key:
|
| 474 |
+
print("Already at last episode.")
|
| 475 |
+
elif action == "prev":
|
| 476 |
+
ep_idx = max(ep_idx - 1, 0)
|
| 477 |
+
if ep_idx == 0 and episodes[ep_idx]["key"] == ep.key:
|
| 478 |
+
print("Already at first episode.")
|
| 479 |
else:
|
| 480 |
+
# natural end of an episode — pause; wait for explicit action
|
| 481 |
+
paused = True
|
| 482 |
|
| 483 |
|
| 484 |
if __name__ == "__main__":
|