File size: 21,891 Bytes
b584148
2dec786
b584148
2dec786
 
 
 
b584148
 
 
2dec786
b584148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dec786
 
b584148
 
 
 
 
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
b584148
 
2dec786
 
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
 
 
 
 
 
2dec786
b584148
 
2dec786
b584148
2dec786
 
 
 
 
 
 
 
 
 
b584148
2dec786
b584148
 
 
 
2dec786
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
 
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
b584148
2dec786
 
 
b584148
 
2dec786
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
 
2dec786
 
 
b584148
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b584148
 
2dec786
b584148
2dec786
b584148
 
 
2dec786
b584148
 
 
 
 
2dec786
b584148
 
 
2dec786
b584148
 
2dec786
 
 
 
 
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
b584148
2dec786
b584148
 
2dec786
 
 
b584148
 
2dec786
 
b584148
2dec786
b584148
 
2dec786
 
b584148
2dec786
 
 
 
 
b584148
2dec786
 
b584148
2dec786
 
 
 
 
 
 
 
 
b584148
2dec786
 
 
b584148
 
2dec786
 
 
 
 
 
 
b584148
 
2dec786
 
b584148
2dec786
b584148
 
2dec786
 
b584148
2dec786
b584148
2dec786
 
 
b584148
 
 
2dec786
 
 
 
 
b584148
2dec786
 
b584148
2dec786
 
b584148
 
 
 
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
"""
Preprocess DROID tracks from local raw data (``data/droid_small``).

Reads ``trajectory.h5`` (cartesian + per-frame camera_extrinsics) and ``recordings/MP4``.
Projection: per-camera ZED intrinsics (ZED 2 vs ZED Mini) + distortion, native 1280x720 then scale to output.
Exterior mesh (7 pts/view): analytical per-frame projection.
Wrist: CoTracker for 25 background grid + 7 gripper mesh (fixed template seeds on frame 0).
"""

from __future__ import annotations

import os
import sys
from pathlib import Path


def _ensure_droid_main_on_syspath() -> Path:
    default_root = Path(__file__).resolve().parent.parent
    env = os.environ.get("DROID_MAIN_ROOT", "").strip()
    if env:
        alt = Path(env).expanduser().resolve()
        root = alt if (alt / "utils").is_dir() else default_root
    else:
        root = default_root
    p = str(root)
    if p not in sys.path:
        sys.path.insert(0, p)
    return root


_ensure_droid_main_on_syspath()

import argparse
import json
from typing import Dict, List, Optional

import cv2
import numpy as np
import torch
from tqdm import tqdm

from utils.cotracker_wrist_grid import (
    NUM_WRIST_GRID,
    NUM_WRIST_MESH,
    NUM_WRIST_POINTS,
    default_cotracker_checkpoint,
    load_cotracker_predictor,
    track_points_on_video,
)
from utils.raw_episode_loader import RawDroidEpisode, iter_raw_droid_episodes
from utils.camera_geometry import (
    DROID_NATIVE_HW,
    make_image_grid,
    project_gripper_mesh,
    scale_pixels_between_hw,
    wrist_gripper_template_pixels,
)
from utils.track_coords import clamp_tracks_pixels_for_draw, normalize_tracks_xy
from utils.karlp_calib import KarlpCalibStore, default_karlp_calib_dir
from utils.zed_intrinsics import load_camera_intrinsics

NUM_EXT_MESH_POINTS = 7
NUM_COMBINED_POINTS = NUM_EXT_MESH_POINTS * 2 + NUM_WRIST_POINTS  # 46

VIEW_ORDER = ("exterior_1", "exterior_2", "wrist")
DEFAULT_IMAGE_SIZE = 448


def _resolve_karlp_calib_dir(karlp_calib_dir: str) -> str:
    """Use explicit dir, else env, else bundled ``droid/calibration/karlp`` if present."""
    explicit = karlp_calib_dir.strip() or os.environ.get("DROID_KARLP_CALIB_DIR", "").strip()
    if explicit:
        return explicit
    default = default_karlp_calib_dir()
    if (default / "cam2base_extrinsics.json").is_file():
        return str(default)
    return ""


def _resize_frames(frames: List[np.ndarray], out_h: int, out_w: int) -> np.ndarray:
    out = [cv2.resize(np.asarray(f, dtype=np.uint8), (out_w, out_h)) for f in frames]
    return np.stack(out, axis=0)


def _extrinsics_for(ep: RawDroidEpisode, view: str, t: int) -> np.ndarray:
    if view == "exterior_1":
        return ep.ext1_extrinsics[t]
    if view == "exterior_2":
        return ep.ext2_extrinsics[t]
    if view == "wrist":
        return ep.wrist_extrinsics[t]
    raise KeyError(view)


def _view_projection_setup(
    ep: RawDroidEpisode,
    view: str,
    *,
    zed_calib_dir: str,
    karlp: KarlpCalibStore | None,
) -> tuple[str, np.ndarray, np.ndarray, str | None, str]:
    if view == "exterior_1":
        serial, ctype, svo = ep.ext1_serial, ep.ext1_camera_type, ep.ext1_svo_path
    elif view == "exterior_2":
        serial, ctype, svo = ep.ext2_serial, ep.ext2_camera_type, ep.ext2_svo_path
    elif view == "wrist":
        serial, ctype, svo = ep.wrist_serial, ep.wrist_camera_type, ep.wrist_svo_path
    else:
        raise KeyError(view)

    intr_source = "zed_default"
    K: np.ndarray | None = None
    dist: np.ndarray | None = None
    if karlp is not None:
        parsed = karlp.intrinsics_for_serial(ep.episode_id, serial)
        if parsed is not None:
            K, dist = parsed
            intr_source = "karlp_intrinsics_json"

    if K is None:
        K, dist = load_camera_intrinsics(
            serial,
            ctype,
            svo_path=str(svo) if svo else None,
            calib_dir=zed_calib_dir,
        )
        if karlp is not None:
            intr_source = "zed_fallback"

    return serial, K, dist, str(svo) if svo else None, intr_source


def _tracks_episode(
    ep: RawDroidEpisode,
    *,
    image_size: int,
    wrist_grid_queries: np.ndarray,
    wrist_gripper_queries: np.ndarray,
    cotracker_model,
    cotracker_device: torch.device,
    zed_calib_dir: str,
    karlp: KarlpCalibStore | None,
) -> tuple[Dict[str, np.ndarray], Dict[str, np.ndarray], Dict[str, np.ndarray], Dict[str, dict]]:
    """Per-view tracks (T,N,2) and vis (T,N) in each panel's own square ``image_size`` frame."""
    t_len = int(ep.cartesian.shape[0])
    s = int(image_size)
    out_hw = (s, s)
    view_images = {
        "exterior_1": _resize_frames(ep.exterior_1_images, s, s),
        "exterior_2": _resize_frames(ep.exterior_2_images, s, s),
        "wrist": _resize_frames(ep.wrist_images, s, s),
    }

    wrist_queries = np.concatenate(
        [
            np.asarray(wrist_grid_queries, dtype=np.float32),
            np.asarray(wrist_gripper_queries, dtype=np.float32),
        ],
        axis=0,
    )
    wrist_trk_px, wrist_vis = track_points_on_video(
        cotracker_model,
        view_images["wrist"],
        wrist_queries,
        cotracker_device,
    )
    if int(wrist_trk_px.shape[1]) != NUM_WRIST_POINTS:
        raise ValueError(
            f"wrist CoTracker expects {NUM_WRIST_POINTS} points, got {wrist_trk_px.shape[1]}"
        )
    wrist_grid_trk_px = wrist_trk_px[:, :NUM_WRIST_GRID]
    wrist_mesh_trk_px = wrist_trk_px[:, NUM_WRIST_GRID : NUM_WRIST_GRID + NUM_WRIST_MESH]
    wrist_grid_vis = wrist_vis[:, :NUM_WRIST_GRID]
    wrist_mesh_vis = wrist_vis[:, NUM_WRIST_GRID : NUM_WRIST_GRID + NUM_WRIST_MESH]
    view_tracks: Dict[str, np.ndarray] = {}
    view_vis: Dict[str, np.ndarray] = {}
    view_calib: Dict[str, dict] = {}

    for view in VIEW_ORDER:
        serial, K_native, dist, svo_path, intr_source = _view_projection_setup(
            ep, view, zed_calib_dir=zed_calib_dir, karlp=karlp
        )
        view_calib[view] = {
            "serial": serial,
            "K_native": K_native,
            "dist": dist,
            "svo_path": svo_path,
            "intrinsic_source": intr_source,
            "extrinsic_source": ep.extrinsic_source.get(view, "h5_camera_extrinsics"),
        }
        if view == "wrist":
            grid_trk = normalize_tracks_xy(wrist_grid_trk_px, s, s)
            mesh_trk = normalize_tracks_xy(wrist_mesh_trk_px, s, s)
            view_tracks[view] = np.concatenate([grid_trk, mesh_trk], axis=1)
            view_vis[view] = np.concatenate([wrist_grid_vis, wrist_mesh_vis], axis=1)
            continue

        n_pts = NUM_EXT_MESH_POINTS
        trk_px = np.zeros((t_len, n_pts, 2), dtype=np.float32)
        vis = np.zeros((t_len, n_pts), dtype=np.float32)
        for t in range(t_len):
            cart = ep.cartesian[t]
            ext6 = _extrinsics_for(ep, view, t)
            mesh_pix, mesh_vis = project_gripper_mesh(
                cart,
                ext6,
                K=K_native,
                dist=dist,
                native_hw=DROID_NATIVE_HW,
                gripper_open=float(ep.gripper_open[t]),
            )
            mesh_pix = scale_pixels_between_hw(mesh_pix, DROID_NATIVE_HW, out_hw)
            trk_px[t] = mesh_pix.astype(np.float32)
            vis[t] = mesh_vis.astype(np.float32)
        view_tracks[view] = normalize_tracks_xy(trk_px, s, s)
        view_vis[view] = vis

    return view_tracks, view_vis, view_images, wrist_trk_px, view_calib


class DROIDTrackPreprocessor:
    def __init__(
        self,
        *,
        raw_data_root: str,
        output_path: str,
        min_len: int = 16,
        max_len: int = 800,
        max_episodes: int = 20000,
        save_viz: bool = True,
        viz_out_dir: Optional[str] = None,
        viz_fps: int = 10,
        viz_trail: int = 15,
        save_query_debug: bool = False,
        img_size: int = DEFAULT_IMAGE_SIZE,
        zed_calib_dir: str = "",
        karlp_calib_dir: str = "",
        cotracker_checkpoint: str | None = None,
        cotracker_device: str = "",
    ):
        self.raw_data_root = Path(raw_data_root)
        self.output_path = Path(output_path)
        self.min_len = min_len
        self.max_len = max_len
        self.max_episodes = max_episodes
        self.save_viz = save_viz
        self.viz_out_dir = Path(viz_out_dir) if viz_out_dir else (self.output_path / "viz_tracks")
        self.viz_fps = viz_fps
        self.viz_trail = max(0, int(viz_trail))
        self.save_query_debug = save_query_debug
        self.image_size = int(img_size) if int(img_size) > 0 else DEFAULT_IMAGE_SIZE
        self.zed_calib_dir = zed_calib_dir.strip()
        karlp_dir = _resolve_karlp_calib_dir(karlp_calib_dir)
        self.karlp: KarlpCalibStore | None = None
        if karlp_dir:
            self.karlp = KarlpCalibStore(karlp_dir)
        self.output_path.mkdir(parents=True, exist_ok=True)
        s = self.image_size
        self.wrist_grid_queries = make_image_grid(s, s, grid_size=5)
        self.wrist_gripper_queries = wrist_gripper_template_pixels((s, s)).astype(np.float32)

        if not self.raw_data_root.is_dir():
            raise FileNotFoundError(f"raw_data_root not found: {self.raw_data_root}")

        ckpt = Path(cotracker_checkpoint) if cotracker_checkpoint else default_cotracker_checkpoint()
        dev_str = cotracker_device.strip() or ("cuda:0" if torch.cuda.is_available() else "cpu")
        self.cotracker_device = torch.device(dev_str)
        self.cotracker_checkpoint = ckpt
        self.cotracker_model = load_cotracker_predictor(ckpt, self.cotracker_device)

    def process_episode(self, ep: RawDroidEpisode) -> bool:
        t_len = int(ep.cartesian.shape[0])
        if t_len < self.min_len or t_len > self.max_len:
            return False

        ep_idx = ep.episode_index
        view_tracks, view_vis, view_images, wrist_trk_px, view_calib = _tracks_episode(
            ep,
            image_size=self.image_size,
            wrist_grid_queries=self.wrist_grid_queries,
            wrist_gripper_queries=self.wrist_gripper_queries,
            cotracker_model=self.cotracker_model,
            cotracker_device=self.cotracker_device,
            zed_calib_dir=self.zed_calib_dir,
            karlp=self.karlp,
        )
        s = self.image_size
        ww = view_tracks["wrist"]
        oob = (
            (ww[..., 0] < 0.0)
            | (ww[..., 0] > 1.0)
            | (ww[..., 1] < 0.0)
            | (ww[..., 1] > 1.0)
        )
        px_oob = (
            (wrist_trk_px[..., 0] < 0)
            | (wrist_trk_px[..., 0] >= s)
            | (wrist_trk_px[..., 1] < 0)
            | (wrist_trk_px[..., 1] >= s)
        )
        if oob.any() or px_oob.any():
            tqdm.write(
                f"  ep {ep_idx:06d} wrist CoTracker OOB: "
                f"norm {100.0 * oob.mean():.1f}%  px {100.0 * px_oob.mean():.1f}%  "
                f"norm range x=[{ww[...,0].min():.3f},{ww[...,0].max():.3f}] "
                f"y=[{ww[...,1].min():.3f},{ww[...,1].max():.3f}]"
            )

        tracks_combined = np.concatenate(
            [view_tracks["exterior_1"], view_tracks["exterior_2"], view_tracks["wrist"]],
            axis=1,
        )
        vis_combined = np.concatenate(
            [view_vis["exterior_1"], view_vis["exterior_2"], view_vis["wrist"]],
            axis=1,
        )

        out_npz = self.output_path / f"episode_{ep_idx:06d}.npz"
        np.savez_compressed(
            out_npz,
            tracks=tracks_combined,
            vis=vis_combined,
            tracks_exterior_1=view_tracks["exterior_1"],
            tracks_exterior_2=view_tracks["exterior_2"],
            tracks_wrist=view_tracks["wrist"],
            vis_exterior_1=view_vis["exterior_1"],
            vis_exterior_2=view_vis["exterior_2"],
            vis_wrist=view_vis["wrist"],
            images_exterior_1=view_images["exterior_1"],
            images_exterior_2=view_images["exterior_2"],
            images_wrist=view_images["wrist"],
            language=np.array(ep.language),
            episode_id=np.array(ep.h5_path.parent.name),
            h5_path=np.array(str(ep.h5_path)),
            num_steps=t_len,
            point_slices=np.array([0, 7, 14, 46], dtype=np.int32),
            karlp_episode_id=np.array(ep.episode_id),
            projection_pose_source=np.array("observation_robot_state_cartesian"),
            projection_extrinsic_source=np.array(
                "ext_karlp_or_h5+wrist_h5_only" if self.karlp else "h5_camera_extrinsics_inv_cam_to_world"
            ),
            extrinsic_source_ext1=np.array(view_calib["exterior_1"]["extrinsic_source"]),
            extrinsic_source_ext2=np.array(view_calib["exterior_2"]["extrinsic_source"]),
            extrinsic_source_wrist=np.array(view_calib["wrist"]["extrinsic_source"]),
            intrinsic_source_ext1=np.array(view_calib["exterior_1"]["intrinsic_source"]),
            intrinsic_source_ext2=np.array(view_calib["exterior_2"]["intrinsic_source"]),
            intrinsic_source_wrist=np.array(view_calib["wrist"]["intrinsic_source"]),
            wrist_grid_source=np.array("cotracker"),
            wrist_mesh_source=np.array("cotracker_fixed_template"),
            wrist_gripper_query_source=np.array("WRIST_GRIPPER_TEMPLATE_FRAC"),
            wrist_projection_chain=np.array("cotracker_frame0_seeds"),
            tracks_coord_space=np.array("normalized_div_wh"),
            cotracker_checkpoint=np.array(str(self.cotracker_checkpoint)),
            projection_native_hw=np.array(DROID_NATIVE_HW, dtype=np.int32),
            intrinsics_ext1_serial=np.array(view_calib["exterior_1"]["serial"]),
            intrinsics_ext2_serial=np.array(view_calib["exterior_2"]["serial"]),
            intrinsics_wrist_serial=np.array(view_calib["wrist"]["serial"]),
            intrinsics_ext1_native_flat=np.asarray(view_calib["exterior_1"]["K_native"].reshape(-1)),
            intrinsics_ext2_native_flat=np.asarray(view_calib["exterior_2"]["K_native"].reshape(-1)),
            intrinsics_wrist_native_flat=np.asarray(view_calib["wrist"]["K_native"].reshape(-1)),
            image_size=np.array(self.image_size, dtype=np.int32),
            proj_image_hw=np.array([self.image_size, self.image_size], dtype=np.int32),
        )

        if self.save_query_debug:
            dbg = self.output_path / "query_debug" / f"episode_{ep_idx:06d}"
            dbg.mkdir(parents=True, exist_ok=True)
            for view in VIEW_ORDER:
                frame0 = view_images[view][0]
                q = clamp_tracks_pixels_for_draw(view_tracks[view][0:1], s, s, normalized=True)[0]
                vis_bgr = cv2.cvtColor(frame0, cv2.COLOR_RGB2BGR)
                for i, (x, y) in enumerate(q):
                    if not np.isfinite(x) or not np.isfinite(y):
                        continue
                    cv2.circle(vis_bgr, (int(round(x)), int(round(y))), 4, (0, 0, 255), -1)
                cv2.imwrite(str(dbg / f"{view}_frame0.jpg"), vis_bgr)

        if self.save_viz:
            from utils.viz_tracks import render_three_view_combined_video

            render_three_view_combined_video(
                view_images=view_images,
                view_tracks=view_tracks,
                view_vis=view_vis,
                out_path=self.viz_out_dir / f"episode_{ep_idx:06d}.mp4",
                fps=self.viz_fps,
                draw_trail=self.viz_trail,
            )
        return True

    def run(self) -> None:
        print("Starting DROID raw preprocessing")
        print(f"  Raw root: {self.raw_data_root}")
        print(f"  Output: {self.output_path}")
        print(f"  Output frames: {self.image_size}x{self.image_size} per view (3-panel MP4 = {self.image_size * 3}x{self.image_size})")
        if self.karlp:
            print(f"  KarlP calib: {self.karlp.calib_dir} ({self.karlp.num_covered_episodes} episodes)")
            print("  Episode filter: union(cam2base, cam2base_superset, cam2cam)")
            print("  Ext ext1/ext2: KarlP cam2base when serial present, else h5")
            print("  Wrist extrinsics: h5 only (observation/camera_extrinsics/{wrist_serial}_left)")
            print("  Intrinsics: KarlP intrinsics.json per episode+serial, else ZED fallback")
        else:
            print(f"  Intrinsics: per-serial ZED (ZED2 ext / ZED Mini wrist) @ 1280x720 -> {self.image_size}x{self.image_size}")
            if self.zed_calib_dir:
                print(f"  ZED calib dir: {self.zed_calib_dir}")
            print("  Extrinsics: h5 observation/camera_extrinsics")
            print(
                "  WARNING: KarlP disabled — full-tree scan is slow on droid_raw. "
                "Pass --karlp-calib-dir or install droid/calibration/karlp/"
            )
        print("  Pose: observation/robot_state/cartesian_position (h5)")
        print("  Tracks: ext1/ext2 gripper mesh analytical; wrist 25-grid + 7-gripper CoTracker")
        print(f"  CoTracker: {self.cotracker_checkpoint} on {self.cotracker_device}")
        if self.save_viz:
            print(f"  Viz: one 3-panel MP4 per episode -> {self.viz_out_dir}/episode_XXXXXX.mp4")
        print()

        processed = skipped = 0
        pbar = tqdm(total=self.max_episodes, desc="Processing episodes")
        for ep in iter_raw_droid_episodes(self.raw_data_root, karlp=self.karlp):
            if processed >= self.max_episodes:
                break
            try:
                if self.process_episode(ep):
                    processed += 1
                    pbar.update(1)
                else:
                    skipped += 1
            except Exception as e:
                print(f"\nError episode {ep.episode_index} ({ep.h5_path}): {e}")
                skipped += 1
        pbar.close()

        meta = {
            "num_processed": processed,
            "num_skipped": skipped,
            "source": "local_raw",
            "raw_data_root": str(self.raw_data_root),
            "image_size": self.image_size,
            "proj_image_hw": [self.image_size, self.image_size],
            "intrinsics": "karlp_intrinsics_json" if self.karlp else "per_serial_zed_native_hd_scaled",
            "karlp_calib_dir": str(self.karlp.calib_dir) if self.karlp else None,
            "karlp_num_covered_episodes": self.karlp.num_covered_episodes if self.karlp else None,
            "zed_calib_dir": self.zed_calib_dir or None,
            "num_points": NUM_COMBINED_POINTS,
            "wrist_grid": "cotracker_25",
            "wrist_mesh": "cotracker_fixed_template_7",
            "cotracker_checkpoint": str(self.cotracker_checkpoint),
            "cotracker_device": str(self.cotracker_device),
        }
        meta_path = self.output_path / "metadata.json"
        meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
        print(f"\nDone: processed={processed}, skipped={skipped}")
        print(f"  Output: {self.output_path}")
        print(f"  Metadata: {meta_path}")


def main() -> None:
    p = argparse.ArgumentParser(description="Preprocess DROID tracks from local raw DROID data")
    p.add_argument(
        "--raw-data-root",
        type=str,
        default="/z/home/zhicao/droid_raw/1.0.1",
        help="Root with lab/success|failure/.../trajectory.h5 + recordings/MP4",
    )
    p.add_argument(
        "--output",
        type=str,
        default="/scratch1/home/zhicao/openpi/data_track/droid_small",
        help="Output directory for .npz and viz",
    )
    p.add_argument("--min-len", type=int, default=16)
    p.add_argument("--max-len", type=int, default=800)
    p.add_argument("--max-episodes", type=int, default=40)
    p.add_argument(
        "--img-size",
        type=int,
        default=DEFAULT_IMAGE_SIZE,
        help=f"Square output per view (default {DEFAULT_IMAGE_SIZE})",
    )
    p.add_argument("--save-query-debug", action="store_true")
    p.add_argument("--no-save-viz", action="store_true")
    p.add_argument("--viz-out-dir", type=str, default="")
    p.add_argument("--viz-fps", type=int, default=10)
    p.add_argument("--viz-trail", type=int, default=15, help="Track polyline tail length (frames)")
    p.add_argument(
        "--karlp-calib-dir",
        type=str,
        default="",
        help=(
            "KarlP/droid folder with cam2base_extrinsics.json, cam2base_extrinsic_superset.json, "
            "cam2cam_extrinsics.json, intrinsics.json. If set, only processes episodes in those files. "
            f"Default after download: {default_karlp_calib_dir()}"
        ),
    )
    p.add_argument(
        "--zed-calib-dir",
        type=str,
        default="",
        help="Folder with Stereolabs SN{serial}.conf (fallback intrinsics; DROID_ZED_CALIB_DIR)",
    )
    p.add_argument(
        "--cotracker-checkpoint",
        type=str,
        default="",
        help="CoTracker checkpoint (default: openpi/co-tracker/checkpoints/scaled_offline.pth)",
    )
    p.add_argument(
        "--cotracker-device",
        type=str,
        default="",
        help="torch device for CoTracker (default: cuda:0 if available else cpu)",
    )
    args = p.parse_args()

    DROIDTrackPreprocessor(
        raw_data_root=args.raw_data_root.strip(),
        output_path=args.output.strip(),
        min_len=args.min_len,
        max_len=args.max_len,
        max_episodes=args.max_episodes,
        save_viz=not args.no_save_viz,
        viz_out_dir=args.viz_out_dir.strip() or None,
        viz_fps=args.viz_fps,
        viz_trail=args.viz_trail,
        save_query_debug=bool(args.save_query_debug),
        img_size=args.img_size,
        zed_calib_dir=args.zed_calib_dir.strip(),
        karlp_calib_dir=args.karlp_calib_dir.strip(),
        cotracker_checkpoint=args.cotracker_checkpoint.strip() or None,
        cotracker_device=args.cotracker_device.strip(),
    ).run()


if __name__ == "__main__":
    main()