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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Batch Process DROID Episodes with Mesh + CoTracker

Processes multiple episodes and saves:
- NPZ files with tracks and metadata
- MP4 videos showing tracked trajectories (using mediapy)
"""

import os
import numpy as np
from pathlib import Path
import argparse
import cv2
import sys

# Import torch first (needs GPU)
import torch
import mediapy as media
from tqdm import tqdm
import datetime
import re

# Import TensorFlow and configure it for CPU only to avoid conflicts
import tensorflow as tf
# Disable GPU for TensorFlow to leave it available for PyTorch/CoTracker
tf.config.set_visible_devices([], 'GPU')
import tensorflow_datasets as tfds

# Add parent directory to path
sys.path.append(str(Path(__file__).parent.parent))

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


def load_cotracker():
    """Load CoTracker v3 model."""
    from cotracker.predictor import CoTrackerPredictor

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = CoTrackerPredictor(checkpoint='/mnt/kevin/vlm_models/cotracker/scaled_offline.pth')
    model = model.to(device)
    model.eval()

    return model, device


def find_closest_calibration(episode, uuid_list, calib_loader):
    """Find closest calibration by timestamp."""
    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 = match.group(1)
        date = match.group(2)
        hour = match.group(3)
        minute = match.group(4)
        second = match.group(5)

        episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S")

        # Find matching calibrations
        matching_calibs = []
        for calib_uuid in uuid_list:
            if calib_uuid.startswith(f"{lab}+") and f"+{date}-" in calib_uuid:
                matching_calibs.append(calib_uuid)

        if len(matching_calibs) == 0:
            return None

        # Find closest by time
        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 Exception as e:
        return None


def process_episode(episode, episode_idx, uuid_list, calib_loader, projector, cotracker, device,
                    camera_view='exterior', max_frames=16, num_sample_points=300,
                    num_chunks=3):
    """
    Process single episode by chunking into multiple segments.

    Args:
        num_sample_points: Total number of points to track (default 300)
        num_chunks: Number of 16-frame chunks to process and concatenate (default 3)
                   Total frames = max_frames * num_chunks

    Returns:
        dict with 'success', 'uuid', 'tracks', 'visibility', 'frames', 'num_points'
        or None if failed
    """
    # Find calibration
    uuid = find_closest_calibration(episode, uuid_list, calib_loader)
    if uuid is None:
        return None

    # Load calibration
    try:
        dual_params = calib_loader.get_dual_view_params(uuid, param_type='refined', require_refined=False)
        if dual_params is None:
            return None

        if not calib_loader.has_refined_extrinsics(uuid):
            return None

    except Exception as e:
        return None

    # Collect frames - get enough for all chunks
    total_frames_needed = max_frames * num_chunks
    frames = []
    action_positions = []  # Use action xyz instead of cartesian_position

    for step_idx, step in enumerate(episode['steps']):
        if step_idx >= total_frames_needed:
            break

        action = step['action'].numpy()
        action_positions.append(action)

        if camera_view == 'exterior':
            img = step['observation']['exterior_image_1_left'].numpy()
        else:
            img = step['observation']['wrist_image_left'].numpy()

        if img is None or len(img.shape) != 3:
            return None

        # Keep original resolution
        frames.append(img)

    if len(frames) < 10:
        return None

    # Adjust num_chunks if we don't have enough frames
    actual_chunks = min(num_chunks, len(frames) // max_frames)
    if actual_chunks == 0:
        actual_chunks = 1

    # Get actual image dimensions from first frame
    img_h, img_w = frames[0].shape[:2]
    print(f"  Image resolution: {img_w}x{img_h}")

    # Get camera params
    if camera_view == 'exterior':
        K, E = dual_params['exterior_1']
    else:
        K, E = dual_params['wrist']

    # Project end-effector position from action[:3]
    action_pos_0 = action_positions[0]
    eef_pos_3d = action_pos_0[:3].reshape(1, 3)  # Just xyz from action

    eef_2d, eef_vis = projector._project_3d_to_2d(
        eef_pos_3d, K, E, img_h=img_h, img_w=img_w
    )

    # Use EEF as the single mesh point for verification
    mesh_2d = eef_2d
    mesh_vis = eef_vis

    visible_mesh = np.sum(mesh_vis)
    if visible_mesh < 1:  # Need at least the EEF visible
        return None

    # Get visible mesh points (just EEF)
    visible_mesh_2d = mesh_2d[mesh_vis]
    num_mesh = len(visible_mesh_2d)

    print(f"  Action xyz 3D: {eef_pos_3d[0]}")
    print(f"  Action projected 2D: {visible_mesh_2d[0] if len(visible_mesh_2d) > 0 else 'NOT VISIBLE'}")

    # Only track the single EEF point for debugging
    query_points = visible_mesh_2d  # Just the EEF
    num_points = len(query_points)

    # Track indices for visualization (everything is the EEF)
    num_random_actual = 0
    num_cluster = 0

    # Keep these variables for chunk processing
    points_per_mesh = 0  # Not used
    mesh_radius = 0  # Not used
    random_points = np.empty((0, 2))  # Empty

    # Process in chunks to avoid GPU OOM
    all_tracks = []
    all_visibility = []

    print(f"  Processing {actual_chunks} chunks of {max_frames} frames each...")

    for chunk_idx in range(actual_chunks):
        chunk_start = chunk_idx * max_frames
        chunk_end = min(chunk_start + max_frames, len(frames))
        chunk_frames = frames[chunk_start:chunk_end]

        if len(chunk_frames) < 4:  # Skip very short chunks
            continue

        # Get EEF position from action at the start of this chunk
        action_pos_chunk = action_positions[chunk_start]
        eef_pos_3d_chunk = action_pos_chunk[:3].reshape(1, 3)

        # Project EEF for this chunk
        eef_2d_chunk, eef_vis_chunk = projector._project_3d_to_2d(
            eef_pos_3d_chunk, K, E, img_h=img_h, img_w=img_w
        )

        if not eef_vis_chunk[0]:
            print(f"    Chunk {chunk_idx+1}: Action xyz not visible, skipping")
            continue

        print(f"    Chunk {chunk_idx+1}: Action xyz 3D={eef_pos_3d_chunk[0]}, 2D={eef_2d_chunk[0]}")

        # Only use the single EEF point for this chunk
        visible_mesh_2d_chunk = eef_2d_chunk[eef_vis_chunk]
        query_points_chunk = visible_mesh_2d_chunk  # Just the EEF point

        # Prepare chunk video
        chunk_video_np = np.array(chunk_frames)
        chunk_video_np = chunk_video_np.transpose(0, 3, 1, 2)
        chunk_video_tensor = torch.from_numpy(chunk_video_np).float() / 255.0
        chunk_video_tensor = chunk_video_tensor.unsqueeze(0).to(device)

        # Queries for this chunk using the updated EEF position
        queries = np.zeros((len(query_points_chunk), 3))
        queries[:, 0] = 0  # Start tracking from first frame of chunk
        queries[:, 1] = query_points_chunk[:, 0]
        queries[:, 2] = query_points_chunk[:, 1]
        queries_tensor = torch.from_numpy(queries).float().unsqueeze(0).to(device)

        # Run CoTracker on chunk
        with torch.no_grad():
            pred_tracks, pred_visibility = cotracker(
                chunk_video_tensor,
                queries=queries_tensor,
                backward_tracking=False
            )

        chunk_tracks = pred_tracks[0].cpu().numpy()  # [T_chunk, N, 2]
        chunk_visibility = pred_visibility[0].cpu().numpy()  # [T_chunk, N]

        all_tracks.append(chunk_tracks)
        all_visibility.append(chunk_visibility)

        print(f"    Chunk {chunk_idx+1}/{actual_chunks}: {chunk_tracks.shape[0]} frames")

    # Concatenate all chunks along time dimension
    tracks = np.concatenate(all_tracks, axis=0)  # [T_total, N, 2]
    visibility = np.concatenate(all_visibility, axis=0)  # [T_total, N]

    # Trim frames to match actual processed length
    frames = frames[:tracks.shape[0]]

    print(f"  Total concatenated frames: {tracks.shape[0]}")

    return {
        'success': True,
        'uuid': uuid,
        'tracks': tracks,
        'visibility': visibility,
        'frames': frames,
        'num_points': num_points,
        'visible_mesh': visible_mesh,
        'num_random': num_random_actual,
        'num_cluster': num_cluster,
        'num_mesh': num_mesh
    }


def visualize_tracks_on_frame(frame, tracks, visibility, frame_idx, num_points,
                             num_random, num_cluster, num_mesh, title=""):
    """
    Draw tracks on single frame.

    Point ordering: [random_points | cluster_points | mesh_vertices]
    """
    viz = frame.copy()

    # Define color scheme
    # Random: light gray trajectories, small blue dots
    # Cluster: light yellow trajectories, small yellow dots
    # Mesh: bright green trajectories, large green dots with labels

    for pt_idx in range(num_points):
        # Determine point type
        if pt_idx < num_random:
            traj_color = (180, 180, 180)  # Light gray
            point_color = (255, 100, 0)   # Blue
            point_size = 1
            is_mesh = False
        elif pt_idx < num_random + num_cluster:
            traj_color = (100, 200, 255)  # Light yellow
            point_color = (0, 200, 255)   # Yellow
            point_size = 2
            is_mesh = False
        else:
            traj_color = (100, 255, 100)  # Light green
            point_color = (0, 255, 0)     # Bright green
            point_size = 5
            is_mesh = True

        # Draw trajectory (past 10 frames)
        if frame_idx > 0:
            for t in range(max(0, frame_idx-10), frame_idx):
                if visibility[t, pt_idx] and visibility[t+1, pt_idx]:
                    pt1 = tuple(tracks[t, pt_idx].astype(int))
                    pt2 = tuple(tracks[t+1, pt_idx].astype(int))
                    cv2.line(viz, pt1, pt2, traj_color, 1)

        # Draw current point
        if visibility[frame_idx, pt_idx]:
            pt = tuple(tracks[frame_idx, pt_idx].astype(int))
            cv2.circle(viz, pt, point_size, point_color, -1)

            # Label mesh vertices
            if is_mesh:
                mesh_idx = pt_idx - num_random - num_cluster
                cv2.putText(viz, str(mesh_idx), (pt[0]+7, pt[1]-7),
                           cv2.FONT_HERSHEY_SIMPLEX, 0.4, point_color, 1)

    # Add title
    if title:
        cv2.putText(viz, title, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)

    visible_count = np.sum(visibility[frame_idx])
    cv2.putText(viz, f"Visible: {visible_count}/{num_points}", (10, 60),
               cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 1)

    return viz


def batch_process_episodes(droid_path: str,
                           calib_dir: str,
                           output_dir: str,
                           num_episodes: int = 10,
                           start_index: int = 0,
                           camera_view: str = 'exterior',
                           max_frames: int = 16,
                           num_sample_points: int = 300,
                           num_chunks: int = 3):
    """Batch process multiple episodes."""

    print("=" * 80)
    print("DROID Batch Processing: Mesh + CoTracker")
    print("=" * 80)
    print(f"  Episodes: {num_episodes} (starting from {start_index})")
    print(f"  Camera: {camera_view}")
    print(f"  Frames per chunk: {max_frames}")
    print(f"  Number of chunks: {num_chunks}")
    print(f"  Total frames per episode: {max_frames * num_chunks}")
    print(f"  Output: {output_dir}")
    print()

    # Create output directories
    output_path = Path(output_dir)
    npz_path = output_path / "npz"
    video_path = output_path / "videos"
    npz_path.mkdir(parents=True, exist_ok=True)
    video_path.mkdir(parents=True, exist_ok=True)

    # Initialize tools
    calib_loader = CameraCalibrationLoader(calib_dir)
    projector = FrankaMeshProjector(use_gui=False)
    cotracker, device = load_cotracker()

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

    # Load DROID dataset
    print("Loading DROID dataset...")
    builder = tfds.builder_from_directory(droid_path)
    dataset = builder.as_dataset(split='train')

    # Process episodes
    processed = 0
    skipped = 0

    pbar = tqdm(total=num_episodes, desc="Processing")

    for episode_idx, episode in enumerate(dataset):
        if episode_idx < start_index:
            continue

        if processed >= num_episodes:
            break

        try:
            result = process_episode(
                episode, episode_idx, uuid_list, calib_loader, projector,
                cotracker, device, camera_view, max_frames,
                num_sample_points=num_sample_points, num_chunks=num_chunks
            )

            if result is None:
                skipped += 1
                continue

            # Save NPZ
            npz_file = npz_path / f"episode_{processed:04d}.npz"
            np.savez_compressed(
                npz_file,
                tracks=result['tracks'],
                visibility=result['visibility'],
                uuid=result['uuid'],
                num_points=result['num_points'],
                visible_mesh=result['visible_mesh'],
                episode_index=episode_idx
            )

            # Create video with mediapy
            video_frames = []
            for frame_idx, frame in enumerate(result['frames']):
                viz = visualize_tracks_on_frame(
                    frame,
                    result['tracks'],
                    result['visibility'],
                    frame_idx,
                    result['num_points'],
                    result['num_random'],
                    result['num_cluster'],
                    result['num_mesh'],
                    title=f"Episode {processed} | Frame {frame_idx}/{len(result['frames'])}"
                )
                video_frames.append(viz)

            video_file = video_path / f"episode_{processed:04d}.mp4"
            media.write_video(str(video_file), video_frames, fps=10)

            processed += 1
            pbar.update(1)

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

    pbar.close()

    print("\n" + "=" * 80)
    print("Batch Processing Complete")
    print("=" * 80)
    print(f"  Processed: {processed} episodes")
    print(f"  Skipped: {skipped} episodes")
    print(f"  NPZ files: {npz_path}")
    print(f"  Videos: {video_path}")
    print("=" * 80)


def main():
    parser = argparse.ArgumentParser(description="Batch process DROID episodes with CoTracker")

    parser.add_argument('--droid-path', type=str,
                       default='/mnt/kevin/data/droid/droid/1.0.0',
                       help='Path to DROID RLDS dataset')
    parser.add_argument('--calib-dir', type=str,
                       default='/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras',
                       help='Path to camera calibration directory')
    parser.add_argument('--output-dir', type=str,
                       default='/tmp/droid_batch_cotracker',
                       help='Output directory')
    parser.add_argument('--num-episodes', type=int, default=10,
                       help='Number of episodes to process')
    parser.add_argument('--start-index', type=int, default=0,
                       help='Starting episode index')
    parser.add_argument('--camera', type=str, default='exterior',
                       choices=['exterior', 'wrist'],
                       help='Camera view')
    parser.add_argument('--max-frames', type=int, default=16,
                       help='Frames per chunk (to avoid GPU OOM)')
    parser.add_argument('--num-chunks', type=int, default=3,
                       help='Number of chunks to process and concatenate')
    parser.add_argument('--num-points', type=int, default=300,
                       help='Total number of points to track')

    args = parser.parse_args()

    batch_process_episodes(
        args.droid_path,
        args.calib_dir,
        args.output_dir,
        args.num_episodes,
        args.start_index,
        args.camera,
        args.max_frames,
        args.num_points,
        args.num_chunks
    )


if __name__ == "__main__":
    main()