File size: 29,418 Bytes
8da704e
2b2cfc6
 
 
5711283
8da704e
 
 
 
 
 
 
 
 
 
 
5711283
 
8da704e
 
5711283
 
8da704e
 
 
 
2b2cfc6
8da704e
 
 
2b2cfc6
8da704e
 
 
 
 
 
 
2b2cfc6
 
8da704e
 
 
 
 
5711283
 
 
8da704e
 
 
 
 
 
 
 
5711283
 
2b2cfc6
5711283
 
 
8da704e
5711283
 
8da704e
5711283
 
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
8da704e
 
 
 
 
5711283
 
 
 
 
2b2cfc6
 
8da704e
2b2cfc6
5711283
8da704e
5711283
 
 
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5711283
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8da704e
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8da704e
 
2b2cfc6
 
8da704e
 
2b2cfc6
 
 
 
8da704e
2b2cfc6
 
 
 
 
 
 
 
8da704e
2b2cfc6
 
 
 
8da704e
2b2cfc6
 
8da704e
2b2cfc6
 
 
8da704e
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
8da704e
 
 
 
 
 
 
 
 
 
2b2cfc6
 
8da704e
2b2cfc6
 
8da704e
5711283
 
 
 
 
8da704e
 
 
 
5711283
8da704e
 
 
 
 
 
 
 
 
 
 
5711283
8da704e
 
5711283
8da704e
 
5711283
2b2cfc6
5711283
 
 
 
2b2cfc6
5711283
8da704e
 
 
5711283
8da704e
 
 
 
 
 
 
5711283
8da704e
 
 
 
 
 
 
 
 
5711283
8da704e
 
 
 
 
 
 
5711283
 
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5711283
 
8da704e
5711283
 
2b2cfc6
 
 
 
 
8da704e
 
 
 
 
5711283
8da704e
2b2cfc6
 
 
 
 
5711283
 
 
2b2cfc6
 
 
 
5711283
8da704e
2b2cfc6
5711283
2b2cfc6
 
 
 
8da704e
 
 
5711283
 
2b2cfc6
8da704e
 
 
 
 
 
2b2cfc6
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
8da704e
2b2cfc6
 
 
 
 
 
 
 
 
8da704e
 
 
 
 
 
 
2b2cfc6
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
 
8da704e
 
2b2cfc6
 
5711283
 
2b2cfc6
 
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
 
5711283
2b2cfc6
 
 
 
5711283
2b2cfc6
 
8da704e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
8da704e
 
2b2cfc6
8da704e
2b2cfc6
8da704e
 
2b2cfc6
8da704e
5711283
2b2cfc6
5711283
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
275
276
277
278
279
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
"""Interactive playback for React data -- accepts a single `.pt` OR a
directory of segments / episodes, concatenates same-episode segments
into one continuous timeline, and lets you switch between source
episodes with N / P.

The viewer reuses `twm.viz.build_preview_panel`'s 1280x480 grid:

    Row 1 (y=0..240):    [left cam | middle cam | right cam | OptiTrack]
    Row 2 (y=240..480):  [gs_L_raw | gs_L_diff | gs_R_raw | gs_R_diff | Controls]

The three RealSense thumbnails and both GelSight raw streams are pulled
from the source HDF5 file (referenced by each .pt segment's
`_contact_meta.source_episode` + `source_h5_frame_range`). When the
source H5 cannot be located, those cells are filled with a "no H5"
placeholder.

Usage
-----
Single .pt file (mode1_v1 episode OR one mode2_v1 segment):
    python scripts/play_react_pt.py \\
        processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt

Episode stem (no .pt suffix) -- loads ALL segments of that episode and
seeds N/P navigation across the rest of the date folder:
    python scripts/play_react_pt.py \\
        processed/mode2_v1/motherboard/2026-05-11/episode_005

Date folder -- all episodes recorded that day:
    python scripts/play_react_pt.py \\
        processed/mode2_v1/motherboard/2026-05-11

Whole task -- every episode across every date:
    python scripts/play_react_pt.py \\
        processed/mode2_v1/motherboard

  In all multi-episode modes, same-episode segments are concatenated
  into one playback timeline; N / P jumps to the next / previous
  source episode.

Headless export (one MP4 per episode):
    python scripts/play_react_pt.py <root> --save_video_dir /tmp/out

Override the source-H5 root (otherwise inferred by replacing
`processed/<mode>` with `data` in the input path):
    python scripts/play_react_pt.py <root> --h5_root /path/to/data/<task>

Controls
--------
    space         pause / resume
    -> / d        next frame
    <- / a        previous frame
    1..6          playback speed 1x / 2x / 5x / 10x / 25x / 50x
    r             reset GelSight diff reference to current frame
    n             next episode
    p             previous episode
    q             quit
"""
import argparse
import re
import sys
import time
from pathlib import Path
from typing import Optional

import cv2
import h5py
import numpy as np
import torch

try:
    from twm.viz import (
        load_optitrack as _viz_load_optitrack,
        optitrack_at as _viz_optitrack_at,
        DISPLAY_ORDER,
    )
except Exception:
    _viz_load_optitrack = None
    _viz_optitrack_at = None
    DISPLAY_ORDER = [1, 2, 0]   # H5 cam_idx order for [left, middle, right]


# ──────────────────────────────────────────────────────────────────────────────
# Layout constants (matches twm.viz.build_preview_panel)
# ──────────────────────────────────────────────────────────────────────────────
PANEL_W, PANEL_H = 1280, 480
RS_THUMB_W, RS_THUMB_H = 320, 240     # RealSense cam cell
GS_THUMB_W, GS_THUMB_H = 240, 240     # GelSight raw/diff cell
CONTROLS_W, CONTROLS_H = 320, 240     # Controls panel (replaces blank in row 2)

TRACKER_COLORS = {
    "sensor_left":  (  0, 255, 120),
    "sensor_right": (  0, 180, 255),
}

SEGMENT_FNAME_RE = re.compile(r"^(episode_\d+)\.segment_(\d+)\.pt$")
PLAIN_EPISODE_RE = re.compile(r"^(episode_\d+)\.pt$")
DATE_RE          = re.compile(r"^\d{4}-\d{2}-\d{2}$")


# ──────────────────────────────────────────────────────────────────────────────
def _tactile_to_bgr(tac_chw):
    rgb = tac_chw.permute(1, 2, 0).numpy()
    return rgb[..., ::-1]


def _missing_cell(w, h, label):
    panel = np.full((h, w, 3), 32, np.uint8)
    cv2.putText(panel, label, (10, h // 2),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (140, 140, 140), 1, cv2.LINE_AA)
    return panel


# ──────────────────────────────────────────────────────────────────────────────
# H5 source resolution
# ──────────────────────────────────────────────────────────────────────────────

def infer_h5_root(pt_path: Path) -> Optional[Path]:
    """Map a .pt path to its source-H5 root by replacing the
    `processed/<mode>/` prefix with `data/`.

    Examples:
        .../twm/processed/mode2_v1/motherboard/2026-05-11/ep.pt
          -> .../twm/data/motherboard
        .../twm/processed/mode2_v1/motherboard
          -> .../twm/data/motherboard
    """
    parts = list(pt_path.parts)
    try:
        i = parts.index("processed")
    except ValueError:
        return None
    if i + 1 >= len(parts):
        return None
    base = parts[:i]
    tail = []
    for p in parts[i + 2:]:
        if DATE_RE.match(p) or p.endswith(".pt"):
            break
        tail.append(p)
    return Path(*base, "data", *tail)


def resolve_h5_path(h5_root: Optional[Path], source_episode: Optional[str]) -> Optional[Path]:
    """`source_episode` is '<date>/<episode_stem>'. Returns
    <h5_root>/<source_episode>.h5 if it exists, else None.
    """
    if not h5_root or not source_episode:
        return None
    candidate = h5_root / f"{source_episode}.h5"
    return candidate if candidate.exists() else None


class H5Source:
    """Lazy read-only access to a source H5: cams, gelsight frames, OT poses."""

    def __init__(self, h5_path: Optional[Path]):
        self.path = h5_path
        self.f = None
        self.n_frames = 0
        self.timestamps = None
        self.gs_left_n = 0
        self.gs_right_n = 0
        self.optitrack = None
        if h5_path is None:
            return
        try:
            self.f = h5py.File(str(h5_path), "r")
            self.n_frames   = int(self.f["timestamps"].shape[0])
            self.timestamps = self.f["timestamps"][:]
            self.gs_left_n  = int(self.f["gelsight/left/frames"].shape[0])
            self.gs_right_n = int(self.f["gelsight/right/frames"].shape[0])
            if _viz_load_optitrack is not None:
                self.optitrack = _viz_load_optitrack(self.f)
        except Exception as e:
            print(f"[player]   ! failed to open H5 {h5_path}: {e}")
            self.close()

    @property
    def ok(self) -> bool:
        return self.f is not None

    def cam(self, idx: int, h5_frame: int) -> Optional[np.ndarray]:
        if not self.ok or h5_frame < 0 or h5_frame >= self.n_frames:
            return None
        return self.f[f"realsense/cam{idx}/color"][h5_frame]

    def gelsight(self, side: str, h5_frame: int) -> Optional[np.ndarray]:
        if not self.ok:
            return None
        n = self.gs_left_n if side == "left" else self.gs_right_n
        if n == 0:
            return None
        return self.f[f"gelsight/{side}/frames"][min(max(h5_frame, 0), n - 1)]

    def ot_at(self, h5_frame: int) -> dict:
        if not self.ok or self.optitrack is None or _viz_optitrack_at is None:
            return {}
        idx = min(max(h5_frame, 0), self.n_frames - 1)
        return _viz_optitrack_at(self.optitrack, float(self.timestamps[idx]))

    def close(self):
        if self.f is not None:
            try: self.f.close()
            except Exception: pass
            self.f = None


# ──────────────────────────────────────────────────────────────────────────────
# Episode discovery
# ──────────────────────────────────────────────────────────────────────────────

def discover_episodes(root: Path) -> list[dict]:
    """Walk `root`, group .pt files by source episode key '<date>/episode_NNN',
    and return one entry per episode with its segment paths sorted.

    Handles both:
      - mode2_v1: `<root>/<date>/episode_NNN.segment_MM.pt`
      - mode1_v1: `<root>/<date>/episode_NNN.pt`
    """
    pts = sorted(root.rglob("*.pt"))
    if not pts:
        raise SystemExit(f"No .pt files under {root}")

    episodes: dict[str, dict] = {}
    for p in pts:
        m_seg = SEGMENT_FNAME_RE.match(p.name)
        m_plain = PLAIN_EPISODE_RE.match(p.name)
        if m_seg:
            ep_stem, seg_idx = m_seg.group(1), int(m_seg.group(2))
        elif m_plain:
            ep_stem, seg_idx = m_plain.group(1), 0
        else:
            continue
        date = p.parent.name
        key = f"{date}/{ep_stem}"
        episodes.setdefault(key, {"date": date, "ep_stem": ep_stem, "segs": []})
        episodes[key]["segs"].append((seg_idx, p))

    out = []
    for key in sorted(episodes):
        ep = episodes[key]
        ep["segs"].sort(key=lambda x: x[0])
        out.append({"key": key, **ep})
    return out


# ──────────────────────────────────────────────────────────────────────────────
# Episode-load
# ──────────────────────────────────────────────────────────────────────────────

class LoadedEpisode:
    """One source episode, with all its segments concatenated for playback.

    The concat timeline only carries .pt scalar/pose tensors; image cells are
    served on-demand from the bound source H5 file.
    """
    PER_FRAME_KEYS = (
        "timestamps",
        "sensor_left_pose", "sensor_right_pose",
        "tactile_left_intensity",  "tactile_right_intensity",
        "tactile_left_mixed",      "tactile_right_mixed",
    )

    def __init__(self, ep_meta: dict, h5_root: Optional[Path] = None):
        self.key = ep_meta["key"]
        self.date = ep_meta["date"]
        self.ep_stem = ep_meta["ep_stem"]
        self.segment_paths = [p for _, p in ep_meta["segs"]]
        print(f"[player] loading episode {self.key}  "
              f"({len(self.segment_paths)} segment{'s' if len(self.segment_paths) > 1 else ''})...")

        per_seg = [torch.load(p, weights_only=False, map_location="cpu") for p in self.segment_paths]

        cat = {}
        for k in self.PER_FRAME_KEYS:
            if k in per_seg[0]:
                cat[k] = torch.cat([s[k] for s in per_seg], dim=0)

        bounds = []
        cursor = 0
        source_ep = None
        for i, s in enumerate(per_seg):
            n = s["view"].shape[0]
            meta = s.get("_contact_meta", {})
            if source_ep is None:
                source_ep = meta.get("source_episode")
            bounds.append({
                "start_in_concat": cursor,
                "end_in_concat":   cursor + n - 1,
                "seg_idx":         int(meta.get("source_segment_idx", i)),
                "source_h5_range": meta.get("source_h5_frame_range"),
                "n_frames":        n,
            })
            cursor += n
        self.data = cat
        self.bounds = bounds
        self.n_frames = cursor
        self.source_episode = source_ep

        # Bind source H5
        h5_path = resolve_h5_path(h5_root, source_ep) if source_ep else None
        self.h5 = H5Source(h5_path)
        if self.h5.ok:
            print(f"[player]   H5 source: {h5_path}  ({self.h5.n_frames} frames)")
        else:
            print(f"[player]   H5 source not available "
                  f"(source_episode={source_ep!r}, h5_root={h5_root}) -- "
                  f"cam/gelsight cells will be blank")

        # GelSight diff references = H5 gelsight at the first segment's H5 start
        self.gs_ref_L = None
        self.gs_ref_R = None
        if self.h5.ok:
            r0 = bounds[0]["source_h5_range"]
            ref_h5_frame = r0[0] if r0 else 0
            self.gs_ref_L = self.h5.gelsight("left",  ref_h5_frame)
            self.gs_ref_R = self.h5.gelsight("right", ref_h5_frame)

        print(f"[player]   total {self.n_frames} frames  ({self.n_frames / 30.0:.1f}s)")

    def segment_at(self, frame_idx: int) -> dict:
        for b in self.bounds:
            if b["start_in_concat"] <= frame_idx <= b["end_in_concat"]:
                return b
        return self.bounds[-1]

    def is_segment_start(self, frame_idx: int) -> bool:
        return any(frame_idx == b["start_in_concat"] for b in self.bounds[1:])

    def h5_frame_for(self, frame_idx: int) -> Optional[int]:
        seg = self.segment_at(frame_idx)
        r = seg["source_h5_range"]
        if r is None:
            return None
        return r[0] + (frame_idx - seg["start_in_concat"])

    def close(self):
        self.h5.close()


# ──────────────────────────────────────────────────────────────────────────────
# Panel renderer (visualize.py-style 1280x480 grid)
# ──────────────────────────────────────────────────────────────────────────────

def _make_ot_panel(ot_poses, t_idx, t_sec, w, h):
    panel = np.zeros((h, w, 3), np.uint8)
    cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
    cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
    y = 56
    for name in ("sensor_left", "sensor_right"):
        color = TRACKER_COLORS[name]
        cv2.putText(panel, name, (8, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1, cv2.LINE_AA)
        y += 18
        pose = ot_poses.get(name) if isinstance(ot_poses, dict) else None
        if pose is None:
            cv2.putText(panel, "  no data", (8, y),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.4, (100, 100, 100), 1, cv2.LINE_AA)
            y += 36
            continue
        _, xyz_quat = pose
        x_m, y_m, z_m = xyz_quat[:3]
        qx, qy, qz, qw = xyz_quat[3:]
        cv2.putText(panel, f"  x={x_m:+.3f} y={y_m:+.3f} z={z_m:+.3f}", (8, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.38, (220, 220, 220), 1, cv2.LINE_AA)
        y += 16
        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)
        y += 16
        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)
        y += 24
    cv2.putText(panel, f"t = {t_sec:.2f} s   (concat frame {t_idx})",
                (8, h - 14), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1, cv2.LINE_AA)
    return panel


def _make_controls_panel(w, h, paused, speed, ep_idx, n_eps):
    panel = np.zeros((h, w, 3), np.uint8)
    cv2.putText(panel, "Controls", (10, 24),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 1, cv2.LINE_AA)
    cv2.line(panel, (10, 32), (w - 10, 32), (80, 80, 80), 1)
    keys = [
        ("SPACE",     "pause / resume"),
        ("-> / d",    "next frame"),
        ("<- / a",    "prev frame"),
        ("1..6",      "speed 1x/2x/5x/10x/25x/50x"),
        ("n / p",     "next / prev episode"),
        ("r",         "reset gel-diff ref"),
        ("q",         "quit"),
    ]
    y = 56
    for key, desc in keys:
        highlight = (key == "SPACE")
        key_color  = (0, 220, 255) if highlight else (140, 200, 140)
        desc_color = (220, 220, 220) if highlight else (160, 160, 160)
        cv2.putText(panel, f"[{key}]", (10, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, key_color, 1, cv2.LINE_AA)
        cv2.putText(panel, desc, (110, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, desc_color, 1, cv2.LINE_AA)
        y += 22
    state_text  = "|| PAUSED" if paused else "> PLAYING"
    state_color = (0, 140, 255) if paused else (0, 220, 80)
    cv2.putText(panel, state_text, (10, h - 32),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, state_color, 2, cv2.LINE_AA)
    cv2.putText(panel, f"speed: {speed}x   ep {ep_idx + 1}/{n_eps}",
                (10, h - 12),
                cv2.FONT_HERSHEY_SIMPLEX, 0.42, (180, 180, 180), 1, cv2.LINE_AA)
    return panel


def _rs_thumb(img, label=None):
    out = cv2.resize(img, (RS_THUMB_W, RS_THUMB_H))
    if label:
        cv2.putText(out, label, (6, 16),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, (220, 220, 220), 1, cv2.LINE_AA)
    return out


def _gs_thumb(img, label=None):
    out = cv2.resize(img, (GS_THUMB_W, GS_THUMB_H))
    if label:
        cv2.putText(out, label, (6, 16),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.42, (220, 220, 220), 1, cv2.LINE_AA)
    return out


def _gs_diff_thumb(frame_bgr, ref_bgr, label=None):
    diff = np.clip(frame_bgr.astype(np.int16) - ref_bgr.astype(np.int16) + 128, 0, 255).astype(np.uint8)
    out = cv2.resize(diff, (GS_THUMB_W, GS_THUMB_H))
    if label:
        cv2.putText(out, label, (6, 16),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.42, (220, 220, 220), 1, cv2.LINE_AA)
    return out


def build_panel(ep: LoadedEpisode, frame_idx: int,
                gs_ref_L, gs_ref_R,
                paused: bool, speed: int,
                ep_idx: int, n_eps: int):
    h5_frame = ep.h5_frame_for(frame_idx)
    t_sec = float(ep.data["timestamps"][frame_idx] - ep.data["timestamps"][0])

    # Row 1: 3 RealSense cams (left, middle, right) + OptiTrack
    cam_thumbs = []
    cam_labels = ["left cam", "middle cam", "right cam"]
    for slot, label in zip(DISPLAY_ORDER, cam_labels):
        img = ep.h5.cam(slot, h5_frame) if h5_frame is not None else None
        if img is None:
            cam_thumbs.append(_missing_cell(RS_THUMB_W, RS_THUMB_H, f"{label}: no H5"))
        else:
            cam_thumbs.append(_rs_thumb(img, label))
    ot_poses = ep.h5.ot_at(h5_frame) if h5_frame is not None else {}
    ot_panel = _make_ot_panel(ot_poses, frame_idx, t_sec, RS_THUMB_W, RS_THUMB_H)
    row1 = np.hstack(cam_thumbs + [ot_panel])

    # Row 2: GelSight raw + diff (L, R) + Controls
    gs_L = ep.h5.gelsight("left",  h5_frame) if h5_frame is not None else None
    gs_R = ep.h5.gelsight("right", h5_frame) if h5_frame is not None else None
    if gs_L is None:
        gs_L_raw = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_L: no H5")
        gs_L_dif = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_L diff: no H5")
    else:
        gs_L_raw = _gs_thumb(gs_L, "tactile_left")
        ref_L = gs_ref_L if gs_ref_L is not None else gs_L
        gs_L_dif = _gs_diff_thumb(gs_L, ref_L, "tac_L diff")
    if gs_R is None:
        gs_R_raw = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_R: no H5")
        gs_R_dif = _missing_cell(GS_THUMB_W, GS_THUMB_H, "tac_R diff: no H5")
    else:
        gs_R_raw = _gs_thumb(gs_R, "tactile_right")
        ref_R = gs_ref_R if gs_ref_R is not None else gs_R
        gs_R_dif = _gs_diff_thumb(gs_R, ref_R, "tac_R diff")
    controls = _make_controls_panel(CONTROLS_W, CONTROLS_H, paused, speed, ep_idx, n_eps)
    row2 = np.hstack([gs_L_raw, gs_L_dif, gs_R_raw, gs_R_dif, controls])

    panel = np.vstack([row1, row2])

    # Top status bar (visualize.py style: thicker cyan text)
    cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
    state = "PAUSED" if paused else "PLAYING"
    seg = ep.segment_at(frame_idx)
    h5r = seg["source_h5_range"]
    seg_label = f"seg {seg['seg_idx']:02d}"
    if h5r:
        seg_label += f"  H5[{h5r[0]}..{h5r[1]}]"
    if h5_frame is not None:
        seg_label += f"  @{h5_frame}"
    status = (f"[{state}]  ep {ep_idx + 1}/{n_eps}  {ep.key}  |  "
              f"frame {frame_idx + 1}/{ep.n_frames}  |  t={t_sec:.2f}s  |  "
              f"{seg_label}  |  {speed}x")
    cv2.putText(panel, status, (10, 16),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 255), 1, cv2.LINE_AA)

    # Segment-cut flash: red border for the first 2 frames of a non-first segment
    if ep.is_segment_start(frame_idx):
        cv2.rectangle(panel, (0, 22), (PANEL_W - 1, PANEL_H - 1), (0, 0, 220), 3)

    return panel


# ──────────────────────────────────────────────────────────────────────────────
# Main
# ──────────────────────────────────────────────────────────────────────────────

def main():
    ap = argparse.ArgumentParser(description="Interactive React .pt player (visualize.py-style layout).")
    ap.add_argument("path", help="A single .pt file OR a directory of episodes/segments.")
    ap.add_argument("--save_video", default=None,
                    help="When `path` is a single .pt: write that one episode as MP4 here.")
    ap.add_argument("--save_video_dir", default=None,
                    help="When `path` is a directory: write one MP4 per episode into this dir.")
    ap.add_argument("--fps", type=float, default=30.0)
    ap.add_argument("--h5_root", default=None,
                    help="Root directory of source H5 files (e.g. <twm>/data/<task>). "
                         "If omitted, inferred by replacing `processed/<mode>` with `data` in `path`.")
    args = ap.parse_args()

    in_path = Path(args.path)

    # Path-stem expansion: if the user typed an incomplete path like
    # `.../2026-05-11/episode_005` (no .pt suffix, possibly no .segment_NN),
    # treat it as an episode-stem filter. We load the parent date folder so
    # N/P navigation still works, then start playback at the matching episode.
    start_episode_key: Optional[str] = None
    if not in_path.exists():
        parent = in_path.parent
        stem = in_path.name
        if parent.is_dir() and stem:
            matches = sorted(parent.glob(f"{stem}*.pt"))
            # Require either an exact-name match or segment_NN siblings
            matches = [p for p in matches
                       if PLAIN_EPISODE_RE.match(p.name) and p.stem == stem
                       or (SEGMENT_FNAME_RE.match(p.name)
                           and SEGMENT_FNAME_RE.match(p.name).group(1) == stem)]
            if matches:
                start_episode_key = f"{parent.name}/{stem}"
                in_path = parent  # discover the whole date folder
                print(f"[player] interpreting '{args.path}' as episode-stem; "
                      f"will start at {start_episode_key}")
    if not in_path.exists():
        print(f"Not found: {args.path}", file=sys.stderr); sys.exit(1)

    if in_path.is_file():
        parent_root = in_path.parent.parent
        episodes = discover_episodes(parent_root)
        target_path = in_path.resolve()
        start_idx = 0
        for i, ep_meta in enumerate(episodes):
            if any(p.resolve() == target_path for _, p in ep_meta["segs"]):
                start_idx = i; break
    else:
        episodes = discover_episodes(in_path)
        start_idx = 0
        if start_episode_key is not None:
            for i, ep_meta in enumerate(episodes):
                if ep_meta["key"] == start_episode_key:
                    start_idx = i; break
            else:
                print(f"[player] WARN: stem '{start_episode_key}' not found in discovered "
                      f"episodes; starting at the first one")
    print(f"[player] discovered {len(episodes)} episode(s) under {in_path}")

    # Resolve H5 root
    h5_root: Optional[Path] = None
    if args.h5_root:
        h5_root = Path(args.h5_root)
    else:
        h5_root = infer_h5_root(in_path)
    if h5_root:
        ok = "ok" if h5_root.exists() else "missing"
        print(f"[player] H5 source root: {h5_root}  ({ok})")
    else:
        print("[player] H5 source root not specified and could not be inferred -- "
              "RealSense + GelSight cells will be blank")

    headless_dir = Path(args.save_video_dir) if args.save_video_dir else None
    headless_single = args.save_video
    if headless_single and len(episodes) > 1 and in_path.is_dir():
        print("--save_video accepts a single output path; for a directory pass --save_video_dir instead.",
              file=sys.stderr)
        sys.exit(1)
    headless = headless_single is not None or headless_dir is not None

    if headless:
        if headless_dir:
            headless_dir.mkdir(parents=True, exist_ok=True)
        for ep_idx in range(start_idx, len(episodes)):
            ep = LoadedEpisode(episodes[ep_idx], h5_root=h5_root)
            try:
                out_path = (Path(headless_single)
                            if headless_single else
                            (headless_dir / f"{ep.date}_{ep.ep_stem}.mp4"))
                fourcc = cv2.VideoWriter_fourcc(*"mp4v")
                writer = cv2.VideoWriter(str(out_path), fourcc, args.fps, (PANEL_W, PANEL_H))
                print(f"  -> {out_path}")
                for f in range(ep.n_frames):
                    panel = build_panel(ep, f, ep.gs_ref_L, ep.gs_ref_R,
                                        paused=False, speed=1,
                                        ep_idx=ep_idx, n_eps=len(episodes))
                    writer.write(panel)
                writer.release()
            finally:
                ep.close()
            if headless_single:
                break
        return

    # Interactive
    paused, speed = False, 1
    SPEEDS = {ord('1'): 1, ord('2'): 2, ord('3'): 5,
              ord('4'): 10, ord('5'): 25, ord('6'): 50}

    ep_idx = start_idx
    while 0 <= ep_idx < len(episodes):
        ep = LoadedEpisode(episodes[ep_idx], h5_root=h5_root)
        action = "stay"
        try:
            WIN = "React .pt player"
            cv2.namedWindow(WIN, cv2.WINDOW_AUTOSIZE)
            cv2.createTrackbar("Frame", WIN, 0, max(1, ep.n_frames - 1), lambda v: None)
            gs_ref_L, gs_ref_R = ep.gs_ref_L, ep.gs_ref_R
            frame_idx = 0
            last_drawn = -1

            while True:
                frame_idx = max(0, min(frame_idx, ep.n_frames - 1))
                pos = cv2.getTrackbarPos("Frame", WIN)
                if pos != frame_idx and pos != last_drawn:
                    frame_idx = pos; paused = True

                panel = build_panel(ep, frame_idx,
                                    gs_ref_L, gs_ref_R,
                                    paused=paused, speed=speed,
                                    ep_idx=ep_idx, n_eps=len(episodes))
                cv2.imshow(WIN, panel)
                if cv2.getTrackbarPos("Frame", WIN) != frame_idx:
                    cv2.setTrackbarPos("Frame", WIN, frame_idx)
                last_drawn = frame_idx

                key = cv2.waitKey(1) & 0xFF
                if   key == ord('q'): action = "quit"; break
                elif key == ord(' '): paused = not paused
                elif key in (81, ord('a')): paused = True; frame_idx -= 1
                elif key in (83, ord('d')): paused = True; frame_idx += 1
                elif key in SPEEDS: speed = SPEEDS[key]
                elif key == ord('r'):
                    h5_frame = ep.h5_frame_for(frame_idx)
                    if h5_frame is not None and ep.h5.ok:
                        gs_ref_L = ep.h5.gelsight("left",  h5_frame)
                        gs_ref_R = ep.h5.gelsight("right", h5_frame)
                        print(f"  gel-diff ref reset to concat frame {frame_idx}  (H5 frame {h5_frame})")
                elif key == ord('n'): action = "next"; break
                elif key == ord('p'): action = "prev"; break

                if not paused:
                    frame_idx += speed
                    if frame_idx >= ep.n_frames:
                        print(f"End of episode {ep.key}.")
                        paused = True
                        frame_idx = ep.n_frames - 1
                    time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))

            cv2.destroyAllWindows()
        finally:
            ep.close()
        if action == "quit": return
        if action == "next":
            new_idx = min(ep_idx + 1, len(episodes) - 1)
            if new_idx == ep_idx:
                print("Already at last episode.")
            ep_idx = new_idx
        elif action == "prev":
            new_idx = max(ep_idx - 1, 0)
            if new_idx == ep_idx:
                print("Already at first episode.")
            ep_idx = new_idx
        else:
            paused = True


if __name__ == "__main__":
    main()