File size: 18,383 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
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 rgbd_to_pointcloud, image_to_float_array, sample_frame_indices, get_instructions, find_data

class TextVideoDataset(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.data_list = find_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 __getitem__(self, data_id):
        data_dict = self.data_list[data_id]
        instructions_file_path = data_dict["instructions_path"]
        instructions_list = get_instructions(instructions_file_path, num=3)
        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()

        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)
        joint_action = jointdata["joint_action"].item()
        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)
        action = action[index_list]
        out_dict["action"] = action

        for cam_name, cam_data in metadata.items():
            # if cam_name == "surround_camera_11":

            intrinsic_cv = np.array(cam_data["intrinsic_cv"]).reshape(3, 3)
            extrinsic_cv = np.eye(4, dtype=np.float64)
            extrinsic_cv[:3,:] = np.array(cam_data["extrinsic_cv"])[:3,:]
            
            rgb_mp4_path = os.path.join(data_dict["data_path"], data_dict["episode_name"], f"{cam_name}.mp4")
            depth_mp4_path = os.path.join(data_dict["data_path"], data_dict["episode_name"], f"{cam_name}_depth.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 = torch.from_numpy(depth_frames).unsqueeze(0)  # T H W -> 1 T H W
            
            # break
            cam_dict = dict()
            cam_dict["intrinsic"] = intrinsic_cv
            cam_dict["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)

            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

        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/
        cache_path = cache_path.replace("/cache/episode", "/cache_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.3328 #3327
        depth_max = 3.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 and os.path.exists(cam_emb_pth_path):
                os.remove(cam_emb_pth_path)
            if 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
                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 RobotWin (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=81)
    parser.add_argument("--height", type=int, default=240)
    parser.add_argument("--width", type=int, default=320)
    parser.add_argument("--num_workers", type=int, default=2)
    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 = TextVideoDataset(
        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)