File size: 11,351 Bytes
84e6423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Demonstrate ReactWindowDataset:
  - build the dataset with sensible defaults
  - sample N random windows
  - render static grid PNG (N rows × 8 cols, each cell a [view | tac_L | tac_R] composite)
  - render one window as a GIF with sensor-frame axes projected on `view`
"""
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from scipy.spatial.transform import Rotation

sys.path.insert(0, "/tmp")
from react_window_dataset import ReactWindowDataset

OUT = Path("/media/yxma/Disk1/twm/figures/dataloader_examples")
OUT.mkdir(parents=True, exist_ok=True)

DATA_ROOT = Path("/media/yxma/Disk1/twm/processed/mode1_v1/motherboard")
BAD_FRAMES = Path("/media/yxma/Disk1/twm/figures/dataset_figures/bad_frames.json")
TASKS_JSON = Path("/tmp/tasks_local.json")    # written below from HF

# `view` in the .pt = realsense/cam0/color, center-cropped 640→480 then resized → 128
# cam0 serial = 143322063538 → T_mocap_to_cam_right.json
CALIB_DIR = Path("/home/yxma/MultimodalData/twm/calibration/result")
CAM_CALIB_FOR_VIEW = CALIB_DIR / "T_mocap_to_cam_right.json"
GEL_LEFT_CALIB = CALIB_DIR / "T_gel_to_rigid_left.json"
GEL_RIGHT_CALIB = CALIB_DIR / "T_gel_to_rigid_right.json"

AX_COLORS_RGB = [(0, 0, 255), (0, 255, 0), (255, 128, 0)]   # X red, Y green, Z blue-ish
AX_LABELS = ["X", "Y", "Z"]
GEL_DOT_COLOR = {"L": (0, 255, 120), "R": (0, 180, 255)}


def load_calib():
    cam = json.loads(CAM_CALIB_FOR_VIEW.read_text())
    return {
        "T_mocap_to_cam": np.array(cam["T_mocap_to_cam"], np.float64),
        "intrinsics": cam["intrinsics"],
        "gel_left":  np.array(json.loads(GEL_LEFT_CALIB.read_text())["gel_center_in_rigid_mm"], np.float64),
        "gel_right": np.array(json.loads(GEL_RIGHT_CALIB.read_text())["gel_center_in_rigid_mm"], np.float64),
    }


def pose_to_T(pose_7):
    """7-vec (x,y,z, qx,qy,qz,qw) in meters → 4×4 in mm."""
    pos_mm = np.array(pose_7[:3], np.float64) * 1000.0
    q = np.array(pose_7[3:], np.float64)
    q /= np.linalg.norm(q)
    T = np.eye(4)
    T[:3, :3] = Rotation.from_quat(q).as_matrix()
    T[:3, 3] = pos_mm
    return T


def project_to_view(P_world_mm, calib, *, view_size=128, orig_w=640, orig_h=480):
    """Project a single mocap-frame point (mm) into 128×128 view coords.

    The .pt `view` was made by center-cropping cam0 from 640×480 → 480×480 and
    then bilinear-resizing to 128×128. We replicate that here.
    """
    T_m2c = calib["T_mocap_to_cam"]
    I = calib["intrinsics"]
    P = (T_m2c @ np.append(P_world_mm, 1.0))[:3]
    if P[2] <= 0:
        return None
    u640 = I["fx"] * P[0] / P[2] + I["ppx"]
    v480 = I["fy"] * P[1] / P[2] + I["ppy"]
    crop_left = (orig_w - orig_h) / 2.0          # 80
    u_in_crop = u640 - crop_left
    s = view_size / orig_h                       # 128/480
    return (u_in_crop * s, v480 * s)


def project_gel_with_axes(pose_7, gel_center_mm, calib, axis_len_mm=80.0):
    """Return (center_uv, [(x_uv, y_uv, z_uv) or None])."""
    if pose_7 is None or np.allclose(pose_7, 0.0):
        return None, None
    T_r2m = pose_to_T(pose_7)
    P_gel = (T_r2m @ np.append(gel_center_mm, 1.0))[:3]
    R = T_r2m[:3, :3]
    tips = [P_gel + R @ np.array([axis_len_mm, 0, 0]),
            P_gel + R @ np.array([0, axis_len_mm, 0]),
            P_gel + R @ np.array([0, 0, axis_len_mm])]
    center = project_to_view(P_gel, calib)
    if center is None:
        return None, None
    return center, [project_to_view(t, calib) for t in tips]


def to_hwc(t):
    return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()


def annotate_view(view_uint8, pose_L, pose_R, calib, *, scale=1):
    """Draw sensor axes on a (H, W, 3) RGB image. Returns annotated copy."""
    H, W, _ = view_uint8.shape
    img = view_uint8.copy()
    for side, pose, gel in [("L", pose_L, calib["gel_left"]),
                             ("R", pose_R, calib["gel_right"])]:
        ctr, axes = project_gel_with_axes(pose, gel, calib)
        if ctr is None:
            continue
        cx, cy = int(round(ctr[0])), int(round(ctr[1]))
        if axes is not None:
            for tip, c, lab in zip(axes, AX_COLORS_RGB, AX_LABELS):
                if tip is None:
                    continue
                tx, ty = int(round(tip[0])), int(round(tip[1]))
                cv2.line(img, (cx, cy), (tx, ty), c, max(1, scale), cv2.LINE_AA)
        dot_color = GEL_DOT_COLOR[side]
        cv2.circle(img, (cx, cy), max(2, 3 * scale), dot_color, -1, cv2.LINE_AA)
        cv2.circle(img, (cx, cy), max(2, 3 * scale) + 1, (255, 255, 255), 1, cv2.LINE_AA)
        cv2.putText(img, side, (cx + 4, cy + 4),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.4 * scale,
                    dot_color, max(1, scale), cv2.LINE_AA)
    return img


def make_static_grid(ds, sample_indices, calib, out_path,
                     n_cols=6, cell_scale=3):
    rows = []
    for idx in sample_indices:
        s = ds[idx]
        T = s["view"].shape[0]
        pick = np.linspace(0, T - 1, n_cols).astype(int)
        cells = []
        for t in pick:
            view_rgb = to_hwc(s["view"][t]).astype(np.uint8)
            view_rgb = annotate_view(view_rgb,
                                      s["sensor_left_pose"][t].numpy() if "left" in s["active_sensors"] else None,
                                      s["sensor_right_pose"][t].numpy() if "right" in s["active_sensors"] else None,
                                      calib, scale=1)
            tl = to_hwc(s["tactile_left"][t])
            tr = to_hwc(s["tactile_right"][t])
            # Stack horizontally: view | tac_L | tac_R, each 128×128
            triplet = np.concatenate([view_rgb, tl, tr], axis=1)  # (128, 384, 3)
            # Upscale for clarity
            triplet = cv2.resize(triplet, (triplet.shape[1] * cell_scale, triplet.shape[0] * cell_scale),
                                 interpolation=cv2.INTER_NEAREST)
            cells.append(triplet)
        rows.append(np.concatenate(cells, axis=1))

    H_row = rows[0].shape[0]
    W_row = rows[0].shape[1]
    pad_y = 16
    label_h = 88                 # vertical label band above each row
    canvas_h = 60 + len(rows) * (H_row + label_h + pad_y)
    canvas = np.full((canvas_h, W_row + 20, 3), 245, dtype=np.uint8)

    # Page header
    cv2.putText(canvas, f"ReactWindowDataset — {n_cols} evenly-spaced frames per sample (time runs left → right)",
                (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 50, 50), 2, cv2.LINE_AA)

    cell_w = W_row // n_cols
    for r, idx in enumerate(sample_indices):
        s = ds[idx]
        y0 = 60 + r * (H_row + label_h + pad_y)
        # Sample label band
        ep = s["episode_key"]
        dur_s = float(s["timestamps"][-1] - s["timestamps"][0])
        mL = float(s["tactile_left_mixed"].max())
        mR = float(s["tactile_right_mixed"].max())
        cv2.putText(canvas, f"sample #{idx}  ·  {ep}  ·  frames {s['frame_start']}-{s['frame_end']}  ({dur_s:.2f}s)  ·  active: {','.join(s['active_sensors'])}  ·  peak mixed L={mL:.2f}  R={mR:.2f}",
                    (10, y0 + 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA)
        # Per-cell time labels
        T = s["view"].shape[0]
        pick = np.linspace(0, T - 1, n_cols).astype(int)
        for c, t in enumerate(pick):
            cv2.putText(canvas, f"t = {int(t)}  (frame {s['frame_start'] + int(t)})",
                        (10 + c * cell_w + 8, y0 + 56), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (90, 90, 90), 1, cv2.LINE_AA)
        cv2.putText(canvas, "view  |  tactile_left  |  tactile_right",
                    (10, y0 + 76), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (130, 130, 130), 1, cv2.LINE_AA)
        # Place row
        canvas[y0 + label_h:y0 + label_h + H_row, 10:10 + W_row] = rows[r]

    Image.fromarray(canvas).save(out_path)
    print(f"  static -> {out_path}  ({out_path.stat().st_size / 1024:.1f} KB)")


def make_gif(ds, sample_idx, calib, out_path, *, panel_scale=3, fps=15):
    s = ds[sample_idx]
    T = s["view"].shape[0]
    frames = []
    for t in range(T):
        view_rgb = to_hwc(s["view"][t]).astype(np.uint8)
        view_ann = annotate_view(view_rgb,
                                  s["sensor_left_pose"][t].numpy() if "left" in s["active_sensors"] else None,
                                  s["sensor_right_pose"][t].numpy() if "right" in s["active_sensors"] else None,
                                  calib, scale=1)
        # Upscale each subpanel
        view_big = cv2.resize(view_ann, (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST)
        tl_big = cv2.resize(to_hwc(s["tactile_left"][t]),
                            (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST)
        tr_big = cv2.resize(to_hwc(s["tactile_right"][t]),
                            (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST)
        triplet = np.concatenate([view_big, tl_big, tr_big], axis=1)
        # Header strip with frame counter
        H, W, _ = triplet.shape
        header = np.full((36, W, 3), 230, dtype=np.uint8)
        text = f"{s['episode_key']}  frame {s['frame_start'] + t}/{s['frame_end']}  ({t+1}/{T})  |  view | tactile_L | tactile_R"
        cv2.putText(header, text, (8, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA)
        panel = np.concatenate([header, triplet], axis=0)
        frames.append(panel)

    # Shared-palette GIF
    pil = [Image.fromarray(f) for f in frames]
    mosaic = Image.new("RGB", (pil[0].width * min(8, len(pil)), pil[0].height))
    for i, im in enumerate(pil[: min(8, len(pil))]):
        mosaic.paste(im, (i * pil[0].width, 0))
    pal = mosaic.quantize(colors=128, method=Image.MEDIANCUT, dither=Image.NONE)
    qframes = [im.quantize(palette=pal, dither=Image.NONE) for im in pil]
    qframes[0].save(out_path, save_all=True, append_images=qframes[1:],
                     duration=int(round(1000 / fps)), loop=0, optimize=True, disposal=0)
    print(f"  gif    -> {out_path}  ({out_path.stat().st_size / 1024:.1f} KB)")


def main():
    # tasks.json was pre-fetched to TASKS_JSON via the base env
    if not TASKS_JSON.exists():
        raise FileNotFoundError(f"{TASKS_JSON} missing; fetch from yxma/React first")
    calib = load_calib()

    print("=== Build dataset ===")
    ds = ReactWindowDataset(
        data_root=DATA_ROOT,
        bad_frames_path=BAD_FRAMES,
        tasks_json_path=TASKS_JSON,
        window_length=16,
        stride=1,
        window_step=16,
        contact_metric="mixed",
        tactile_threshold=0.4,
        min_contact_fraction=0.6,
        which_sensors="any",
        skip_bad_frames=True,
        respect_active_sensors=True,
    )

    rng = np.random.default_rng(42)
    pick = rng.choice(len(ds), 4, replace=False)
    print(f"\n=== Render 4 random samples ===")
    make_static_grid(ds, pick, calib, OUT / "sample_grid.png")
    print(f"\n=== Render one as GIF ===")
    make_gif(ds, int(pick[0]), calib, OUT / "sample_window.gif")

    print("\nSample dict shapes (sample 0):")
    s = ds[int(pick[0])]
    for k, v in s.items():
        if isinstance(v, torch.Tensor):
            print(f"  {k:30s} {tuple(v.shape)}  {v.dtype}")
        else:
            print(f"  {k:30s} {v!r}")


if __name__ == "__main__":
    main()