File size: 20,676 Bytes
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
"""
Multi-GPU DROID Preprocessing Script

Processes full DROID dataset in parallel across multiple GPUs.
Usage:
    # Machine 1 (GPUs 0-7):
    bash scripts/run_multigpu_machine1.sh

    # Machine 2 (GPUs 0-7):
    bash scripts/run_multigpu_machine2.sh

Each GPU processes a subset of episodes based on GPU_ID % NUM_GPUS.
"""

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import os
import numpy as np
import torch
import mediapy as media
import tensorflow as tf
tf.config.set_visible_devices([], 'GPU')
import tensorflow_datasets as tfds
import cv2
import datetime
import re
import json
from tqdm import tqdm
from scipy.spatial.transform import Rotation as R

from utils.load_camera_calibration import CameraCalibrationLoader
from utils.franka_mesh_projection import FrankaMeshProjector


# 7 gripper offsets in gripper frame
GRIPPER_OFFSETS = np.array([
    [0.0, 0.0, 0.0],      # 0: gripper base
    [0.0, 0.045, 0.161],  # 1: finger 1 tip
    [0.0, -0.045, 0.161], # 2: finger 2 tip
    [0.0, 0.045, 0.13],   # 3: finger 1 end
    [0.0, -0.045, 0.13],  # 4: finger 2 end
    [0.0, 0.0, 0.13],     # 5: gripper center front
    [0.0, 0.0, 0.065],    # 6: gripper center middle
])


def euler_xyz_to_rotation_matrix(euler_xyz):
    """Convert Euler XYZ angles to rotation matrix."""
    return R.from_euler('xyz', euler_xyz).as_matrix()


def transform_gripper_offsets(action):
    """Transform gripper offsets using action position and rotation."""
    pos = action[:3]
    rot_euler = action[3:6]
    rot_matrix = euler_xyz_to_rotation_matrix(rot_euler)
    gripper_points_3d = (rot_matrix @ GRIPPER_OFFSETS.T).T + pos
    return gripper_points_3d


def sample_arm_shaped_points(mesh_2d_visible, img_h, img_w, num_points=993, seed=None):
    """Sample points in arm shape around visible mesh vertices."""
    if seed is not None:
        np.random.seed(seed)

    points = []
    num_visible = len(mesh_2d_visible)

    if num_visible == 0:
        return np.random.rand(num_points, 2) * [img_w, img_h]

    # Gaussian around each visible mesh vertex
    points_per_mesh = min(50, num_points // max(num_visible, 1))
    gaussian_sigma = 15.0

    for mesh_pt in mesh_2d_visible:
        gaussian_pts = np.random.randn(points_per_mesh, 2) * gaussian_sigma + mesh_pt
        gaussian_pts[:, 0] = np.clip(gaussian_pts[:, 0], 0, img_w - 1)
        gaussian_pts[:, 1] = np.clip(gaussian_pts[:, 1], 0, img_h - 1)
        points.append(gaussian_pts)

    # Lines between visible meshes
    if num_visible >= 2:
        points_per_line = 10
        for i in range(num_visible - 1):
            line_pts = np.linspace(mesh_2d_visible[i], mesh_2d_visible[i+1], points_per_line + 2)
            points.append(line_pts[1:-1])

    # Fill remaining with uniform random
    current_count = sum(len(p) for p in points)
    remaining = num_points - current_count

    if remaining > 0:
        uniform_pts = np.random.rand(remaining, 2) * [img_w, img_h]
        points.append(uniform_pts)

    all_points = np.vstack(points) if points else np.empty((0, 2))

    if len(all_points) < num_points:
        extra = np.random.rand(num_points - len(all_points), 2) * [img_w, img_h]
        all_points = np.vstack([all_points, extra])
    elif len(all_points) > num_points:
        all_points = all_points[:num_points]

    return all_points


def sample_wrist_points(img_h, img_w, num_sparse=300, num_dense=700, seed=None):
    """Sample wrist points: sparse uniform + dense in bottom 60%-100%."""
    if seed is not None:
        np.random.seed(seed)

    sparse = np.random.rand(num_sparse, 2) * [img_w, img_h]

    # Dense in bottom 60%-100% region
    y_min = int(img_h * 0.60)
    y_max = img_h
    y_range = y_max - y_min

    dense_x = np.random.rand(num_dense) * img_w
    dense_y = np.random.rand(num_dense) * y_range + y_min
    dense = np.column_stack([dense_x, dense_y])

    return np.vstack([sparse, dense])


def find_closest_calibration(episode, uuid_list):
    """Find closest calibration UUID for episode."""
    try:
        recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8')
        match = re.search(r'/([A-Z]+)/success/(\d{4}-\d{2}-\d{2})/\w+_\w+_+\d+_(\d{2}):(\d{2}):(\d{2})_\d{4}/', recording_path)
        if not match:
            return None
        lab, date, hour, minute, second = match.groups()
        episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S")
        matching_calibs = [uuid for uuid in uuid_list if uuid.startswith(f"{lab}+") and f"+{date}-" in uuid]
        if len(matching_calibs) == 0:
            return None
        best_uuid = None
        min_time_diff = float('inf')
        for calib_uuid in matching_calibs:
            parts = calib_uuid.split('+')
            if len(parts) >= 3:
                time_str = parts[2].replace('_cameras', '')
                match_time = re.search(r'(\d{2})h-(\d{2})m-(\d{2})s', time_str)
                if match_time:
                    calib_hour = int(match_time.group(1))
                    calib_min = int(match_time.group(2))
                    calib_sec = int(match_time.group(3))
                    calib_time = datetime.datetime.strptime(
                        f"{date} {calib_hour}:{calib_min}:{calib_sec}",
                        "%Y-%m-%d %H:%M:%S"
                    )
                    time_diff = abs((episode_time - calib_time).total_seconds())
                    if time_diff < min_time_diff:
                        min_time_diff = time_diff
                        best_uuid = calib_uuid
        return best_uuid
    except:
        return None


def process_episode(episode, episode_idx, projector, calib_loader, uuid, cotracker, device,
                    max_frames=400, save_video=False, output_dir=None):
    """Process a single episode."""

    # Get dual view params
    dual_params = calib_loader.get_dual_view_params(uuid, param_type='refined', require_refined=True)
    K_ext, E_ext = dual_params['exterior_1']
    K_wrist, E_wrist = dual_params['wrist']

    # First pass: count valid frames to check if episode is too long
    valid_frame_count = 0
    for step in episode['steps']:
        img_ext = step['observation']['exterior_image_1_left'].numpy()
        img_wrist = step['observation']['wrist_image_left'].numpy()
        if img_ext is not None and img_wrist is not None:
            valid_frame_count += 1
            if valid_frame_count > max_frames:
                # Episode is too long, skip it
                return None

    # Check minimum length
    if valid_frame_count < 10:
        return None

    # Collect frames and actions
    frames_ext = []
    frames_wrist = []
    actions = []

    for step_idx, step in enumerate(episode['steps']):
        img_ext = step['observation']['exterior_image_1_left'].numpy()
        img_wrist = step['observation']['wrist_image_left'].numpy()
        action = step['action'].numpy()

        if img_ext is not None and img_wrist is not None:
            frames_ext.append(img_ext)
            frames_wrist.append(img_wrist)
            actions.append(action)

    T = len(frames_ext)
    img_h, img_w = frames_ext[0].shape[:2]

    # Step 1: Project mesh vertices for exterior view
    all_mesh_2d_ext = []
    all_mesh_vis_ext = []

    for t in range(T):
        gripper_3d = transform_gripper_offsets(actions[t])
        mesh_2d, mesh_vis = projector._project_3d_to_2d(
            gripper_3d, K_ext, E_ext, img_h=img_h, img_w=img_w
        )
        all_mesh_2d_ext.append(mesh_2d)
        all_mesh_vis_ext.append(mesh_vis)

    all_mesh_2d_ext = np.array(all_mesh_2d_ext)  # [T, 7, 2]
    all_mesh_vis_ext = np.array(all_mesh_vis_ext)  # [T, 7]

    # Check if at least some mesh points visible in first frame
    if np.sum(all_mesh_vis_ext[0]) < 2:
        return None

    # Step 2: Sample CoTracker query points at frame 0
    mesh_2d_0 = all_mesh_2d_ext[0]
    mesh_2d_visible_0 = mesh_2d_0[all_mesh_vis_ext[0]]

    additional_points_ext = sample_arm_shaped_points(
        mesh_2d_visible_0, img_h, img_w, num_points=993, seed=episode_idx
    )
    query_points_ext = np.vstack([mesh_2d_0, additional_points_ext])  # [1000, 2]

    query_points_wrist = sample_wrist_points(
        img_h, img_w, num_sparse=300, num_dense=700, seed=episode_idx
    )

    # Step 3: Run CoTracker
    video_ext_np = np.array(frames_ext).transpose(0, 3, 1, 2)
    video_ext_tensor = torch.from_numpy(video_ext_np).float() / 255.0
    video_ext_tensor = video_ext_tensor.unsqueeze(0).to(device)

    queries_ext = np.zeros((len(query_points_ext), 3))
    queries_ext[:, 0] = 0
    queries_ext[:, 1:] = query_points_ext
    queries_ext_tensor = torch.from_numpy(queries_ext).float().unsqueeze(0).to(device)

    with torch.no_grad():
        tracks_ext, vis_ext = cotracker(
            video_ext_tensor,
            queries=queries_ext_tensor,
            backward_tracking=False
        )

    tracks_ext = tracks_ext[0].cpu().numpy()  # [T, 1000, 2]
    vis_ext = vis_ext[0].cpu().numpy()  # [T, 1000]

    # Wrist view
    video_wrist_np = np.array(frames_wrist).transpose(0, 3, 1, 2)
    video_wrist_tensor = torch.from_numpy(video_wrist_np).float() / 255.0
    video_wrist_tensor = video_wrist_tensor.unsqueeze(0).to(device)

    queries_wrist = np.zeros((len(query_points_wrist), 3))
    queries_wrist[:, 0] = 0
    queries_wrist[:, 1:] = query_points_wrist
    queries_wrist_tensor = torch.from_numpy(queries_wrist).float().unsqueeze(0).to(device)

    with torch.no_grad():
        tracks_wrist, vis_wrist = cotracker(
            video_wrist_tensor,
            queries=queries_wrist_tensor,
            backward_tracking=False
        )

    tracks_wrist = tracks_wrist[0].cpu().numpy()
    vis_wrist = vis_wrist[0].cpu().numpy()

    # Step 4: Save preview video if requested
    if save_video and output_dir is not None:
        video_frames = []
        for t in range(T):
            # Exterior view
            viz_ext = frames_ext[t].copy()

            # Draw ground truth mesh vertices (blue hollow)
            for i in range(7):
                if all_mesh_vis_ext[t, i]:
                    pt = tuple(all_mesh_2d_ext[t, i].astype(int))
                    cv2.circle(viz_ext, pt, 5, (255, 0, 0), 2)
                    cv2.putText(viz_ext, str(i), (pt[0]+6, pt[1]-6),
                               cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 0, 0), 1)

            # Draw tracked mesh vertices (red filled) - first 7 of CoTracker
            for i in range(7):
                if vis_ext[t, i]:
                    pt = tuple(tracks_ext[t, i].astype(int))
                    cv2.circle(viz_ext, pt, 3, (0, 0, 255), -1)

            # Draw other tracked points (green)
            for i in range(7, len(tracks_ext[t])):
                if vis_ext[t, i]:
                    pt = tuple(tracks_ext[t, i].astype(int))
                    cv2.circle(viz_ext, pt, 1, (0, 255, 0), -1)

            cv2.putText(viz_ext, f"Ext: GT mesh (blue) | Tracked mesh (red) | Others (green)",
                       (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1)

            # Wrist view
            viz_wrist = frames_wrist[t].copy()

            for i in range(len(tracks_wrist[t])):
                if vis_wrist[t, i]:
                    pt = tuple(tracks_wrist[t, i].astype(int))
                    color = (255, 255, 0) if i < 300 else (0, 255, 255)
                    cv2.circle(viz_wrist, pt, 1, color, -1)

            cv2.putText(viz_wrist, f"Wrist: 300 sparse (cyan) + 700 dense bottom (yellow)",
                       (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1)

            combined = np.concatenate([viz_ext, viz_wrist], axis=1)
            cv2.putText(combined, f"Episode {episode_idx} | Frame {t}/{T}",
                       (5, img_h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)
            video_frames.append(combined)

        video_path = output_dir / f"preview_episode_{episode_idx:06d}.mp4"
        media.write_video(str(video_path), video_frames, fps=10)

    return {
        'episode_idx': episode_idx,
        'uuid': uuid,
        'frames_exterior': np.array(frames_ext),
        'frames_wrist': np.array(frames_wrist),
        'actions': np.array(actions),
        'mesh_vertices_2d_exterior': all_mesh_2d_ext,
        'mesh_vertices_vis_exterior': all_mesh_vis_ext,
        'tracks_exterior': tracks_ext,
        'tracks_vis_exterior': vis_ext,
        'tracks_wrist': tracks_wrist,
        'tracks_vis_wrist': vis_wrist,
    }


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu-id', type=int, required=True, help='GPU ID (0-15 for 2 machines)')
    parser.add_argument('--num-gpus', type=int, default=16, help='Total number of GPUs')
    parser.add_argument('--machine-id', type=int, required=True, help='Machine ID (0 or 1)')
    parser.add_argument('--output-dir', type=str, required=True, help='Output directory')
    parser.add_argument('--max-frames', type=int, default=400, help='Max frames per episode')
    parser.add_argument('--preview-total', type=int, default=20, help='Total preview videos across all GPUs')
    args = parser.parse_args()

    # Set CUDA device
    os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu_id)
    device = torch.device('cuda:0')

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    data_dir = output_dir / 'data'
    data_dir.mkdir(exist_ok=True)
    preview_dir = output_dir / 'preview_videos'
    preview_dir.mkdir(exist_ok=True)

    global_gpu_id = args.machine_id * 8 + args.gpu_id  # Global GPU ID across machines

    print("=" * 80)
    print(f"Multi-GPU DROID Preprocessing")
    print("=" * 80)
    print(f"  Machine ID: {args.machine_id}")
    print(f"  Local GPU ID: {args.gpu_id}")
    print(f"  Global GPU ID: {global_gpu_id}/{args.num_gpus}")
    print(f"  Output: {output_dir}")
    print(f"  Max frames: {args.max_frames}")
    print(f"  Preview videos: {args.preview_total} total (distributed)")
    print("=" * 80)

    # Load calibration
    calib_dir = '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras'
    calib_loader = CameraCalibrationLoader(calib_dir)
    projector = FrankaMeshProjector(use_gui=False)

    calib_path = Path(calib_dir)
    uuid_list = [f.stem.replace('_cameras', '') for f in sorted(calib_path.glob("*_cameras.json"))]
    print(f"Loaded {len(uuid_list)} camera calibrations")

    # Load CoTracker
    print("Loading CoTracker...")
    from cotracker.predictor import CoTrackerOnlinePredictor, CoTrackerPredictor

    # Try multiple checkpoint locations
    cotracker_paths = [
        '/mnt/kevin/vlm_models/cotracker/scaled_offline.pth',
        '/mnt/kevin/vlm_models/hub/checkpoints/scaled_offline.pth',
        '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/co-tracker/checkpoints/scaled_offline.pth',
    ]

    cotracker_checkpoint = None
    for path in cotracker_paths:
        if Path(path).exists():
            cotracker_checkpoint = path
            print(f"Found CoTracker checkpoint: {cotracker_checkpoint}")
            break

    if cotracker_checkpoint is None:
        raise FileNotFoundError(f"CoTracker checkpoint not found. Tried:\n" + "\n".join(cotracker_paths))

    cotracker = CoTrackerPredictor(checkpoint=cotracker_checkpoint)
    cotracker = cotracker.to(device)
    cotracker.eval()

    # Load DROID dataset
    print("Loading DROID dataset...")
    droid_path = '/mnt/kevin/data/droid/droid/1.0.0'
    builder = tfds.builder_from_directory(droid_path)
    dataset = builder.as_dataset(split='train')

    # Count total episodes
    print("Counting total episodes...")
    total_episodes = sum(1 for _ in dataset)
    print(f"Total episodes in dataset: {total_episodes}")

    # Calculate episodes for this GPU
    episodes_per_gpu = total_episodes // args.num_gpus
    start_idx = global_gpu_id * episodes_per_gpu
    end_idx = start_idx + episodes_per_gpu if global_gpu_id < args.num_gpus - 1 else total_episodes

    print(f"This GPU will process episodes {start_idx} to {end_idx-1} ({end_idx - start_idx} episodes)")

    # Determine preview strategy (distribute 20 videos evenly)
    preview_interval = max(1, (end_idx - start_idx) // max(1, args.preview_total // args.num_gpus))

    processed_count = 0
    skipped_count = 0
    preview_count = 0

    pbar = tqdm(total=end_idx - start_idx, desc=f"GPU {global_gpu_id}")

    for episode_idx, episode in enumerate(dataset):
        # Skip episodes not assigned to this GPU
        if episode_idx < start_idx:
            continue
        if episode_idx >= end_idx:
            break

        local_idx = episode_idx - start_idx

        # Find calibration
        uuid = find_closest_calibration(episode, uuid_list)
        if uuid is None or not calib_loader.has_refined_extrinsics(uuid):
            skipped_count += 1
            pbar.update(1)
            continue

        # Decide if we save video for this episode
        save_video = (local_idx % preview_interval == 0) and (preview_count < args.preview_total // args.num_gpus)

        try:
            result = process_episode(
                episode, episode_idx, projector, calib_loader, uuid,
                cotracker, device, max_frames=args.max_frames,
                save_video=save_video, output_dir=preview_dir
            )

            if result is None:
                skipped_count += 1
                pbar.update(1)
                continue

            # Save NPZ
            npz_path = data_dir / f"episode_{episode_idx:06d}.npz"
            np.savez_compressed(
                npz_path,
                episode_idx=result['episode_idx'],
                uuid=result['uuid'],
                images_exterior=result['frames_exterior'],
                images_wrist=result['frames_wrist'],
                actions=result['actions'],
                mesh_vertices_2d_exterior=result['mesh_vertices_2d_exterior'],
                mesh_vertices_vis_exterior=result['mesh_vertices_vis_exterior'],
                tracks_exterior=result['tracks_exterior'],
                tracks_vis_exterior=result['tracks_vis_exterior'],
                tracks_wrist=result['tracks_wrist'],
                tracks_vis_wrist=result['tracks_vis_wrist'],
                mesh_indices=np.array([0, 1, 2, 3, 4, 5, 6], dtype=np.int32),
            )

            processed_count += 1
            if save_video:
                preview_count += 1
            pbar.update(1)

        except Exception as e:
            print(f"\nError processing episode {episode_idx}: {e}")
            skipped_count += 1
            pbar.update(1)
            continue

    pbar.close()

    # Save GPU-specific metadata
    metadata = {
        'gpu_id': global_gpu_id,
        'machine_id': args.machine_id,
        'local_gpu_id': args.gpu_id,
        'processed_episodes': processed_count,
        'skipped_episodes': skipped_count,
        'preview_videos': preview_count,
        'episode_range': [start_idx, end_idx],
        'split': 'train',
        'camera_params': {
            'exterior': {
                'extrinsics': 'refined',
                'intrinsics': 'measured',
                'inversion': False
            },
            'wrist': {
                'sampling': 'random',
                'dense_region': 'bottom_60_100_pct'
            }
        },
        'point_distribution': {
            'exterior': {
                'total_tracked_points': 1000,
                'mesh_vertices_tracked': 7,
                'additional_points': 993,
                'arm_shaped_strategy': 'gaussian_15px_per_mesh + lines_between',
            },
            'wrist': {
                'total_tracked_points': 1000,
                'sparse_uniform': 300,
                'dense_bottom': 700
            }
        },
        'image_resolution': [180, 320],
        'max_frames_per_episode': args.max_frames,
        'cotracker_model': 'scaled_offline.pth',
        'cotracker_chunking': 'automatic_internal_only'
    }

    metadata_path = output_dir / f'metadata_gpu{global_gpu_id:02d}.json'
    with open(metadata_path, 'w') as f:
        json.dump(metadata, f, indent=2)

    print("\n" + "=" * 80)
    print(f"GPU {global_gpu_id} Complete")
    print("=" * 80)
    print(f"  Processed: {processed_count} episodes")
    print(f"  Skipped: {skipped_count} episodes")
    print(f"  Preview videos: {preview_count}")
    print(f"  Metadata: {metadata_path}")
    print("=" * 80)


if __name__ == "__main__":
    main()