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
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
"""
Test Preprocessing with Visualizations

Quick test of DROID preprocessing pipeline with visual output:
- Processes small number of episodes (5-10)
- Uses cartesian_position + refined_extrinsics filtering
- Generates visualization images showing projected tracks
- Saves NPZ files for inspection
"""

import numpy as np
import tensorflow_datasets as tfds
from pathlib import Path
import argparse
import cv2
import sys
from tqdm import tqdm
import os

# Force TensorFlow to use CPU to avoid GPU memory issues
os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'

# 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 visualize_tracks(img: np.ndarray,
                    tracks: np.ndarray,
                    visibility: np.ndarray,
                    title: str = "") -> np.ndarray:
    """
    Visualize 32 tracks on image.

    Args:
        img: RGB image (H, W, 3)
        tracks: Track points (32, 2)
        visibility: Visibility mask (32,)
        title: Title for image

    Returns:
        Annotated image
    """
    viz = img.copy()

    # Draw grid points (0-24) in blue
    for i in range(25):
        if visibility[i]:
            pt = tuple(tracks[i].astype(int))
            cv2.circle(viz, pt, 4, (0, 0, 255), -1)

    # Draw mesh points (25-31) in green
    for i in range(25, 32):
        if visibility[i]:
            pt = tuple(tracks[i].astype(int))
            cv2.circle(viz, pt, 5, (0, 255, 0), -1)
            cv2.putText(viz, str(i-25), (pt[0]+7, pt[1]-7),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0), 1)

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

    # Add statistics
    visible_grid = np.sum(visibility[:25])
    visible_mesh = np.sum(visibility[25:])
    cv2.putText(viz, f"Grid: {visible_grid}/25  Mesh: {visible_mesh}/7", (10, 60),
               cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 1)

    return viz


def test_preprocessing(droid_path: str,
                      calib_dir: str,
                      output_dir: str,
                      num_episodes: int = 5,
                      use_cartesian: bool = True,
                      require_refined: bool = True):
    """
    Test preprocessing with visualizations.

    Args:
        droid_path: Path to DROID RLDS dataset
        calib_dir: Path to camera calibration directory
        output_dir: Output directory for test results
        num_episodes: Number of episodes to process
        use_cartesian: Use cartesian_position (vs FK)
        require_refined: Require refined_extrinsics
    """
    print("=" * 80)
    print("DROID Preprocessing Test with Visualizations")
    print("=" * 80)
    print(f"  Output: {output_dir}")
    print(f"  Episodes: {num_episodes}")
    print(f"  Projection: {'cartesian_position' if use_cartesian else 'joint_position (FK)'}")
    print(f"  Require refined: {require_refined}")
    print()

    # Create output directories
    output_path = Path(output_dir)
    npz_path = output_path / "npz_files"
    viz_path = output_path / "visualizations"
    npz_path.mkdir(parents=True, exist_ok=True)
    viz_path.mkdir(parents=True, exist_ok=True)

    # Initialize tools
    calib_loader = CameraCalibrationLoader(calib_dir)
    projector = FrankaMeshProjector(use_gui=False)

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

    # Get list of all calibration files for UUID matching
    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"Found {len(uuid_list)} camera calibration files")

    # Filter to refined only
    if require_refined:
        refined_uuids = [uuid for uuid in uuid_list if calib_loader.has_refined_extrinsics(uuid)]
        print(f"  {len(refined_uuids)}/{len(uuid_list)} have refined_extrinsics ({100*len(refined_uuids)/len(uuid_list):.1f}%)")
        uuid_list = refined_uuids

    # Process episodes
    processed = 0
    skipped = 0
    skipped_reasons = {
        'no_uuid': 0,
        'no_calib': 0,
        'decode_error': 0,
        'other': 0
    }

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

    for episode_idx, episode in enumerate(dataset):
        if processed >= num_episodes:
            break

        try:
            # Try to match UUID first (before loading steps)
            uuid = uuid_list[episode_idx % len(uuid_list)]

            # Load calibration
            try:
                dual_params = calib_loader.get_dual_view_params(
                    uuid,
                    param_type='refined',
                    require_refined=require_refined
                )

                if dual_params is None:
                    skipped += 1
                    skipped_reasons['no_calib'] += 1
                    continue

            except Exception as e:
                skipped += 1
                skipped_reasons['no_calib'] += 1
                continue

            # IMPORTANT: Don't call list() on episode['steps'] - iterate directly
            # This avoids loading entire episode into memory
            all_tracks_ext = []
            all_tracks_wrist = []
            all_vis_ext = []
            all_vis_wrist = []
            all_images_ext = []
            all_images_wrist = []

            decode_failed = False
            step_count = 0
            max_steps_per_episode = 30  # Limit to 30 steps for testing

            # Iterate steps incrementally without loading all at once
            for step_idx, step in enumerate(episode['steps']):
                # Limit steps per episode
                if step_idx >= max_steps_per_episode:
                    break

                step_count += 1
                # Get robot state
                if use_cartesian:
                    cart_pos = step['observation']['cartesian_position'].numpy()
                else:
                    joint_pos = step['observation']['joint_position'].numpy()

                # Load images
                img_ext_bytes = step['observation']['exterior_image_1_left'].numpy()
                img_ext = cv2.imdecode(np.frombuffer(img_ext_bytes, dtype=np.uint8), cv2.IMREAD_COLOR)

                img_wrist_bytes = step['observation']['wrist_image_left'].numpy()
                img_wrist = cv2.imdecode(np.frombuffer(img_wrist_bytes, dtype=np.uint8), cv2.IMREAD_COLOR)

                if img_ext is None or img_wrist is None:
                    decode_failed = True
                    break

                # Resize and convert
                img_ext = cv2.resize(img_ext, (448, 448))
                img_ext = cv2.cvtColor(img_ext, cv2.COLOR_BGR2RGB)
                all_images_ext.append(img_ext)

                img_wrist = cv2.resize(img_wrist, (448, 448))
                img_wrist = cv2.cvtColor(img_wrist, cv2.COLOR_BGR2RGB)
                all_images_wrist.append(img_wrist)

                # Project tracks
                K_ext, E_ext = dual_params['exterior_1']
                K_wrist, E_wrist = dual_params['wrist']

                if use_cartesian:
                    tracks_ext, vis_ext = projector.project_32_points_cartesian(
                        cart_pos, K_ext, E_ext, img_h=448, img_w=448, rotation_format='euler_xyz'
                    )
                    tracks_wrist, vis_wrist = projector.project_32_points_cartesian(
                        cart_pos, K_wrist, E_wrist, img_h=448, img_w=448, rotation_format='euler_xyz'
                    )
                else:
                    tracks_ext, vis_ext = projector.project_32_points(
                        joint_pos, K_ext, E_ext, img_h=448, img_w=448
                    )
                    tracks_wrist, vis_wrist = projector.project_32_points(
                        joint_pos, K_wrist, E_wrist, img_h=448, img_w=448
                    )

                all_tracks_ext.append(tracks_ext)
                all_tracks_wrist.append(tracks_wrist)
                all_vis_ext.append(vis_ext)
                all_vis_wrist.append(vis_wrist)

                # Create visualizations for first, middle, and last frames
                viz_indices = [0, max_steps_per_episode//2, max_steps_per_episode-1]
                if step_idx in viz_indices:
                    viz_ext = visualize_tracks(
                        img_ext,
                        tracks_ext,
                        vis_ext,
                        title=f"Episode {processed} | Frame {step_idx} | Exterior"
                    )
                    viz_wrist = visualize_tracks(
                        img_wrist,
                        tracks_wrist,
                        vis_wrist,
                        title=f"Episode {processed} | Frame {step_idx} | Wrist"
                    )

                    # Save visualizations
                    cv2.imwrite(
                        str(viz_path / f"ep{processed:03d}_frame{step_idx:04d}_exterior.jpg"),
                        cv2.cvtColor(viz_ext, cv2.COLOR_RGB2BGR)
                    )
                    cv2.imwrite(
                        str(viz_path / f"ep{processed:03d}_frame{step_idx:04d}_wrist.jpg"),
                        cv2.cvtColor(viz_wrist, cv2.COLOR_RGB2BGR)
                    )

            if decode_failed:
                skipped += 1
                skipped_reasons['decode_error'] += 1
                continue

            # Skip if too few steps
            if step_count < 10:
                skipped += 1
                skipped_reasons['other'] += 1
                continue

            # Convert to arrays
            tracks_ext = np.array(all_tracks_ext)
            tracks_wrist = np.array(all_tracks_wrist)
            vis_ext = np.array(all_vis_ext)
            vis_wrist = np.array(all_vis_wrist)
            images_ext = np.array(all_images_ext)
            images_wrist = np.array(all_images_wrist)

            # Get language instruction from first stored step
            language = "unknown"  # Default if not available

            # Save NPZ
            npz_file = npz_path / f"episode_{processed:03d}.npz"
            np.savez_compressed(
                npz_file,
                tracks_exterior=tracks_ext,
                tracks_wrist=tracks_wrist,
                vis_exterior=vis_ext,
                vis_wrist=vis_wrist,
                images_exterior=images_ext,
                images_wrist=images_wrist,
                language=language,
                uuid=uuid,
                num_steps=step_count
            )

            processed += 1
            pbar.update(1)

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

    pbar.close()

    # Print summary
    print("\n" + "=" * 80)
    print("Test Preprocessing Complete")
    print("=" * 80)
    print(f"  Processed: {processed} episodes")
    print(f"  Skipped: {skipped} episodes")
    print(f"    No calibration: {skipped_reasons['no_calib']}")
    print(f"    Decode error: {skipped_reasons['decode_error']}")
    print(f"    Other: {skipped_reasons['other']}")
    print()
    print(f"  NPZ files: {npz_path}")
    print(f"  Visualizations: {viz_path}")
    print(f"    ({processed * 6} images generated)")
    print("=" * 80)

    # Create montage of first episode visualizations
    if processed > 0:
        print("\nCreating summary montage...")
        montage_images = []

        # Look for existing visualization files for first episode
        viz_files = sorted(viz_path.glob("ep000_frame*_exterior.jpg"))

        for ext_file in viz_files[:3]:  # Take up to 3 frames
            wrist_file = ext_file.parent / ext_file.name.replace('_exterior.jpg', '_wrist.jpg')

            if ext_file.exists() and wrist_file.exists():
                img_ext = cv2.imread(str(ext_file))
                img_wrist = cv2.imread(str(wrist_file))
                if img_ext is not None and img_wrist is not None:
                    montage_images.append(np.hstack([img_ext, img_wrist]))

        if montage_images:
            montage = np.vstack(montage_images)
            montage_file = viz_path / "summary_montage.jpg"
            cv2.imwrite(str(montage_file), montage)
            print(f"  ✓ Saved summary montage: {montage_file}")


def main():
    parser = argparse.ArgumentParser(
        description="Test DROID preprocessing with visualizations"
    )

    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_preprocessing_test',
        help='Output directory for test results'
    )
    parser.add_argument(
        '--num-episodes',
        type=int,
        default=5,
        help='Number of episodes to process'
    )
    parser.add_argument(
        '--use-cartesian',
        action='store_true',
        default=True,
        help='Use cartesian_position (default: True)'
    )
    parser.add_argument(
        '--use-joints',
        dest='use_cartesian',
        action='store_false',
        help='Use joint_position with FK'
    )
    parser.add_argument(
        '--require-refined',
        action='store_true',
        default=True,
        help='Require refined_extrinsics (default: True)'
    )
    parser.add_argument(
        '--no-require-refined',
        dest='require_refined',
        action='store_false',
        help='Allow measured extrinsics'
    )

    args = parser.parse_args()

    test_preprocessing(
        args.droid_path,
        args.calib_dir,
        args.output_dir,
        args.num_episodes,
        args.use_cartesian,
        args.require_refined
    )


if __name__ == "__main__":
    main()