File size: 6,838 Bytes
cc62065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e6423
cc62065
84e6423
 
 
 
 
 
cc62065
84e6423
cc62065
 
84e6423
 
 
cc62065
 
84e6423
 
 
cc62065
 
 
 
84e6423
 
cc62065
 
 
 
84e6423
 
 
 
 
 
 
cc62065
 
 
 
 
 
 
 
 
84e6423
 
 
 
 
cc62065
84e6423
 
cc62065
84e6423
 
 
 
 
 
 
 
 
 
cc62065
 
 
 
 
 
 
84e6423
 
 
 
cc62065
 
84e6423
 
 
 
cc62065
84e6423
cc62065
84e6423
 
 
cc62065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e6423
cc62065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e6423
 
cc62065
 
 
 
84e6423
cc62065
 
 
 
 
 
84e6423
 
 
 
 
cc62065
 
 
 
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
"""End-to-end usage example for `ReactWindowDataset`.

Run this against a local checkout of the React HF dataset:

  python examples/demo_react_window.py \\
      --data_root processed/mode1_v1/motherboard \\
      --bad_frames bad_frames.json \\
      --tasks_json tasks.json \\
      --n_samples 4 \\
      --out_dir /tmp/react_demo_out

What this script does
---------------------
1. Builds `ReactWindowDataset` with all four quality filters on (see the
   module docstring of `react_window_dataset.py` for what each catches).
2. Prints how many windows survived and the shape of one sample.
3. Renders a static grid of `--n_samples` random windows as a PNG. Each
   row = one window; each cell = `view | tactile_left | tactile_right`
   for a single frame inside that window.

Self-contained: only depends on numpy, torch, Pillow, and `cv2`. No
recording-machine code is needed — everything required to read the
published .pt files is shipped here.
"""
import argparse
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image

# Same-directory import.
sys.path.insert(0, str(Path(__file__).parent))
from react_window_dataset import ReactWindowDataset


def _to_hwc(t):
    """(3, H, W) torch uint8 → (H, W, 3) numpy uint8."""
    return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()


def _view_to_rgb(view_chw_uint8):
    """`view` was extracted from RealSense cam0 which records BGR
    (`rs.format.bgr8`); convert to RGB for PIL."""
    return view_chw_uint8.permute(1, 2, 0).numpy()[..., ::-1].copy()


def make_static_grid(ds, sample_indices, out_path: Path, *,
                     n_cols: int = 6, cell_scale: int = 3) -> None:
    """One row per window, `n_cols` evenly-spaced frames per window. Each
    cell is `view | tactile_left | tactile_right`."""
    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  = _view_to_rgb(s["view"][t]).astype(np.uint8)
            tac_L = _to_hwc(s["tactile_left"][t]).astype(np.uint8)
            tac_R = _to_hwc(s["tactile_right"][t]).astype(np.uint8)
            triplet = np.concatenate([view, tac_L, tac_R], axis=1)  # (128, 384, 3)
            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]
    label_h = 88
    pad_y = 16
    canvas_h = 60 + len(rows) * (H_row + label_h + pad_y)
    canvas = np.full((canvas_h, W_row + 20, 3), 245, np.uint8)
    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)
        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}  ·  {s['episode_key']}  ·  frames {s['frame_start']}-{s['frame_end']}  "
             f"({dur_s:.2f}s)  ·  active: {','.join(s['active_sensors'])}  ·  "
             f"peak mixed L={mL:.2f}  R={mR:.2f}"),
            (10, y0 + 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA,
        )
        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)
        canvas[y0 + label_h:y0 + label_h + H_row, 10:10 + W_row] = rows[r]

    out_path.parent.mkdir(parents=True, exist_ok=True)
    Image.fromarray(canvas).save(out_path)
    print(f"  grid -> {out_path}  ({out_path.stat().st_size / 1024:.1f} KB)")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data_root", required=True,
                    help="processed/mode1_v1/motherboard (relative to dataset root)")
    ap.add_argument("--bad_frames", default="bad_frames.json")
    ap.add_argument("--tasks_json", default="tasks.json")
    ap.add_argument("--n_samples", type=int, default=4)
    ap.add_argument("--out_dir", default="/tmp/react_demo_out")
    ap.add_argument("--window_length", type=int, default=16)
    ap.add_argument("--seed", type=int, default=42)
    ap.add_argument("--no_motion_filter", action="store_true",
                    help="Disable the motion filter (useful if you want stationary "
                         "contact windows for studying static tactile patterns).")
    args = ap.parse_args()

    print("=== Building dataset (all four quality filters on) ===")
    ds = ReactWindowDataset(
        data_root        = args.data_root,
        bad_frames_path  = args.bad_frames,
        tasks_json_path  = args.tasks_json,
        window_length    = args.window_length,
        stride           = 1,
        window_step      = max(1, args.window_length // 2),
        contact_metric        = "mixed",
        tactile_threshold     = 0.4,
        min_contact_fraction  = 0.5,
        which_sensors         = "any",
        skip_bad_frames        = True,
        respect_active_sensors = True,
        require_motion              = not args.no_motion_filter,
        min_motion_mps              = 0.03,
        min_motion_fraction         = 0.5,
        which_sensors_must_move     = "all_active",
    )

    if len(ds) == 0:
        print("No windows passed the filters. Try lowering `min_contact_fraction` "
              "or disabling `require_motion`.")
        return

    rng = np.random.default_rng(args.seed)
    pick = rng.choice(len(ds), min(args.n_samples, len(ds)), replace=False)

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

    print(f"\n=== Static grid of {len(pick)} random windows ===")
    out_dir = Path(args.out_dir)
    make_static_grid(ds, pick, out_dir / "sample_grid.png")


if __name__ == "__main__":
    main()