File size: 11,368 Bytes
596242b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import random
from typing import List

import av
import av.logging

import PIL
import numpy as np
from torch.utils.data import Dataset
from einops import rearrange
# from cache_decorator import Cache

import torch.nn.functional as F
import torchvision.transforms.functional as TF

import cv2


class VideoFolder(Dataset):
    IMG_EXTENSIONS = [
        ".png",
        ".PNG",
        ".jpg",
        ".JPG"
    ]
    VIDEO_EXTENSIONS = [".mp4", ".MP4", ".avi", ".AVI"]

    def __init__(
        self,
        path: str,
        size: List[int],
        nframes: int = 128,
    ):
        if isinstance(size, (list, tuple)):
            if len(size) not in [1, 2]:
                raise ValueError(
                    f"Size must be an int or a 1 or 2 element tuple/list, not a {len(size)} element tuple/list"
                )

        if isinstance(size, int):
            size = [size, size]

        def _find_all_path(_path):
            _all_fnames = {
                os.path.relpath(os.path.join(root, fname), start=_path)
                for root, _dirs, files in os.walk(_path)
                for fname in files
            }
            _video_fnames = sorted(
                fname
                for fname in _all_fnames
                if self._file_ext(fname) in self.VIDEO_EXTENSIONS
            ) + sorted(
                list(
                    set(
                        (
                            os.path.dirname(fname)
                            for fname in _all_fnames
                            if self._file_ext(fname) in self.IMG_EXTENSIONS
                        )
                    )
                )
            )
            _video_fnames = sorted(_video_fnames)
            return _video_fnames

        _video_fnames = _find_all_path(path)

        self.path = path
        self.size = size
        self.nframes = nframes

        self._video_fnames = _video_fnames
        self._total_size = len(self._video_fnames)

    @staticmethod
    def _file_ext(fname):
        return os.path.splitext(fname)[1].lower()

    def _read_video_opencv(self, video_path, nframes, size):
        video = []
        if os.path.isdir(video_path):
            _all_fnames = {
                os.path.relpath(os.path.join(root, fname), start=video_path)
                for root, _dirs, files in os.walk(video_path)
                for fname in files
            }
            _video_fnames = sorted(
                fname
                for fname in _all_fnames
                if self._file_ext(fname) in self.IMG_EXTENSIONS
            )
            for fname in _video_fnames:
                with open(os.path.join(video_path, fname), "rb") as f:
                    video.append(
                        np.array(
                            PIL.Image.open(f)
                            .convert("RGB")
                            .resize(
                                size, resample=3
                            )  # PIL.Image.Resampling.LANCZOS = 1 PIL.Image.Resampling.BICUBIC = 3
                        )
                    )
        else:
            video = []
            cap = cv2.VideoCapture(video_path)
            while cap.isOpened():
                success, image = cap.read()
                if success:
                    video.append(
                        np.asarray(
                            cv2.resize(image, size, interpolation=cv2.INTER_CUBIC)[
                                :, :, ::-1
                            ]
                        )
                    )
                else:
                    break
            cap.release()

            if len(video) != nframes:
                frame_scale = len(video) / nframes
                frame_scaled_idxs = [int(i * frame_scale) for i in range(nframes)]
                video = [video[i] for i in range(len(video)) if i in frame_scaled_idxs]

        # for cache
        video = np.stack(video).astype(np.uint8)
        return video

    # @Cache(
    #     cache_path="/data/kmei1/caches/{_hash}.pkl",
    # )
    def _read_video(self, video_path, nframes, size):
        video = []
        if os.path.isdir(video_path):
            _all_fnames = {
                os.path.relpath(os.path.join(root, fname), start=video_path)
                for root, _dirs, files in os.walk(video_path)
                for fname in files
            }
            _video_fnames = sorted(
                [fname
                for fname in _all_fnames
                if self._file_ext(fname) in self.IMG_EXTENSIONS],
                key = lambda x: int(x[:-4])
            )
            for fname in _video_fnames:
                with open(os.path.join(video_path, fname), "rb") as f:
                    video.append(
                        np.array(
                            PIL.Image.open(f)
                            .convert("RGB")
                            .resize(
                                self.size, resample=1
                            )  # PIL.Image.Resampling.LANCZOS = 1 PIL.Image.Resampling.BICUBIC = 3
                        )
                    )
        else:
            with av.open(video_path) as container:
                container.streams.video[0].thread_type = "AUTO"
                container.streams.video[0].thread_count = 2
                total_frames = container.streams.video[0].frames

                frame_scale = total_frames / nframes
                frame_scaled_idxs = [int(i * frame_scale) for i in range(total_frames)]

                for idx, frame in enumerate(container.decode(video=0)):
                    if idx in frame_scaled_idxs:
                        video.append(
                            np.asarray(
                                frame.to_image().resize(
                                    size, resample=1
                                )  # PIL.Image.Resampling.LANCZOS = 1 PIL.Image.Resampling.BICUBIC = 3
                            ).clip(0, 255)
                        )
                container.close()

        frame_scale = len(video) / nframes
        frame_scaled_idxs = [int(i * frame_scale) for i in range(nframes)]
        video = [video[i] for i in range(len(video)) if i in frame_scaled_idxs]
        video = np.stack(video).astype(np.uint8)    # for cache
        return video

    def _read_video_metric(self, video_path, nframes, size):
        video = []
        if os.path.isdir(video_path):
            _all_fnames = {
                os.path.relpath(os.path.join(root, fname), start=video_path)
                for root, _dirs, files in os.walk(video_path)
                for fname in files
            }
            _video_fnames = sorted(
                fname
                for fname in _all_fnames
                if self._file_ext(fname) in self.IMG_EXTENSIONS
            )
            for fname in _video_fnames:
                with open(os.path.join(video_path, fname), "rb") as f:
                    video.append(
                        np.array(
                            PIL.Image.open(f)
                            .convert("RGB")
                            .resize(
                                self.size, resample=1
                            )  # PIL.Image.Resampling.LANCZOS = 1 PIL.Image.Resampling.BICUBIC = 3
                        )
                    )
        else:
            with av.open(video_path) as container:
                container.streams.video[0].thread_type = "AUTO"
                container.streams.video[0].thread_count = 2
                total_frames = container.streams.video[0].frames

                frame_scale = total_frames / nframes
                frame_scaled_idxs = [int(i * frame_scale) for i in range(total_frames)]

                for idx, frame in enumerate(container.decode(video=0)):
                    if idx in frame_scaled_idxs:
                        frame = F.interpolate(TF.pil_to_tensor(frame.to_image()).unsqueeze(0), size=size[0], mode='bilinear', align_corners=False)[0].numpy().clip(0, 255)
                        video.append(frame)
                container.close()

        frame_scale = len(video) / nframes
        frame_scaled_idxs = [int(i * frame_scale) for i in range(nframes)]
        video = [video[i] for i in range(len(video)) if i in frame_scaled_idxs]
        # for cache
        video = np.stack(video).astype(np.uint8)
        return video

    def __getitem__(self, index):
        video_path = os.path.join(self.path, self._video_fnames[index])
        try:
            video = self._read_video_metric(
                video_path=video_path, nframes=self.nframes, size=self.size
            )
        except Exception as e:
            print("=> error with loading video", video_path, e)
            video = self.__getitem__(index + 1)

        if video.shape[0] != self.nframes: print("=> unconsisitent video frames", video_path, video.shape[0], "v.s.", self.nframes)

        video = video.astype(np.float32)
        video = (video - 127.5) / 127.5

        return video

    def __len__(self):
        return self._total_size


class Dataset(VideoFolder):
    def __init__(
        self,
        data_root: str,
        resolution: List[int],
        video_length: int = 128,
        latent_scale = 8,
        actions = 7,
    ):
        super().__init__(data_root, size=resolution, nframes=video_length)
        self.data_root = data_root
        self.actions = actions

        videos = os.listdir(data_root)
        videos.sort()
        videos = videos[:100_000]

        self._video_fnames = videos

        self._total_size = len(self._video_fnames)
        self.latent_scale = latent_scale

    def __getitem__(self, index):
        index = index % self._total_size
        video_path = os.path.join(self.data_root, self._video_fnames[index])

        video = self._read_video(
            video_path=video_path, nframes=self.nframes, size=self.size
        )
        video = video.astype(np.float32)
        video = (video - 127.5) / 127.5

        if video.shape[0] != self.nframes:
            raise ValueError(
                f"{video_path} has less than {self.nframes} frames only have {video.shape[0]}"
            )

        actions = []
        with open(
            os.path.join(self.data_root, self._video_fnames[index], "actions.txt"), "r"
        ) as f:
             for line in f: actions.append(int(line.strip()))

        # SIMPLE_MOVEMENT = [
        #     ['NOOP'],
        #     ['right'],
        #     ['right', 'A'],
        #     ['right', 'B'],
        #     ['right', 'A', 'B'],
        #     ['A'],
        #     ['left'],
        # ]

        video = rearrange(video, 'T H W C -> C T H W')
        grid_size = [self.nframes, video.shape[2] // self.latent_scale, video.shape[3] // self.latent_scale, self.actions]
        grid_t = np.arange(grid_size[0], dtype=np.float32)
        grid_h = np.arange(grid_size[1], dtype=np.float32)
        grid_w = np.arange(grid_size[2], dtype=np.float32)
        grid_action = np.arange(grid_size[3], dtype=np.float32)
        grid = np.meshgrid(grid_t, grid_h, grid_w, grid_action, indexing='ij')  # here w goes first
        grid = np.stack(grid, axis=0)
        grid = rearrange(grid[:, np.arange(grid_size[0]), :, :, actions], "T N H W -> N T H W")

        return (video, actions, grid)

    def __len__(self):
        return self._total_size