File size: 9,454 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
#!/usr/bin/env python3
"""
Process a specific chunk of DROID episodes.
Reads chunk file with episode indices and processes only those episodes.
"""

import json
from pathlib import Path
import tensorflow_datasets as tfds
from tqdm import tqdm
import torch
import numpy as np
import cv2
from droid.calibration.calibration_loader import CalibrationLoader
from droid.misc.projector import Projector

# Import preprocessing functions from the main script
import sys
sys.path.insert(0, str(Path(__file__).parent))

# Copy necessary functions
def find_closest_calibration(episode, uuid_list):
    """Find closest calibration UUID by timestamp."""
    ts = float(episode['episode_metadata']['recording_timestamp'].numpy())
    closest_uuid = None
    min_diff = float('inf')
    for uuid, calib_ts in uuid_list:
        diff = abs(ts - calib_ts)
        if diff < min_diff:
            min_diff = diff
            closest_uuid = uuid
    return closest_uuid

def sample_arm_shaped_points(mesh_2d_visible, img_h, img_w, num_points=993, seed=0):
    """Sample points in arm-shaped region excluding mesh vertices."""
    np.random.seed(seed)
    u_coords = []
    v_coords = []

    mesh_u = mesh_2d_visible[:, 0]
    mesh_v = mesh_2d_visible[:, 1]

    u_min = max(0, int(mesh_u.min()) - 50)
    u_max = min(img_w, int(mesh_u.max()) + 50)
    v_min = max(0, int(mesh_v.min()) - 50)
    v_max = min(img_h, int(mesh_v.max()) + 50)

    attempts = 0
    max_attempts = num_points * 100

    while len(u_coords) < num_points and attempts < max_attempts:
        u = np.random.randint(u_min, u_max)
        v = np.random.randint(v_min, v_max)

        # Check distance from mesh vertices
        dists = np.sqrt((mesh_u - u)**2 + (mesh_v - v)**2)
        if dists.min() > 10:
            u_coords.append(u)
            v_coords.append(v)

        attempts += 1

    if len(u_coords) < num_points:
        remaining = num_points - len(u_coords)
        u_coords.extend([img_w // 2] * remaining)
        v_coords.extend([img_h // 2] * remaining)

    return np.array(u_coords), np.array(v_coords)

def sample_wrist_points(img_h, img_w, num_sparse=300, num_dense=700, seed=0):
    """Sample wrist camera points with dense sampling in bottom region."""
    np.random.seed(seed)

    # Sparse uniform sampling
    u_sparse = np.random.randint(0, img_w, num_sparse)
    v_sparse = np.random.randint(0, img_h, num_sparse)

    # Dense sampling in bottom 60%-100%
    v_min_dense = int(img_h * 0.6)
    u_dense = np.random.randint(0, img_w, num_dense)
    v_dense = np.random.randint(v_min_dense, img_h, num_dense)

    u_all = np.concatenate([u_sparse, u_dense])
    v_all = np.concatenate([v_sparse, v_dense])

    return u_all, v_all

def load_cotracker():
    """Load CoTracker v3 offline model."""
    from cotracker.predictor import CoTrackerPredictor
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    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()
    return cotracker, device

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

    # ... [Copy full function from preprocess_droid_rlds_final.py]
    # I'll use the existing implementation
    from preprocess_droid_rlds_final import process_episode as original_process_episode
    return original_process_episode(
        episode, episode_idx, uuid, calib_loader, projector, cotracker, device,
        max_frames, save_preview, output_dir
    )

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--chunk-file', type=str, required=True,
                        help='Chunk JSON file with episode indices to process')
    parser.add_argument('--output-dir', type=str, default='/mnt/kevin/data/droid_processed_1000pts',
                        help='Output directory')
    parser.add_argument('--max-frames', type=int, default=400,
                        help='Max frames per episode')
    parser.add_argument('--save-previews', type=int, default=3,
                        help='Number of preview videos to save')
    parser.add_argument('--chunk-id', type=int, default=None,
                        help='Chunk ID for logging')
    args = parser.parse_args()

    # Load chunk data
    with open(args.chunk_file) as f:
        chunk_data = json.load(f)

    chunk_id = chunk_data['chunk_id'] if args.chunk_id is None else args.chunk_id
    episode_indices_set = set(chunk_data['episode_indices'])

    label = f"Chunk {chunk_id}"

    print("="*80)
    print(f"DROID Preprocessing: {label}")
    print("="*80)
    print(f"  Chunk file: {args.chunk_file}")
    print(f"  Episodes to process: {len(episode_indices_set)}")
    print(f"  Output: {args.output_dir}")
    print("="*80)

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

    # Load CoTracker
    cotracker, device = load_cotracker()

    # Load camera calibrations
    calib_loader = CalibrationLoader()
    uuid_list = [(uuid, calib_loader.get_timestamp(uuid))
                 for uuid in calib_loader.list_calibrations()]
    print(f"Loaded {len(uuid_list)} camera calibrations")

    # Setup projector
    projector = Projector()

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

    # Process only episodes in chunk
    processed_count = 0
    skipped_count = 0
    preview_count = 0

    pbar = tqdm(total=len(episode_indices_set), desc=label)

    for episode_idx, episode in enumerate(dataset):
        # Skip episodes not in this chunk
        if episode_idx not in episode_indices_set:
            continue

        # Check if already processed
        npz_path = data_dir / f"episode_{episode_idx:06d}.npz"
        if npz_path.exists():
            processed_count += 1
            pbar.update(1)
            continue

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

        # Process episode
        try:
            save_preview = (preview_count < args.save_previews)

            result = process_episode(
                episode, episode_idx, uuid, calib_loader, projector,
                cotracker, device, args.max_frames, save_preview, output_dir
            )

            if result is not None:
                # Save as NPZ
                np.savez_compressed(
                    npz_path,
                    episode_idx=result['episode_idx'],
                    tracked_points_exterior=result['tracks_exterior'],
                    tracked_points_wrist=result['tracks_wrist'],
                    tracks_vis_exterior=result['tracks_vis_exterior'],
                    tracks_vis_wrist=result['tracks_vis_wrist'],
                    images_exterior=result['images_exterior'],
                    images_wrist=result['images_wrist'],
                    actions=result['actions'],
                    uuid=uuid
                )
                processed_count += 1

                if save_preview:
                    preview_count += 1
            else:
                skipped_count += 1

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

        pbar.update(1)

        # Early exit if all episodes processed
        if processed_count + skipped_count >= len(chunk_data['episode_indices']):
            break

    pbar.close()

    # Save metadata
    metadata = {
        'chunk_id': chunk_id,
        'chunk_file': str(args.chunk_file),
        'processed': processed_count,
        'skipped': skipped_count,
        'total': len(chunk_data['episode_indices'])
    }

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

    print("\n" + "="*80)
    print("Preprocessing Complete")
    print("="*80)
    print(f"  Processed: {processed_count} episodes")
    print(f"  Skipped: {skipped_count} episodes")
    print(f"  Preview videos: {preview_dir}")
    print(f"  NPZ data: {data_dir}")
    print(f"  Metadata: {metadata_path}")
    print("="*80)

if __name__ == '__main__':
    main()