File size: 31,584 Bytes
6cf2c86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
import copy
import os
import re
import torch, os, imageio, argparse, imageio_ffmpeg
from torchvision.transforms import v2
from einops import rearrange
import lightning as pl
import pandas as pd
from diffsynth import WanVideoPipeline, ModelManager, load_state_dict
import torchvision
from PIL import Image
import numpy as np
import random
import json
import torch.nn as nn
import torch.nn.functional as F
import shutil
import open3d as o3d
import h5py
import cv2
import math

from robotwin_utils import get_instructions_rlbench, rgbd_to_pointcloud, image_to_float_array, sample_frame_indices, find_rlbench_data

def quaternion_to_matrix(quaternions: torch.Tensor) -> torch.Tensor:
    """
    Convert rotations given as quaternions to rotation matrices.

    Args:
        quaternions: quaternions with real part first,
            as tensor of shape (..., 4).

    Returns:
        Rotation matrices as tensor of shape (..., 3, 3).
    """
    r, i, j, k = torch.unbind(quaternions, -1)
    # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
    two_s = 2.0 / (quaternions * quaternions).sum(-1)

    o = torch.stack(
        (
            1 - two_s * (j * j + k * k),
            two_s * (i * j - k * r),
            two_s * (i * k + j * r),
            two_s * (i * j + k * r),
            1 - two_s * (i * i + k * k),
            two_s * (j * k - i * r),
            two_s * (i * k - j * r),
            two_s * (j * k + i * r),
            1 - two_s * (i * i + j * j),
        ),
        -1,
    )
    return o.reshape(quaternions.shape[:-1] + (3, 3))


def matrix_to_rotation_6d(matrix: torch.Tensor) -> torch.Tensor:
    """
    Converts rotation matrices to 6D rotation representation by Zhou et al. [1]
    by dropping the last row. Note that 6D representation is not unique.
    Args:
        matrix: batch of rotation matrices of size (*, 3, 3)

    Returns:
        6D rotation representation, of size (*, 6)

    [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H.
    On the Continuity of Rotation Representations in Neural Networks.
    IEEE Conference on Computer Vision and Pattern Recognition, 2019.
    Retrieved from http://arxiv.org/abs/1812.07035
    """
    batch_dim = matrix.size()[:-2]
    return matrix[..., :2, :].clone().reshape(batch_dim + (6,))

class RLBenchTextVideoDataset(torch.utils.data.Dataset):
    def __init__(self, base_path, metadata_path, max_num_frames=81, frame_interval=1, num_frames=81, height=240, width=320, is_i2v=False):
        # metadata = pd.read_csv(metadata_path)
        # self.path = [os.path.join(base_path, "train", file_name) for file_name in metadata["file_name"]]
        # self.text = metadata["text"].to_list()
        self.base_path = base_path

        self.data_list = find_rlbench_data(base_path)
        
        self.max_num_frames = max_num_frames
        self.frame_interval = frame_interval
        self.num_frames = num_frames
        self.height = height
        self.width = width
        self.is_i2v = is_i2v
            
        self.frame_process = v2.Compose([
            # v2.CenterCrop(size=(height, width)),
            # v2.Resize(size=(height, width), antialias=True),
            v2.ToTensor(),
            v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
        ])
        
    def _task_name(self, data_path: str) -> str:
        rel = os.path.relpath(data_path, self.base_path)
        return rel.split(os.sep)[0]

    def get_task_name(self, index: int) -> str:
        return self._task_name(self.data_list[index]["data_path"])


    def __getitem__(self, data_id):
        data_dict = self.data_list[data_id]
        instructions_file_path = data_dict["instructions_path"]
        instructions_list = get_instructions_rlbench(instructions_file_path)
        text = instructions_list[0]
        # video_path = os.path.join(data_dict["data_path"], data_dict["episode_name"])
        # text = self.text[data_id]
        # path = self.data_list[data_id]
        # print(1)
        # metadata = pd.read_json(os.path.join(data_dict["data_path"], f"{data_dict['episode_name']}.json"))
        
        out_dict=dict()
        out_dict["cache_path"] = data_dict["cache_path"]
        out_dict["text"] = text
        out_dict["cam"] = dict()

        scene_data = np.load(data_dict["scene_data_path"], allow_pickle=True).items()

        # for key, value in scene_data:
        #     print(f"scene_data key: {key}, value type: {type(value)}")
        # scene_data key: left_shoulder_camera, value type: <class 'numpy.ndarray'>
        # scene_data key: right_shoulder_camera, value type: <class 'numpy.ndarray'>
        # scene_data key: front_camera, value type: <class 'numpy.ndarray'>
        # scene_data key: wrist_camera, value type: <class 'numpy.ndarray'>
        # scene_data key: overhead_camera, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_0, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_1, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_2, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_3, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_4, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_5, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_6, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_7, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_8, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_9, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_10, value type: <class 'numpy.ndarray'>
        # scene_data key: cam_11, value type: <class 'numpy.ndarray'>

        # print(f"cache_path: {out_dict['cache_path']}, text: {text}")
        # print(f"scene_data keys: {scene_data}")

        # assert 0

        # num_frames = int(metadata[list(metadata.keys())[0]]["num_frames"])
        # index_list = sample_frame_indices(num_frames, self.num_frames)
        # index_list= np.arange(0, self.num_frames, self.frame_interval)
        # index_list = list(range(0, self.num_frames, self.frame_interval))
        
        jointdata = np.load(data_dict["jointdata_path"], allow_pickle=True)
        # for key, value in jointdata:
        #     print(f"jointdata key: {key}, value type: {type(value)}")
        # jointdata key: random_seed, value type: <class 'numpy.ndarray'>
        # jointdata key: num_reset_attempts, value type: <class 'numpy.ndarray'>
        # jointdata key: observations, value type: <class 'numpy.ndarray'>
        # assert 0
        joint_action = jointdata["observations"].item()
        # joint_action keys: dict_keys(['vector', 'joint_velocities', 'joint_positions', 'joint_forces', 'gripper_pose', 'gripper_joint_positions', 'gripper_touch_forces', 'task_low_dim_state'])

        # print(joint_action)
        # print(f"joint_action keys: {joint_action.keys()}")

        # left_arm = np.stack(joint_action["left_arm"], axis=0).astype(np.float32)
        # left_gripper = np.stack(joint_action["left_gripper"], axis=0).astype(np.float32)[..., None]
        # right_arm = np.stack(joint_action["right_arm"], axis=0).astype(np.float32)
        # right_gripper = np.stack(joint_action["right_gripper"], axis=0).astype(np.float32)[..., None]
        # action = np.concatenate([left_arm, left_gripper, right_arm, right_gripper], axis=-1)

        endpose7d = joint_action["gripper_pose"] # xyz quaternion
        gripper_open = joint_action["gripper_open"] # 0 1
        # gripper_joint_positions = joint_action["gripper_joint_positions"]

        xyz = endpose7d[..., :3]
        quaternion = endpose7d[..., 3:]

        matrix = quaternion_to_matrix(torch.from_numpy(quaternion).float())  # N x 3 x 3
        rotation_6d = matrix_to_rotation_6d(matrix).numpy()  # N x 6

        action = np.concatenate([xyz, rotation_6d, gripper_open[..., None]], axis=-1).astype(np.float32)

        num_frames = action.shape[0]
        index_list= sample_frame_indices(num_frames, self.num_frames)

        # print(f"joint_positions shape: {np.array(joint_positions).shape}") # joint_positions shape: (58, 7)
        # print(f"gripper_positions shape: {np.array(gripper_positions).shape}") # gripper_positions shape: (58, 2)
        # print(f"gripper_joint_positions shape: {np.array(gripper_joint_positions).shape}") # gripper_joint_positions shape: (58, 2)
        
        # print(f"joint_positions[30:35]: {joint_positions[30:35]}")
        # print(f"gripper_positions[30:35]: {gripper_positions[30:35]}")
        # print(f"gripper_joint_positions[30:35]: {gripper_joint_positions[30:35]}")

        # assert 0

        action = action[index_list]
        out_dict["action"] = action

        for cam_name, cam_data in scene_data:
            # print(f"cam_name: {cam_name}, cam_data type: {type(cam_data)}")
            if not cam_name.startswith("cam_"):
                continue

            # print(f"Processing camera: {cam_name}")
            # print(f"Camera data keys: {cam_data}")

            # Camera data keys: {'intrinsics': array([[-439.596401,    0.      ,  120.      ],
            # [   0.      , -439.596401,  160.      ],
            # [   0.      ,    0.      ,    1.      ]]), 'near_plane': 0.009999999776482582, 'far_plane': 3.200000047683716, 'extrinsics': array([[ 1.73648179e-01,  8.92538846e-01,  4.16198105e-01,
            #     -1.74999714e-01],
            # [ 9.84807789e-01, -1.57378674e-01, -7.33871460e-02,
            #     2.00000003e-01],
            # [-1.78813934e-07,  4.22618657e-01, -9.06307697e-01,
            #     1.97999895e+00],
            # [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
            #     1.00000000e+00]])}

            # assert 0
            # if cam_name == "surround_camera_11":

            cam_data = cam_data.item()

            far_plane = cam_data['far_plane']
            near_plane = cam_data['near_plane']

            intrinsic_cv = np.array(cam_data["intrinsics"]).reshape(3, 3)
            intrinsic_cv = np.abs(intrinsic_cv)
            extrinsic_cv = np.eye(4, dtype=np.float64)
            extrinsic_cv[:3,:] = np.array(cam_data["extrinsics"])[:3,:]

            C = np.expand_dims(extrinsic_cv[:3, 3], 0).T
            R = extrinsic_cv[:3, :3]
            R_inv = R.T  # inverse of rot matrix is transpose

            tf = np.array([[-1,0,0],
                           [0,-1,0],
                           [0,0,1]], dtype=np.float64)

            R_inv_C = np.matmul(R_inv, C)

            extrinsic_cv[:3,:] = tf @ np.concatenate((R_inv, -R_inv_C), -1)[:3,:]
            # print(f"Original extrinsic: {extrinsic_cv}")
            # print(f"extrinsic.shape: {extrinsic_cv.shape}")
            # rotate 90 degrees around y
            # tf0 = np.array([[0, 0, 1, 0],
            #     [0, 1, 0, 0],
            #     [-1, 0, 0, 0],
            #     [0, 0, 0, 1]], dtype=np.float64)

            # tf = np.array([[-1, 0, 0, 0],
            #     [0, -1, 0, 0],
            #     [0, 0, 1, 0],
            #     [0, 0, 0, 1]], dtype=np.float64)

            # extrinsic_cv = np.linalg.inv(extrinsic_cv)
            # extrinsic_cv = tf @ extrinsic_cv

            # extrinsic_cv[:3, :3] = tf[:3, :3] @ extrinsic_cv[:3, :3]
            # extrinsic_cv[:3, 3] = -extrinsic_cv[:3, 3]

            # opengl to opencv
            # extrinsic_cv[3, :2] *= -1
            # extrinsic_cv[1:3, :] *= -1
            
            # extrinsic_cv = extrinsic_cv
            
            rgb_mp4_path = os.path.join(data_dict["data_path"], f"cam_rgb_{cam_name.split('_')[-1]}.mp4")
            depth_mp4_path = os.path.join(data_dict["data_path"], f"cam_depth_{cam_name.split('_')[-1]}.mp4")
            
            if not os.path.exists(rgb_mp4_path) or not os.path.exists(depth_mp4_path):
                print(f"RGBD video path {rgb_mp4_path} or {depth_mp4_path} does not exist, skip.")
                raise FileNotFoundError(f"RGBD video path {rgb_mp4_path} or {depth_mp4_path} does not exist, skip.")
            
            # import time
            # start_time = time.time()

            # input_params = [
            #     "-hwaccel", "cuvid",
            #     "-c:v", "h264_cuvid"
            # ]
            input_params = []
            # rgb_reader = imageio.get_reader(rgb_mp4_path, 'ffmpeg')
            rgb_reader = imageio_ffmpeg.read_frames(rgb_mp4_path, input_params=input_params)
            # depth_reader = imageio.get_reader(depth_mp4_path, 'ffmpeg')
            depth_reader = imageio_ffmpeg.read_frames(depth_mp4_path, input_params=input_params)

            rgb_frames = np.zeros((self.num_frames, self.height, self.width, 3), dtype=np.float32)
            depth_frames = np.zeros((self.num_frames, self.height, self.width, 3), dtype=np.float32)

            rgb_meta, depth_meta = next(rgb_reader), next(depth_reader)
            # print(rgb_meta, depth_meta) # {'ffmpeg_version': '7.0.2-static https://johnvansickle.com/ffmpeg/ built with gcc 8 (Debian 8.3.0-6)', 'codec': 'h264', 'pix_fmt': 'yuv420p(progressive)', 'fps': 30.0, 'source_size': (832, 480), 'size': (832, 480), 'rotate': 0, 'duration': 4.73}
            rgb_size = (rgb_meta["size"][1], rgb_meta["size"][0], 3)
            depth_size = (depth_meta["size"][1], depth_meta["size"][0], 3)

            assert rgb_size == (self.height, self.width, 3), f"RGB size {rgb_size} does not match expected size {(self.height, self.width, 3)}"
            assert depth_size == (self.height, self.width, 3), f"Depth size {depth_size} does not match expected size {(self.height, self.width, 3)}"

            for rgb_frame, depth_frame, i in zip(rgb_reader, depth_reader, range(num_frames)):
                # read frame from the generator
                # print(rgb_frame)
                if i in index_list:
                    select_idx = index_list.index(i)
                    rgb_frames[select_idx] = np.frombuffer(rgb_frame, dtype=np.uint8).reshape(rgb_size)
                    depth_frames[select_idx] = np.frombuffer(depth_frame, dtype=np.uint8).reshape(depth_size)
            # end_time = time.time()
            # print(f"Reading frames time: {end_time - start_time:.5f}s")

            rgb_first_frame = rgb_frames[0].copy().astype(np.uint8) # H W C
            rgb_frames = torch.from_numpy(rgb_frames).float().permute(0, 3, 1, 2)  # T H W C -> T C H W
            rgb_frames /= 255.0
            rgb_frames = self.frame_process(rgb_frames)  # Normalize
            rgb_frames = rgb_frames.permute(1, 0, 2, 3)  # T C H W -> C T H W
            depth_frames = image_to_float_array(depth_frames, scale_factor=256000.0)
            depth_frames = near_plane + depth_frames * (far_plane - near_plane)
            # depth_frames = torch.from_numpy(depth_frames).unsqueeze(0)  # T H W -> 1 T H W
            depth_frames = np.expand_dims(depth_frames, axis=0)  # T H W -> 1 T H W
            # print(f"depth min , max before clipping: {depth_frames.min()}, {depth_frames.max()}")
            
            # break
            cam_dict = dict()
            cam_dict["intrinsic"] = intrinsic_cv
            cam_dict["extrinsic"] = extrinsic_cv
            # print(f"Camera {cam_name} extrinsic: {extrinsic_cv}")

            ## used to load original rgb and depth when testing ## 
            cam_dict["rgb_mp4_path"] = rgb_mp4_path
            cam_dict["depth_mp4_path"] = depth_mp4_path
            cam_dict["num_frames"] = int(self.num_frames)
            cam_dict["frame_interval"] = int(self.frame_interval)

            # print(f"cam {cam_name} depth min {depth_frames.min()}, max {depth_frames.max()}")

            cam_dict["rgb"] = rgb_frames
            cam_dict["rgb_first_frame"] = rgb_first_frame
            cam_dict["depth"] = depth_frames # [1, 81, 480, 832]
            # print(type(depth_frames), depth_frames.shape, depth_frames.min(), depth_frames.max())
            # assert 0
            
            out_dict["cam"][cam_name] = cam_dict

        # def axis_map_to_T4(newx_from, sx, newy_from, sy, newz_from, sz):
        #     """
        #     construct a 4x4 homogeneous matrix T such that:
        #     v_new = R @ v_old
        #     v_old/v_new are both [x,y,z]^T
        #     newx_from/newy_from/newz_from take 'x'/'y'/'z'
        #     sx/sy/sz take +1 or -1
        #     """
        #     idx = {'x': 0, 'y': 1, 'z': 2}
        #     R = np.zeros((3, 3), dtype=float)
        #     R[0, idx[newx_from]] = float(sx)
        #     R[1, idx[newy_from]] = float(sy)
        #     R[2, idx[newz_from]] = float(sz)

        #     T = np.eye(4, dtype=float)
        #     T[:3, :3] = R
        #     return T

        # def generate_T4_list_axis_permute_sign(include_det_pos=True, include_det_neg=True):
        #     """
        #     return list[np.ndarray], each element is 4x4.
        #     - include_det_pos=True: includes the 24 matrices with det=+1
        #     - include_det_neg=True: includes the 24 matrices with det=-1
        #     """
        #     Ts = []

        #     # 6 axis permutations
        #     perms = [
        #         ('x','y','z'),
        #         ('x','z','y'),
        #         ('y','x','z'),
        #         ('y','z','x'),
        #         ('z','x','y'),
        #         ('z','y','x'),
        #     ]

        #     # 8 sign combinations
        #     signs = [
        #         (+1,+1,+1),
        #         (+1,+1,-1),
        #         (+1,-1,+1),
        #         (+1,-1,-1),
        #         (-1,+1,+1),
        #         (-1,+1,-1),
        #         (-1,-1,+1),
        #         (-1,-1,-1),
        #     ]

        #     for a, b, c in perms:
        #         for sx, sy, sz in signs:
        #             T = axis_map_to_T4(a, sx, b, sy, c, sz)
        #             det = int(round(np.linalg.det(T[:3, :3])))
        #             if det == 1 and include_det_pos:
        #                 Ts.append(T)
        #             elif det == -1 and include_det_neg:
        #                 Ts.append(T)

        #     return Ts
        # # directly get list[np.ndarray], each is 4x4
        # T_list = generate_T4_list_axis_permute_sign()

        # print(T_list[6])
        # print(T_list[6])
        # print(T_list[6])
        # print(T_list[6])


        # for i in range(len(T_list)):
        #     T = T_list[i]
        #     pointcloud = []
        #     # print(f"T {i} det: {det}")
        #     for cam_name, cam_data in out_dict["cam"].items():

        #         first_rgb = cam_data["rgb_first_frame"]
        #         first_depth = cam_data["depth"][0,0]
        #         intrinsic = cam_data["intrinsic"]
        #         extrinsic = cam_data["extrinsic"]
        #         extrinsic = T @ cam_data["extrinsic"]


        #         # print dtype
        #         print(f"first_rgb dtype: {first_rgb.dtype}, first_depth dtype: {first_depth.dtype}, intrinsic dtype: {intrinsic.dtype}, extrinsic dtype: {extrinsic.dtype}")

        #         # first_rgb = first_rgb.numpy()
        #         # first_depth = first_depth.numpy()
        #         # first_depth = torch.from_numpy(first_depth).float()
        #         # intrinsic = torch.from_numpy(intrinsic).float()
        #         # extrinsic = torch.from_numpy(extrinsic).float()

        #         pc = rgbd_to_pointcloud(
        #             rgb=first_rgb,
        #             depth=first_depth,
        #             intrinsic=intrinsic,
        #             extrinsic=extrinsic)
                
        #         pc = np.concatenate([pc[0], pc[1]], axis=-1)  # N x 6

        #         # print(f"Pointcloud from {cam_name} has shape {pc.shape}")
                
        #         pointcloud.append(pc)

        #     # all_pc = torch.cat(pointcloud, dim=0)
        #     all_pc = np.concatenate(pointcloud, axis=0)
        #     print(f"shape {all_pc.shape}")
        #     import open3d as o3d
        #     o3d_pc = o3d.geometry.PointCloud()
        #     o3d_pc.points = o3d.utility.Vector3dVector(all_pc[:, :3].astype(np.float64))
        #     if all_pc.shape[1] >= 6:
        #         o3d_pc.colors = o3d.utility.Vector3dVector((all_pc[:, 3:6] / 255.0).astype(np.float64))

        #     xyz = all_pc[:, :3]
        #     x_range = -xyz[:, 0].min()+ xyz[:, 0].max()
        #     y_range = -xyz[:, 1].min()+ xyz[:, 1].max()
        #     z_range = -xyz[:, 2].min()+ xyz[:, 2].max()

        #     o3d.io.write_point_cloud(f"./llll/debug_pc_{i}_{x_range:.2f}_{y_range:.2f}_{z_range:.2f}.ply", o3d_pc)
        #     # take a picture of the pointcloud

        #     print(f"Saved pointcloud with {all_pc.shape[0]} points to debug_pc_{i}.ply")
        # # # assert 0

        return out_dict

    

    def __len__(self):
        return len(self.data_list)

def robust_depth_range(depth_tensor: torch.Tensor, q_low=1.0, q_high=99.0):
    depth_tensor = depth_tensor.to(torch.float32)
    valid = depth_tensor[depth_tensor > 1e-6]
    if valid.numel() == 0:
        return 1e-3, 1.0
    lo = torch.nanquantile(valid, q_low / 100.0).item()
    hi = torch.nanquantile(valid, q_high / 100.0).item()
    if hi - lo < 1e-6:
        hi = lo + 1e-3
    return max(lo, 1e-4), max(hi, lo + 1e-3)
    

class LightningModelForDataProcess(pl.LightningModule):
    def __init__(self, text_encoder_path, vae_path, image_encoder_path=None, tiled=False, tile_size=(34, 34), tile_stride=(18, 16), overwrite=True):
        super().__init__()
        model_path = [text_encoder_path, vae_path]
        if image_encoder_path is not None:
            model_path.append(image_encoder_path)
        model_manager = ModelManager(torch_dtype=torch.bfloat16, device="cpu")
        model_manager.load_models(model_path)
        self.pipe = WanVideoPipeline.from_model_manager(model_manager)
        self.pipe.torch_dtype = model_manager.torch_dtype
        self.pipe.vae.dtype = model_manager.torch_dtype
        self.pipe.vae.to(model_manager.device)
        print(f"Loaded pipeline to {model_manager.device} with dtype {model_manager.torch_dtype}")
        # assert 0

        self.overwrite = overwrite

        self.tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}

        self.debug_flag = True
        
    def test_step(self, batch, batch_idx):
        self.pipe.device = self.device

        # print(f"batch.keys() {batch.keys()}") # batch.keys() dict_keys(['cache_path', 'text', 'cam'])
        # for key, value in batch.items():
        #     print(f"{key}: {type(value)}")
        # cache_path: <class 'list'>
        # text: <class 'list'>
        # cam: <class 'dict'>

        text = batch["text"][0]
        cam = batch["cam"]
        cache_path = batch["cache_path"][0]
        action = batch["action"]

        # data/pp_tasks_/place_a2b_left/ARX-X5+ARX-X5/demo_randomized/cache/episode0/ to data/pp_tasks_/place_a2b_left/ARX-X5+ARX-X5/demo_randomized/cache_wan2_2/episode0/
        # .replace("/cache/", "/cache_rlbench_wan2_2/")
        cache_path = cache_path.replace("/cache/episode", "/cache_rlbench_wan2_2/episode")
        if self.debug_flag:
            print(f"Processing data for text: {text}, cache_path: {cache_path}")

        os.makedirs(cache_path, exist_ok=True)
        prompt_emb_pth_path = os.path.join(cache_path, "prompt_emb.pth")
        # if not os.path.exists(prompt_emb_pth_path):
            # prompt
        # delete the torch.save file if exists
        if self.overwrite and os.path.exists(prompt_emb_pth_path):
            os.remove(prompt_emb_pth_path)
        prompt_emb = self.pipe.encode_prompt(text)
        torch.save(prompt_emb, prompt_emb_pth_path)

        depth_min = 0.01
        depth_max = 6.0000
        log_depth_bounds = (math.log(depth_min), math.log(depth_max))


        for cam_name, cam_data in cam.items():
            cam_emb_pth_path = os.path.join(cache_path, f"{cam_name}_emb.pth")

            if self.overwrite or not os.path.exists(cam_emb_pth_path):
                # video
                video = cam_data["rgb"]
                # print("video shape : ", video.shape)

                rgb_mp4_path = cam_data["rgb_mp4_path"]
                depth_mp4_path = cam_data["depth_mp4_path"]
                num_frames = cam_data["num_frames"]
                frame_interval = cam_data["frame_interval"]

                video = video.to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
                #### encode videos ####
                video_frames = video[0]  # [3, T, H, W]
                num_frames = video_frames.shape[1]
                height, width = video_frames.shape[2], video_frames.shape[3]

                rgb_latent = self.pipe.vae.encode(videos=[video_frames])[0]

                depth_videos = cam_data["depth"].to(dtype=self.pipe.torch_dtype, device=self.pipe.device)  # [1, 1, T, H, W]
                depth_frames = depth_videos.squeeze(0).clamp_min(1e-4)
                log_depth = torch.log(depth_frames)
                log_depth = torch.clamp(log_depth, min=log_depth_bounds[0], max=log_depth_bounds[1])
                denom = (log_depth_bounds[1] - log_depth_bounds[0]) + 1e-6
                depth_norm = (log_depth - log_depth_bounds[0]) / denom
                depth_norm = depth_norm * 2 - 1
                # assert 0
                depth_video_frames = depth_norm.repeat(3, 1, 1, 1)  # [3, T, H, W]
                # print(depth_video_frames.shape)
                # print(depth_video_frames.min())
                # print(depth_video_frames.max())
                # assert 0

                # def decode_video(latent, to_numpy=True):
                #     frames = self.pipe.decode_video(latent)
                #     # if self.
                #     # print(f"Decoded frames shape (C H W T): {frames.shape}")
                #     frames = rearrange(frames, "N C T H W -> N T C H W")
                #     frames = ((frames.float() + 1) * 127.5).clip(0, 255)
                #     if to_numpy:
                #         frames = frames.cpu().numpy().astype(np.uint8)
                #     return frames

                depth_latent = self.pipe.vae.encode(videos=[depth_video_frames])[0]
                # print("depth_latent.shape : ",depth_latent.shape) # 48 21 15 20
                # depth_recon = decode_video([depth_latent])
                # # print(depth_recon.shape)
                # # print(depth_video_frames.shape)
                # # assert 0
                # # def tensor_to_uint8(img_tensor):
                # #     img_tensor = img_tensor.detach().cpu().float()
                # #     img_tensor = (img_tensor + 1) / 2  # back to [0,1]
                # #     img_tensor = img_tensor.clamp(0, 1)
                # #     return (img_tensor * 255).byte()
                # print(" depth video frames shape ", depth_video_frames.shape)
                # print("depth_recon : ", depth_recon.shape)
                # def save_depth_video(tensor_frames, name, fps=5):
                #     frames = tensor_frames.float().cpu().numpy()  # T H W C
                #     # input()
                #     video_path = os.path.join(f"{name}.mp4")
                #     imageio.mimwrite(video_path, frames, fps=fps)

                # save_depth_video(depth_video_frames.permute(1,2,3,0), "depth_input")
                # save_depth_video(torch.tensor(depth_recon).squeeze(0).permute(0,2,3,1), "depth_recon")
                
                # assert 0

                data = {
                    "rgb_latent": rgb_latent,  # [C_vace, T_latent, H_latent, W_latent]
                    "depth_latent": depth_latent,  # [C_vace, T_latent, H_latent, W_latent]
                    # "rgb_original": video_frames, # 3, T, H, W
                    # "depth_original": depth_videos, # 1, T , H, W before log norm
                    "rgb_mp4_path":rgb_mp4_path,
                    "depth_mp4_path":depth_mp4_path,
                    "num_frames": num_frames,
                    "frame_interval": frame_interval,

                    "intrinsic": cam_data["intrinsic"][0],  # [3, 3]
                    "extrinsic": cam_data["extrinsic"][0],  # [4, 4]
                    "log_depth_bounds": log_depth_bounds,  # tuple
                    "action": action
                }

                if self.debug_flag == True:
                    for key, value in data.items():
                        if isinstance(value, torch.Tensor):
                            print(f"{key}: type {type(value)}, shape {value.shape}, dtype {value.dtype}, device {value.device}")
                        else:
                            print(f"{key}: type {type(value)}, value {value}")
                    self.debug_flag = False

                # assert 0
                # print(f"Saving camera embeddings to {cam_emb_pth_path}")
                if self.overwrite and os.path.exists(cam_emb_pth_path):
                    os.remove(cam_emb_pth_path)
                torch.save(data, cam_emb_pth_path)
            else:
                print(f"File {cam_emb_pth_path} already exists, skipping.")

class Camera(object):
    def __init__(self, c2w):
        c2w_mat = np.array(c2w).reshape(4, 4)
        self.c2w_mat = c2w_mat
        self.w2c_mat = np.linalg.inv(c2w_mat)

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="Preprocess RLBench (depth) videos into Wan2.2 latent cache (*.pth).")
    parser.add_argument("--data_dir", required=True,
                        help="Extracted dataset root for this source (see the dataset README).")
    parser.add_argument("--model_dir", default="./model_weights/Wan-AI/Wan2.2-TI2V-5B",
                        help="Dir holding Wan2.2 VAE (Wan2.2_VAE.pth), the T5 text encoder "
                             "(models_t5_umt5-xxl-enc-bf16.safetensors or .pth) and the "
                             "google/umt5-xxl/ tokenizer folder. Download from Wan-AI/Wan2.2-TI2V-5B.")
    parser.add_argument("--num_frames", type=int, default=41)
    parser.add_argument("--height", type=int, default=240)
    parser.add_argument("--width", type=int, default=320)
    parser.add_argument("--num_workers", type=int, default=1)
    args = parser.parse_args()

    # locate the T5 text-encoder weight (.safetensors preferred, .pth fallback)
    text_encoder_path = None
    for _name in ("models_t5_umt5-xxl-enc-bf16.safetensors", "models_t5_umt5-xxl-enc-bf16.pth"):
        _p = os.path.join(args.model_dir, _name)
        if os.path.exists(_p):
            text_encoder_path = _p
            break
    if text_encoder_path is None:
        raise FileNotFoundError(f"T5 text encoder not found under {args.model_dir}")
    vae_path = os.path.join(args.model_dir, "Wan2.2_VAE.pth")

    text_video_dataset = RLBenchTextVideoDataset(
        base_path=args.data_dir,
        metadata_path="",
        max_num_frames=args.num_frames,
        frame_interval=1,
        num_frames=args.num_frames,
        height=args.height,
        width=args.width,
        is_i2v=False,
    )
    text_video_dataloader = torch.utils.data.DataLoader(
        text_video_dataset,
        shuffle=False,
        batch_size=1,
        num_workers=args.num_workers,
        prefetch_factor=1,
        pin_memory=True,
        pin_memory_device="cuda",
    )
    data_preprocess_model = LightningModelForDataProcess(
        text_encoder_path=text_encoder_path,
        vae_path=vae_path,
        image_encoder_path=None,
    )
    trainer = pl.Trainer(
        accelerator="gpu",
        devices="auto",
        default_root_dir=args.data_dir,
    )
    trainer.test(data_preprocess_model, text_video_dataloader)