ltttttttttttttt commited on
Commit
898bfa5
·
verified ·
1 Parent(s): e256e9b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/common/io_utils.py +78 -0
  2. REGEN-main/cosmos_policy/_src/imaginaire/datasets/augmentors/merge_datadict.py +54 -0
  3. REGEN-main/cosmos_policy/_src/imaginaire/datasets/augmentors/v3_text_transforms.py +213 -0
  4. REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/__init__.py +14 -0
  5. REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/json_loader.py +33 -0
  6. REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/pkl_loader.py +33 -0
  7. REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/video_decoder.py +775 -0
  8. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/__init__.py +14 -0
  9. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/augmentor.py +64 -0
  10. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/geometry/camera.py +184 -0
  11. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/geometry/depth.py +184 -0
  12. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/geometry/pointcloud.py +390 -0
  13. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/__init__.py +14 -0
  14. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/cropping.py +122 -0
  15. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/flip.py +44 -0
  16. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/misc.py +61 -0
  17. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/normalize.py +48 -0
  18. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/padding.py +82 -0
  19. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/resize.py +190 -0
  20. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/config/schema.py +84 -0
  21. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/dataloader.py +78 -0
  22. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/__init__.py +14 -0
  23. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/depth.py +153 -0
  24. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/image.py +45 -0
  25. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/pickle.py +33 -0
  26. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/__init__.py +26 -0
  27. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/basic.py +158 -0
  28. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio.py +274 -0
  29. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio_v2.py +252 -0
  30. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio_v2_test.py +125 -0
  31. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/utils/iterators.py +619 -0
  32. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/utils/misc.py +90 -0
  33. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/utils/stream.py +111 -0
  34. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/webdataset.py +286 -0
  35. REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/webdataset_ext.py +118 -0
  36. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/__init__.py +14 -0
  37. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/__init__.py +36 -0
  38. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/auto_auth.py +70 -0
  39. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/base_backend.py +147 -0
  40. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/boto3_backend.py +866 -0
  41. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/boto3_client.py +640 -0
  42. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/http_backend.py +198 -0
  43. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/local_backend.py +599 -0
  44. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/msc_backend.py +911 -0
  45. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/registry_utils.py +130 -0
  46. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/easy_io.py +1116 -0
  47. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/file_client.py +459 -0
  48. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/handlers/__init__.py +29 -0
  49. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/handlers/base.py +44 -0
  50. REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/handlers/byte_handler.py +39 -0
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/common/io_utils.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import glob
17
+ from dataclasses import dataclass
18
+
19
+ import imageio
20
+ import numpy as np
21
+
22
+ from cosmos_policy._src.imaginaire.utils import log
23
+
24
+
25
+ @dataclass
26
+ class VideoData:
27
+ frames: np.ndarray # Shape: [B, H, W, C]
28
+ fps: int
29
+ duration: int # in seconds
30
+
31
+
32
+ def get_video_filepaths(input_dir: str) -> list[str]:
33
+ """Get a list of filepaths for all videos in the input directory."""
34
+ paths = glob.glob(f"{input_dir}/**/*.mp4", recursive=True)
35
+ paths += glob.glob(f"{input_dir}/**/*.avi", recursive=True)
36
+ paths += glob.glob(f"{input_dir}/**/*.mov", recursive=True)
37
+ paths = sorted(paths)
38
+ log.debug(f"Found {len(paths)} videos")
39
+ return paths
40
+
41
+
42
+ def read_video(filepath: str) -> VideoData:
43
+ """Read a video file and extract its frames and metadata."""
44
+ try:
45
+ reader = imageio.get_reader(filepath, "ffmpeg")
46
+ except Exception as e:
47
+ raise ValueError(f"Failed to read video file: {filepath}") from e
48
+
49
+ # Extract metadata from the video file
50
+ try:
51
+ metadata = reader.get_meta_data()
52
+ fps = metadata.get("fps")
53
+ duration = metadata.get("duration")
54
+ except Exception as e:
55
+ reader.close()
56
+ raise ValueError(f"Failed to extract metadata from video file: {filepath}") from e
57
+
58
+ # Extract frames from the video file
59
+ try:
60
+ frames = np.array([frame for frame in reader])
61
+ except Exception as e:
62
+ raise ValueError(f"Failed to extract frames from video file: {filepath}") from e
63
+ finally:
64
+ reader.close()
65
+
66
+ return VideoData(frames=frames, fps=fps, duration=duration)
67
+
68
+
69
+ def save_video(filepath: str, frames: np.ndarray, fps: int) -> None:
70
+ """Save a video file from a sequence of frames."""
71
+ try:
72
+ writer = imageio.get_writer(filepath, fps=fps, macro_block_size=1)
73
+ for frame in frames:
74
+ writer.append_data(frame)
75
+ except Exception as e:
76
+ raise ValueError(f"Failed to save video file to {filepath}") from e
77
+ finally:
78
+ writer.close()
REGEN-main/cosmos_policy/_src/imaginaire/datasets/augmentors/merge_datadict.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
19
+ from cosmos_policy._src.imaginaire.utils import log
20
+
21
+
22
+ class DataDictMerger(Augmentor):
23
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
24
+ super().__init__(input_keys, output_keys, args)
25
+
26
+ def __call__(self, data_dict: dict) -> dict:
27
+ r"""Merge the dictionary associated with the input keys into data_dict. Only keys in output_keys are merged.
28
+
29
+ Args:
30
+ data_dict (dict): Input data dict
31
+ Returns:
32
+ data_dict (dict): Output dict with dictionary associated with the input keys merged.
33
+ """
34
+ for key in self.input_keys:
35
+ if key not in data_dict:
36
+ log.warning(
37
+ f"DataDictMerger dataloader error: missing {key}, {data_dict['__url__']}, {data_dict['__key__']}",
38
+ rank0_only=False,
39
+ )
40
+ return None
41
+ key_dict = data_dict.pop(key)
42
+ if key == "depth" and "depth" in self.output_keys:
43
+ data_dict["depth"] = key_dict
44
+ if key == "human_annotation" and "human_annotation" in self.output_keys:
45
+ data_dict["human_annotation"] = key_dict
46
+ elif key == "segmentation" and "segmentation" in self.output_keys:
47
+ data_dict["segmentation"] = key_dict
48
+ elif key == "canny" and "canny" in self.output_keys:
49
+ data_dict["canny"] = key_dict
50
+ for sub_key in key_dict:
51
+ if sub_key in self.output_keys and sub_key not in data_dict:
52
+ data_dict[sub_key] = key_dict[sub_key]
53
+ del key_dict
54
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/augmentors/v3_text_transforms.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import random
17
+ from typing import Optional
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
23
+
24
+
25
+ def pad_and_resize(
26
+ arr_np: np.ndarray, ntokens: int, is_mask_all_ones: bool = False
27
+ ) -> tuple[torch.Tensor, torch.Tensor]:
28
+ r"""Function for padding and resizing a numpy array.
29
+ Args:
30
+ arr (np.ndarray): Input array
31
+ ntokens (int): Number of output tokens after padding
32
+ is_mask_all_ones (bool): if true, set mask to ones
33
+ Returns:
34
+ arr_padded (torch.Tensor): Padded output tensor
35
+ mask (torch.Tensor): Padding mask
36
+ """
37
+
38
+ if isinstance(arr_np, np.ndarray):
39
+ arr = torch.from_numpy(arr_np)
40
+ elif isinstance(arr_np, torch.Tensor):
41
+ arr = arr_np.clone().detach()
42
+ else:
43
+ raise TypeError("`arr_np` should be a numpy array or torch tensor.")
44
+ embed_dim = arr.shape[1]
45
+
46
+ arr_padded = torch.zeros(ntokens, embed_dim, device=arr.device, dtype=torch.float32)
47
+
48
+ # If the input text is larger than num_text_tokens, clip it.
49
+ if arr.shape[0] > ntokens:
50
+ arr = arr[0:ntokens]
51
+
52
+ mask = torch.LongTensor(ntokens).zero_()
53
+ if len(arr.shape) > 1:
54
+ mask[0 : arr.shape[0]] = 1
55
+
56
+ if len(arr.shape) > 1:
57
+ arr_padded[0 : arr.shape[0]] = arr
58
+
59
+ if is_mask_all_ones:
60
+ mask.fill_(1)
61
+
62
+ return arr_padded, mask
63
+
64
+
65
+ def _obtain_embeddings(cfg: dict, embeddings_captions: dict[str, list], caption_idx: int) -> dict:
66
+ r"""Function for obtaining text embeddings and text mask.
67
+ Args:
68
+ cfg (dict): Config dict
69
+ embeddings_captions (np.ndarray): Caption embeddings
70
+ caption_idx (int): Caption index
71
+ Returns:
72
+ Dictionary containing embeddings and mask
73
+ """
74
+ out_dict = dict()
75
+ is_mask_all_ones = cfg["is_mask_all_ones"]
76
+ if "byt5_tokens" in cfg:
77
+ out_byt5_text, out_byt5_text_mask = pad_and_resize(
78
+ embeddings_captions["byt5_fp8"][caption_idx],
79
+ cfg["byt5_tokens"]["num"],
80
+ is_mask_all_ones=is_mask_all_ones,
81
+ )
82
+ out_dict["byt5_text_embeddings"] = out_byt5_text
83
+ out_dict["byt5_text_mask"] = out_byt5_text_mask
84
+
85
+ if "t5_tokens" in cfg:
86
+ out_t5, out_t5_mask = pad_and_resize(
87
+ embeddings_captions["t5_xxl_fp8"][caption_idx],
88
+ cfg["t5_tokens"]["num"],
89
+ is_mask_all_ones=is_mask_all_ones,
90
+ )
91
+ out_dict["t5_text_embeddings"] = out_t5
92
+ out_dict["t5_text_mask"] = out_t5_mask
93
+
94
+ return out_dict
95
+
96
+
97
+ def obtain_data_dict_from_mixed_gt_and_ai_captions(data_dict: dict, input_keys: list, args: Optional[dict] = None):
98
+ out_pkl_dict = dict()
99
+
100
+ captions_gt = data_dict[input_keys[0]]
101
+ decoded_captions_ai = data_dict[input_keys[1]]
102
+ embeddings_captions_gt = data_dict[input_keys[2]]
103
+ embeddings_captions_ai = data_dict[input_keys[3]]
104
+
105
+ assert args is not None, "Please specify args in augmentation"
106
+ probabilities = [args["caption_probs"]["ground_truth"], args["caption_probs"]["vfc_fidelity"]]
107
+ valid_captions_indices = list(range(len(probabilities)))
108
+ caption_idx = random.choices(valid_captions_indices, weights=probabilities, k=1)[0]
109
+
110
+ # If VFC Fidelity caption is not valid, we will use the ground truth caption
111
+ if caption_idx == 1 and decoded_captions_ai["had_parse_issue"]:
112
+ caption_idx = 0
113
+
114
+ # Merging GT and AI caption raw text
115
+ captions = captions_gt["text"] + [decoded_captions_ai["captions"]["vfc_fidelity"]]
116
+
117
+ # Merging GT and AI caption embeddings
118
+ gt_embeddings = []
119
+ for key in ["ground_truth_headline", "ground_truth"]:
120
+ if key in embeddings_captions_gt:
121
+ if embeddings_captions_gt[key] is not None:
122
+ gt_embeddings.append(embeddings_captions_gt[key])
123
+
124
+ # Randomly select one of the GT embeddings
125
+ gt_embedding = random.choice(gt_embeddings)
126
+ embeddings_captions = {}
127
+ for key in embeddings_captions_ai["vfc_fidelity"]["embeddings"].keys():
128
+ embeddings_captions[key] = [
129
+ gt_embedding["embeddings"][key],
130
+ embeddings_captions_ai["vfc_fidelity"]["embeddings"][key],
131
+ ]
132
+
133
+ # Sampling raw caption and embeddings
134
+ raw_captions = captions[caption_idx]
135
+ data_dict["raw_captions"] = raw_captions
136
+
137
+ embeddings_dict = _obtain_embeddings(
138
+ cfg=args,
139
+ embeddings_captions=embeddings_captions,
140
+ caption_idx=caption_idx,
141
+ )
142
+ out_pkl_dict.update(embeddings_dict)
143
+
144
+ data_dict.update(out_pkl_dict)
145
+ for key in input_keys:
146
+ del data_dict[key]
147
+
148
+ return data_dict
149
+
150
+
151
+ class TextTransform(Augmentor):
152
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
153
+ super().__init__(input_keys, output_keys, args)
154
+
155
+ def __call__(self, data_dict: dict) -> dict:
156
+ r"""Performs camera transformation.
157
+
158
+ Args:
159
+ data_dict (dict): Input data dict
160
+ Returns:
161
+ data_dict (dict): Output dict with camera attributes added
162
+ """
163
+ return obtain_data_dict_from_mixed_gt_and_ai_captions(data_dict, self.input_keys, self.args)
164
+
165
+
166
+ class TextTransformAIOnly(Augmentor):
167
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
168
+ super().__init__(input_keys, output_keys, args)
169
+
170
+ def __call__(self, data_dict: dict) -> dict:
171
+ r"""Performs text transform for datasets where there are only AI captions (ex., NVCC).
172
+
173
+ Args:
174
+ data_dict (dict): Input data dict
175
+ Returns:
176
+ data_dict (dict): Output dict with camera attributes added
177
+ """
178
+
179
+ out_pkl_dict = dict()
180
+ decoded_captions_ai = data_dict[self.input_keys[0]]
181
+ embeddings_captions_ai = data_dict[self.input_keys[1]]
182
+
183
+ assert self.args is not None, "Please specify args in augmentation"
184
+
185
+ raw_captions = decoded_captions_ai["captions"]["vfc"]
186
+ embeddings_captions = {}
187
+
188
+ if decoded_captions_ai["had_parse_issue"]:
189
+ raw_captions = decoded_captions_ai["captions"]["kosmos_2"]
190
+ _embeddings_captions = embeddings_captions_ai["kosmos2"]
191
+ else:
192
+ raw_captions = decoded_captions_ai["captions"]["vfc"]
193
+ _embeddings_captions = embeddings_captions_ai["vfc_fidelity"]
194
+
195
+ for key in _embeddings_captions["embeddings"].keys():
196
+ embeddings_captions[key] = [
197
+ _embeddings_captions["embeddings"][key],
198
+ ]
199
+
200
+ # Sampling raw caption and embeddings
201
+ data_dict["raw_captions"] = raw_captions
202
+ embeddings_dict = _obtain_embeddings(
203
+ cfg=self.args,
204
+ embeddings_captions=embeddings_captions,
205
+ caption_idx=0,
206
+ )
207
+ out_pkl_dict.update(embeddings_dict)
208
+
209
+ data_dict.update(out_pkl_dict)
210
+ for key in self.input_keys:
211
+ del data_dict[key]
212
+
213
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/json_loader.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import re
18
+ from typing import Optional
19
+
20
+
21
+ def json_decoder(key: str, data: bytes) -> Optional[dict]:
22
+ r"""
23
+ Function to decode a json file.
24
+ Args:
25
+ key: Data key.
26
+ data: Data dict.
27
+ """
28
+ extension = re.sub(r".*[.]", "", key)
29
+ if extension == "json":
30
+ data_dict = json.loads(data)
31
+ return data_dict
32
+ else:
33
+ return None
REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/pkl_loader.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import pickle
17
+ import re
18
+ from typing import Optional
19
+
20
+
21
+ def pkl_decoder(key: str, data: bytes) -> Optional[dict]:
22
+ r"""
23
+ Function to decode a pkl file.
24
+ Args:
25
+ key: Data key.
26
+ data: Data dict.
27
+ """
28
+ extension = re.sub(r".*[.]", "", key)
29
+ if extension == "pkl":
30
+ data_dict = pickle.loads(data)
31
+ return data_dict
32
+ else:
33
+ return None
REGEN-main/cosmos_policy/_src/imaginaire/datasets/decoders/video_decoder.py ADDED
@@ -0,0 +1,775 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import math
18
+ import re
19
+ from random import randint
20
+ from typing import Callable, List, Tuple
21
+
22
+ import decord
23
+ import numpy as np
24
+ import torch
25
+ from PIL import Image
26
+
27
+ from cosmos_policy._src.imaginaire.utils import log
28
+
29
+ Image.MAX_IMAGE_PIXELS = 933120000
30
+ _VIDEO_EXTENSIONS = "mp4 avi webm mov".split()
31
+
32
+ VIDEO_DECODER_OPTIONS = {}
33
+
34
+
35
+ def video_decoder_register(key):
36
+ def decorator(func):
37
+ VIDEO_DECODER_OPTIONS[key] = func
38
+ return func
39
+
40
+ return decorator
41
+
42
+
43
+ @video_decoder_register("video_decoder_metadata")
44
+ def video_decoder_metadata(num_threads, **kwargs):
45
+ """
46
+ Video decoder using the video's native fps
47
+ """
48
+
49
+ def video_decoder(key: str, data: bytes):
50
+ extension = re.sub(r".*[.]", "", key)
51
+ if extension.lower() not in _VIDEO_EXTENSIONS:
52
+ return None
53
+ video_buffer = io.BytesIO(data)
54
+ reader = decord.VideoReader(video_buffer, num_threads=num_threads)
55
+ num_frames = len(reader)
56
+ video_fps = int(np.round(reader.get_avg_fps()))
57
+ length_in_s = float(num_frames) / float(video_fps)
58
+ bitrate = video_buffer.getbuffer().nbytes * 8 / length_in_s
59
+ video_frames = reader.get_batch([0]).asnumpy()
60
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
61
+ return video_frames, {"fps": video_fps, "num_frames": num_frames, "bitrate": bitrate}
62
+
63
+ return video_decoder
64
+
65
+
66
+ @video_decoder_register("video_decoder_w_controlled_fps")
67
+ def video_decoder_w_controlled_fps(
68
+ sequence_length: int = 34,
69
+ chunk_size: int = 0,
70
+ use_fps_control: bool = False,
71
+ min_fps_thres: int = 4,
72
+ max_fps_thres: int = 30,
73
+ sampling_reweighting: bool = False,
74
+ sampling_reweighting_factor: int = 1,
75
+ num_threads=4,
76
+ limit_fps_range: bool = False,
77
+ save_raw: bool = False,
78
+ ):
79
+ """
80
+ Video decoder using with fps control.
81
+ This function samples videos with fps in the range [min_fps_thres, max_fps_thres].
82
+ We adjust the fps range if min and max fps cannot be supported to get the sequence length with desired chunk size.
83
+
84
+ Parameters:
85
+ - sequence_length (int) : Number of frames returned by the function
86
+ - chunk_size (int): How the video is divided into chunks. Only return frames within a chunk. chunk_size=0 means we use full video length. Defaults to 0.
87
+ - min_fps_thres (int): Minimum fps threshold to sample from.
88
+ - max_fps_thres (int): Maximum fps threshold to sample from.
89
+ - sampling_reweighting (bool): If False, sample fps weights uniformly. If True, reweight sampling distrubution.
90
+ - sampling_reweighting_factor (int): The fps sampling distribution reweighting factor. If sampling_reweighting_factor > 1, sample more on lower fps side.
91
+ - num_thread (int): Number of threads for decord.
92
+ - save_raw (bool): If True, will also return entire raw video in data_dict key "video_raw_bytes", alongside with the video frames. Only enable this for visualization and debug.
93
+ """
94
+
95
+ def video_decoder(
96
+ key: str,
97
+ data: bytes,
98
+ ):
99
+ extension = re.sub(r".*[.]", "", key)
100
+ if extension.lower() not in _VIDEO_EXTENSIONS:
101
+ return None
102
+
103
+ video_buffer = io.BytesIO(data)
104
+ video_reader = decord.VideoReader(video_buffer, num_threads=num_threads)
105
+ num_target_frames = sequence_length if sequence_length > 0 else len(video_reader)
106
+ num_orig_frames = len(video_reader)
107
+
108
+ # Obtain the number of chunks
109
+ if chunk_size == 0:
110
+ curr_chunk_size = num_orig_frames
111
+ else:
112
+ curr_chunk_size = chunk_size
113
+ num_chunks = max(num_orig_frames // curr_chunk_size, 1)
114
+
115
+ # Checks to ensure that number of target frames we need is present in the video / chunk.
116
+ if num_target_frames > curr_chunk_size:
117
+ raise ValueError(
118
+ f"Specified sequence_length {num_target_frames} exceeds curr_chunk_size {curr_chunk_size}, num_orig_frames={num_orig_frames}, chunk_size={chunk_size}"
119
+ )
120
+
121
+ if num_target_frames > num_orig_frames:
122
+ raise ValueError(
123
+ f"Specified sequence_length {num_target_frames} exceeds num frames in video {num_orig_frames}."
124
+ )
125
+
126
+ # Now obtain min and max fps that we can use within this chunk
127
+ video_fps = int(np.round(video_reader.get_avg_fps()))
128
+
129
+ if video_fps < 1:
130
+ raise ValueError("Video fps lower than 1, skipping")
131
+ if limit_fps_range:
132
+ if video_fps < min_fps_thres:
133
+ raise ValueError(f"Video fps {video_fps} lower than {min_fps_thres}, skipping")
134
+ if video_fps > max_fps_thres:
135
+ raise ValueError(f"Video fps {video_fps} larger than {max_fps_thres}, skipping")
136
+
137
+ # Check if the last chunk has separate window
138
+ # This happens only if remainder frames >= curr_chunk_size / 2 [data annotation was done this way]
139
+ # Else this is used as a part of previous window.
140
+ num_frames_in_last_chunk = num_orig_frames - num_chunks * curr_chunk_size
141
+ if num_frames_in_last_chunk >= int(0.5 * curr_chunk_size):
142
+ if num_frames_in_last_chunk > num_target_frames:
143
+ num_chunks += 1
144
+
145
+ # Sample which chunk to use
146
+ chunk_index = randint(0, num_chunks - 1)
147
+
148
+ if chunk_index == num_chunks - 1:
149
+ # For the last chunk, use all of the remaining frames
150
+ num_samples_in_chunk = num_orig_frames - chunk_index * curr_chunk_size
151
+ else:
152
+ # Else use only the chunk size
153
+ num_samples_in_chunk = curr_chunk_size
154
+
155
+ if use_fps_control:
156
+ # When fps control is provided, sample random fps.
157
+ min_fps = max(min_fps_thres, math.ceil(video_fps * float(num_target_frames) / float(num_samples_in_chunk)))
158
+ max_fps = min(max_fps_thres, video_fps)
159
+
160
+ # Randomly sample a target fps in the range of (min_fps, max_fps)
161
+ if max_fps > min_fps:
162
+ fps_selections = list(range(min_fps, max_fps + 1))
163
+
164
+ # Sample reweighting favors the smaller fps more
165
+ if sampling_reweighting:
166
+ dist = [1 / (float(pp) ** sampling_reweighting_factor) for pp in fps_selections]
167
+ target_fps = np.random.choice(fps_selections, 1, p=[pp / sum(dist) for pp in dist])
168
+ else:
169
+ target_fps = np.random.choice(fps_selections, 1)
170
+ else:
171
+ target_fps = max_fps
172
+
173
+ else:
174
+ # If not, use native fps
175
+ target_fps = video_fps
176
+
177
+ # stride used for subsampling video
178
+ stride = int(video_fps / target_fps)
179
+
180
+ # This is the actual target fps we obtain after subsampling
181
+ target_fps = video_fps / stride
182
+
183
+ # Select the frame start index and frame end index
184
+ chunk_frame_start = chunk_index * curr_chunk_size
185
+ if num_samples_in_chunk <= num_target_frames * stride:
186
+ raise ValueError(
187
+ f"Decoded video not long enough, num_samples_in_chunk={num_samples_in_chunk}, num_target_frames={num_target_frames}, stride={stride}, video_fps={video_fps}, target_fps={target_fps}, min_fps_thres={min_fps_thres}, max_fps_thres={max_fps_thres}, use_fps_control={use_fps_control}"
188
+ )
189
+ # Start index is randomly selected in the chunk
190
+ frame_start = chunk_frame_start + int(
191
+ np.random.choice(num_samples_in_chunk - int(num_target_frames * stride), 1)
192
+ )
193
+ frame_end = frame_start + num_target_frames * stride
194
+
195
+ # Subsample the frames
196
+ if "depth" in key:
197
+ frame_start = video_decoder.frame_start
198
+ frame_end = video_decoder.frame_end
199
+ stride = video_decoder.stride
200
+ chunk_index = video_decoder.chunk_index
201
+ else:
202
+ video_decoder.frame_start = frame_start
203
+ video_decoder.frame_end = frame_end
204
+ video_decoder.stride = stride
205
+ video_decoder.chunk_index = chunk_index
206
+ video_frames = video_reader.get_batch(np.arange(frame_start, frame_end, stride).tolist()).asnumpy()
207
+
208
+ # Return the frames and metadata
209
+ if num_target_frames is not None and video_frames.shape[0] < num_target_frames:
210
+ raise ValueError("Decoded video not long enough, skipping")
211
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
212
+ video_reader.seek(0) # set video reader point back to 0 to clean up cache
213
+ del video_reader # delete the reader to avoid memory leak
214
+
215
+ ret_dict = {
216
+ "video": video_frames,
217
+ "fps": float(target_fps),
218
+ "num_frames": video_frames.shape[1],
219
+ "chunk_index": chunk_index,
220
+ "frame_start": frame_start,
221
+ "frame_end": frame_end,
222
+ "stride": stride,
223
+ "orig_num_frames": num_orig_frames,
224
+ }
225
+ if save_raw:
226
+ ret_dict["video_raw_bytes"] = data
227
+ return ret_dict
228
+
229
+ return video_decoder
230
+
231
+
232
+ @video_decoder_register("video_decoder_for_kd_dataset")
233
+ def video_decoder_for_kd_dataset(
234
+ sequence_length: int = 34,
235
+ num_threads: int = 4,
236
+ save_raw: bool = False,
237
+ **kwargs,
238
+ ):
239
+ """
240
+ Video decoder for Knowledge Distillation dataset.
241
+ This function reads in the raw video frames, without any fps control.
242
+
243
+ Parameters:
244
+ - sequence_length (int) : Number of frames returned by the function
245
+ - num_thread (int): Number of threads for decord.
246
+ - save_raw (bool): If True, will also return entire raw video in data_dict key "video_raw_bytes", alongside with the video frames. Only enable this for visualization and debug.
247
+ """
248
+
249
+ def video_decoder(
250
+ key: str,
251
+ data: bytes,
252
+ ):
253
+ extension = re.sub(r".*[.]", "", key)
254
+ if extension.lower() not in _VIDEO_EXTENSIONS:
255
+ return None
256
+
257
+ video_buffer = io.BytesIO(data)
258
+ video_reader = decord.VideoReader(video_buffer, num_threads=num_threads)
259
+ num_target_frames = sequence_length if sequence_length > 0 else len(video_reader)
260
+ num_orig_frames = len(video_reader)
261
+ assert num_target_frames == num_orig_frames, (
262
+ "Number of target frames must be equal to the number of original frames"
263
+ )
264
+
265
+ # Now obtain min and max fps that we can use within this chunk
266
+ video_fps = int(np.round(video_reader.get_avg_fps()))
267
+ assert video_fps == 24, "Generated video FPS should be 24"
268
+
269
+ # Sample which chunk to use
270
+ chunk_index = 0
271
+ frame_start = 0
272
+ stride = 1
273
+ frame_end = frame_start + num_target_frames * stride
274
+ video_frames = video_reader.get_batch(np.arange(frame_start, frame_end, stride).tolist()).asnumpy()
275
+
276
+ # Return the frames and metadata
277
+ if num_target_frames is not None and video_frames.shape[0] < num_target_frames:
278
+ raise ValueError("Decoded video not long enough, skipping")
279
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
280
+ video_reader.seek(0) # set video reader point back to 0 to clean up cache
281
+ del video_reader # delete the reader to avoid memory leak
282
+
283
+ ret_dict = {
284
+ "video": video_frames,
285
+ "fps": float(video_fps),
286
+ "num_frames": video_frames.shape[1],
287
+ "chunk_index": chunk_index,
288
+ "frame_start": frame_start,
289
+ "frame_end": frame_end,
290
+ "stride": stride,
291
+ "orig_num_frames": num_orig_frames,
292
+ }
293
+ if save_raw:
294
+ ret_dict["video_raw_bytes"] = data
295
+ return ret_dict
296
+
297
+ return video_decoder
298
+
299
+
300
+ @video_decoder_register("video_decoder_basic")
301
+ def video_decoder_basic(
302
+ sequence_length: int = 25,
303
+ use_fps_control: bool = False,
304
+ min_fps_thres: int = 4,
305
+ max_fps_thres: int = 30,
306
+ num_threads=4,
307
+ **kwargs,
308
+ ) -> Callable[[str, bytes], dict[str, torch.Tensor | int]]:
309
+ """Basic video decoder for a specified sequence length.
310
+
311
+ If loaded video has fewer frames than requested, temporally pads with the last frame.
312
+ Optionally, allows subsampling video with a variable FPS in [`min_fps_thres` .. `max_fps_thres`].
313
+
314
+ Args:
315
+ sequence_length (int) : The number of frames to sample from the loaded video.
316
+ use_fps_control (bool) : Controls whether to temporally subsample.
317
+ min_fps_thres (int): Minimum FPS threshold to sample from.
318
+ max_fps_thres (int): Maximum FPS threshold to sample from.
319
+ num_thread (int): Number of threads for the decord.
320
+
321
+ Returns:
322
+ Returns a callable that returns a dictionary of:
323
+ - The sampled video(torch.Tensor, torch.uint8), layout (C, T, H, W).
324
+ - The FPS (int) of the sample.
325
+ """
326
+
327
+ def video_decoder(
328
+ key: str,
329
+ data: bytes,
330
+ ) -> dict[str, torch.Tensor | int]:
331
+ extension = re.sub(r".*[.]", "", key)
332
+ if extension.lower() not in _VIDEO_EXTENSIONS:
333
+ return None
334
+
335
+ video_buffer = io.BytesIO(data)
336
+ video_reader = decord.VideoReader(video_buffer, num_threads=num_threads)
337
+
338
+ # video and request metadata.
339
+ num_target_frames = sequence_length if sequence_length > 0 else len(video_reader)
340
+ num_orig_frames = len(video_reader)
341
+ assert num_orig_frames > 0, "Video has no frames."
342
+ video_fps = max(1, int(video_reader.get_avg_fps() + 0.5))
343
+
344
+ if use_fps_control:
345
+ # When fps control is provided, sample random fps.
346
+ min_fps = max(min_fps_thres, math.ceil(video_fps * float(num_target_frames) / float(num_orig_frames)))
347
+ max_fps = min(max_fps_thres, video_fps)
348
+
349
+ # If frame range is valid, sample random fps in the range of (min_fps, max_fps)
350
+ if max_fps > min_fps:
351
+ fps_selections = list(range(min_fps, max_fps + 1))
352
+ target_fps = np.random.choice(fps_selections, 1)
353
+ else:
354
+ target_fps = max_fps
355
+ else:
356
+ target_fps = video_fps
357
+
358
+ # This is the actual target fps we obtain after subsampling.
359
+ stride = int(video_fps / target_fps)
360
+ target_fps = video_fps / stride
361
+ num_target_stride_frames = int(num_target_frames * stride)
362
+
363
+ # Start index is randomly selected in the
364
+ valid_length = max(num_orig_frames - num_target_stride_frames, 1)
365
+ frame_start = np.random.choice(valid_length, 1)
366
+ frame_end = min(frame_start + num_target_stride_frames, num_orig_frames)
367
+ frame_indices = np.arange(frame_start, frame_end, stride).tolist()
368
+
369
+ # Grab the frames.
370
+ video_frames = video_reader.get_batch(frame_indices).asnumpy()
371
+
372
+ # If sampled frames are less than requested, pad with the last frame via replication
373
+ if video_frames.shape[0] < num_target_frames:
374
+ pad_size = num_target_frames - video_frames.shape[0]
375
+ video_frames = np.pad(video_frames, ((0, pad_size), (0, 0), (0, 0), (0, 0)), mode="edge")
376
+
377
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
378
+ video_reader.seek(0) # set video reader point back to 0 to clean up cache
379
+ del video_reader # delete the reader to avoid memory leak
380
+ return {
381
+ "video": video_frames,
382
+ "fps": float(target_fps),
383
+ }
384
+
385
+ return video_decoder
386
+
387
+
388
+ @video_decoder_register("video_decoder_still_padding")
389
+ def video_decoder_still_padding(
390
+ sequence_length: int = 25,
391
+ use_fps_control: bool = False,
392
+ min_fps_thres: int = 4,
393
+ max_fps_thres: int = 30,
394
+ num_threads=4,
395
+ sampling_reweighting: bool = False,
396
+ sampling_reweighting_factor: int = 1,
397
+ limit_fps_range: bool = False,
398
+ **kwargs,
399
+ ) -> Callable[[str, bytes], dict[str, torch.Tensor | int]]:
400
+ """Video decoder for a specified sequence length.
401
+
402
+ If loaded video has fewer frames than requested, temporally pads with the last frame.
403
+ Optionally, allows subsampling video with a variable FPS in [`min_fps_thres` .. `max_fps_thres`].
404
+
405
+ Args:
406
+ sequence_length (int) : The number of frames to sample from the loaded video.
407
+ use_fps_control (bool) : Controls whether to temporally subsample.
408
+ min_fps_thres (int): Minimum FPS threshold to sample from.
409
+ max_fps_thres (int): Maximum FPS threshold to sample from.
410
+ num_thread (int): Number of threads for the decord.
411
+
412
+ Returns:
413
+ Returns a callable that returns a dictionary of:
414
+ - The sampled video(torch.Tensor, torch.uint8), layout (C, T, H, W).
415
+ - number of video frames
416
+ - frame_start
417
+ - frame_end
418
+ """
419
+
420
+ def video_decoder(
421
+ key: str,
422
+ data: bytes,
423
+ ) -> dict[str, torch.Tensor | int]:
424
+ extension = re.sub(r".*[.]", "", key)
425
+ if extension.lower() not in _VIDEO_EXTENSIONS:
426
+ return None
427
+
428
+ video_buffer = io.BytesIO(data)
429
+ video_reader = decord.VideoReader(video_buffer, num_threads=num_threads)
430
+
431
+ # video and request metadata.
432
+ num_target_frames = sequence_length if sequence_length > 0 else len(video_reader)
433
+ num_orig_frames = len(video_reader)
434
+ assert num_orig_frames > 0, "Video has no frames."
435
+
436
+ if num_target_frames > num_orig_frames:
437
+ log.warning(
438
+ f"Specified sequence_length {num_target_frames} exceeds num frames in video {num_orig_frames}. Padding last frame"
439
+ )
440
+ # Grab the frames.
441
+ video_frames = video_reader.get_batch(range(num_orig_frames)).asnumpy()
442
+
443
+ # Pad with the last frame via replication
444
+ pad_size = num_target_frames - video_frames.shape[0]
445
+ video_frames = np.pad(video_frames, ((0, pad_size), (0, 0), (0, 0), (0, 0)), mode="edge")
446
+
447
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
448
+ video_reader.seek(0) # set video reader point back to 0 to clean up cache
449
+ del video_reader # delete the reader to avoid memory leak
450
+ return {
451
+ "video": video_frames,
452
+ "frame_start": 0,
453
+ "frame_end": num_orig_frames,
454
+ "num_frames": video_frames.shape[1],
455
+ }
456
+
457
+ video_fps = max(1, int(video_reader.get_avg_fps() + 0.5))
458
+
459
+ if video_fps < 1:
460
+ raise ValueError("Video fps lower than 1, skipping")
461
+ if limit_fps_range:
462
+ if video_fps < min_fps_thres:
463
+ raise ValueError(f"Video fps {video_fps} lower than {min_fps_thres}, skipping")
464
+ if video_fps > max_fps_thres:
465
+ raise ValueError(f"Video fps {video_fps} larger than {max_fps_thres}, skipping")
466
+
467
+ if use_fps_control:
468
+ # When fps control is provided, sample random fps.
469
+ min_fps = max(min_fps_thres, math.ceil(video_fps * float(num_target_frames) / float(num_orig_frames)))
470
+ max_fps = min(max_fps_thres, video_fps)
471
+
472
+ # If frame range is valid, sample random fps in the range of (min_fps, max_fps)
473
+ if max_fps > min_fps:
474
+ fps_selections = list(range(min_fps, max_fps + 1))
475
+
476
+ # Sample reweighting favors the smaller fps more
477
+ if sampling_reweighting:
478
+ dist = [1 / (float(pp) ** sampling_reweighting_factor) for pp in fps_selections]
479
+ target_fps = np.random.choice(fps_selections, 1, p=[pp / sum(dist) for pp in dist])
480
+ else:
481
+ target_fps = np.random.choice(fps_selections, 1)
482
+ else:
483
+ target_fps = max_fps
484
+ else:
485
+ target_fps = video_fps
486
+
487
+ # This is the actual target fps we obtain after subsampling.
488
+ stride = int(video_fps / target_fps)
489
+ target_fps = video_fps / stride
490
+ num_target_stride_frames = int(num_target_frames * stride)
491
+
492
+ # Start index is randomly selected in the
493
+ valid_length = max(num_orig_frames - num_target_stride_frames, 1)
494
+ frame_start = np.random.choice(valid_length, 1)
495
+ frame_end = min(frame_start + num_target_stride_frames, num_orig_frames)
496
+ frame_indices = np.arange(frame_start, frame_end, stride).tolist()
497
+
498
+ # Grab the frames.
499
+ video_frames = video_reader.get_batch(frame_indices).asnumpy()
500
+
501
+ # If sampled frames are less than requested, pad with the last frame via replication
502
+ if video_frames.shape[0] < num_target_frames:
503
+ pad_size = num_target_frames - video_frames.shape[0]
504
+ video_frames = np.pad(video_frames, ((0, pad_size), (0, 0), (0, 0), (0, 0)), mode="edge")
505
+
506
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
507
+ video_reader.seek(0) # set video reader point back to 0 to clean up cache
508
+ del video_reader # delete the reader to avoid memory leak
509
+ return {
510
+ "video": video_frames,
511
+ "frame_start": frame_start,
512
+ "frame_end": frame_end,
513
+ "num_frames": video_frames.shape[1],
514
+ }
515
+
516
+ return video_decoder
517
+
518
+
519
+ def video_decoder_w_lower_fps_get_indices(
520
+ num_orig_frames: int,
521
+ video_fps: int,
522
+ min_fps_thres: int,
523
+ max_fps_thres: int,
524
+ sequence_length: int,
525
+ ) -> Tuple[List[int], float]:
526
+ """Generates frame indices for video sampling with FPS control.
527
+
528
+ This function determines valid stride lengths for sampling frames from a video,
529
+ preferring lower FPS (larger strides) when multiple options are available.
530
+ It returns both the selected frame indices and the resulting FPS.
531
+
532
+ Args:
533
+ num_orig_frames: Total number of frames in the original video.
534
+ video_fps: Original video frames per second.
535
+ min_fps_thres: Minimum allowed frames per second.
536
+ max_fps_thres: Maximum allowed frames per second.
537
+ sequence_length: Number of frames to sample.
538
+
539
+ Returns:
540
+ A tuple containing:
541
+ - list[int]: Frame indices to sample from the original video.
542
+ - float: The resulting frames per second after sampling.
543
+
544
+ Raises:
545
+ ValueError: If no valid stride options are available given the constraints.
546
+ ValueError: If input parameters are invalid (e.g., negative values).
547
+ """
548
+ # Validate input parameters
549
+ if num_orig_frames <= 0:
550
+ raise ValueError("num_orig_frames must be positive")
551
+ if video_fps <= 0:
552
+ raise ValueError("video_fps must be positive")
553
+ if min_fps_thres <= 0:
554
+ raise ValueError("min_fps_thres must be positive")
555
+ if max_fps_thres < min_fps_thres:
556
+ raise ValueError("max_fps_thres must be greater than or equal to min_fps_thres")
557
+ if sequence_length <= 1:
558
+ raise ValueError("sequence_length must be greater than 1")
559
+ if sequence_length > num_orig_frames:
560
+ raise ValueError("sequence_length cannot be greater than num_orig_frames")
561
+
562
+ # Calculate stride range
563
+ min_stride = 1
564
+ max_stride = (num_orig_frames - 1) // (sequence_length - 1)
565
+
566
+ valid_strides = []
567
+ for stride in range(min_stride, max_stride + 1):
568
+ # Check if we can get sequence_length frames with this stride
569
+ if (num_orig_frames - stride * (sequence_length - 1)) > 0:
570
+ new_fps = video_fps / stride
571
+ if min_fps_thres <= new_fps <= max_fps_thres:
572
+ valid_strides.append(stride)
573
+
574
+ if not valid_strides:
575
+ raise ValueError(
576
+ f"No valid stride options available for the given constraints. "
577
+ f"stride range = [{min_stride}, {max_stride}]; "
578
+ f"original FPS = {video_fps}; "
579
+ f"sequence_length = {sequence_length}; "
580
+ f"min_fps_thres = {min_fps_thres}; "
581
+ f"max_fps_thres = {max_fps_thres}; "
582
+ f"original num_frames = {num_orig_frames}"
583
+ )
584
+
585
+ # Select stride with weighted probability
586
+ if len(valid_strides) >= 2:
587
+ stride_choices = valid_strides[-2:] # Taking last two as they're the largest
588
+ weights = [0.01, 0.99] # [smaller_stride, larger_stride]
589
+ selected_stride = np.random.choice(stride_choices, p=weights)
590
+ else:
591
+ selected_stride = valid_strides[0]
592
+
593
+ # Calculate the maximum valid start index and random start frame
594
+ max_start_idx = num_orig_frames - (sequence_length - 1) * selected_stride
595
+ frame_start = np.random.randint(0, max_start_idx)
596
+
597
+ # Generate frame indices
598
+ frame_indices = [frame_start + i * selected_stride for i in range(sequence_length)]
599
+ return frame_indices, video_fps / selected_stride
600
+
601
+
602
+ @video_decoder_register("video_decoder_w_lower_fps")
603
+ def video_decoder_w_lower_fps(
604
+ chunk_size: int = 0,
605
+ sequence_length: int = 34,
606
+ min_fps_thres: int = 4,
607
+ max_fps_thres: int = 30,
608
+ num_threads: int = 4,
609
+ return_frame_indices: bool = False,
610
+ **kwargs,
611
+ ) -> dict:
612
+ """
613
+ Simplified video decoder with FPS control and frame sampling.
614
+
615
+ Args:
616
+ key: Video file name/key
617
+ data: Video binary data
618
+ min_fps_thres: Minimum FPS threshold
619
+ max_fps_thres: Maximum FPS threshold
620
+ sequence_length: Number of frames to return
621
+ num_threads: Number of threads for decord
622
+ limit_fps_range: Whether to enforce FPS limits
623
+ return_frame_indices: Whether to return frame indices
624
+
625
+ Returns:
626
+ dict with video frames tensor and target FPS
627
+ """
628
+ del kwargs # Unused
629
+
630
+ def video_decoder(
631
+ key: str,
632
+ data: bytes,
633
+ ) -> dict[str, torch.Tensor | int]:
634
+ # Check video extension
635
+ extension = re.sub(r".*[.]", "", key)
636
+ if extension.lower() not in _VIDEO_EXTENSIONS:
637
+ return None
638
+
639
+ # Read video
640
+ video_buffer = io.BytesIO(data)
641
+ video_reader = decord.VideoReader(video_buffer, num_threads=num_threads)
642
+ num_target_frames = sequence_length if sequence_length > 0 else len(video_reader)
643
+
644
+ # Get video metadata
645
+ num_orig_frames = len(video_reader)
646
+ video_fps = int(np.round(video_reader.get_avg_fps()))
647
+
648
+ # Basic validations
649
+ # Obtain the number of chunks
650
+ if chunk_size == 0:
651
+ curr_chunk_size = num_orig_frames
652
+ else:
653
+ curr_chunk_size = chunk_size
654
+ num_chunks = max(num_orig_frames // curr_chunk_size, 1)
655
+
656
+ # Checks to ensure that number of target frames we need is present in the video / chunk.
657
+ if num_target_frames > curr_chunk_size:
658
+ raise ValueError("Specified sequence_length exceeds curr_chunk_size.")
659
+
660
+ if num_target_frames > num_orig_frames:
661
+ raise ValueError(
662
+ f"Specified sequence_length {num_target_frames} exceeds num frames in video {num_orig_frames}."
663
+ )
664
+
665
+ if video_fps < 1:
666
+ raise ValueError("Video fps lower than 1, skipping")
667
+ if video_fps < min_fps_thres:
668
+ raise ValueError(f"Video fps {video_fps} lower than {min_fps_thres}, skipping")
669
+
670
+ # Check if the last chunk has separate window
671
+ # This happens only if remainder frames >= curr_chunk_size / 2 [data annotation was done this way]
672
+ # Else this is used as a part of previous window.
673
+ num_frames_in_last_chunk = num_orig_frames - num_chunks * curr_chunk_size
674
+ if num_frames_in_last_chunk >= int(0.5 * curr_chunk_size):
675
+ if num_frames_in_last_chunk > num_target_frames:
676
+ num_chunks += 1
677
+
678
+ # Sample which chunk to use
679
+ chunk_index = randint(0, num_chunks - 1)
680
+
681
+ if chunk_index == num_chunks - 1:
682
+ # For the last chunk, use all of the remaining frames
683
+ num_samples_cur_chunk = num_orig_frames - chunk_index * curr_chunk_size
684
+ else:
685
+ # Else use only the chunk size
686
+ num_samples_cur_chunk = curr_chunk_size
687
+ idx_first_in_cur_chunk = chunk_index * curr_chunk_size
688
+
689
+ frame_indices, adjusted_fps = video_decoder_w_lower_fps_get_indices(
690
+ num_orig_frames=num_samples_cur_chunk,
691
+ video_fps=video_fps,
692
+ min_fps_thres=min_fps_thres,
693
+ max_fps_thres=max_fps_thres,
694
+ sequence_length=num_target_frames,
695
+ )
696
+ frame_indices = [idx_first_in_cur_chunk + idx for idx in frame_indices]
697
+
698
+ # Sample frames
699
+ video_frames = video_reader.get_batch(frame_indices).asnumpy()
700
+ video_frames = torch.from_numpy(video_frames).permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
701
+
702
+ # Clean up
703
+ video_reader.seek(0)
704
+ del video_reader
705
+
706
+ output = {
707
+ "video": video_frames,
708
+ "fps": float(adjusted_fps),
709
+ "orig_fps": video_fps,
710
+ "frame_start": frame_indices[0],
711
+ "frame_end": frame_indices[-1],
712
+ "num_frames": video_frames.shape[1],
713
+ "orig_num_frames": num_orig_frames,
714
+ "chunk_index": chunk_index,
715
+ }
716
+ if return_frame_indices:
717
+ output["frame_indices"] = frame_indices
718
+ return output
719
+
720
+ return video_decoder
721
+
722
+
723
+ @video_decoder_register("video_naive_bytes")
724
+ def video_naive_bytes(*args, **kwargs):
725
+ """
726
+ do nothing, just return the video bytes
727
+ """
728
+ del args, kwargs
729
+
730
+ def video_decoder(
731
+ key: str,
732
+ data: bytes,
733
+ ):
734
+ extension = re.sub(r".*[.]", "", key)
735
+ if extension.lower() not in _VIDEO_EXTENSIONS:
736
+ return None
737
+
738
+ return data
739
+
740
+ return video_decoder
741
+
742
+
743
+ def construct_video_decoder(
744
+ video_decoder_name: str = "video_decoder_w_controlled_fps",
745
+ sequence_length: int = 34,
746
+ chunk_size: int = 0,
747
+ use_fps_control: bool = False,
748
+ min_fps_thres: int = 4,
749
+ max_fps_thres: int = 24,
750
+ sampling_reweighting: bool = False,
751
+ sampling_reweighting_factor: int = 1,
752
+ num_threads=4,
753
+ limit_fps_range: bool = False,
754
+ # if true, video decoder will additionally save the raw video (alongside with processed frames) to the data_dict
755
+ # set to true for inference/debugging
756
+ save_raw: bool = False,
757
+ ):
758
+ return VIDEO_DECODER_OPTIONS[video_decoder_name](
759
+ sequence_length=sequence_length,
760
+ chunk_size=chunk_size,
761
+ use_fps_control=use_fps_control,
762
+ min_fps_thres=min_fps_thres,
763
+ max_fps_thres=max_fps_thres,
764
+ sampling_reweighting=sampling_reweighting,
765
+ sampling_reweighting_factor=sampling_reweighting_factor,
766
+ num_threads=num_threads,
767
+ limit_fps_range=limit_fps_range,
768
+ save_raw=save_raw,
769
+ )
770
+
771
+
772
+ def construct_video_decoder_metadata(
773
+ num_threads=4,
774
+ ):
775
+ return VIDEO_DECODER_OPTIONS["video_decoder_metadata"](num_threads=num_threads)
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/augmentor.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from collections.abc import Iterable
17
+ from typing import Any, Generator, Optional
18
+
19
+
20
+ class Augmentor:
21
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
22
+ r"""Base augmentor class
23
+
24
+ Args:
25
+ input_keys (list): List of input keys
26
+ output_keys (list): List of output keys
27
+ args (dict): Arguments associated with the augmentation
28
+ """
29
+ self.input_keys = input_keys
30
+ self.output_keys = output_keys
31
+ self.args = args
32
+
33
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
34
+ raise ValueError("Augmentor not implemented")
35
+
36
+
37
+ class IterableAugmentor:
38
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
39
+ r"""Base augmentor class
40
+
41
+ Args:
42
+ input_keys (list): List of input keys
43
+ output_keys (list): List of output keys
44
+ args (dict): Arguments associated with the augmentation
45
+ """
46
+ self.input_keys = input_keys
47
+ self.output_keys = output_keys
48
+ self.args = args
49
+ self.is_generator = True
50
+
51
+ def __call__(self, data: Iterable) -> Generator:
52
+ r"""Example usage:
53
+
54
+ for data_dict in data:
55
+ # Do something to data_dict
56
+ data_dict["input"] = data_dict["raw_sequence"][:, :-1]
57
+ data_dict["target"] = data_dict["raw_sequence"][:, 1:]
58
+ # Skip sample if needed
59
+ if data_dict["input"].shape[1] < 64:
60
+ continue
61
+ # Construct a generator
62
+ yield data_dict
63
+ """
64
+ raise ValueError("Augmentor not implemented")
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/geometry/camera.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Camera parameter augmentors for webdataset."""
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+
22
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
23
+ from cosmos_policy._src.imaginaire.modules.camera import Camera
24
+
25
+
26
+ class CameraParamDecoder(Augmentor):
27
+ """Decodes camera parameters from text files.
28
+
29
+ The text file format is: fx fy cx cy qx qy qz qw tx ty tz
30
+ where:
31
+ - fx, fy: focal lengths
32
+ - cx, cy: principal points
33
+ - qx, qy, qz, qw: quaternion rotation (world to camera)
34
+ - tx, ty, tz: translation vector (world to camera)
35
+ """
36
+
37
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
38
+ """Initialize the camera parameter decoder.
39
+
40
+ Args:
41
+ input_keys: List of input keys (typically ['camera'])
42
+ output_keys: List of output keys (typically ['intrinsics', 'world_to_cam'])
43
+ args: Additional arguments (not used)
44
+ """
45
+ super().__init__(input_keys, output_keys, args)
46
+
47
+ def __call__(self, data_dict: dict) -> dict:
48
+ """Decode camera parameters from text data.
49
+
50
+ Args:
51
+ data_dict: Input data dictionary containing camera text data
52
+
53
+ Returns:
54
+ data_dict: Output data dictionary with decoded camera parameters
55
+ """
56
+ # Get the camera text data
57
+ camera_text = data_dict[self.input_keys[0]]
58
+
59
+ # Convert text to string if it's bytes
60
+ if isinstance(camera_text, bytes):
61
+ camera_text = camera_text.decode("utf-8")
62
+
63
+ # Parse the camera parameters
64
+ parts = list(map(float, camera_text.strip().split()))
65
+ if len(parts) != 11:
66
+ raise ValueError(f"Invalid camera parameter format. Expected 11 values, got {len(parts)}")
67
+
68
+ # Extract parameters
69
+ fx, fy, cx, cy = parts[0:4] # focal lengths and principal points
70
+ quat = parts[4:8] # qx, qy, qz, qw
71
+ trans = parts[8:11] # tx, ty, tz
72
+
73
+ # Convert intrinsics to 3x3 matrix via helper
74
+ intrinsics = Camera.intrinsic_params_to_matrices(torch.tensor([fx, fy, cx, cy], dtype=torch.float32))
75
+
76
+ # Convert quaternion + translation to 4x4 World->Cam matrix via helper
77
+ qxyzw_t = torch.tensor([*quat, *trans], dtype=torch.float32)
78
+ w2c_3x4 = Camera.extrinsic_params_to_matrices(qxyzw_t)
79
+ world_to_cam = torch.eye(4, dtype=torch.float32)
80
+ world_to_cam[:3, :] = w2c_3x4
81
+
82
+ # Convert to torch tensors
83
+ intrinsics = intrinsics.float()
84
+ world_to_cam = world_to_cam.float()
85
+
86
+ # Store in output dictionary
87
+ data_dict[self.output_keys[0]] = intrinsics
88
+ data_dict[self.output_keys[1]] = world_to_cam
89
+
90
+ # Remove the original camera text data
91
+ data_dict.pop(self.input_keys[0])
92
+
93
+ return data_dict
94
+
95
+
96
+ class CameraParamListDecoder(Augmentor):
97
+ """Decodes a list of camera parameters from text files.
98
+
99
+ The text file format is multiple lines, where each line contains:
100
+ fx fy cx cy qx qy qz qw tx ty tz
101
+ where:
102
+ - fx, fy: focal lengths
103
+ - cx, cy: principal points
104
+ - qx, qy, qz, qw: quaternion rotation (world to camera)
105
+ - tx, ty, tz: translation vector (world to camera)
106
+
107
+ Each line corresponds to one frame's camera parameters.
108
+ """
109
+
110
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
111
+ """Initialize the camera parameter list decoder.
112
+
113
+ Args:
114
+ input_keys: List of input keys (typically ['camera'])
115
+ output_keys: List of output keys (typically ['intrinsics', 'world_to_cam'])
116
+ args: Additional arguments (not used)
117
+ """
118
+ super().__init__(input_keys, output_keys, args)
119
+
120
+ def __call__(self, data_dict: dict) -> dict:
121
+ """Decode a list of camera parameters from text data.
122
+
123
+ Args:
124
+ data_dict: Input data dictionary containing camera text data
125
+
126
+ Returns:
127
+ data_dict: Output data dictionary with decoded camera parameters as lists
128
+ """
129
+ # Get the camera text data
130
+ camera_text = data_dict[self.input_keys[0]]
131
+
132
+ # Convert text to string if it's bytes
133
+ if isinstance(camera_text, bytes):
134
+ camera_text = camera_text.decode("utf-8")
135
+
136
+ # Split into lines and parse each line
137
+ lines = camera_text.strip().split("\n")
138
+ num_frames = len(lines)
139
+
140
+ if num_frames == 0:
141
+ raise ValueError("Empty camera parameter file")
142
+
143
+ # Initialize lists to store camera parameters
144
+ intrinsics_list = []
145
+ world_to_cam_list = []
146
+
147
+ # Parse each line
148
+ for i, line in enumerate(lines):
149
+ line = line.strip()
150
+ if not line: # Skip empty lines
151
+ continue
152
+
153
+ parts = list(map(float, line.split()))
154
+ if len(parts) != 11:
155
+ raise ValueError(
156
+ f"Invalid camera parameter format at line {i + 1}. Expected 11 values, got {len(parts)}"
157
+ )
158
+
159
+ # Extract parameters
160
+ fx, fy, cx, cy = parts[0:4] # focal lengths and principal points
161
+ quat = parts[4:8] # qx, qy, qz, qw
162
+ trans = parts[8:11] # tx, ty, tz
163
+
164
+ # Convert intrinsics and extrinsics via helpers
165
+ intrinsics = Camera.intrinsic_params_to_matrices(torch.tensor([fx, fy, cx, cy], dtype=torch.float32))
166
+ qxyzw_t = torch.tensor([*quat, *trans], dtype=torch.float32)
167
+ w2c_3x4 = Camera.extrinsic_params_to_matrices(qxyzw_t)
168
+ world_to_cam = torch.eye(4, dtype=torch.float32)
169
+ world_to_cam[:3, :] = w2c_3x4
170
+
171
+ intrinsics_list.append(intrinsics)
172
+ world_to_cam_list.append(world_to_cam)
173
+
174
+ # Convert lists to torch tensors with batch dimension
175
+ intrinsics_tensor = torch.stack(intrinsics_list).float() # T x 3 x 3
176
+ world_to_cam_tensor = torch.stack(world_to_cam_list).float() # T x 4 x 4
177
+
178
+ # Store in output dictionary
179
+ data_dict[self.output_keys[0]] = intrinsics_tensor
180
+ data_dict[self.output_keys[1]] = world_to_cam_tensor
181
+
182
+ # Remove the original camera text data
183
+ data_dict.pop(self.input_keys[0])
184
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/geometry/depth.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Depth augmentors for webdataset."""
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+
22
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
23
+
24
+
25
+ class DepthMask(Augmentor):
26
+ """Generates a binary mask for valid depth values.
27
+
28
+ This augmentor takes a depth image and generates a binary mask indicating
29
+ which pixels have valid depth values. A pixel is considered valid if:
30
+ 1. Its depth value is greater than min_depth
31
+ 2. Its depth value is less than max_depth
32
+ 3. Its depth value is not NaN or infinite
33
+ 4. Its depth value is not larger than median_multiplier times the median depth
34
+
35
+ Args:
36
+ min_depth (float): Minimum valid depth value
37
+ max_depth (float): Maximum valid depth value
38
+ median_multiplier (float): Maximum allowed depth as a multiple of median depth
39
+ """
40
+
41
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
42
+ """Initialize the depth mask generator.
43
+
44
+ Args:
45
+ input_keys: List of input keys (typically ['depth'])
46
+ output_keys: List of output keys (typically ['depth_mask'])
47
+ args: Additional arguments including:
48
+ - min_depth (float): Minimum valid depth value
49
+ - max_depth (float): Maximum valid depth value
50
+ - median_multiplier (float): Maximum allowed depth as a multiple of median depth
51
+ """
52
+ super().__init__(input_keys, output_keys, args)
53
+ self.min_depth = args.get("min_depth", 0.1) if args else 0.1
54
+ self.max_depth = args.get("max_depth", 100.0) if args else 100.0
55
+ self.median_multiplier = args.get("median_multiplier", 10) if args else 10
56
+
57
+ def __call__(self, data_dict: dict) -> dict:
58
+ """Generate depth mask.
59
+
60
+ Args:
61
+ data_dict: Input data dictionary containing depth image
62
+
63
+ Returns:
64
+ data_dict: Output data dictionary with depth mask
65
+ """
66
+ # Get depth image
67
+ depth = data_dict[self.input_keys[0]] # H x W
68
+
69
+ # Create mask for valid depth values
70
+ mask = torch.ones_like(depth, dtype=torch.bool)
71
+
72
+ # Check for minimum depth
73
+ mask = mask & (depth > self.min_depth)
74
+
75
+ # Check for maximum depth
76
+ mask = mask & (depth < self.max_depth)
77
+
78
+ # Check for NaN and infinite values
79
+ mask = mask & torch.isfinite(depth) & (~torch.isnan(depth))
80
+
81
+ # Compute median depth from currently valid depths
82
+ if mask.any():
83
+ valid_depths = depth[mask]
84
+ median_depth = torch.median(valid_depths)
85
+
86
+ # Filter out depths larger than median_multiplier times the median
87
+ max_allowed_depth = self.median_multiplier * median_depth
88
+ mask = mask & (depth <= max_allowed_depth)
89
+
90
+ # Store in output dictionary
91
+ data_dict[self.output_keys[0]] = mask
92
+ data_dict[self.input_keys[0]][~mask] = self.max_depth
93
+ return data_dict
94
+
95
+
96
+ class ConsecutiveFrameSampler(Augmentor):
97
+ """Randomly samples N consecutive frames from a video sequence.
98
+
99
+ This augmentor takes a video sequence and randomly samples N consecutive frames
100
+ starting from a random position within the valid range.
101
+
102
+ Args:
103
+ num_frames (int): Number of consecutive frames to sample
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ input_keys: list,
109
+ output_keys: Optional[list] = None,
110
+ random_sample: bool = True,
111
+ args: Optional[dict] = None,
112
+ ) -> None:
113
+ """Initialize the consecutive frame sampler.
114
+
115
+ Args:
116
+ input_keys: List of input keys (typically ['depth', 'points', etc.])
117
+ output_keys: List of output keys (same as input_keys)
118
+ args: Additional arguments including:
119
+ - num_frames (int): Number of consecutive frames to sample
120
+ """
121
+ super().__init__(input_keys, output_keys, args)
122
+ self.num_frames = args.get("num_frames", 25) if args else 25
123
+ self.random_sample = random_sample
124
+
125
+ def __call__(self, data_dict: dict) -> dict:
126
+ """Sample consecutive frames from video sequences.
127
+
128
+ Args:
129
+ data_dict: Input data dictionary containing video sequences
130
+
131
+ Returns:
132
+ data_dict: Output data dictionary with sampled frames
133
+ """
134
+
135
+ # Get the first input key to determine the temporal dimension
136
+ first_key = self.input_keys[0]
137
+ video_tensor = data_dict[first_key]
138
+
139
+ if video_tensor.dim() == 4: # CxTxHxW
140
+ total_frames = video_tensor.shape[1]
141
+ elif video_tensor.dim() == 3: # TxHxW
142
+ total_frames = video_tensor.shape[0]
143
+ else:
144
+ raise ValueError(f"Expected 3D (TxHxW) or 4D (CxTxHxW) tensor, got {video_tensor.dim()}D")
145
+
146
+ # Calculate valid start indices
147
+ max_start_idx = max(0, total_frames - self.num_frames)
148
+ if self.num_frames > total_frames:
149
+ return None
150
+
151
+ if max_start_idx == 0:
152
+ # If video is shorter than requested frames, use all available frames
153
+ start_idx = 0
154
+ actual_num_frames = total_frames
155
+ else:
156
+ if self.random_sample:
157
+ # Randomly sample start index
158
+ start_idx = torch.randint(0, max_start_idx + 1, size=(1,)).item()
159
+ else:
160
+ start_idx = 0
161
+ actual_num_frames = self.num_frames
162
+
163
+ # Sample frames for all input keys
164
+ for input_key, output_key in zip(self.input_keys, self.output_keys):
165
+ tensor = data_dict[input_key]
166
+
167
+ if tensor.dim() == 4: # CxTxHxW
168
+ sampled_tensor = tensor[:, start_idx : start_idx + actual_num_frames, :, :]
169
+ assert sampled_tensor.shape[1] == actual_num_frames, (
170
+ f"Sampled tensor {input_key} has {sampled_tensor.shape[1]} frames, expected {actual_num_frames}"
171
+ )
172
+ elif tensor.dim() == 3: # TxHxW
173
+ sampled_tensor = tensor[start_idx : start_idx + actual_num_frames, :, :]
174
+ assert sampled_tensor.shape[0] == actual_num_frames, (
175
+ f"Sampled tensor {input_key} has {sampled_tensor.shape[0]} frames, expected {actual_num_frames}"
176
+ )
177
+ else:
178
+ raise ValueError(f"Expected 3D (TxHxW) or 4D (CxTxHxW) tensor for {input_key}, got {tensor.dim()}D")
179
+
180
+ data_dict[output_key] = sampled_tensor
181
+ data_dict["frame_start"] = start_idx
182
+ data_dict["frame_end"] = start_idx + actual_num_frames
183
+
184
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/geometry/pointcloud.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Point cloud augmentors for webdataset."""
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+ from einops import rearrange
22
+
23
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
24
+ from cosmos_policy._src.imaginaire.modules.camera import Camera
25
+
26
+
27
+ class DepthToPointcloud(Augmentor):
28
+ """Converts depth images to point clouds using camera intrinsics.
29
+
30
+ This augmentor takes a depth image and camera intrinsics to generate a point cloud.
31
+ The depth image should be in meters and the intrinsics should be a 3x3 matrix.
32
+
33
+ Args:
34
+ to_world_coords (bool): If True, uses the first frame as the coordinate frame for video sequences
35
+ """
36
+
37
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
38
+ """Initialize the depth to point cloud converter.
39
+
40
+ Args:
41
+ input_keys: List of input keys (typically ['depth', 'intrinsics', 'world_to_cam'])
42
+ output_keys: List of output keys (typically ['points'])
43
+ args: Additional arguments including:
44
+ - to_world_coords (bool): Whether to use first frame as coordinate frame
45
+ """
46
+ assert "depth" in input_keys, "Depth image is required for point cloud conversion"
47
+ assert "intrinsics" in input_keys, "Intrinsics are required for point cloud conversion"
48
+ assert "world_to_cam" in input_keys or not self.to_world_coords, (
49
+ "World to camera matrix is required for point cloud conversion"
50
+ )
51
+ super().__init__(input_keys, output_keys, args)
52
+ self.to_world_coords = args.get("to_world_coords", False) if args else False
53
+
54
+ def __call__(self, data_dict: dict) -> dict:
55
+ """Convert depth image to point cloud.
56
+
57
+ Args:
58
+ data_dict: Input data dictionary containing depth image and camera intrinsics
59
+
60
+ Returns:
61
+ data_dict: Output data dictionary with point cloud
62
+ """
63
+ # Get depth image and intrinsics
64
+ depth = data_dict[self.input_keys[0]] # T x H x W or H x W
65
+ intrinsics = data_dict[self.input_keys[1]] # T x 3 x 3 or 3 x 3
66
+
67
+ # Check if we're dealing with video sequences (temporal dimension)
68
+ if depth.dim() == 3 and intrinsics.dim() == 3:
69
+ # Video sequence: T x H x W and T x 3 x 3
70
+ T, H, W = depth.shape
71
+
72
+ # Create pixel coordinates (same for all frames)
73
+ y, x = torch.meshgrid(
74
+ torch.arange(H, device=depth.device), torch.arange(W, device=depth.device), indexing="ij"
75
+ )
76
+ pixels = torch.stack([x, y, torch.ones_like(x)], dim=-1).float() # H x W x 3
77
+ pixels_hw3 = pixels.reshape(-1, 3) # (H*W) x 3
78
+
79
+ # Back-project to camera space using Camera.image2camera
80
+ pixels_batched = pixels_hw3.unsqueeze(0).expand(T, -1, -1) # T x (H*W) x 3
81
+ points_cam = Camera.image2camera(pixels_batched, intrinsics) # T x (H*W) x 3
82
+ depth_flat = depth.reshape(T, -1)
83
+ points_cam = points_cam * depth_flat.unsqueeze(-1)
84
+
85
+ # Transform to first frame coordinate system if requested
86
+ if self.to_world_coords:
87
+ world_to_cam = data_dict[self.input_keys[2]] # T x 4 x 4
88
+ w2c = world_to_cam[:, :3, :] # T x 3 x 4
89
+ # relative pose from cam_t to cam_0: rel = w2c_0 ∘ c2w_t
90
+ w2c0 = w2c[0]
91
+ c2w = Camera.invert_pose(w2c) # T x 3 x 4
92
+ w2c0_exp = w2c0.unsqueeze(0).expand_as(c2w)
93
+ rel = Camera.compose_poses([w2c0_exp, c2w]) # T x 3 x 4
94
+ points = Camera.world2camera(points_cam, rel) # T x (H*W) x 3
95
+ else:
96
+ points = points_cam
97
+
98
+ # Reshape to T x 3 x H x W
99
+ points = rearrange(points, "t (h w) c -> c t h w", h=H, w=W, c=3)
100
+
101
+ else:
102
+ # Single frame: H x W and 3 x 3
103
+ H, W = depth.shape[-2:]
104
+
105
+ # Create pixel coordinates
106
+ y, x = torch.meshgrid(
107
+ torch.arange(H, device=depth.device), torch.arange(W, device=depth.device), indexing="ij"
108
+ )
109
+
110
+ # Create homogeneous coordinates and convert to float
111
+ pixels = torch.stack([x, y, torch.ones_like(x)], dim=-1).float() # H x W x 3
112
+ pixels_hw3 = pixels.reshape(-1, 3)
113
+ depth_flat = depth.reshape(-1) # (H*W)
114
+
115
+ # Back-project to camera space
116
+ points_cam = Camera.image2camera(pixels_hw3, intrinsics) # (H*W) x 3
117
+ points_cam = points_cam * depth_flat.unsqueeze(-1) # (H*W) x 3
118
+
119
+ # For single frame, just use camera coordinates or transform to world coords as before
120
+ if self.to_world_coords:
121
+ world_to_cam = data_dict[self.input_keys[2]] # 4 x 4
122
+ w2c = world_to_cam[:3, :]
123
+ points = Camera.camera2world(points_cam, w2c) # (H*W) x 3
124
+ else:
125
+ points = points_cam
126
+
127
+ # Reshape to 3 x H x W
128
+ points = rearrange(points, "(h w) c -> c h w", h=H, w=W, c=3)
129
+
130
+ # Store in output dictionary
131
+ data_dict[self.output_keys[0]] = points
132
+
133
+ return data_dict
134
+
135
+
136
+ class PointcloudRescale(Augmentor):
137
+ """Rescales point clouds to have a mean distance of 1 from the origin.
138
+
139
+ This augmentor takes a point cloud and rescales it so that the mean distance
140
+ of all points from the origin is 1. It also adjusts the world-to-camera
141
+ transformation matrix accordingly.
142
+
143
+ Args:
144
+ input_keys: List of input keys (typically ['points', 'world_to_cam'])
145
+ output_keys: List of output keys (typically ['points', 'world_to_cam'])
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ input_keys: list,
151
+ output_keys: Optional[list] = None,
152
+ mask_key: Optional[str] = None,
153
+ args: Optional[dict] = None,
154
+ ) -> None:
155
+ """Initialize the point cloud rescaler.
156
+
157
+ Args:
158
+ input_keys: List of input keys (typically ['points', 'world_to_cam'])
159
+ output_keys: List of output keys (typically ['points', 'world_to_cam'])
160
+ args: Additional arguments (not used in this augmentor)
161
+ """
162
+ assert "points" in input_keys, "Points are required for rescaling"
163
+ assert "world_to_cam" in input_keys, "World to camera matrix is required for rescaling"
164
+ super().__init__(input_keys, output_keys, args)
165
+ self.mask_key = mask_key
166
+
167
+ def __call__(self, data_dict: dict) -> dict:
168
+ """Rescale point cloud and adjust world-to-camera transformation.
169
+
170
+ This augmentor computes the average Euclidean distance of all 3D points to the origin
171
+ and uses this scale to normalize both the camera translations and point cloud.
172
+
173
+ Args:
174
+ data_dict: Input data dictionary containing points and world_to_cam
175
+
176
+ Returns:
177
+ data_dict: Output data dictionary with rescaled points and adjusted world_to_cam
178
+ """
179
+ # Get points and world_to_cam
180
+ points = data_dict[self.input_keys[0]] # 3 x T x H x W or 3 x H x W
181
+ world_to_cam = data_dict[self.input_keys[1]] # T x 4 x 4 or 4 x 4
182
+
183
+ # Check if we're dealing with video sequences (temporal dimension)
184
+ if points.dim() == 4 and world_to_cam.dim() == 3:
185
+ # Video sequence: 3 x T x H x W and T x 4 x 4
186
+ T = world_to_cam.shape[0]
187
+
188
+ # Reshape points to T x N x 3 for easier computation
189
+ points_flat = points.permute(1, 0, 2, 3).reshape(T, 3, -1).transpose(1, 2) # T x N x 3
190
+
191
+ # Compute average Euclidean distance to origin across all frames
192
+ if self.mask_key is not None:
193
+ # Get mask and reshape to match points
194
+ mask = data_dict[self.mask_key] # T x H x W
195
+ mask_flat = mask.reshape(T, -1) # T x N
196
+
197
+ # Only compute average over valid points across all frames
198
+ # Compute squared distances for all frames at once
199
+ squared_distances = torch.sum(points_flat**2, dim=2) # T x N
200
+
201
+ # Apply mask and compute mean across all frames
202
+ valid_distances = torch.sqrt(squared_distances[mask_flat])
203
+ avg_dist = valid_distances.mean() # Single value
204
+ else:
205
+ # Compute average Euclidean distance to origin for all points across all frames
206
+ avg_dist = torch.sqrt(torch.sum(points_flat**2, dim=2)).mean() # Single value
207
+
208
+ # Compute scale factor to achieve average distance of 1 across all frames
209
+ scale = 1.0 / avg_dist # Single value
210
+
211
+ # Rescale points for all frames at once
212
+ points_scaled = points * scale # 3 x T x H x W
213
+
214
+ # Adjust world_to_cam matrix for all frames at once
215
+ # We need to scale the translation component by the same factor
216
+ world_to_cam_scaled = world_to_cam.clone()
217
+ world_to_cam_scaled[:, :3, 3] *= scale # T x 4 x 4
218
+
219
+ # Scale depth for all frames at once
220
+ depth = data_dict[self.input_keys[2]] # T x H x W
221
+ depth_scaled = depth * scale # T x H x W
222
+ else:
223
+ # Single frame: 3 x H x W and 4 x 4
224
+ # Reshape points to N x 3 for easier computation
225
+ points_flat = points.reshape(3, -1).T # N x 3
226
+
227
+ # Compute average Euclidean distance to origin
228
+ if self.mask_key is not None:
229
+ # Get mask and reshape to match points
230
+ mask = data_dict[self.mask_key] # H x W
231
+ mask_flat = mask.reshape(-1) # N
232
+
233
+ # Only compute average over valid points
234
+ valid_points = points_flat[mask_flat]
235
+ # Compute average Euclidean distance to origin
236
+ avg_dist = torch.sqrt(torch.sum(valid_points**2, dim=1)).mean()
237
+ else:
238
+ # Compute average Euclidean distance to origin for all points
239
+ avg_dist = torch.sqrt(torch.sum(points_flat**2, dim=1)).mean()
240
+
241
+ # Compute scale factor to achieve average distance of 1
242
+ scale = 1.0 / avg_dist
243
+
244
+ # Rescale points
245
+ points_scaled = points * scale
246
+
247
+ # Adjust world_to_cam matrix
248
+ # We need to scale the translation component by the same factor
249
+ world_to_cam_scaled = world_to_cam.clone()
250
+ world_to_cam_scaled[:3, 3] *= scale
251
+
252
+ # Scale depth
253
+ depth = data_dict[self.input_keys[2]] # H x W
254
+ depth_scaled = depth * scale
255
+
256
+ # Store in output dictionary
257
+ data_dict[self.output_keys[0]] = points_scaled
258
+ data_dict[self.output_keys[1]] = world_to_cam_scaled
259
+ data_dict[self.output_keys[2]] = depth_scaled
260
+ return data_dict
261
+
262
+
263
+ class PointcloudMaskFill(Augmentor):
264
+ """Fills point cloud values with 0 when point cloud mask is False.
265
+
266
+ This augmentor takes a point cloud and a point cloud mask, and sets point cloud values to 0
267
+ wherever the mask is False. This is useful for cleaning up point clouds by
268
+ removing invalid or unreliable point measurements.
269
+
270
+ Args:
271
+ input_keys: List of input keys (typically ['points', 'pcd_mask'])
272
+ output_keys: List of output keys (typically ['points'])
273
+ """
274
+
275
+ def __init__(
276
+ self, input_keys: list, output_keys: Optional[list] = None, fill_value: float = 0.0, args: Optional[dict] = None
277
+ ) -> None:
278
+ """Initialize the point cloud mask filler.
279
+
280
+ Args:
281
+ input_keys: List of input keys (typically ['points', 'pcd_mask'])
282
+ output_keys: List of output keys (typically ['points'])
283
+ args: Additional arguments (not used in this augmentor)
284
+ """
285
+ super().__init__(input_keys, output_keys, args)
286
+ self.fill_value = fill_value
287
+
288
+ def __call__(self, data_dict: dict) -> dict:
289
+ """Fill point cloud values with 0 where point cloud mask is False.
290
+
291
+ Args:
292
+ data_dict: Input data dictionary containing point cloud and point cloud mask
293
+
294
+ Returns:
295
+ data_dict: Output data dictionary with masked point cloud
296
+ """
297
+ # Get point cloud and point cloud mask
298
+ points = data_dict[self.input_keys[0]] # 3 x T x H x W or 3 x H x W
299
+ depth_mask = data_dict[self.input_keys[1]] # T x H x W or H x W
300
+
301
+ # Check if we're dealing with video sequences (temporal dimension)
302
+ if points.dim() == 4 and depth_mask.dim() == 3:
303
+ # Video sequence: 3 x T x H x W and T x H x W
304
+ # Create a copy of the point cloud
305
+ points_filled = points.clone()
306
+
307
+ # Expand mask to match points dimensions: 3 x T x H x W
308
+ mask_expanded = depth_mask.unsqueeze(0).expand(3, -1, -1, -1) # 3 x T x H x W
309
+
310
+ # Set point cloud values to fill_value where mask is False for all channels at once
311
+ points_filled[~mask_expanded] = self.fill_value
312
+
313
+ else:
314
+ # Single frame: 3 x H x W and H x W
315
+ # Create a copy of the point cloud
316
+ points_filled = points.clone()
317
+
318
+ # Expand mask to match points dimensions: 3 x H x W
319
+ mask_expanded = depth_mask.unsqueeze(0).expand(3, -1, -1) # 3 x H x W
320
+
321
+ # Set point cloud values to fill_value where mask is False for all channels at once
322
+ points_filled[~mask_expanded] = self.fill_value
323
+
324
+ # Store in output dictionary
325
+ data_dict[self.output_keys[0]] = points_filled
326
+
327
+ return data_dict
328
+
329
+
330
+ def verify_backprojection(data_dict: dict, scale: float) -> bool:
331
+ """Verify that backprojection of rescaled depth and camera poses matches rescaled point cloud.
332
+
333
+ This function checks if the backprojection of the rescaled depth image using
334
+ the rescaled camera poses produces the same point cloud as the rescaled point cloud.
335
+
336
+ Args:
337
+ data_dict: Dictionary containing:
338
+ - points_scaled: Rescaled point cloud (3 x H x W)
339
+ - depth_scaled: Rescaled depth image (H x W)
340
+ - world_to_cam_scaled: Rescaled world to camera matrix (4 x 4)
341
+ - intrinsics: Camera intrinsics matrix (3 x 3)
342
+ scale: The scale factor used for rescaling
343
+
344
+ Returns:
345
+ bool: True if backprojection matches rescaled point cloud within tolerance
346
+ """
347
+ # Get required data
348
+ points_scaled = data_dict["points"] # 3 x H x W
349
+ depth_scaled = data_dict["depth"] # H x W
350
+ world_to_cam_scaled = data_dict["world_to_cam"] # 4 x 4
351
+ intrinsics = data_dict["intrinsics"] # 3 x 3
352
+
353
+ # Get image dimensions
354
+ H, W = depth_scaled.shape[-2:]
355
+
356
+ # Create pixel coordinates
357
+ y, x = torch.meshgrid(
358
+ torch.arange(H, device=depth_scaled.device), torch.arange(W, device=depth_scaled.device), indexing="ij"
359
+ )
360
+
361
+ # Create homogeneous coordinates
362
+ pixels = torch.stack([x, y, torch.ones_like(x)], dim=-1).float() # H x W x 3
363
+
364
+ # Reshape for batch processing
365
+ pixels = pixels.reshape(-1, 3) # (H*W) x 3
366
+ depth_flat = depth_scaled.reshape(-1) # (H*W)
367
+
368
+ # Get inverse of intrinsics
369
+ intrinsics_inv = torch.inverse(intrinsics)
370
+
371
+ # Back-project to camera space
372
+ points_cam = (intrinsics_inv @ pixels.T).T # (H*W) x 3
373
+ points_cam = points_cam * depth_flat.unsqueeze(-1) # (H*W) x 3
374
+
375
+ # Convert to world coordinates
376
+ cam_to_world = torch.inverse(world_to_cam_scaled) # 4 x 4
377
+ points_cam_h = torch.cat([points_cam, torch.ones_like(points_cam[:, :1])], dim=-1) # (H*W) x 4
378
+ points_world_h = (cam_to_world @ points_cam_h.T).T # (H*W) x 4
379
+ points_world = points_world_h[:, :3] # (H*W) x 3
380
+
381
+ # Reshape back to image dimensions
382
+ points_world = points_world.reshape(H, W, 3) # H x W x 3
383
+ points_world = points_world.permute(2, 0, 1) # 3 x H x W
384
+
385
+ # Compare with rescaled point cloud
386
+ # Use a small tolerance for floating point comparison
387
+ tolerance = 1e-6
388
+ is_close = torch.allclose(points_world, points_scaled, rtol=tolerance, atol=tolerance)
389
+
390
+ return is_close
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/cropping.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torchvision.transforms.functional as transforms_F
20
+ from loguru import logger as logging
21
+
22
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
23
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.image.misc import (
24
+ obtain_augmentation_size,
25
+ obtain_image_size,
26
+ )
27
+
28
+
29
+ class CenterCrop(Augmentor):
30
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
31
+ super().__init__(input_keys, output_keys, args)
32
+
33
+ def __call__(self, data_dict: dict) -> dict:
34
+ r"""Performs center crop.
35
+
36
+ Args:
37
+ data_dict (dict): Input data dict
38
+ Returns:
39
+ data_dict (dict): Output dict where images are center cropped.
40
+ We also save the cropping parameters in the aug_params dict
41
+ so that it will be used by other transforms.
42
+ """
43
+ assert (self.args is not None) and ("size" in self.args), "Please specify size in args"
44
+
45
+ img_size = obtain_augmentation_size(data_dict, self.args)
46
+ width, height = img_size
47
+
48
+ orig_w, orig_h = obtain_image_size(data_dict, self.input_keys)
49
+ for key in self.input_keys:
50
+ data_dict[key] = transforms_F.center_crop(data_dict[key], [height, width])
51
+
52
+ # We also add the aug params we use. This will be useful for other transforms
53
+ crop_x0 = (orig_w - width) // 2
54
+ crop_y0 = (orig_h - height) // 2
55
+ cropping_params = {
56
+ "resize_w": orig_w,
57
+ "resize_h": orig_h,
58
+ "crop_x0": crop_x0,
59
+ "crop_y0": crop_y0,
60
+ "crop_w": width,
61
+ "crop_h": height,
62
+ }
63
+
64
+ if "aug_params" not in data_dict:
65
+ data_dict["aug_params"] = dict()
66
+
67
+ data_dict["aug_params"]["cropping"] = cropping_params
68
+ data_dict["padding_mask"] = torch.zeros((1, cropping_params["crop_h"], cropping_params["crop_w"]))
69
+ return data_dict
70
+
71
+
72
+ class RandomCrop(Augmentor):
73
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
74
+ super().__init__(input_keys, output_keys, args)
75
+
76
+ def __call__(self, data_dict: dict) -> dict:
77
+ r"""Performs random crop.
78
+
79
+ Args:
80
+ data_dict (dict): Input data dict
81
+ Returns:
82
+ data_dict (dict): Output dict where images are center cropped.
83
+ We also save the cropping parameters in the aug_params dict
84
+ so that it will be used by other transforms.
85
+ """
86
+
87
+ img_size = obtain_augmentation_size(data_dict, self.args)
88
+ width, height = img_size
89
+
90
+ orig_w, orig_h = obtain_image_size(data_dict, self.input_keys)
91
+ # Obtaining random crop coords
92
+ try:
93
+ crop_x0 = int(torch.randint(0, orig_w - width + 1, size=(1,)).item())
94
+ crop_y0 = int(torch.randint(0, orig_h - height + 1, size=(1,)).item())
95
+ except Exception:
96
+ logging.warning(
97
+ f"Random crop failed. Performing center crop, original_size(wxh): {orig_w}x{orig_h}, random_size(wxh): {width}x{height}"
98
+ )
99
+ for key in self.input_keys:
100
+ data_dict[key] = transforms_F.center_crop(data_dict[key], [height, width])
101
+ crop_x0 = (orig_w - width) // 2
102
+ crop_y0 = (orig_h - height) // 2
103
+
104
+ # We also add the aug params we use. This will be useful for other transforms
105
+ cropping_params = {
106
+ "resize_w": orig_w,
107
+ "resize_h": orig_h,
108
+ "crop_x0": crop_x0,
109
+ "crop_y0": crop_y0,
110
+ "crop_w": width,
111
+ "crop_h": height,
112
+ }
113
+
114
+ if "aug_params" not in data_dict:
115
+ data_dict["aug_params"] = dict()
116
+
117
+ data_dict["aug_params"]["cropping"] = cropping_params
118
+
119
+ # We must perform same random cropping for all input keys
120
+ for key in self.input_keys:
121
+ data_dict[key] = transforms_F.crop(data_dict[key], crop_y0, crop_x0, height, width)
122
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/flip.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torchvision.transforms.functional as transforms_F
20
+
21
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
22
+
23
+
24
+ class HorizontalFlip(Augmentor):
25
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
26
+ super().__init__(input_keys, output_keys, args)
27
+
28
+ def __call__(self, data_dict: dict) -> dict:
29
+ r"""Performs horizontal flipping.
30
+
31
+ Args:
32
+ data_dict (dict): Input data dict
33
+ Returns:
34
+ data_dict (dict): Output dict where images are center cropped.
35
+ """
36
+ flip_enabled = getattr(self.args, "enabled", True)
37
+ if flip_enabled:
38
+ p = getattr(self.args, "prob", 0.5)
39
+ coin_flip = torch.rand(1).item() > p
40
+ for key in self.input_keys:
41
+ if coin_flip:
42
+ data_dict[key] = transforms_F.hflip(data_dict[key])
43
+
44
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/misc.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Union
17
+
18
+ import torch
19
+ from PIL import Image
20
+
21
+
22
+ def obtain_image_size(data_dict: dict, input_keys: list) -> tuple[int, int]:
23
+ r"""Function for obtaining the image size from the data dict.
24
+
25
+ Args:
26
+ data_dict (dict): Input data dict
27
+ input_keys (list): List of input keys
28
+ Returns:
29
+ width (int): Width of the input image
30
+ height (int): Height of the input image
31
+ """
32
+
33
+ data1 = data_dict[input_keys[0]]
34
+ if isinstance(data1, Image.Image):
35
+ width, height = data1.size
36
+ elif isinstance(data1, torch.Tensor):
37
+ height, width = data1.size()[-2:]
38
+ else:
39
+ raise ValueError("data to random crop should be PIL Image or tensor")
40
+
41
+ return width, height
42
+
43
+
44
+ def obtain_augmentation_size(data_dict: dict, augmentor_cfg: dict) -> Union[int, tuple]:
45
+ r"""Function for obtaining size of the augmentation.
46
+ When dealing with multi-aspect ratio dataloaders, we need to
47
+ find the augmentation size from the aspect ratio of the data.
48
+
49
+ Args:
50
+ data_dict (dict): Input data dict
51
+ augmentor_cfg (dict): Augmentor config
52
+ Returns:
53
+ aug_size (int): Size of augmentation
54
+ """
55
+ if "__url__" in data_dict and "aspect_ratio" in data_dict["__url__"].meta.opts:
56
+ aspect_ratio = data_dict["__url__"].meta.opts["aspect_ratio"]
57
+ aug_size = augmentor_cfg["size"][aspect_ratio]
58
+ else: # Non-webdataset format
59
+ aspect_ratio = data_dict["aspect_ratio"]
60
+ aug_size = augmentor_cfg["size"][aspect_ratio]
61
+ return aug_size
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/normalize.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torchvision.transforms.functional as transforms_F
20
+
21
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
22
+
23
+
24
+ class Normalize(Augmentor):
25
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
26
+ super().__init__(input_keys, output_keys, args)
27
+
28
+ def __call__(self, data_dict: dict) -> dict:
29
+ r"""Performs data normalization.
30
+
31
+ Args:
32
+ data_dict (dict): Input data dict
33
+ Returns:
34
+ data_dict (dict): Output dict where images are center cropped.
35
+ """
36
+ assert self.args is not None, "Please specify args"
37
+
38
+ mean = self.args["mean"]
39
+ std = self.args["std"]
40
+
41
+ for key in self.input_keys:
42
+ if isinstance(data_dict[key], torch.Tensor):
43
+ data_dict[key] = data_dict[key].to(dtype=torch.get_default_dtype()).div(255)
44
+ else:
45
+ data_dict[key] = transforms_F.to_tensor(data_dict[key]) # division by 255 is applied in to_tensor()
46
+
47
+ data_dict[key] = transforms_F.normalize(tensor=data_dict[key], mean=mean, std=std)
48
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/padding.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import omegaconf
19
+ import torch
20
+ import torchvision.transforms.functional as transforms_F
21
+
22
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
23
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.image.misc import (
24
+ obtain_augmentation_size,
25
+ obtain_image_size,
26
+ )
27
+
28
+
29
+ class ReflectionPadding(Augmentor):
30
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
31
+ super().__init__(input_keys, output_keys, args)
32
+
33
+ def __call__(self, data_dict: dict) -> dict:
34
+ r"""Performs reflection padding. This function also returns a padding mask.
35
+
36
+ Args:
37
+ data_dict (dict): Input data dict
38
+ Returns:
39
+ data_dict (dict): Output dict where images are center cropped.
40
+ """
41
+
42
+ assert self.args is not None, "Please specify args in augmentation"
43
+ if self.output_keys is None:
44
+ self.output_keys = self.input_keys
45
+
46
+ # Obtain image and augmentation sizes
47
+ orig_w, orig_h = obtain_image_size(data_dict, self.input_keys)
48
+ target_size = obtain_augmentation_size(data_dict, self.args)
49
+
50
+ assert isinstance(target_size, (tuple, omegaconf.listconfig.ListConfig)), "Please specify target size as tuple"
51
+ target_w, target_h = target_size
52
+
53
+ target_w = int(target_w)
54
+ target_h = int(target_h)
55
+
56
+ # Calculate padding vals
57
+ padding_left = int((target_w - orig_w) / 2)
58
+ padding_right = target_w - orig_w - padding_left
59
+ padding_top = int((target_h - orig_h) / 2)
60
+ padding_bottom = target_h - orig_h - padding_top
61
+ padding_vals = [padding_left, padding_top, padding_right, padding_bottom]
62
+
63
+ for inp_key, out_key in zip(self.input_keys, self.output_keys):
64
+ if max(padding_vals[0], padding_vals[2]) >= orig_w or max(padding_vals[1], padding_vals[3]) >= orig_h:
65
+ # In this case, we can't perform reflection padding. This is because padding values
66
+ # are larger than the image size. So, perform edge padding instead.
67
+ data_dict[out_key] = transforms_F.pad(data_dict[inp_key], padding_vals, padding_mode="edge")
68
+ else:
69
+ # Perform reflection padding
70
+ data_dict[out_key] = transforms_F.pad(data_dict[inp_key], padding_vals, padding_mode="reflect")
71
+
72
+ if out_key != inp_key:
73
+ del data_dict[inp_key]
74
+
75
+ # Return padding_mask when padding is performed.
76
+ # Padding mask denotes which pixels are padded.
77
+ padding_mask = torch.ones((1, target_h, target_w))
78
+ padding_mask[:, padding_top : (padding_top + orig_h), padding_left : (padding_left + orig_w)] = 0
79
+ data_dict["padding_mask"] = padding_mask
80
+ data_dict["image_size"] = torch.tensor([target_h, target_w, orig_h, orig_w], dtype=torch.float)
81
+
82
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/augmentors/image/resize.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional
17
+
18
+ import omegaconf
19
+ import torchvision.transforms.functional as transforms_F
20
+
21
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
22
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.image.misc import (
23
+ obtain_augmentation_size,
24
+ obtain_image_size,
25
+ )
26
+
27
+
28
+ class ResizeSmallestSide(Augmentor):
29
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
30
+ super().__init__(input_keys, output_keys, args)
31
+
32
+ def __call__(self, data_dict: dict) -> dict:
33
+ r"""Performs resizing to smaller side
34
+
35
+ Args:
36
+ data_dict (dict): Input data dict
37
+ Returns:
38
+ data_dict (dict): Output dict where images are resized
39
+ """
40
+
41
+ if self.output_keys is None:
42
+ self.output_keys = self.input_keys
43
+ assert self.args is not None, "Please specify args in augmentations"
44
+
45
+ for inp_key, out_key in zip(self.input_keys, self.output_keys):
46
+ out_size = obtain_augmentation_size(data_dict, self.args)
47
+ assert isinstance(out_size, int), "Arg size in resize should be an integer"
48
+ data_dict[out_key] = transforms_F.resize(
49
+ data_dict[inp_key],
50
+ size=out_size, # type: ignore
51
+ interpolation=getattr(self.args, "interpolation", transforms_F.InterpolationMode.BICUBIC),
52
+ antialias=True,
53
+ )
54
+ if out_key != inp_key:
55
+ del data_dict[inp_key]
56
+ return data_dict
57
+
58
+
59
+ class ResizeLargestSide(Augmentor):
60
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
61
+ super().__init__(input_keys, output_keys, args)
62
+
63
+ def __call__(self, data_dict: dict) -> dict:
64
+ r"""Performs resizing to larger side
65
+
66
+ Args:
67
+ data_dict (dict): Input data dict
68
+ Returns:
69
+ data_dict (dict): Output dict where images are resized
70
+ """
71
+
72
+ if self.output_keys is None:
73
+ self.output_keys = self.input_keys
74
+ assert self.args is not None, "Please specify args in augmentations"
75
+
76
+ for inp_key, out_key in zip(self.input_keys, self.output_keys):
77
+ out_size = obtain_augmentation_size(data_dict, self.args)
78
+ assert isinstance(out_size, int), "Arg size in resize should be an integer"
79
+ orig_w, orig_h = obtain_image_size(data_dict, self.input_keys)
80
+
81
+ scaling_ratio = min(out_size / orig_w, out_size / orig_h)
82
+ target_size = [int(scaling_ratio * orig_h), int(scaling_ratio * orig_w)]
83
+
84
+ data_dict[out_key] = transforms_F.resize(
85
+ data_dict[inp_key],
86
+ size=target_size,
87
+ interpolation=getattr(self.args, "interpolation", transforms_F.InterpolationMode.BICUBIC),
88
+ antialias=True,
89
+ )
90
+ if out_key != inp_key:
91
+ del data_dict[inp_key]
92
+ return data_dict
93
+
94
+
95
+ class ResizeSmallestSideAspectPreserving(Augmentor):
96
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
97
+ super().__init__(input_keys, output_keys, args)
98
+
99
+ def __call__(self, data_dict: dict) -> dict:
100
+ r"""Performs aspect-ratio preserving resizing.
101
+ Image is resized to the dimension which has the smaller ratio of (size / target_size).
102
+ First we compute (w_img / w_target) and (h_img / h_target) and resize the image
103
+ to the dimension that has the smaller of these ratios.
104
+
105
+ Args:
106
+ data_dict (dict): Input data dict
107
+ Returns:
108
+ data_dict (dict): Output dict where images are resized
109
+ """
110
+
111
+ if self.output_keys is None:
112
+ self.output_keys = self.input_keys
113
+ assert self.args is not None, "Please specify args in augmentations"
114
+
115
+ img_size = obtain_augmentation_size(data_dict, self.args)
116
+ assert isinstance(img_size, (tuple, omegaconf.listconfig.ListConfig)), (
117
+ f"Arg size in resize should be a tuple, get {type(img_size)}, {img_size}"
118
+ )
119
+ img_w, img_h = img_size
120
+
121
+ orig_w, orig_h = obtain_image_size(data_dict, self.input_keys)
122
+ scaling_ratio = max((img_w / orig_w), (img_h / orig_h))
123
+ target_size = (int(scaling_ratio * orig_h + 0.5), int(scaling_ratio * orig_w + 0.5))
124
+
125
+ assert target_size[0] >= img_h and target_size[1] >= img_w, (
126
+ f"Resize error. orig {(orig_w, orig_h)} desire {img_size} compute {target_size}"
127
+ )
128
+
129
+ for inp_key, out_key in zip(self.input_keys, self.output_keys):
130
+ data_dict[out_key] = transforms_F.resize(
131
+ data_dict[inp_key],
132
+ size=target_size, # type: ignore
133
+ interpolation=(
134
+ self.args["interpolation"]
135
+ if "interpolation" in self.args
136
+ else transforms_F.InterpolationMode.BICUBIC
137
+ ),
138
+ antialias=True,
139
+ )
140
+
141
+ if out_key != inp_key:
142
+ del data_dict[inp_key]
143
+ return data_dict
144
+
145
+
146
+ class ResizeLargestSideAspectPreserving(Augmentor):
147
+ def __init__(self, input_keys: list, output_keys: Optional[list] = None, args: Optional[dict] = None) -> None:
148
+ super().__init__(input_keys, output_keys, args)
149
+
150
+ def __call__(self, data_dict: dict) -> dict:
151
+ r"""Performs aspect-ratio preserving resizing.
152
+ Image is resized to the dimension which has the larger ratio of (size / target_size).
153
+ First we compute (w_img / w_target) and (h_img / h_target) and resize the image
154
+ to the dimension that has the larger of these ratios.
155
+
156
+ Args:
157
+ data_dict (dict): Input data dict
158
+ Returns:
159
+ data_dict (dict): Output dict where images are resized
160
+ """
161
+
162
+ if self.output_keys is None:
163
+ self.output_keys = self.input_keys
164
+ assert self.args is not None, "Please specify args in augmentations"
165
+
166
+ img_size = obtain_augmentation_size(data_dict, self.args)
167
+ assert isinstance(img_size, (tuple, omegaconf.listconfig.ListConfig)), (
168
+ f"Arg size in resize should be a tuple, get {type(img_size)}, {img_size}"
169
+ )
170
+ img_w, img_h = img_size
171
+
172
+ orig_w, orig_h = obtain_image_size(data_dict, self.input_keys)
173
+ scaling_ratio = min((img_w / orig_w), (img_h / orig_h))
174
+ target_size = (int(scaling_ratio * orig_h + 0.5), int(scaling_ratio * orig_w + 0.5))
175
+
176
+ assert target_size[0] <= img_h and target_size[1] <= img_w, (
177
+ f"Resize error. orig {(orig_w, orig_h)} desire {img_size} compute {target_size}"
178
+ )
179
+
180
+ for inp_key, out_key in zip(self.input_keys, self.output_keys):
181
+ data_dict[out_key] = transforms_F.resize(
182
+ data_dict[inp_key],
183
+ size=target_size, # type: ignore
184
+ interpolation=getattr(self.args, "interpolation", transforms_F.InterpolationMode.BICUBIC),
185
+ antialias=True,
186
+ )
187
+
188
+ if out_key != inp_key:
189
+ del data_dict[inp_key]
190
+ return data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/config/schema.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional, Type
17
+
18
+ import attrs
19
+ from torch.utils.data import IterableDataset
20
+
21
+ from cosmos_policy._src.imaginaire import config
22
+ from cosmos_policy._src.imaginaire.config import make_freezable
23
+ from cosmos_policy._src.imaginaire.datasets.webdataset.augmentors.augmentor import Augmentor
24
+
25
+
26
+ @make_freezable
27
+ @attrs.define(slots=False)
28
+ class DatasetInfo:
29
+ object_store_config: config.ObjectStoreConfig # Object strore config
30
+ wdinfo: list[str] # List of wdinfo files
31
+ opts: dict = attrs.Factory(dict) # Additional dataset info args
32
+ per_dataset_keys: list[str] = attrs.Factory(list) # List of keys per dataset
33
+ source: str = "" # data source
34
+
35
+
36
+ @make_freezable
37
+ @attrs.define(slots=False)
38
+ class TarSample:
39
+ path: str # Path to the sample
40
+ root: str # Root folder
41
+ keys: list # List of keys to be loaded from the webdataset
42
+ meta: DatasetInfo # Metadata
43
+ dset_id: str # Dataset id
44
+ sample_keys_full_list: str = None # Path to the file containing full sample keys for the tar file
45
+
46
+
47
+ @make_freezable
48
+ @attrs.define(slots=False)
49
+ class Wdinfo:
50
+ tar_files: list[TarSample] # List of all tar samples
51
+ total_key_count: int # Total number of elements present in the dataset
52
+ chunk_size: int # Number of elements present in each tar
53
+
54
+
55
+ @make_freezable
56
+ @attrs.define(slots=False)
57
+ class AugmentorConfig:
58
+ # Type of augmentor
59
+ type: Type[Augmentor]
60
+ # Input keys used by the augmentor
61
+ input_keys: list[str]
62
+ # Output keys returned by the augmentor
63
+ output_keys: Optional[list[str]] = None
64
+ # Additional arguments used by the augmentor
65
+ args: Optional[dict] = None
66
+
67
+ def make_instance(self) -> Augmentor:
68
+ return self.type(input_keys=self.input_keys, output_keys=self.output_keys, args=self.args)
69
+
70
+
71
+ @make_freezable
72
+ @attrs.define(slots=False)
73
+ class DatasetConfig:
74
+ keys: list[str] # List of keys used
75
+ buffer_size: int # Buffer size used by each worker
76
+ dataset_info: list[DatasetInfo] # List of dataset info files, one for each dataset
77
+ distributor: IterableDataset # Iterator for returning list of tar files
78
+ decoders: list # List of decoder functions for decoding bytestream
79
+ augmentation: dict[str, AugmentorConfig] # Dictionary containing all augmentations
80
+ streaming_download: bool = True # Whether to use streaming loader
81
+ remove_extension_from_keys: bool = True # True: objects will have a key of data_type; False: data_type.extension
82
+ sample_keys_full_list_path: Optional[str] = (
83
+ None # Path to the file containing all keys present in the dataset, e.g., "index"
84
+ )
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/dataloader.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+
18
+ import webdataset
19
+
20
+ import cosmos_policy._src.imaginaire.datasets.webdataset.webdataset
21
+ from cosmos_policy._src.imaginaire.utils.distributed import get_world_size
22
+
23
+
24
+ class Sampler:
25
+ r"""
26
+ A sampler function for setting the epoch number and iteration number.
27
+ In webdataset, information is propagated using environment flags.
28
+ In our case,
29
+ WDS_EPOCH_NUM: Epoch number
30
+ WDS_START_INDEX: Start index in this epoch.
31
+ """
32
+
33
+ def __init__(self, mode: str):
34
+ self.mode = mode
35
+ assert self.mode in ["train", "val"]
36
+
37
+ def set_epoch(self, epoch: int):
38
+ if self.mode == "train":
39
+ os.environ["WDS_EPOCH_NUM"] = str(epoch)
40
+ else:
41
+ pass
42
+
43
+ def set_iteration(self, start_index: int):
44
+ # start_index should be iters * batch_size
45
+ # It is the number of samples that have been seen by one GPU
46
+ if self.mode == "train":
47
+ os.environ["WDS_START_INDEX"] = str(start_index)
48
+ else:
49
+ pass
50
+
51
+
52
+ class DataLoader(webdataset.WebLoader):
53
+ r"""
54
+ This class is a wrapper on webloader class with a len attribute.
55
+ len function is needed in Imaginaire dataloaders.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ dataset: cosmos_policy._src.imaginaire.datasets.webdataset.webdataset.Dataset,
61
+ batch_size: int = 1,
62
+ *args,
63
+ **kw,
64
+ ): # type: ignore
65
+ # Setting data length. Webdataset is an iterable dataset, so it does not have data_len attr.
66
+ # So, we compute it from dataset and set it.
67
+ dataset_obj = dataset.build_dataset()
68
+ world_size = get_world_size()
69
+ if dataset_obj.total_images < world_size * batch_size: # type: ignore
70
+ data_length = 1
71
+ else:
72
+ data_length = dataset_obj.total_images // (world_size * batch_size) # type: ignore
73
+ self.data_len = data_length
74
+
75
+ super().__init__(dataset_obj, batch_size, *args, **kw)
76
+
77
+ def __len__(self) -> int:
78
+ return self.data_len
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/depth.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Depth decoder for EXR files."""
17
+
18
+ import re
19
+ from io import BytesIO
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ _EXR_EXTENSIONS = "exr"
25
+ MAX_DEPTH = 100000
26
+ _NPZ_EXTENSIONS = "npz"
27
+
28
+
29
+ def exr_loader(key, data):
30
+ """Load depth data from EXR file.
31
+
32
+ Args:
33
+ key (str): Key of the data
34
+ data (bytes): Raw EXR file data
35
+
36
+ Returns:
37
+ torch.Tensor: Depth map as tensor
38
+ """
39
+ # pyrefly: ignore # import-error
40
+ import OpenEXR
41
+
42
+ extension = re.sub(r".*[.]", "", key)
43
+ if extension.lower() not in _EXR_EXTENSIONS:
44
+ return None
45
+
46
+ # Convert bytes to BytesIO for OpenEXR
47
+ exr_file = OpenEXR.InputFile(BytesIO(data))
48
+
49
+ # Get the header information
50
+ header = exr_file.header()
51
+ dw = header["dataWindow"]
52
+ w = dw.max.x - dw.min.x + 1
53
+ h = dw.max.y - dw.min.y + 1
54
+
55
+ # Read the depth data from 'R' channel
56
+ depth = np.frombuffer(exr_file.channel("R"), dtype=np.float32).reshape((h, w))
57
+ mask = depth == np.nan
58
+ depth = depth.copy()
59
+ depth[mask] = MAX_DEPTH
60
+
61
+ # Convert to tensor and normalize to [0, 1]
62
+ depth = torch.from_numpy(depth).float()
63
+
64
+ depth = depth.unsqueeze(0)
65
+ return depth
66
+
67
+
68
+ def npz_loader(key, data):
69
+ """Load depth data from NPZ file."""
70
+
71
+ extension = re.sub(r".*[.]", "", key)
72
+ if extension.lower() not in _NPZ_EXTENSIONS:
73
+ return None
74
+
75
+ # Convert bytes to BytesIO for np.load
76
+ npz_file = BytesIO(data)
77
+
78
+ # Load the NPZ file
79
+ with np.load(npz_file) as npz_data:
80
+ # Assuming the depth data is stored in the first array
81
+ # You may need to adjust this based on your specific NPZ file structure
82
+ depth_array = npz_data[list(npz_data.keys())[0]]
83
+ # Convert to tensor and normalize to [0, 1] if needed
84
+ depth = torch.from_numpy(depth_array).float()
85
+
86
+ return depth
87
+
88
+
89
+ def construct_videodepth_decoder():
90
+ """Construct videodepth decoder with frame count filtering.
91
+
92
+ Args:
93
+ min_frames (int): Minimum number of frames required. Samples with fewer frames will be skipped.
94
+
95
+ Returns:
96
+ callable: Videodepth decoder function that filters by frame count
97
+ """
98
+
99
+ def videodepth_decoder(key, data):
100
+ """Decode depth video data from NPZ file and filter by frame count.
101
+
102
+ Args:
103
+ key (str): Key of the data
104
+ data (bytes): Raw NPZ file data
105
+
106
+ Returns:
107
+ torch.Tensor: Depth video tensor if it has enough frames, None otherwise (to skip)
108
+ """
109
+ # Load the depth data using npz_loader
110
+ depth = npz_loader(key, data)
111
+ if depth is None:
112
+ return None
113
+
114
+ # Check frame count - determine temporal dimension
115
+ if depth.dim() == 4: # CxTxHxW
116
+ total_frames = depth.shape[1]
117
+ elif depth.dim() == 3: # TxHxW
118
+ total_frames = depth.shape[0]
119
+ else:
120
+ # For 2D depth maps (single frame), skip filtering
121
+ return depth
122
+
123
+ return depth
124
+
125
+ return videodepth_decoder
126
+
127
+
128
+ def construct_depth_decoder(sequence_length: int = 0):
129
+ """Construct depth decoder.
130
+
131
+ Args:
132
+ sequence_length (int): Number of frames to decode. Set to 0 for single frame.
133
+
134
+ Returns:
135
+ callable: Depth decoder function
136
+ """
137
+
138
+ def depth_decoder(key, sample):
139
+ """Decode depth data from sample.
140
+
141
+ Args:
142
+ key (str): Key of the data
143
+ sample (dict): Sample dictionary containing depth data
144
+
145
+ Returns:
146
+ dict: Sample dictionary with decoded depth data
147
+ """
148
+ depth = exr_loader(key, sample)
149
+ if depth is None:
150
+ return None
151
+ return depth
152
+
153
+ return depth_decoder
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/image.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import re
18
+ from typing import Optional
19
+
20
+ from PIL import Image
21
+
22
+ Image.MAX_IMAGE_PIXELS = 933120000
23
+ _IMG_EXTENSIONS = "jpg jpeg png ppm pgm pbm pnm".split()
24
+
25
+
26
+ def pil_loader(key: str, data: bytes) -> Optional[Image.Image]:
27
+ r"""
28
+ Function to load an image.
29
+ If the image is corrupt, it returns a black image.
30
+ Args:
31
+ key (str): Image key.
32
+ data (bytes): Image data stream.
33
+ Returns:
34
+ PIL image
35
+ """
36
+ extension = re.sub(r".*[.]", "", key)
37
+ if extension.lower() not in _IMG_EXTENSIONS:
38
+ return None
39
+
40
+ with io.BytesIO(data) as stream:
41
+ img = Image.open(stream)
42
+ img.load()
43
+ img = img.convert("RGB")
44
+
45
+ return img
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/decoders/pickle.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import pickle
17
+ import re
18
+ from typing import Optional
19
+
20
+
21
+ def pkl_decoder(key: str, data: bytes) -> Optional[dict]:
22
+ r"""
23
+ Function to decode a pkl file.
24
+ Args:
25
+ key: Data key.
26
+ data: Data dict.
27
+ """
28
+ extension = re.sub(r".*[.]", "", key)
29
+ if extension == "pkl" or extension == "pickle":
30
+ data_dict = pickle.loads(data)
31
+ return data_dict
32
+ else:
33
+ return None
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from cosmos_policy._src.imaginaire.datasets.webdataset.distributors.basic import ShardlistBasic
17
+ from cosmos_policy._src.imaginaire.datasets.webdataset.distributors.multi_aspect_ratio import ShardlistMultiAspectRatio
18
+ from cosmos_policy._src.imaginaire.datasets.webdataset.distributors.multi_aspect_ratio_v2 import (
19
+ ShardlistMultiAspectRatioInfinite,
20
+ )
21
+
22
+ distributors_list = {
23
+ "basic": ShardlistBasic,
24
+ "multi_aspect_ratio": ShardlistMultiAspectRatio,
25
+ "multi_aspect_ratio_infinite": ShardlistMultiAspectRatioInfinite,
26
+ }
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/basic.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ import random
18
+ import time
19
+
20
+ from webdataset.pytorch import IterableDataset
21
+ from webdataset.utils import pytorch_worker_info
22
+
23
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import TarSample
24
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.misc import repeat_list
25
+ from cosmos_policy._src.imaginaire.utils import log
26
+
27
+
28
+ class ShardlistBasic(IterableDataset):
29
+ r"""
30
+ An iterable dataset that parses and yields tar files.
31
+ The dataset restored from an iteration number and index number.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ shuffle: bool = True,
37
+ split_by_node: bool = True,
38
+ split_by_worker: bool = True,
39
+ resume_flag: bool = True,
40
+ verbose: bool = False,
41
+ is_infinite_loader: bool = False,
42
+ max_epochs: int = 100000,
43
+ repeat_url: bool = True,
44
+ ):
45
+ r"""Create a ShardList.
46
+ Args:
47
+ shuffle (bool): shuffle samples before iterating.
48
+ split_by_node (bool): split shards by node if True
49
+ split_by_worker (bool): split shards by worker if True
50
+ resume_flag (bool): If enabled, resumes from a specific iteration and epoch number.
51
+ verbose (bool): Prints some logs if true
52
+ is_infinite_loader (bool): If true, creates an infinite dataloader.
53
+ So, the dataset will be only one epoch and will not terminate.
54
+ max_epochs (int): Infinite dataloader is created with max_epochs number of epochs.
55
+ Should be a very large number.
56
+ repeat_url (bool): If true, each worker will receive the same number of batches by repeating urls.
57
+ """
58
+ super().__init__()
59
+
60
+ self.verbose = verbose
61
+ if self.verbose:
62
+ log.info("ShardListWithResumes init")
63
+ self.epoch = 0
64
+ self.start_index = 0
65
+ self.shuffle = shuffle
66
+ self.split_by_node = split_by_node
67
+ self.split_by_worker = split_by_worker
68
+ self.resume_flag = resume_flag
69
+ self.is_infinite_loader = is_infinite_loader
70
+ self.max_epochs = max_epochs
71
+ self.repeat_url = repeat_url
72
+
73
+ def set_urls(self, urls: list[TarSample]):
74
+ """Set urls
75
+
76
+ Args:
77
+ urls (list[TarSample]): a list of tar files along with their metadata
78
+ """
79
+ self.urls = urls
80
+
81
+ def set_chunk_size(self, chunk_size: int):
82
+ """Set chunk size
83
+
84
+ Args:
85
+ chunk_size (int): chunk size used in webdataset creation
86
+ """
87
+ self.chunk_size = chunk_size
88
+
89
+ def set_epoch(self, epoch: int, start_index: int):
90
+ r"""Set the current epoch. Used for per-node shuffling.
91
+ Args:
92
+ epoch (int): Epoch number
93
+ start_index (int): iteraton number
94
+ """
95
+ self.epoch = epoch
96
+ self.start_index = start_index
97
+
98
+ def obtain_url_list(self):
99
+ r"""Return an iterator over the shards."""
100
+
101
+ rank, world_size, worker_id, num_workers = pytorch_worker_info()
102
+
103
+ # Setting epoch and start index
104
+ if self.resume_flag:
105
+ self.epoch = int(os.environ.get("WDS_EPOCH_NUM", 0))
106
+ # This tells us number of chunks that have been seen by one GPU
107
+ self.start_index = int(os.environ.get("WDS_START_INDEX", 0)) // self.chunk_size
108
+
109
+ urls = self.urls
110
+ num_urls = len(urls)
111
+
112
+ if self.repeat_url:
113
+ # Extending urls so that each workers receive the same number of batches.
114
+ # This serves the job of ddp_equalize.
115
+ nworkers_all = world_size * num_workers
116
+ num_urls_per_process = (num_urls + nworkers_all - 1) // nworkers_all
117
+ extended_url_list_size = num_urls_per_process * nworkers_all
118
+ urls = repeat_list(urls, extended_url_list_size)
119
+
120
+ # Splits the urls by node and worker id. This ensures each worker sees different urls.
121
+ if self.split_by_node:
122
+ urls = urls[rank::world_size]
123
+ if self.split_by_worker:
124
+ urls = urls[worker_id::num_workers]
125
+
126
+ if self.verbose:
127
+ log.info("List of urls (before shuffle)")
128
+ log.info(urls[0:10])
129
+
130
+ if self.shuffle:
131
+ # Shuffle based on the world worker id.
132
+ random.Random(rank * num_workers + worker_id).shuffle(urls)
133
+
134
+ # This tells us the number of chunks seen by one worker.
135
+ # Do not iterate over the seen chunks.
136
+ start_index_per_worker = self.start_index // num_workers
137
+ if not self.is_infinite_loader:
138
+ urls = urls[start_index_per_worker:]
139
+
140
+ if self.verbose:
141
+ log.info("List of urls (after shuffle)")
142
+ log.info(urls[0:10])
143
+ log.info(f"PytorchShardList got {len(urls)} urls")
144
+
145
+ return urls
146
+
147
+ def __iter__(self):
148
+ url_list = self.obtain_url_list()
149
+
150
+ if self.is_infinite_loader:
151
+ for _ in range(self.max_epochs):
152
+ cur_time = int(time.time())
153
+ random.Random(cur_time).shuffle(url_list)
154
+ for url in url_list:
155
+ yield dict(url=url)
156
+ else:
157
+ for url in url_list:
158
+ yield dict(url=url)
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # This script contains the code for multi-aspect ratio shard iterator
17
+
18
+ import math
19
+ import os
20
+ import random
21
+ import time
22
+ from collections import defaultdict
23
+ from copy import deepcopy
24
+
25
+ from webdataset.pytorch import IterableDataset
26
+ from webdataset.utils import pytorch_worker_info
27
+
28
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import TarSample
29
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.misc import repeat_list
30
+ from cosmos_policy._src.imaginaire.utils import log
31
+
32
+
33
+ class ShardlistMultiAspectRatio(IterableDataset):
34
+ r"""
35
+ An iterable dataset that parses and yields tar files.
36
+ This distributor handles the multi-aspect ratio case. For the dataloader to be successful,
37
+ each worker should load only one aspect ratio. Else, there can be a batch where two
38
+ aspect ratios would be present which would raise an error in collate function.
39
+ So, we design data distribution strategy so that each worker sees only one aspect ratio.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ shuffle: bool = True,
45
+ split_by_node: bool = True,
46
+ split_by_worker: bool = True,
47
+ chunk_size: int = 1,
48
+ resume_flag: bool = True,
49
+ verbose: bool = False,
50
+ is_infinite_loader: bool = False,
51
+ ):
52
+ r"""Create a multi-aspect ratio ShardList.
53
+ Args:
54
+ urls (list[TarSample]): a list of tar files along with their metadata
55
+ epoch_shuffle (bool): Shuffles the whole epoch. If disabled, each node will see the same set of urls.
56
+ shuffle (bool): shuffle samples before iterating.
57
+ split_by_node (bool): split shards by node if True
58
+ split_by_worker (bool): split shards by worker if True
59
+ chunk_size (int): chunk size used in webdataset creation
60
+ resume_flag (bool): If enabled, resumes from a specific iteration and epoch number.
61
+ verbose (bool): Prints some logs if true
62
+ is_infinite_loader (bool): If true, creates an infinite dataloader.
63
+ So, the dataset will be only one epoch and will not terminate.
64
+ """
65
+ super().__init__()
66
+
67
+ self.verbose = verbose
68
+ if self.verbose:
69
+ log.info("ShardListWithResumes init")
70
+ self.epoch = 0
71
+ self.start_index = 0
72
+ self.shuffle = shuffle
73
+ self.split_by_node = split_by_node
74
+ self.split_by_worker = split_by_worker
75
+ self.chunk_size = chunk_size
76
+ self.resume_flag = resume_flag
77
+ self.is_infinite_loader = is_infinite_loader
78
+
79
+ def set_urls(self, urls: list[TarSample]):
80
+ self.urls = urls
81
+ self._split_urls_by_aspect_ratio()
82
+
83
+ def set_chunk_size(self, chunk_size: int):
84
+ """Set chunk size
85
+
86
+ Args:
87
+ chunk_size (int): chunk size used in webdataset creation
88
+ """
89
+ self.chunk_size = chunk_size
90
+
91
+ def set_epoch(self, epoch: int, start_index: int):
92
+ r"""Set the current epoch. Used for per-node shuffling.
93
+ Args:
94
+ epoch (int): Epoch number
95
+ start_index (int): iteraton number
96
+ """
97
+ self.epoch = epoch
98
+ self.start_index = start_index
99
+
100
+ def _split_urls_by_aspect_ratio(self):
101
+ r"""Function for splitting urls by aspect ratio.
102
+ We assume that urls are grouped by dataset_id. That is, data belonging to
103
+ one dataset_id should have all data in the same aspect ratio.
104
+ """
105
+
106
+ url_aspect_split = defaultdict(list)
107
+
108
+ for url in self.urls:
109
+ dset_info = url.meta
110
+ if "aspect_ratio" not in dset_info.opts:
111
+ raise ValueError("aspect_ratio should be specified in dataset_info when using multi aspect distributor")
112
+ aspect_ratio = dset_info.opts["aspect_ratio"]
113
+ url_aspect_split[aspect_ratio].append(url)
114
+
115
+ aspect_ratio_with_most_elems = -1
116
+ aspect_ratio_with_least_elems = -1
117
+ max_aspect_ratio_count = -1
118
+ min_aspect_ratio_count = 1000000000
119
+
120
+ for aspect_ratio in url_aspect_split:
121
+ # Sort the url list
122
+ url_aspect_split[aspect_ratio] = sorted(
123
+ url_aspect_split[aspect_ratio], key=lambda tar: (tar.path, tar.root)
124
+ )
125
+
126
+ # Finding max and min tar counts per aspect ratio
127
+ if len(url_aspect_split[aspect_ratio]) > max_aspect_ratio_count:
128
+ aspect_ratio_with_most_elems = aspect_ratio
129
+ max_aspect_ratio_count = len(url_aspect_split[aspect_ratio])
130
+ if len(url_aspect_split[aspect_ratio]) < min_aspect_ratio_count:
131
+ aspect_ratio_with_least_elems = aspect_ratio
132
+ min_aspect_ratio_count = len(url_aspect_split[aspect_ratio])
133
+
134
+ self.url_aspect_split = url_aspect_split
135
+ self.aspect_ratio_with_most_elems = aspect_ratio_with_most_elems
136
+ self.aspect_ratio_with_least_elems = aspect_ratio_with_least_elems
137
+
138
+ def _ddp_equalize(
139
+ self, url_aspect_split: dict[str, list[TarSample]], nworkers_all: int
140
+ ) -> tuple[dict[str, list[TarSample]], int]:
141
+ r"""This function performs tar file equalization. That is, we repeat the number of tars in each aspect
142
+ ratio so that when the tars are split across workers, each worker recieves the same number of tars.
143
+ This function is important for ddp to terminate well at the end of each epoch.
144
+
145
+ Args:
146
+ url_aspect_split (dict[list[TarSample]]): TarSample split by aspect ratio
147
+ nworkers_all (int): Total number of dataloader workers
148
+
149
+ Returns:
150
+ url_aspect_split (dict[list[TarSample]]): TarSample split after DDP equalization
151
+ num_urls_per_worker (int): Number of tars in each worker
152
+ """
153
+ betas = []
154
+ n_total = sum([len(url_aspect_split[aspect_ratio]) for aspect_ratio in url_aspect_split])
155
+
156
+ # Initial assignment
157
+ aspect_ind_with_most_elems = 0
158
+ for i, aspect_ratio in enumerate(url_aspect_split):
159
+ betas.append(math.ceil((len(url_aspect_split[aspect_ratio]) / n_total) * nworkers_all))
160
+ if aspect_ratio == self.aspect_ratio_with_most_elems:
161
+ aspect_ind_with_most_elems = i
162
+
163
+ # Constraint that total number of workers is fixed
164
+ betas[aspect_ind_with_most_elems] += nworkers_all - sum(betas)
165
+
166
+ # Rebalance the number of urls
167
+ num_urls_per_worker = math.ceil(n_total / sum(betas))
168
+ for i, aspect_ratio in enumerate(url_aspect_split):
169
+ url_aspect_split[aspect_ratio] = repeat_list(url_aspect_split[aspect_ratio], betas[i] * num_urls_per_worker)
170
+
171
+ return url_aspect_split, num_urls_per_worker
172
+
173
+ def _obtain_node_worker_url_mapping(
174
+ self,
175
+ url_aspect_split: dict[str, list[TarSample]],
176
+ num_urls_per_worker: int,
177
+ rank: int,
178
+ world_size: int,
179
+ worker_id: int,
180
+ num_workers: int,
181
+ ):
182
+ r"""This function obtains the worker-URL mapping. It assigns the tar list seen by
183
+ each workers.
184
+
185
+ Args:
186
+ url_aspect_split (dict[list[TarSample]]: TarSample split by aspect ratio
187
+ num_urls_per_worker (int): Number of tar files seen by each worker
188
+ rank (int): Rank of the current GPU
189
+ world_size (int): Total number of GPUs
190
+ worker_id (int): ID for the current worker in the dataloader
191
+ num_workers (int): Total number of workers in the dataloader
192
+
193
+ Returns:
194
+ URL list for the current worker
195
+ """
196
+ assert self.split_by_node is True and self.split_by_worker is True
197
+
198
+ # First chunk the tars
199
+ chunk_mappings = []
200
+ for aspect_ratio in url_aspect_split:
201
+ samples_asp = url_aspect_split[aspect_ratio]
202
+ nchunks_asp = int(len(samples_asp) / num_urls_per_worker)
203
+ for chunk_id in range(nchunks_asp):
204
+ chunk_mappings.append((aspect_ratio, samples_asp[chunk_id::nchunks_asp]))
205
+
206
+ # Split by rank and workers
207
+ chunk_mappings = chunk_mappings[rank::world_size]
208
+ chunk_mappings = chunk_mappings[worker_id::num_workers]
209
+
210
+ assert len(chunk_mappings) == 1
211
+ return chunk_mappings[0][1]
212
+
213
+ def obtain_url_list(self):
214
+ r"""Return an iterator over the shards."""
215
+
216
+ rank, world_size, worker_id, num_workers = pytorch_worker_info()
217
+
218
+ # Setting epoch and start index
219
+ if self.resume_flag:
220
+ self.epoch = int(os.environ.get("WDS_EPOCH_NUM", 0))
221
+
222
+ # This tells us number of chunks that have been seen by one GPU
223
+ self.start_index = int(os.environ.get("WDS_START_INDEX", 0)) // self.chunk_size
224
+
225
+ urls = deepcopy(self.urls)
226
+ url_aspect_split = deepcopy(self.url_aspect_split)
227
+
228
+ # Splitting the shards by worker and node
229
+ if self.verbose:
230
+ log.info(f"PytorchShardList rank {rank} of {world_size}")
231
+ log.info(f"PytorchShardList worker {worker_id} of {num_workers}")
232
+
233
+ nworkers_all = world_size * num_workers
234
+
235
+ # Perform DDP equalization
236
+ url_aspect_split, num_urls_per_worker = self._ddp_equalize(url_aspect_split, nworkers_all)
237
+
238
+ # Form a mapping of url_aspect_split to node and workers
239
+ urls = self._obtain_node_worker_url_mapping(
240
+ url_aspect_split, num_urls_per_worker, rank, world_size, worker_id, num_workers
241
+ )
242
+
243
+ if self.verbose:
244
+ log.info("List of urls (before shuffle)")
245
+ log.info(urls[0:10])
246
+
247
+ if self.shuffle:
248
+ random.Random(rank * num_workers + worker_id).shuffle(urls)
249
+
250
+ # This tells us the number of chunks seen by one worker.
251
+ # Do not iterate over the seen chunks.
252
+ start_index_per_worker = self.start_index // num_workers
253
+ if not self.is_infinite_loader:
254
+ urls = urls[start_index_per_worker:]
255
+
256
+ if self.verbose:
257
+ log.info("List of urls (after shuffle)")
258
+ log.info(urls[0:10])
259
+ log.info(f"PytorchShardList got {len(urls)} urls")
260
+
261
+ return urls
262
+
263
+ def __iter__(self):
264
+ url_list = self.obtain_url_list()
265
+
266
+ if self.is_infinite_loader:
267
+ while True:
268
+ cur_time = time.time_ns()
269
+ random.Random(cur_time).shuffle(url_list)
270
+ for url in url_list:
271
+ yield dict(url=url)
272
+ else:
273
+ for url in url_list:
274
+ yield dict(url=url)
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio_v2.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # This script contains the code for multi-aspect ratio shard iterator
17
+
18
+ import random
19
+ import time
20
+ from collections import defaultdict
21
+
22
+ import numpy as np
23
+ from webdataset.pytorch import IterableDataset
24
+ from webdataset.utils import pytorch_worker_info
25
+
26
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import TarSample
27
+ from cosmos_policy._src.imaginaire.utils import log
28
+
29
+
30
+ class ShardlistMultiAspectRatioInfinite(IterableDataset):
31
+ r"""
32
+ An iterable dataset that parses and yields tar files.
33
+ This distributor handles the multi-aspect ratio case. For the dataloader to be successful,
34
+ each worker should load only one aspect ratio. Else, there can be a batch where two
35
+ aspect ratios would be present which would raise an error in collate function.
36
+ So, we design data distribution strategy so that each worker sees only one aspect ratio.
37
+
38
+ This version only supports infinite loader mode. This enables a simpler code that is faster to initialize
39
+ and produces samples better matching the dataset distribution.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ shuffle: bool = True,
45
+ split_by_node: bool = True,
46
+ split_by_worker: bool = True,
47
+ chunk_size: int = 1,
48
+ resume_flag: bool = True,
49
+ verbose: bool = False,
50
+ is_infinite_loader: bool = True,
51
+ ):
52
+ r"""Create a multi-aspect ratio ShardList.
53
+ Args:
54
+ urls (list[TarSample]): a list of tar files along with their metadata
55
+ epoch_shuffle (bool): Shuffles the whole epoch. If disabled, each node will see the same set of urls.
56
+ shuffle (bool): shuffle samples before iterating.
57
+ split_by_node (bool): split shards by node if True
58
+ split_by_worker (bool): split shards by worker if True
59
+ chunk_size (int): Ignored
60
+ resume_flag (bool): Ignored
61
+ verbose (bool): Prints some logs if true
62
+ is_infinite_loader (bool): If true, creates an infinite dataloader.
63
+ So, the dataset will be only one epoch and will not terminate.
64
+ """
65
+ super().__init__()
66
+
67
+ self.verbose = verbose
68
+ if self.verbose:
69
+ log.info("ShardlistMultiAspectRatioInfinite init")
70
+ self.shuffle = shuffle
71
+ self.split_by_node = split_by_node
72
+ self.split_by_worker = split_by_worker
73
+ self.chunk_size = chunk_size # Ignored
74
+ self.resume_flag = resume_flag # Ignored
75
+ assert is_infinite_loader is True
76
+
77
+ def set_urls(self, urls: list[TarSample]):
78
+ self.url_aspect_split = self._split_urls_by_aspect_ratio(urls)
79
+
80
+ def set_chunk_size(self, chunk_size: int):
81
+ """Set chunk size
82
+ For backward compatibility. Ignored.
83
+
84
+ Args:
85
+ chunk_size (int): chunk size used in webdataset creation
86
+ """
87
+ self.chunk_size = chunk_size
88
+
89
+ def set_epoch(self, epoch: int, start_index: int):
90
+ r"""Set the current epoch. Used for per-node shuffling.
91
+ For backward compatibility. Ignored.
92
+
93
+ Args:
94
+ epoch (int): Epoch number
95
+ start_index (int): iteraton number
96
+ """
97
+ self.epoch = epoch
98
+ self.start_index = start_index
99
+
100
+ def _split_urls_by_aspect_ratio(self, urls):
101
+ r"""Function for splitting urls by aspect ratio.
102
+ We assume that urls are grouped by dataset_id. That is, data belonging to
103
+ one dataset_id should have all data in the same aspect ratio.
104
+ """
105
+
106
+ url_aspect_split = defaultdict(list)
107
+
108
+ for url in urls:
109
+ dset_info = url.meta
110
+ if "aspect_ratio" not in dset_info.opts:
111
+ raise ValueError("aspect_ratio should be specified in dataset_info when using multi aspect distributor")
112
+ aspect_ratio = dset_info.opts["aspect_ratio"]
113
+ url_aspect_split[aspect_ratio].append(url)
114
+
115
+ for aspect_ratio in url_aspect_split:
116
+ # Sort the url list
117
+ url_aspect_split[aspect_ratio] = sorted(
118
+ url_aspect_split[aspect_ratio], key=lambda tar: (tar.path, tar.root)
119
+ )
120
+
121
+ return url_aspect_split
122
+
123
+ def _allocate_workers_to_aspects(
124
+ self, url_aspect_split: dict[str, list[TarSample]], num_workers_all: int
125
+ ) -> list[tuple[str, int]]:
126
+ r"""Allocate workers to each aspect ratio so that:
127
+ 1. Each aspect ratio has at least one worker
128
+ 2. All the workers have jobs to do
129
+
130
+ Args:
131
+ url_aspect_split (dict[list[TarSample]]): TarSample split by aspect ratio
132
+ num_workers_all (int): Total number of dataloader workers
133
+
134
+ Returns:
135
+ aspect_worker_allocation (list): List of tuple containing (aspect_key, num_workers)
136
+ """
137
+ if self.verbose:
138
+ log.info(
139
+ f"#URLs for each aspect ratio: {[len(url_aspect_split[aspect_ratio]) for aspect_ratio in url_aspect_split]}"
140
+ )
141
+
142
+ # Must have more global workers than the number of aspect ratios, as each global worker can only load a single
143
+ # aspect ratio.
144
+ num_aspects = len(url_aspect_split)
145
+ assert num_workers_all >= num_aspects
146
+
147
+ aspect_keys = list(url_aspect_split.keys())
148
+ # Allocate at least one worker per aspect ratios
149
+ target_ratio = np.array([len(url_aspect_split[key]) for key in aspect_keys])
150
+ target_ratio = target_ratio / target_ratio.sum()
151
+ aspect_worker_allocation = np.ones([num_aspects], dtype=np.int64)
152
+ for _i in range(num_workers_all - num_aspects):
153
+ current_ratio = aspect_worker_allocation / aspect_worker_allocation.sum()
154
+ aspect_worker_allocation[np.argmin(current_ratio - target_ratio)] += 1
155
+
156
+ if self.verbose:
157
+ log.info(f"Aspects: {aspect_keys}")
158
+ log.info(f"Target ratio: {target_ratio}")
159
+ log.info(f"Worker allocation: {aspect_worker_allocation}")
160
+ log.info(f"Discrepancy: {aspect_worker_allocation / aspect_worker_allocation.sum() / target_ratio}")
161
+ return [(k, v) for k, v in zip(aspect_keys, aspect_worker_allocation.tolist())]
162
+
163
+ def _obtain_node_worker_url_mapping(
164
+ self,
165
+ url_aspect_split: dict[str, list[TarSample]],
166
+ aspect_worker_allocation: list[tuple[str, int]],
167
+ rank: int,
168
+ world_size: int,
169
+ worker_id: int,
170
+ num_workers: int,
171
+ ):
172
+ r"""This function obtains the worker-URL mapping. It assigns the tar list seen by
173
+ each workers.
174
+
175
+ Args:
176
+ url_aspect_split (dict[list[TarSample]]: TarSample split by aspect ratio
177
+ aspect_worker_allocation (dict): Number of workers allocated to each aspect ratio
178
+ rank (int): Rank of the current GPU
179
+ world_size (int): Total number of GPUs
180
+ worker_id (int): ID for the current worker in the dataloader
181
+ num_workers (int): Total number of workers in the dataloader
182
+
183
+ Returns:
184
+ URL list for the current worker
185
+ """
186
+ assert self.split_by_node is True and self.split_by_worker is True
187
+
188
+ # First determine the aspect ratio for the current worker
189
+ global_worker_id = rank * num_workers + worker_id
190
+
191
+ cumulative = 0
192
+ for aspect_key, worker_count in aspect_worker_allocation:
193
+ cumulative += worker_count
194
+ if global_worker_id < cumulative:
195
+ chunk_id = global_worker_id - cumulative + worker_count
196
+ break
197
+
198
+ if self.verbose:
199
+ log.info(f"GID={global_worker_id}, aspect_key={aspect_key}, chunk_id={chunk_id}")
200
+ # chunk the urls for the target aspect ratio
201
+ urls_asp = url_aspect_split[aspect_key]
202
+ if len(urls_asp) >= worker_count:
203
+ url_chunk = urls_asp[chunk_id::worker_count]
204
+ else:
205
+ url_chunk = urls_asp[chunk_id % len(urls_asp) : chunk_id % len(urls_asp) + 1]
206
+
207
+ return url_chunk
208
+
209
+ def obtain_url_list(self):
210
+ r"""Return an iterator over the shards."""
211
+
212
+ rank, world_size, worker_id, num_workers = pytorch_worker_info()
213
+
214
+ # Splitting the shards by worker and node
215
+ if self.verbose:
216
+ log.info(f"PytorchShardList rank {rank} of {world_size}")
217
+ log.info(f"PytorchShardList worker {worker_id} of {num_workers}")
218
+
219
+ nworkers_all = world_size * num_workers
220
+
221
+ # Assigning workers to process each aspect ratio
222
+ aspect_worker_allocation = self._allocate_workers_to_aspects(self.url_aspect_split, nworkers_all)
223
+
224
+ # Form a mapping of url_aspect_split to node and workers
225
+ urls = self._obtain_node_worker_url_mapping(
226
+ self.url_aspect_split, aspect_worker_allocation, rank, world_size, worker_id, num_workers
227
+ )
228
+
229
+ if self.verbose:
230
+ log.info("List of urls (before shuffle)")
231
+ log.info(urls[0:10])
232
+
233
+ if self.shuffle:
234
+ global_worker_id = rank * num_workers + worker_id
235
+ random.Random(global_worker_id).shuffle(urls)
236
+
237
+ if self.verbose:
238
+ log.info("List of urls (after shuffle)")
239
+ log.info(urls[0:10])
240
+ log.info(f"PytorchShardList got {len(urls)} urls")
241
+
242
+ return urls
243
+
244
+ def __iter__(self):
245
+ url_list = self.obtain_url_list()
246
+ while True:
247
+ if self.shuffle:
248
+ cur_time = time.time_ns()
249
+ random.Random(cur_time).shuffle(url_list)
250
+ assert len(url_list) > 0, "No urls found"
251
+ for url in url_list:
252
+ yield dict(url=url)
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio_v2_test.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Usage:
18
+ pytest --L1 -s cosmos_policy/_src/imaginaire/datasets/webdataset/distributors/multi_aspect_ratio_v2_test.py
19
+ """
20
+
21
+ import os
22
+
23
+ import pytest
24
+
25
+ from cosmos_policy._src.imaginaire.config import ObjectStoreConfig
26
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import DatasetInfo, TarSample
27
+ from cosmos_policy._src.imaginaire.datasets.webdataset.distributors.multi_aspect_ratio_v2 import (
28
+ ShardlistMultiAspectRatioInfinite,
29
+ )
30
+ from cosmos_policy._src.imaginaire.utils import log, misc
31
+
32
+
33
+ @pytest.mark.skip(reason="not a test, it prepare test data")
34
+ def generate_data(counts):
35
+ urls = []
36
+ for aspect_key, num_urls in zip(["1:1", "4:3", "3:4", "16:9", "9:16"], counts):
37
+ dataset_info = DatasetInfo(
38
+ object_store_config=ObjectStoreConfig(), wdinfo=[], opts={"aspect_ratio": aspect_key}
39
+ )
40
+ for i in range(num_urls):
41
+ urls.append(
42
+ TarSample(
43
+ path=f"this_is_a_url_to_a_tar_file_{i:09d}",
44
+ root="root/",
45
+ keys=[],
46
+ meta=dataset_info,
47
+ dset_id="mock",
48
+ )
49
+ )
50
+ log.info(f"Generated a total of {len(urls)} urls")
51
+ return urls
52
+
53
+
54
+ @pytest.fixture(autouse=True)
55
+ def run_before_and_after_tests(tmpdir):
56
+ # Setup: run before the test
57
+ rank = os.environ.get("RANK", None)
58
+ world_size = os.environ.get("WORLD_SIZE", None)
59
+ worker = os.environ.get("WORKER", None)
60
+ num_workers = os.environ.get("NUM_WORKERS", None)
61
+
62
+ yield # this is where the testing happens
63
+
64
+ # Teardown: run after the test
65
+ def restore_env(name, value):
66
+ if value is None:
67
+ os.environ.pop(name, None)
68
+ else:
69
+ os.environ.set(name, value)
70
+
71
+ restore_env("RANK", rank)
72
+ restore_env("WORLD_SIZE", world_size)
73
+ restore_env("WORKER", worker)
74
+ restore_env("NUM_WORKERS", num_workers)
75
+
76
+
77
+ @misc.timer("test_shardlist_multi_aspect_ratio_infinite_mini")
78
+ @pytest.mark.L1
79
+ def test_shardlist_multi_aspect_ratio_infinite_mini():
80
+ urls = generate_data([100, 100, 100, 100, 100])
81
+
82
+ aspect_ratios = set()
83
+ for worker_id in range(16):
84
+ os.environ["RANK"] = "0"
85
+ os.environ["WORLD_SIZE"] = "1"
86
+ os.environ["WORKER"] = str(worker_id)
87
+ os.environ["NUM_WORKERS"] = "16"
88
+
89
+ distributor = ShardlistMultiAspectRatioInfinite(verbose=True, shuffle=False)
90
+ distributor.set_urls(urls)
91
+
92
+ distributor_iter = iter(distributor)
93
+
94
+ # Print first 10 URLs produced by the distributor
95
+ for i in range(2):
96
+ url = next(distributor_iter)
97
+ aspect_ratios.add(url["url"].meta.opts["aspect_ratio"])
98
+
99
+ assert len(aspect_ratios) == 5
100
+
101
+
102
+ # Test on a large dataset. Takes 1 minute
103
+ @misc.timer("test_shardlist_multi_aspect_ratio_infinite_large")
104
+ @pytest.mark.L1
105
+ def test_shardlist_multi_aspect_ratio_infinite_large():
106
+ urls = generate_data([123456, 234567, 10000, 500000, 500000])
107
+
108
+ aspect_ratios = set()
109
+ for worker_id in range(7):
110
+ os.environ["RANK"] = "0"
111
+ os.environ["WORLD_SIZE"] = "1"
112
+ os.environ["WORKER"] = str(worker_id)
113
+ os.environ["NUM_WORKERS"] = "7"
114
+
115
+ distributor = ShardlistMultiAspectRatioInfinite(verbose=True, shuffle=False)
116
+ distributor.set_urls(urls)
117
+
118
+ distributor_iter = iter(distributor)
119
+
120
+ # Print first 10 URLs produced by the distributor
121
+ for i in range(2):
122
+ url = next(distributor_iter)
123
+ aspect_ratios.add(url["url"].meta.opts["aspect_ratio"])
124
+
125
+ assert len(aspect_ratios) == 5
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/utils/iterators.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import os
18
+ import random
19
+ import sys
20
+ import time
21
+ from typing import IO, Any, BinaryIO, Callable, Dict, Iterable, Iterator, Optional, Tuple, Union
22
+ from urllib.parse import urlparse
23
+
24
+ import botocore
25
+ import botocore.exceptions
26
+ import pandas as pd
27
+ import webdataset.gopen as gopen_webdata
28
+ import yaml
29
+ from webdataset import cache, filters, shardlists
30
+ from webdataset.compat import FluidInterface
31
+ from webdataset.handlers import reraise_exception
32
+ from webdataset.pipeline import DataPipeline
33
+ from webdataset.pytorch import IterableDataset
34
+ from webdataset.tariterators import group_by_keys, tar_file_iterator
35
+
36
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import TarSample
37
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.stream import RetryingStream
38
+ from cosmos_policy._src.imaginaire.utils import log
39
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends import BaseStorageBackend
40
+
41
+ # Number of attempts to read s3 objects.
42
+ _NUM_OBJECT_STORE_READ_ATTEMPTS = 10
43
+
44
+
45
+ def gopen(url: Tuple, mode: str = "rb", bufsize: int = 8192, **kw) -> Union[io.BytesIO, RetryingStream, BinaryIO, IO]:
46
+ r"""Open the URL.
47
+ This uses the `gopen_schemes` dispatch table to dispatch based
48
+ on scheme.
49
+ Support for the following schemes is built-in: pipe, file,
50
+ http, https, sftp, ftps, scp.
51
+ When no scheme is given the url is treated as a file.
52
+ You can use the OPEN_VERBOSE argument to get info about
53
+ files being opened.
54
+ Args:
55
+ url (tuple): (source URL, dataset id)
56
+ the source URL is join(TarSample.root, one of TarSample.keys, TarSample.path)
57
+ e.g. join("openx_short_cmu_playing_with_food_202505/v2.3/resolution_lt_720/aspect_ratio_4_3/duration_5_10/", "videos", "part_000000/000000.tar")
58
+ mode (str): the mode ("rb", "r")
59
+ bufsize (int): the buffer size
60
+ Returns:
61
+ Byte streams
62
+ """
63
+ global fallback_gopen
64
+ verbose = int(os.environ.get("GOPEN_VERBOSE", 0))
65
+ if verbose:
66
+ log.info("GOPEN", url, gopen_webdata.info, file=sys.stderr)
67
+
68
+ assert mode in ["rb", "wb"], mode
69
+ if url == "-":
70
+ if mode == "rb":
71
+ return sys.stdin.buffer
72
+ elif mode == "wb":
73
+ return sys.stdout.buffer
74
+ else:
75
+ raise ValueError(f"unknown mode {mode}")
76
+
77
+ # If we specify 'object_store' in keyword arguments,
78
+ # then we would load from s3.
79
+ if "object_store" in kw and kw["object_store"]:
80
+ assert isinstance(url, tuple)
81
+ return gopen_s3(
82
+ url,
83
+ easy_io_backends=kw["easy_io_backend"],
84
+ s3_bucket_name=kw["s3_bucket_name"],
85
+ streaming_download=kw["streaming_download"],
86
+ )
87
+
88
+ # For all other gopen schemes, use the native webdataset gopen functions.
89
+ # pr = gopen_webdata.urlparse(url)
90
+ # this should be a path to an existing file on local machine
91
+ url = url[0]
92
+ assert isinstance(url, str)
93
+ pr = urlparse(url)
94
+ if pr.scheme == "":
95
+ bufsize = int(os.environ.get("GOPEN_BUFFER", -1))
96
+ return open(url, mode, buffering=bufsize)
97
+ if pr.scheme == "file":
98
+ bufsize = int(os.environ.get("GOPEN_BUFFER", -1))
99
+ return open(pr.path, mode, buffering=bufsize)
100
+ handler = gopen_webdata.gopen_schemes["__default__"]
101
+ handler = gopen_webdata.gopen_schemes.get(pr.scheme, handler)
102
+ return handler(url, mode, bufsize, **kw) # type: ignore
103
+
104
+
105
+ def gopen_s3(
106
+ url: tuple,
107
+ easy_io_backends: Dict[str, BaseStorageBackend],
108
+ s3_bucket_name: Dict[str, str],
109
+ streaming_download=True,
110
+ ) -> Union[io.BytesIO, RetryingStream]:
111
+ r"""Gopen scheme for s3.
112
+ Function for reading urls from s3
113
+ Args:
114
+ url (list[TarSample]): the source URL
115
+ easy_io_backends: easy_io backends for downloading from object storage
116
+ s3_bucket_name (str): Bucket name for the S3 data
117
+ Returns:
118
+ Byte streams
119
+ """
120
+
121
+ attempt = 0
122
+
123
+ url_path = url[0]
124
+ dset_id = url[1]
125
+ easy_io_backend = easy_io_backends[dset_id]
126
+ bucket = s3_bucket_name[dset_id]
127
+
128
+ while attempt < _NUM_OBJECT_STORE_READ_ATTEMPTS:
129
+ try:
130
+ if streaming_download:
131
+ # Downloads in a streaming fashion
132
+ s3_stream = RetryingStream(easy_io_backend, bucket=bucket, key=url_path)
133
+ return s3_stream
134
+ else:
135
+ # Downloads the entire file
136
+ buffer = io.BytesIO()
137
+ buffer.write(easy_io_backend.get(filepath=f"s3://{bucket}/{url_path}"))
138
+ buffer.seek(0)
139
+ return buffer
140
+ except botocore.exceptions.ClientError as e:
141
+ # If there is an exception (usually connectivity error or protocol error), read again
142
+ attempt += 1
143
+ retry_interval = min(
144
+ 0.1 * 2**attempt + random.uniform(0, 1), 30
145
+ ) # sleep workers randomly to avoid burst of requests
146
+ log.info(
147
+ f"Got an exception while downloading data {url_path}: attempt={attempt} - {e}. {type(e)}",
148
+ rank0_only=False,
149
+ )
150
+ log.info(f"Retrying tar file download after {retry_interval}s", rank0_only=False)
151
+ time.sleep(retry_interval)
152
+ continue
153
+ raise ConnectionError("Unable to read {} from PBSS. {} attempts tried.".format(url, attempt))
154
+
155
+
156
+ def url_opener(data: Iterable, handler: Callable = reraise_exception, **kw) -> Iterator[dict]:
157
+ r"""Given a stream of url names (packaged in `dict(url=url)`), yield opened streams.
158
+
159
+ Args:
160
+ data (Iterable): Iterator of dictionaires containing url paths.
161
+ handler (Callable): Exception handler.
162
+
163
+ Yields:
164
+ Dictionaries with this structure:
165
+ {"url": ...
166
+ "stream": list[Union[io.BytesIO, RetryingStream]]}
167
+ """
168
+ for sample in data:
169
+ assert isinstance(sample, dict), sample
170
+ assert "url" in sample
171
+
172
+ url = sample["url"]
173
+ assert isinstance(url, TarSample), "URL should be of type TarSample"
174
+ try:
175
+ stream = []
176
+ for data_key in url.keys:
177
+ url_path_full = os.path.join(url.root, data_key, url.path)
178
+ url_key = (url_path_full, url.dset_id)
179
+ stream.append(gopen(url_key, **kw))
180
+
181
+ sample.update(stream=stream)
182
+ yield sample
183
+ except Exception as exn:
184
+ log.info(f"Got an exception while opening urls - {exn}", rank0_only=False)
185
+ exn.args = exn.args + (url,)
186
+ if handler(exn):
187
+ continue
188
+ else:
189
+ break
190
+
191
+
192
+ def process_sample(sample, url, key_idx):
193
+ assert isinstance(sample, dict) and "data" in sample and "fname" in sample
194
+ # Edit the url entries
195
+ sample["__url__"] = url
196
+ # This is the folder name
197
+ data_key = url.keys[key_idx]
198
+ # Handle the case where data_key has "/"
199
+ data_key = data_key.replace("/", "_")
200
+ # Edit the fname to include the data_key
201
+ fname_splits = sample["fname"].split(".")
202
+ if len(fname_splits) == 2:
203
+ prefix, suffix = fname_splits # {sample_key}.{suffix} e.g. "id_1410095.json"
204
+ else: # if the fname here contains more than one dot, we replace all the dots except the last one with "-"
205
+ prefix = "-".join(fname_splits[:-1])
206
+ suffix = fname_splits[-1]
207
+
208
+ # e.g. "id_1410095.caption_ai_from_image.json"
209
+ sample["fname"] = f"{prefix}.{data_key}.{suffix}"
210
+
211
+ return sample
212
+
213
+
214
+ def tar_file_expander(
215
+ data: Iterable[Dict[str, Any]],
216
+ handler: Callable[[Exception], bool] = reraise_exception,
217
+ select_files: Optional[Callable[[str], bool]] = None,
218
+ rename_files: Optional[Callable[[str], str]] = None,
219
+ easy_io_backend: Optional[Dict[str, BaseStorageBackend]] = None,
220
+ s3_bucket_name: Optional[Dict[str, str]] = None,
221
+ ) -> Iterator[Dict[str, Any]]:
222
+ """Expand tar files.
223
+
224
+ Args:
225
+ data (Iterable[Iterable[Dict[str, Any]]]): iterator over opened tar file streams.
226
+ handler (Callable[[Exception], bool]): exception handler.
227
+ select_files (Optional[Callable[[str], bool]]): select files from tarfiles by name (permits skipping files).
228
+ rename_files (Optional[Callable[[str], bool]]): Renaming tar files.
229
+
230
+ Optional args if reading sample_keys_full_list:
231
+ easy_io_backend: If loading from object store, specify easy_io backend. Keys is the dset_id, i.e. dataset id since different dataset could use different easy_io backend and bucket
232
+ s3_bucket_name (Dict[str, str]): If loading from object store, specify S3 bucket name.
233
+
234
+ Yields:
235
+ a stream of samples.
236
+ """
237
+ for source in data:
238
+ url = source["url"]
239
+ try:
240
+ assert isinstance(source, dict)
241
+ assert "stream" in source
242
+ tar_file_iterator_list = []
243
+ for stream_id in range(len(source["stream"])):
244
+ tar_file_iterator_list.append(
245
+ tar_file_iterator(
246
+ source["stream"][stream_id],
247
+ handler=handler,
248
+ select_files=select_files,
249
+ rename_files=rename_files,
250
+ )
251
+ )
252
+ if url.sample_keys_full_list is None: # Original behavior
253
+ # tar_file_iterator_list is a list of iterator: [tar_file_iterator_0, tar_file_iterator_1, ... tar_file_iterator_N]
254
+ for sample in zip(*tar_file_iterator_list):
255
+ # Merging data from all streams
256
+ # sample is list of dictionaries, each dictionary contains data and fname
257
+ # sample [tar_file_iterator_0[0], tar_file_iterator_1[0], ... tar_file_iterator_N[0]], length = num_of_data_key
258
+ for key_idx, sample_key in enumerate(sample):
259
+ sample_key = process_sample(sample_key, url, key_idx)
260
+ yield sample_key
261
+ else:
262
+ # Read the index file from object storage
263
+ assert easy_io_backend is not None, "No easy_io backends"
264
+ assert s3_bucket_name is not None, "No S3 bucket names"
265
+ easy_io_backend_cur = easy_io_backend[url.dset_id]
266
+ bucket_cur = s3_bucket_name[url.dset_id]
267
+ sample_keys_full_list = read_sample_keys_full_list(
268
+ url.sample_keys_full_list, easy_io_backend_cur, bucket_cur
269
+ ) # e.g. ["has_material_glb_from_obj_v4_1410095_0", "has_material_glb_from_obj_v4_1410095_1", ...]
270
+ sample_keys_full_to_index = {element: index for index, element in enumerate(sample_keys_full_list)}
271
+
272
+ # Start reading the tar files
273
+ target_index = 0
274
+ last_index = [-1] * len(tar_file_iterator_list) # Keep track of the last index of each tar file
275
+ sample_list = [] # List of samples from each tar file
276
+ while True: # Exit until target_index reach the max value
277
+ skip_offset = False
278
+ for key_idx, iterator in enumerate(tar_file_iterator_list):
279
+ if last_index[key_idx] >= target_index:
280
+ # This tar is moving faster than others, skip it and wait for others
281
+ continue
282
+
283
+ # Read the tar file until current_index >= target_index
284
+ sample, current_index = run_iterator_to_index(
285
+ iterator,
286
+ target_index,
287
+ sample_keys_full_to_index,
288
+ name=f"{url.sample_keys_full_list}.{url.keys[key_idx]}",
289
+ )
290
+ if sample is None: # Iterator {key_idx} already reached the end, exit the for loop
291
+ if target_index < len(sample_keys_full_to_index): # Missing keys
292
+ missing_info = f"index_path={url.sample_keys_full_list} | id={target_index}, sample_key={sample_keys_full_list[target_index]};"
293
+ log.info(
294
+ f"[missing keys] found in tar file: data_key={url.keys[key_idx]} | {missing_info}",
295
+ rank0_only=False,
296
+ )
297
+ sample_list = [] # Reset the sample_list
298
+ break
299
+
300
+ # Update the last_index
301
+ last_index[key_idx] = current_index
302
+
303
+ # Process sample dict
304
+ sample = process_sample(sample, url=url, key_idx=key_idx)
305
+
306
+ # Now check if the current index is matched or ahead
307
+ if current_index == target_index: # Nice!
308
+ sample_list.append(sample)
309
+ elif current_index > target_index:
310
+ # This means there is missing keys in this tar, this tar is moving faster than others
311
+
312
+ # Log the missing info
313
+ missing_info = f"index_path={url.sample_keys_full_list} | "
314
+ for missing_idx in range(target_index, current_index):
315
+ missing_info += f" id={missing_idx}, sample_key={sample_keys_full_list[missing_idx]}; "
316
+ log.info(
317
+ f"[missing keys] found in tar file: data_key={url.keys[key_idx]} | {missing_info}",
318
+ rank0_only=False,
319
+ )
320
+
321
+ # Update the target_index to current_index, skip index inbetween old target_index and current_index
322
+ target_index = current_index
323
+
324
+ # Reset sample_list, save the sample from this tar into sample_list and wait for others
325
+ sample_list = [
326
+ sample
327
+ ] # Attnetion: this will change the order of sample_list, we will put them in the right order later
328
+ skip_offset = True # Skip the offset of target_index, since we are waiting for others
329
+ break
330
+ elif current_index < target_index:
331
+ # This should not happen
332
+ raise ValueError(
333
+ "Invalid output from run_iterator_to_index function. current_index should be equal or less than target_index"
334
+ )
335
+
336
+ # Decide where to yield the samples
337
+ if len(sample_list) == len(tar_file_iterator_list):
338
+ # Only yeild the samples if all the tars are preserved
339
+ all_prefix = [sample["fname"].split(".")[0] for sample in sample_list]
340
+ # Check all the prefix are the same
341
+ assert all(prefix == all_prefix[0] for prefix in all_prefix), (
342
+ f"prefixes are not the same: {all_prefix}"
343
+ )
344
+ # Correct the order of sample_list
345
+ sample_list = correct_order(sample_list, url.keys)
346
+ # Yield all the samples
347
+ for sample in sample_list:
348
+ assert isinstance(sample, dict) and "data" in sample and "fname" in sample
349
+ yield sample
350
+ sample_list = [] # Reset the sample_list
351
+ elif len(sample_list) > 1:
352
+ # Unexpected
353
+ raise ValueError(f"Unexpected length of sample_list: {len(sample_list)}")
354
+ elif len(sample_list) == 0 or len(sample_list) == 1:
355
+ # If the sample_list is empty, it means the tar file is exhausted
356
+ # If the sample_list has only one element, it means one tar file is moving faster than others
357
+ pass # Do nothing
358
+
359
+ if not skip_offset:
360
+ # If sample_list has one element, we stay at current target_index until others catch up
361
+ target_index += 1 # Increase it by 1
362
+ if target_index == len(sample_keys_full_to_index):
363
+ break # Reach the maximum index
364
+ # Make sure all the iterator are closed
365
+ for iterators in tar_file_iterator_list:
366
+ try:
367
+ next(iterators)
368
+ except StopIteration:
369
+ pass
370
+
371
+ except Exception as exn:
372
+ log.info(f"Got an exception while expanding tars - {exn}", rank0_only=False)
373
+ exn.args = exn.args + (source.get("stream"), source.get("url"))
374
+ if handler(exn):
375
+ continue
376
+ else:
377
+ break
378
+
379
+
380
+ def correct_order(sample_list: list[Dict], expected_keys_order: list[str]) -> list[Dict]:
381
+ """Make sure the order of samples are the same as the url.keys order."""
382
+ data_keys_per_sample = [sample["fname"].split(".")[1] for sample in sample_list]
383
+ expected_keys_order = [key.replace("/", "_") for key in expected_keys_order]
384
+ if data_keys_per_sample == expected_keys_order: # Correct order
385
+ return sample_list
386
+ # Order the sample_list based on the expected_keys_order
387
+ sample_list_ordered = [None] * len(expected_keys_order)
388
+ for data_key, sample in zip(data_keys_per_sample, sample_list):
389
+ idx = expected_keys_order.index(data_key)
390
+ sample_list_ordered[idx] = sample
391
+ return sample_list_ordered
392
+
393
+
394
+ def load_func_parquet(buffer):
395
+ data_list = pd.read_parquet(buffer).values.tolist()
396
+ names = [data[0] for data in data_list]
397
+ return names
398
+
399
+
400
+ def _read_sample_keys_full_list(key, easy_io_backend: BaseStorageBackend, s3_bucket_name: str):
401
+ with io.BytesIO() as buffer:
402
+ buffer.write(easy_io_backend.get(filepath=f"s3://{s3_bucket_name}/{key}"))
403
+ buffer.seek(0)
404
+ sample_keys_full_list = load_func_parquet(buffer)
405
+ sample_keys_full_list = [key.split(".")[0] for key in sample_keys_full_list]
406
+ return sample_keys_full_list
407
+
408
+
409
+ def read_sample_keys_full_list(key: str, easy_io_backend: BaseStorageBackend, s3_bucket_name: str, max_attempts=10):
410
+ for attempt in range(max_attempts):
411
+ try:
412
+ return _read_sample_keys_full_list(key, easy_io_backend, s3_bucket_name)
413
+ except botocore.exceptions.ClientError as e:
414
+ retry_interval = min(
415
+ 0.1 * 2**attempt + random.uniform(0, 1), 30
416
+ ) # sleep workers randomly to avoid burst of requests
417
+ log.exception(
418
+ f"Failed to read sample_keys_full_list {key}, attempt {attempt}. {e}. Retrying after {retry_interval}s."
419
+ )
420
+ if attempt < max_attempts - 1:
421
+ time.sleep(retry_interval)
422
+ raise ConnectionError(f"Unable to read sample_keys_full_list {key} after {max_attempts} attempts.")
423
+
424
+
425
+ def run_iterator_to_index(iterator, target_index: int, sample_keys_full_to_index: dict, name: str = ""):
426
+ """
427
+ Iterates over samples from an iterator, checking against the index of current sample (current_index)
428
+ to target_index, until it finds
429
+ 1) the sample key corresponds to the target index
430
+ or 2) the target index is passed (i,e, the target keys are missing)
431
+ or 3) until the iterator is exhausted.
432
+
433
+ This function is designed to handle cases where there are unexpected, duplicated, or missing
434
+ sample keys based on the index mapping provided.
435
+
436
+ Args:
437
+ iterator (iterator): An iterator yielding dictionaries that must include a key 'fname',
438
+ which contains the filename. The filename should be in the format 'prefix.suffix',
439
+ where 'prefix' will be used as the sample key.
440
+ target_index (int): The index of the sample to be retrieved according to the dictionary
441
+ mapping sample keys to indices.
442
+ sample_keys_full_to_index (dict): A dictionary mapping sample keys (extracted from the
443
+ 'fname' prefix of the iterator's samples) to their respective indices. This mapping
444
+ dictates the order in which samples are considered valid and should be found.
445
+ e.g. {"name_0": 0, "name_1": 1, "name_2": 2}
446
+ name (str): Names of the tar file, used to log the progress.
447
+
448
+ Returns:
449
+ tuple: A tuple containing:
450
+ - sample (dict or None): The sample dictionary that matches the target index, or None
451
+ if no such sample is found by the time the iterator is exhausted.
452
+ - current_index (int or None): The index of the found sample according to the mapping,
453
+ or None if no sample is found.
454
+
455
+ Raises:
456
+ StopIteration: If the iterator is exhausted without finding a matching sample, though this
457
+ is caught internally and handled by returning None values.
458
+ """
459
+ sample, current_index = None, None
460
+ skip_count = 0
461
+ while True:
462
+ try:
463
+ sample = next(iterator)
464
+ prefix, suffix = sample["fname"].split(".")
465
+ sample_key = prefix
466
+
467
+ if sample_key not in sample_keys_full_to_index: # extra sample_key
468
+ log.info(
469
+ f"Skipping ({skip_count}) unexpected key {sample_key}; not found in the sample_keys_full_to_index {name} {sample_keys_full_to_index.keys()}"
470
+ )
471
+ skip_count += 1
472
+ continue
473
+ current_index = sample_keys_full_to_index[sample_key] # can be <,=,> target_index
474
+ if current_index < target_index:
475
+ # Note: current_index < target_index happens when duplicated keys or it's under catching up process
476
+ # e.g. [name_0, name_0, name_1] with target index = 1
477
+ # Pointer at ^
478
+ # Current index is 0, which is less than target index 1
479
+ # In this case, we keep iterating
480
+ # log.info(f"[Skip] key {sample_key}; current_index={current_index} < target_index={target_index} {name}")
481
+ continue
482
+ elif current_index >= target_index: # Note: current_index > targer_index happens when there is missing keys
483
+ # Note: current_index > targer_index happens when there is missing keys
484
+ # e.g. [name_0, name_2, name_3] with target index 1
485
+ # Pointer at ^
486
+ # Current index is 2, which is greater than target index 1
487
+ # In this case, we return the current_index, set the target_index to 2 and tell other tars to catch up.
488
+ # if current_index == target_index: # Matched!
489
+ # log.info(f"[Pass!] current_index={current_index} == target_index={target_index}")
490
+ # else: # Missing keys
491
+ # log.info(f"[Missing key detected!] current_index={current_index} > target_index={target_index} {name}")
492
+ break
493
+
494
+ except StopIteration:
495
+ sample = None
496
+ current_index = None
497
+ break
498
+ return sample, current_index
499
+
500
+
501
+ def tarfile_samples(
502
+ src: Iterable,
503
+ handler: Callable = reraise_exception,
504
+ load_from_object_store: bool = False,
505
+ easy_io_backend: Optional[Dict[str, BaseStorageBackend]] = None,
506
+ s3_bucket_name: Optional[Dict[str, str]] = None,
507
+ streaming_download: bool = True,
508
+ ) -> Iterator[Dict]:
509
+ r"""
510
+ Given an iterator of filenames, this function opens the URL streams
511
+ and groups data by keys.
512
+
513
+ Args:
514
+ src (Iterable): Iterator of TarSample.
515
+ handler (Callable): Exception handler.
516
+ load_from_object_store (bool): A boolean flag to specify whether to load from
517
+ object store.
518
+ easy_io_backend: If loading from object store, specify easy_io backend.
519
+ s3_bucket_name (str): If loading from object store, specify S3 bucket name.
520
+ streaming_download(bool): If enabled, performs streaming download.
521
+ """
522
+ streams = url_opener(
523
+ src,
524
+ handler=handler,
525
+ object_store=load_from_object_store,
526
+ easy_io_backend=easy_io_backend,
527
+ s3_bucket_name=s3_bucket_name,
528
+ streaming_download=streaming_download,
529
+ )
530
+ files = tar_file_expander(streams, handler=handler, easy_io_backend=easy_io_backend, s3_bucket_name=s3_bucket_name)
531
+ samples = group_by_keys(files, handler=handler)
532
+ return samples
533
+
534
+
535
+ tarfile_to_samples = filters.pipelinefilter(tarfile_samples)
536
+
537
+
538
+ class WebDataset(DataPipeline, FluidInterface):
539
+ r"""Webdataset class modified to support loading from object store."""
540
+
541
+ def __init__(
542
+ self,
543
+ urls: list[TarSample],
544
+ handler: Callable = reraise_exception,
545
+ resampled: bool = False,
546
+ shardshuffle: Optional[bool] = None,
547
+ cache_size: int = -1,
548
+ cache_dir: Optional[str] = None,
549
+ detshuffle: bool = False,
550
+ nodesplitter: Callable = shardlists.single_node_only,
551
+ verbose: bool = False,
552
+ load_from_object_store: bool = False,
553
+ easy_io_backend: Optional[Dict[str, BaseStorageBackend]] = None,
554
+ s3_bucket_name: Optional[Dict[str, str]] = None,
555
+ streaming_download: bool = True,
556
+ ):
557
+ r"""
558
+ Args:
559
+ urls (list[TarSample]): An iterator containing a list of url names.
560
+ handler (Callable): Exception handler.
561
+ resampled (bool): If true, sample shards from shard list with replacement.
562
+ shardshuffle (bool): If true, shuffles the entire shard list.
563
+ cache_size (int): Size of cache.
564
+ cache_dir (str): Path to store cache.
565
+ detshuffle (bool): Whether to use deterministic shuffling when shardshuffle is True.
566
+ nodesplitter (Callable): Function for splitting urls among nodes.
567
+ verbose (bool): If True, prints logs.
568
+ load_from_object_store (bool): A boolean flag to specify whether to load from
569
+ object store.
570
+ easy_io_backend: If loading from object store, specify easy_io backend.
571
+ s3_bucket_name (str): If loading from object store, specify S3 bucket name.
572
+ streaming_download (bool): Whether to do streaming download or full object download.
573
+ """
574
+ super().__init__()
575
+ if isinstance(urls, IterableDataset):
576
+ assert not resampled
577
+ self.append(urls)
578
+ elif isinstance(urls, str) and (urls.endswith(".yaml") or urls.endswith(".yml")):
579
+ with open(urls) as stream:
580
+ spec = yaml.safe_load(stream)
581
+ assert "datasets" in spec
582
+ self.append(shardlists.MultiShardSample(spec))
583
+ elif isinstance(urls, dict):
584
+ assert "datasets" in urls
585
+ self.append(shardlists.MultiShardSample(urls))
586
+ elif resampled:
587
+ self.append(shardlists.ResampledShards(urls))
588
+ else:
589
+ self.append(shardlists.SimpleShardList(urls))
590
+ self.append(nodesplitter)
591
+ self.append(shardlists.split_by_worker)
592
+ if shardshuffle is True:
593
+ shardshuffle = 100 # type: ignore
594
+ if shardshuffle is not None:
595
+ if detshuffle:
596
+ self.append(filters.detshuffle(shardshuffle))
597
+ else:
598
+ self.append(filters.shuffle(shardshuffle))
599
+ if cache_dir is None or cache_size == 0:
600
+ self.append(
601
+ tarfile_to_samples(
602
+ handler=handler,
603
+ load_from_object_store=load_from_object_store,
604
+ easy_io_backend=easy_io_backend,
605
+ s3_bucket_name=s3_bucket_name,
606
+ streaming_download=streaming_download,
607
+ )
608
+ )
609
+ else:
610
+ # We dont use cache.
611
+ assert cache_size == -1 or cache_size > 0
612
+ self.append(
613
+ cache.cached_tarfile_to_samples(
614
+ handler=handler,
615
+ verbose=verbose,
616
+ cache_size=cache_size,
617
+ cache_dir=cache_dir,
618
+ )
619
+ )
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/utils/misc.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ from typing import Iterator
18
+
19
+
20
+ def repeat_list(x: list, n: int) -> list:
21
+ r"""Function to repeat the list to a fixed shape.
22
+ n is the desired length of the extended list.
23
+ Args:
24
+ x (list): Input list
25
+ n (int): Desired length
26
+ Returns:
27
+ Extended list
28
+ """
29
+ if n == 0:
30
+ return []
31
+ assert len(x) > 0
32
+
33
+ x_extended = []
34
+ while len(x_extended) < n:
35
+ x_extended = x_extended + x
36
+ x_extended = x_extended[0:n]
37
+
38
+ return x_extended
39
+
40
+
41
+ def remove_extensions_from_keys(data: Iterator[dict]) -> Iterator[dict]:
42
+ r"""Function to remove extension from keys
43
+ Args:
44
+ data (dict): Input data dict
45
+ Returns:
46
+ data dict with keys removed
47
+ """
48
+
49
+ for data_dict in data:
50
+ data_dict_remapped = dict()
51
+
52
+ for key in data_dict:
53
+ key_split = key.split(".")
54
+ if len(key_split) > 1:
55
+ key_new = ".".join(key_split[:-1])
56
+ else:
57
+ key_new = key
58
+ data_dict_remapped[key_new] = data_dict[key]
59
+
60
+ yield data_dict_remapped
61
+
62
+
63
+ def update_url(data: Iterator[dict]) -> Iterator[dict]:
64
+ r"""Function to update the URLs so that the TarSample is removed from data.
65
+ Instead, we replace the URL with a string.
66
+ Args:
67
+ data (dict): Input data dict
68
+ Returns:
69
+ data dict with URL replaced with a string
70
+ """
71
+ for data_dict in data:
72
+ data_dict["__url__"] = os.path.join(data_dict["__url__"].root, data_dict["__url__"].path)
73
+ yield data_dict
74
+
75
+
76
+ def skip_keys(data: Iterator[dict]) -> Iterator[dict]:
77
+ r"""
78
+ Function to skip keys
79
+ Args:
80
+ data (dict): Input data dict
81
+ Returns:
82
+ data_dict with keys skipped
83
+ """
84
+
85
+ for data_dict in data:
86
+ if ("keys_to_skip" in data_dict) and (int(data_dict["keys_to_skip"]) == 1):
87
+ # Skip this key if data_dict["skip_key"] is True
88
+ continue
89
+ else:
90
+ yield data_dict
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/utils/stream.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ # PBSS
18
+ import time
19
+ from typing import Optional
20
+
21
+ from botocore.exceptions import EndpointConnectionError
22
+ from multistorageclient.types import RetryableError
23
+ from urllib3.exceptions import ProtocolError as URLLib3ProtocolError
24
+ from urllib3.exceptions import ReadTimeoutError as URLLib3ReadTimeoutError
25
+ from urllib3.exceptions import SSLError as URLLib3SSLError
26
+
27
+ from cosmos_policy._src.imaginaire.utils import log
28
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends import BaseStorageBackend
29
+
30
+
31
+ class RetryingStream:
32
+ def __init__(self, easy_io_backend: BaseStorageBackend, bucket: str, key: str, retries: int = 10): # type: ignore
33
+ r"""Class for loading data in a streaming fashion from an object store.
34
+ Args:
35
+ easy_io_backend (BaseStorageBackend): easy_io backend, must support 's3://' URLs
36
+ bucket (str): Bucket where data is stored
37
+ key (str): Key to read
38
+ retries (int): Number of retries
39
+ """
40
+ self.easy_io_backend = easy_io_backend
41
+ self.filepath = f"s3://{bucket}/{key}"
42
+ self.retries = retries
43
+ self.content_size = self.easy_io_backend.size(filepath=self.filepath)
44
+ self._amount_read = 0
45
+
46
+ self.name = f"{bucket}/{key}"
47
+
48
+ def read(self, amt: Optional[int] = None) -> bytes:
49
+ r"""Read function for reading the data stream.
50
+ Args:
51
+ amt (int, optional): Amount of data to read
52
+ Returns:
53
+ chunk (bytes): Bytes read
54
+ """
55
+
56
+ chunk = b""
57
+ for cur_retry_idx in range(self.retries):
58
+ try:
59
+ chunk = self.easy_io_backend.get(
60
+ filepath=self.filepath,
61
+ offset=self._amount_read,
62
+ size=amt or (self.content_size - self._amount_read),
63
+ )
64
+ if len(chunk) == 0 and self._amount_read != self.content_size:
65
+ raise IOError
66
+ break
67
+ except URLLib3ReadTimeoutError as e:
68
+ log.warning(
69
+ f"URLLib3ReadTimeoutError: {e} {self.name} retry: {cur_retry_idx} / {self.retries}",
70
+ rank0_only=False,
71
+ )
72
+ except URLLib3ProtocolError as e:
73
+ log.warning(
74
+ f"URLLib3ProtocolError: {e} {self.name} retry: {cur_retry_idx} / {self.retries}",
75
+ rank0_only=False,
76
+ )
77
+ except URLLib3SSLError as e:
78
+ log.warning(
79
+ f"URLLib3SSLError: {e} {self.name} retry: {cur_retry_idx} / {self.retries}", rank0_only=False
80
+ )
81
+ except IOError as e:
82
+ log.warning(
83
+ f"Premature end of stream. IOError {e}. Retrying... {self.name} retry: {cur_retry_idx} / {self.retries}",
84
+ rank0_only=False,
85
+ )
86
+ except RetryableError as e:
87
+ log.warning(
88
+ f"RetryableError: {e} {self.name} retry: {cur_retry_idx} / {self.retries}",
89
+ rank0_only=False,
90
+ )
91
+ except RuntimeError as e:
92
+ log.warning(
93
+ f"RuntimeError: {e} {self.name} retry: {cur_retry_idx} / {self.retries}",
94
+ rank0_only=False,
95
+ )
96
+ except EndpointConnectionError as e:
97
+ log.error(
98
+ f"EndpointConnectionError: {e} {self.name} retry: {cur_retry_idx} / {self.retries}",
99
+ rank0_only=False,
100
+ )
101
+ time.sleep(1)
102
+
103
+ if len(chunk) == 0 and self._amount_read != self.content_size:
104
+ log.warning(
105
+ f"After {self.retries} retries, chunk is empty and self._amount_read != self.content_size {self._amount_read} != {self.content_size} {self.name}",
106
+ rank0_only=False,
107
+ )
108
+ raise IOError
109
+
110
+ self._amount_read += len(chunk)
111
+ return chunk
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/webdataset.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import os
18
+ import time
19
+ import warnings
20
+ from collections.abc import Iterable
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ from functools import partial
23
+ from typing import Callable
24
+
25
+ import omegaconf
26
+ import webdataset as wds
27
+ from webdataset.handlers import reraise_exception
28
+
29
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import (
30
+ AugmentorConfig,
31
+ DatasetConfig,
32
+ DatasetInfo,
33
+ TarSample,
34
+ Wdinfo,
35
+ )
36
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.iterators import WebDataset
37
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.misc import (
38
+ remove_extensions_from_keys,
39
+ skip_keys,
40
+ update_url,
41
+ )
42
+ from cosmos_policy._src.imaginaire.lazy_config import instantiate
43
+ from cosmos_policy._src.imaginaire.utils import log
44
+ from cosmos_policy._src.imaginaire.utils.distributed import get_world_size
45
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends import BaseStorageBackend
46
+ from cosmos_policy._src.imaginaire.utils.object_store import ObjectStore
47
+
48
+
49
+ def wrap_augmentor_func_as_generator(func: Callable, data: Iterable):
50
+ for data_dict in data:
51
+ data_dict_out = func(data_dict)
52
+ if data_dict_out is None:
53
+ # Skip "unhealthy" samples
54
+ continue
55
+ yield data_dict_out
56
+
57
+
58
+ class Dataset:
59
+ def __init__(
60
+ self,
61
+ config: DatasetConfig,
62
+ handler: Callable = reraise_exception,
63
+ ):
64
+ r"""Webdataloader class
65
+
66
+ Args:
67
+ config: Dataset config
68
+ world_size: Total number of GPUs
69
+ """
70
+ super().__init__()
71
+
72
+ self.config = config
73
+
74
+ self.world_size = get_world_size()
75
+
76
+ dataset_info = config.dataset_info
77
+ self.streaming_download = config.streaming_download
78
+
79
+ self.use_object_store: bool = False
80
+ self.easy_io_backend: dict[str, BaseStorageBackend] = dict()
81
+ self.bucket: dict[str, str] = dict()
82
+ self.data_keys = config.keys
83
+
84
+ # Parse the metadata
85
+ self.wdinfo = Wdinfo([], 0, 0)
86
+ self.parse_dataset_info(dataset_info=dataset_info, use_multithread=True)
87
+ self.handler = handler
88
+ self.augmentors = dict()
89
+
90
+ def parse_dataset_info(self, dataset_info: list[DatasetInfo], use_multithread: bool = True):
91
+ r"""Parse metadata about the list of tar files.
92
+
93
+ Args:
94
+ dataset_info (list): List of dictionaries containing paths to metadata files.
95
+ use_multithread (bool): Whether to use multi-threaded parsing across datasets. Default: True.
96
+ """
97
+ log.info(f"Start parsing dataset info with {len(dataset_info)} entries, use multithread = {use_multithread}")
98
+ tic = time.time()
99
+
100
+ def process_single_dataset(dset_num: int, dset_info: DatasetInfo):
101
+ # For each dataset, we parse the file paths and store them as a list of TarSample.
102
+ # TarSample will then be used by each worker to load the data.
103
+ use_object_store = dset_info.object_store_config.enabled
104
+ self.use_object_store = use_object_store
105
+ dset_id = "dset: {}".format(dset_num)
106
+ if use_object_store:
107
+ object_store_reader = ObjectStore(config_object_storage=dset_info.object_store_config)
108
+
109
+ # Create object store config if data is loaded from object storage
110
+ easy_io_backend_dset = object_store_reader.easy_io_backend
111
+ bucket_dset = dset_info.object_store_config.bucket
112
+ else:
113
+ object_store_reader = None
114
+ easy_io_backend_dset = None
115
+ bucket_dset = None
116
+
117
+ tar_samples = []
118
+ total_key_count = 0
119
+ chunk_sizes = []
120
+
121
+ # Read all wdinfo files and obtain the DataSample list
122
+ for wdinfo_path in dset_info.wdinfo:
123
+ if use_object_store:
124
+ if not object_store_reader.object_exists(wdinfo_path):
125
+ raise FileNotFoundError(f"{wdinfo_path} not found")
126
+ cur_dset_info = object_store_reader.load_object(key=wdinfo_path, type="json") # type: ignore
127
+ else:
128
+ with open(wdinfo_path, "r") as fp:
129
+ cur_dset_info = json.load(fp)
130
+
131
+ data_root = cur_dset_info["root"]
132
+ # Strip s3://bucket/ prefix from root if present, as the bucket is specified separately
133
+ if data_root.startswith("s3://"):
134
+ # Remove s3://bucket/ prefix (e.g., "s3://debug/path/" -> "path/")
135
+ parts = data_root[5:].split("/", 1) # Split after "s3://"
136
+ if len(parts) > 1:
137
+ data_root = parts[1] # Take everything after bucket name
138
+ else:
139
+ data_root = ""
140
+ tar_files_list = cur_dset_info["data_list"]
141
+ local_tar_samples = [
142
+ TarSample(
143
+ path=tar_file,
144
+ root=data_root,
145
+ keys=(
146
+ dset_info.per_dataset_keys if dset_info.per_dataset_keys else self.data_keys
147
+ ), # use per dataset keys if available
148
+ meta=dset_info,
149
+ dset_id=dset_id,
150
+ sample_keys_full_list=None,
151
+ )
152
+ for tar_file in tar_files_list
153
+ ]
154
+ tar_samples.extend(local_tar_samples)
155
+ total_key_count += cur_dset_info["total_key_count"]
156
+ chunk_sizes.append(cur_dset_info["chunk_size"])
157
+
158
+ return {
159
+ "dset_id": dset_id,
160
+ "tar_samples": tar_samples,
161
+ "total_key_count": total_key_count,
162
+ "chunk_sizes": chunk_sizes,
163
+ "easy_io_backend": easy_io_backend_dset,
164
+ "bucket": bucket_dset,
165
+ }
166
+
167
+ dataset_results = []
168
+
169
+ if use_multithread:
170
+ num_workers = os.cpu_count()
171
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
172
+ futures = []
173
+ for i, dset_info in enumerate(dataset_info):
174
+ if len(dset_info.wdinfo) == 0:
175
+ log.warning(f"No wdinfo found for dataset {i}, skipping...")
176
+ continue
177
+ log.info(f"Adding: {dset_info.wdinfo}")
178
+ futures.append(executor.submit(process_single_dataset, i, dset_info))
179
+ for future in as_completed(futures):
180
+ dataset_results.append(future.result())
181
+ else:
182
+ for i, dset_info in enumerate(dataset_info):
183
+ log.info(f"Adding: {dset_info.wdinfo}")
184
+ dataset_results.append(process_single_dataset(i, dset_info))
185
+
186
+ # Merge results
187
+ for result in dataset_results:
188
+ dset_id = result["dset_id"]
189
+ self.wdinfo.tar_files.extend(result["tar_samples"])
190
+ self.wdinfo.total_key_count += result["total_key_count"]
191
+ if len(set(result["chunk_sizes"])) > 1:
192
+ warnings.warn(
193
+ f"Multiple chunk_size values found in {dset_id}: {result['chunk_sizes']}. Using the first one."
194
+ )
195
+ self.wdinfo.chunk_size = result["chunk_sizes"][0]
196
+ if result["easy_io_backend"]:
197
+ self.easy_io_backend[dset_id] = result["easy_io_backend"]
198
+ if result["bucket"]:
199
+ self.bucket[dset_id] = result["bucket"]
200
+ toc = time.time()
201
+ log.info(
202
+ f"Parsed dataset info with {len(dataset_info)} wdinfos (num_keys = {self.wdinfo.total_key_count}, num_tars = {len(self.wdinfo.tar_files)}) and multithread = {use_multithread}, took {(toc - tic):.2f} seconds"
203
+ )
204
+
205
+ @staticmethod
206
+ # This is the function that calls each augmentor in sequence.
207
+ def augmentor_fn(data, augmentations):
208
+ # Build augmentor chain
209
+ for aug_fn in augmentations:
210
+ # Use generator function as augmentor
211
+ # (recommended, allows skipping or replicating samples inside the augmentor)
212
+ if getattr(aug_fn, "is_generator", False):
213
+ data = aug_fn(data)
214
+ else: # Use regular function as augmentor (backward compatibility)
215
+ data = wrap_augmentor_func_as_generator(aug_fn, data)
216
+ yield from data
217
+
218
+ def build_data_augmentor(self, augmentor_cfg: dict[str, AugmentorConfig]) -> Callable:
219
+ r"""Function for building data augmentors from augmentor config."""
220
+ augmentations = []
221
+ for aug in augmentor_cfg.keys():
222
+ augmentations.append(instantiate(augmentor_cfg[aug]))
223
+
224
+ # This is the function that calls each augmentor in sequence.
225
+ return partial(Dataset.augmentor_fn, augmentations=augmentations)
226
+
227
+ def build_dataset(self, **kwargs) -> WebDataset:
228
+ tar_list = self.wdinfo.tar_files
229
+ num_tars = len(tar_list)
230
+ assert num_tars > 0, "Did not find any data."
231
+
232
+ shuffle_buffer_size = getattr(self.config, "buffer_size", self.wdinfo.chunk_size)
233
+
234
+ # update distributor urls and chunk size
235
+ distributor_fn = self.config.distributor
236
+
237
+ distributor_fn.set_urls(tar_list)
238
+ distributor_fn.set_chunk_size(self.wdinfo.chunk_size)
239
+
240
+ dataset = WebDataset(
241
+ distributor_fn,
242
+ load_from_object_store=self.use_object_store,
243
+ easy_io_backend=self.easy_io_backend,
244
+ s3_bucket_name=self.bucket,
245
+ streaming_download=self.streaming_download,
246
+ handler=self.handler,
247
+ )
248
+
249
+ # Creating a shuffle buffer
250
+ if shuffle_buffer_size > 0:
251
+ dataset.append(wds.shuffle(shuffle_buffer_size))
252
+
253
+ # Adding decoders
254
+ # Decoders are functions that decode the input IO stream
255
+ decoder_list = getattr(self.config, "decoders", [])
256
+ decoder_functions = []
257
+ for decoder in decoder_list:
258
+ # If the specified decoder is a string, use the webdataset decoder
259
+ # If its a callable function, use the defined function to decode data
260
+ assert isinstance(decoder, str) or callable(decoder), "Decoder should either be callable or a str"
261
+ decoder_functions.append(decoder)
262
+ dataset.append(wds.decode(*decoder_functions))
263
+
264
+ # After the decoders are added, remove extension from the keys
265
+ # Extensions in the data keys are needed for auto-detection of decoders in webdataset.
266
+ if self.config.remove_extension_from_keys:
267
+ dataset.append(remove_extensions_from_keys)
268
+
269
+ # Function to skip keys
270
+ dataset.append(skip_keys)
271
+ # Building augmentors
272
+ augmentor_cfg = getattr(self.config, "augmentation", None)
273
+ assert isinstance(augmentor_cfg, (dict, omegaconf.dictconfig.DictConfig)), (
274
+ f"getting type: {type(augmentor_cfg)}"
275
+ )
276
+ augmentation_fn = self.build_data_augmentor(augmentor_cfg)
277
+ dataset.append(augmentation_fn)
278
+
279
+ # Updates URL names so that the collate function can handle
280
+ dataset.append(update_url)
281
+
282
+ dataset.total_images = self.wdinfo.total_key_count # type: ignore
283
+ log.info("Total number of training shards: %d" % num_tars)
284
+ log.info("Total training key count: %d" % dataset.total_images) # type: ignore
285
+
286
+ return dataset
REGEN-main/cosmos_policy/_src/imaginaire/datasets/webdataset/webdataset_ext.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Callable, Optional
17
+
18
+ import omegaconf
19
+ import webdataset as wds
20
+ from webdataset import filters
21
+ from webdataset.handlers import reraise_exception
22
+
23
+ from cosmos_policy._src.imaginaire.datasets.webdataset.config.schema import DatasetConfig
24
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.iterators import WebDataset
25
+ from cosmos_policy._src.imaginaire.datasets.webdataset.utils.misc import (
26
+ remove_extensions_from_keys,
27
+ skip_keys,
28
+ update_url,
29
+ )
30
+ from cosmos_policy._src.imaginaire.datasets.webdataset.webdataset import Dataset as BaseDataset
31
+ from cosmos_policy._src.imaginaire.utils import log
32
+
33
+
34
+ class Dataset(BaseDataset):
35
+ def __init__(
36
+ self,
37
+ config: DatasetConfig,
38
+ handler: Callable = reraise_exception,
39
+ decoder_handler: Optional[Callable] = None,
40
+ detshuffle: bool = False,
41
+ ):
42
+ r"""Webdataloader class
43
+
44
+ Args:
45
+ config: Dataset config
46
+ handler (Callable): Error handler for webdataset class
47
+ decoder_handler (Callable): Error handler during decoding
48
+ """
49
+ super().__init__(config=config, handler=handler)
50
+ self.decoder_handler = decoder_handler
51
+ self.detshuffle = detshuffle
52
+
53
+ def build_dataset(self, **kwargs) -> WebDataset:
54
+ r"""
55
+ Build the dataset object.
56
+ The function only diffs from BaseDataset.build_dataset by only adding the decoder_handler to the WebDataset object.
57
+ """
58
+ tar_list = self.wdinfo.tar_files
59
+ num_tars = len(tar_list)
60
+ assert num_tars > 0, "Did not find any data."
61
+
62
+ shuffle_buffer_size = getattr(self.config, "buffer_size", self.wdinfo.chunk_size)
63
+
64
+ # update distributor urls and chunk size
65
+ distributor_fn = self.config.distributor
66
+
67
+ distributor_fn.set_urls(tar_list)
68
+ distributor_fn.set_chunk_size(self.wdinfo.chunk_size)
69
+
70
+ dataset = WebDataset(
71
+ distributor_fn,
72
+ load_from_object_store=self.use_object_store,
73
+ easy_io_backend=self.easy_io_backend,
74
+ s3_bucket_name=self.bucket,
75
+ streaming_download=self.streaming_download,
76
+ handler=self.handler,
77
+ )
78
+
79
+ # Creating a shuffle buffer
80
+ if self.detshuffle:
81
+ dataset.append(filters.detshuffle(shuffle_buffer_size))
82
+ else:
83
+ dataset.append(wds.shuffle(shuffle_buffer_size))
84
+
85
+ # Adding decoders
86
+ # Decoders are functions that decode the input IO stream
87
+ decoder_list = getattr(self.config, "decoders", [])
88
+ decoder_functions = []
89
+ for decoder in decoder_list:
90
+ # If the specified decoder is a string, use the webdataset decoder
91
+ # If its a callable function, use the defined function to decode data
92
+ assert isinstance(decoder, str) or callable(decoder), "Decoder should either be callable or a str"
93
+ decoder_functions.append(decoder)
94
+ dataset.append(wds.decode(*decoder_functions, handler=self.decoder_handler))
95
+
96
+ # After the decoders are added, remove extension from the keys
97
+ # Extensions in the data keys are needed for auto-detection of decoders in webdataset.
98
+ if self.config.remove_extension_from_keys:
99
+ dataset.append(remove_extensions_from_keys)
100
+
101
+ # Function to skip keys
102
+ dataset.append(skip_keys)
103
+ # Building augmentors
104
+ augmentor_cfg = getattr(self.config, "augmentation", None)
105
+ assert isinstance(augmentor_cfg, (dict, omegaconf.dictconfig.DictConfig)), (
106
+ f"getting type: {type(augmentor_cfg)}"
107
+ )
108
+ augmentation_fn = self.build_data_augmentor(augmentor_cfg)
109
+ dataset.append(augmentation_fn)
110
+
111
+ # Updates URL names so that the collate function can handle
112
+ dataset.append(update_url)
113
+
114
+ dataset.total_images = self.wdinfo.total_key_count # type: ignore
115
+ log.info("Total number of training shards: %d" % num_tars)
116
+ log.info("Total training key count: %d" % dataset.total_images) # type: ignore
117
+
118
+ return dataset
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.base_backend import BaseStorageBackend
17
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.boto3_backend import Boto3Backend
18
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.http_backend import HTTPBackend
19
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.local_backend import LocalBackend
20
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.msc_backend import MSCBackend
21
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.registry_utils import (
22
+ backends,
23
+ prefix_to_backends,
24
+ register_backend,
25
+ )
26
+
27
+ __all__ = [
28
+ "BaseStorageBackend",
29
+ "LocalBackend",
30
+ "HTTPBackend",
31
+ "Boto3Backend",
32
+ "MSCBackend",
33
+ "register_backend",
34
+ "backends",
35
+ "prefix_to_backends",
36
+ ]
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/auto_auth.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import contextlib
17
+ import json
18
+ from collections.abc import Generator
19
+ from typing import IO, Any, Optional, Union
20
+
21
+ from cosmos_policy._src.imaginaire.utils import log
22
+ from cosmos_policy._src.imaginaire.utils.env_parsers.cred_env_parser import CRED_ENVS, CRED_ENVS_DICT
23
+
24
+ DEPLOYMENT_ENVS = ["prod", "dev", "stg"]
25
+
26
+
27
+ # context manger to open a file or read from env variable
28
+ @contextlib.contextmanager
29
+ def open_auth(s3_credential_path: Optional[Any], mode: str) -> Generator[Union[None, dict[str, Any], IO]]:
30
+ if not s3_credential_path:
31
+ log.info(f"No credential file provided {s3_credential_path}.")
32
+ yield None
33
+ return
34
+
35
+ name = s3_credential_path.split("/")[-1].split(".")[0]
36
+ if not name:
37
+ raise ValueError(f"Could not parse into env var: {s3_credential_path}")
38
+ cred_env_name = f"PROD_{name.upper()}"
39
+
40
+ if CRED_ENVS.APP_ENV in DEPLOYMENT_ENVS and cred_env_name in CRED_ENVS_DICT:
41
+ object_storage_config = get_creds_from_env(cred_env_name)
42
+ log.info(f"using ENV vars for {cred_env_name}")
43
+ yield object_storage_config
44
+ else:
45
+ log.info(f"using credential file: {s3_credential_path}")
46
+ with open(s3_credential_path, mode) as f:
47
+ yield f
48
+
49
+
50
+ def get_creds_from_env(cred_env_name: str) -> dict[str, Any]:
51
+ try:
52
+ object_storage_config = CRED_ENVS_DICT[cred_env_name]
53
+ except KeyError:
54
+ raise ValueError(f"Could not find {cred_env_name} in CRED_ENVS")
55
+ empty_args = {key.upper() for key in object_storage_config if object_storage_config[key] == ""}
56
+ if empty_args:
57
+ raise ValueError(f"Some required environment variable(s) were not provided for {cred_env_name}", empty_args)
58
+ return object_storage_config
59
+
60
+
61
+ def json_load_auth(f: Union[None, dict[str, Any], IO]) -> dict[str, Any]:
62
+ # None.
63
+ if f is None:
64
+ return {}
65
+ # dict[str, Any].
66
+ elif isinstance(f, dict):
67
+ return f
68
+ # IO.
69
+ else:
70
+ return json.load(f)
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/base_backend.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import os
18
+ import os.path as osp
19
+ from abc import ABCMeta, abstractmethod
20
+ from collections.abc import Generator, Iterator
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+ from typing import Optional, Union
24
+
25
+
26
+ def mkdir_or_exist(dir_name, mode=0o777):
27
+ if dir_name == "":
28
+ return
29
+ dir_name = osp.expanduser(dir_name)
30
+ os.makedirs(dir_name, mode=mode, exist_ok=True)
31
+
32
+
33
+ def has_method(obj, method):
34
+ return hasattr(obj, method) and callable(getattr(obj, method))
35
+
36
+
37
+ class BaseStorageBackend(metaclass=ABCMeta):
38
+ """Abstract class of storage backends."""
39
+
40
+ # a flag to indicate whether the backend can create a symlink for a file
41
+ # This attribute will be deprecated in future.
42
+ _allow_symlink: bool = False
43
+
44
+ @property
45
+ def allow_symlink(self) -> bool:
46
+ return self._allow_symlink
47
+
48
+ @property
49
+ def name(self) -> str:
50
+ return self.__class__.__name__
51
+
52
+ @abstractmethod
53
+ def size(self, filepath: Union[str, Path]) -> int:
54
+ pass
55
+
56
+ @abstractmethod
57
+ def get(self, filepath: Union[str, Path], offset: Optional[int] = None, size: Optional[int] = None) -> bytes:
58
+ pass
59
+
60
+ @abstractmethod
61
+ def get_text(self, filepath: Union[str, Path], encoding: str = "utf-8") -> str:
62
+ pass
63
+
64
+ @abstractmethod
65
+ def put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path]) -> None:
66
+ pass
67
+
68
+ @abstractmethod
69
+ def put_text(self, obj: str, filepath: Union[str, Path], encoding: str = "utf-8") -> None:
70
+ pass
71
+
72
+ @abstractmethod
73
+ def exists(self, filepath: Union[str, Path]) -> bool:
74
+ pass
75
+
76
+ @abstractmethod
77
+ def isdir(self, filepath: Union[str, Path]) -> bool:
78
+ pass
79
+
80
+ @abstractmethod
81
+ def isfile(self, filepath: Union[str, Path]) -> bool:
82
+ pass
83
+
84
+ @abstractmethod
85
+ def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str:
86
+ pass
87
+
88
+ @abstractmethod
89
+ @contextmanager
90
+ def get_local_path(self, filepath: Union[str, Path]) -> Generator[Union[str, Path], None, None]:
91
+ pass
92
+
93
+ @abstractmethod
94
+ def copyfile(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
95
+ pass
96
+
97
+ @abstractmethod
98
+ def copytree(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
99
+ pass
100
+
101
+ @abstractmethod
102
+ def copyfile_from_local(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
103
+ pass
104
+
105
+ @abstractmethod
106
+ def copytree_from_local(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
107
+ pass
108
+
109
+ @abstractmethod
110
+ def copyfile_to_local(
111
+ self,
112
+ src: Union[str, Path],
113
+ dst: Union[str, Path],
114
+ dst_type: str, # Choose from ["file", "dir"]
115
+ ) -> Union[str, Path]:
116
+ pass
117
+
118
+ @abstractmethod
119
+ def copytree_to_local(self, src: Union[str, Path], dst: Union[str, Path]) -> Union[str, Path]:
120
+ pass
121
+
122
+ @abstractmethod
123
+ def remove(self, filepath: Union[str, Path]) -> None:
124
+ pass
125
+
126
+ @abstractmethod
127
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
128
+ pass
129
+
130
+ @abstractmethod
131
+ def copy_if_symlink_fails(self, src: Union[str, Path], dst: Union[str, Path]) -> bool:
132
+ pass
133
+
134
+ @abstractmethod
135
+ def list_dir(self, dir_path: Union[str, Path]) -> Generator[str, None, None]:
136
+ pass
137
+
138
+ @abstractmethod
139
+ def list_dir_or_file( # pylint: disable=too-many-arguments
140
+ self,
141
+ dir_path: Union[str, Path],
142
+ list_dir: bool = True,
143
+ list_file: bool = True,
144
+ suffix: Optional[Union[str, tuple[str]]] = None,
145
+ recursive: bool = False,
146
+ ) -> Iterator[str]:
147
+ pass
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/boto3_backend.py ADDED
@@ -0,0 +1,866 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import os
18
+ import re
19
+ import tempfile
20
+ from collections.abc import Generator, Iterator
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+ from shutil import SameFileError
24
+ from typing import Optional, Union
25
+
26
+ from cosmos_policy._src.imaginaire.utils import log
27
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.base_backend import (
28
+ BaseStorageBackend,
29
+ has_method,
30
+ mkdir_or_exist,
31
+ )
32
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.boto3_client import Boto3Client
33
+
34
+
35
+ class Boto3Backend(BaseStorageBackend):
36
+ """boto3 storage backend (for internal usage).
37
+
38
+ **Deprecated**. Use the MSC backend instead.
39
+
40
+ Boto3Backend supports reading and writing data to multiple clusters.
41
+ If the file path contains the cluster name, Boto3Backend will read data
42
+ from specified cluster or write data to it. Otherwise, Boto3Backend will
43
+ access the default cluster.
44
+
45
+ Args:
46
+ path_mapping (dict, optional): Path mapping dict from local path to
47
+ Boto3 path. When ``path_mapping={'src': 'dst'}``, ``src`` in
48
+ ``filepath`` will be replaced by ``dst``. Defaults to None.
49
+ s3_credential_path (str, optional): Config path of Boto3 client. Default: None.
50
+ `New in version 0.3.3`.
51
+
52
+ Examples:
53
+ >>> backend = Boto3Backend()
54
+ >>> filepath1 = 's3://path/of/file'
55
+ >>> filepath2 = 'cluster-name:s3://path/of/file'
56
+ >>> backend.get(filepath1) # get data from default cluster
57
+ >>> client.get(filepath2) # get data from 'cluster-name' cluster
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ s3_credential_path: str = "",
63
+ path_mapping: Optional[dict] = None,
64
+ ):
65
+ self._client = Boto3Client(s3_credential_path=s3_credential_path)
66
+ assert isinstance(path_mapping, dict) or path_mapping is None
67
+ self.path_mapping = path_mapping
68
+ if path_mapping:
69
+ for k, v in path_mapping.items():
70
+ log.critical(f"Path mapping: {k} -> {v}", rank0_only=False)
71
+
72
+ def _map_path(self, filepath: Union[str, Path]) -> str:
73
+ """Map ``filepath`` to a string path whose prefix will be replaced by
74
+ :attr:`self.path_mapping`.
75
+
76
+ Args:
77
+ filepath (str or Path): Path to be mapped.
78
+ """
79
+ filepath = str(filepath)
80
+ if self.path_mapping is not None:
81
+ for k, v in self.path_mapping.items():
82
+ filepath = filepath.replace(k, v, 1)
83
+ return filepath
84
+
85
+ def _format_path(self, filepath: str) -> str:
86
+ """Convert a ``filepath`` to standard format of s3 oss.
87
+
88
+ If the ``filepath`` is concatenated by ``os.path.join``, in a Windows
89
+ environment, the ``filepath`` will be the format of
90
+ 's3://bucket_name\\image.jpg'. By invoking :meth:`_format_path`, the
91
+ above ``filepath`` will be converted to 's3://bucket_name/image.jpg'.
92
+
93
+ Args:
94
+ filepath (str): Path to be formatted.
95
+ """
96
+ return re.sub(r"\\+", "/", filepath)
97
+
98
+ def _replace_prefix(self, filepath: Union[str, Path]) -> str:
99
+ filepath = str(filepath)
100
+ return filepath
101
+ # return filepath.replace('s3://', 's3://')
102
+
103
+ def size(self, filepath: Union[str, Path]) -> int:
104
+ """Get the file size in bytes for a given ``filepath``.
105
+
106
+ Args:
107
+ filepath (str or Path): Path to get file size in bytes.
108
+
109
+ Returns:
110
+ int: File size in bytes for filepath.
111
+
112
+ Examples:
113
+ >>> backend = Boto3Backend()
114
+ >>> filepath = 's3://path/of/file'
115
+ >>> backend.size(filepath) # file containing 'hello world'
116
+ 11
117
+ """
118
+ filepath = self._map_path(filepath)
119
+ filepath = self._format_path(filepath)
120
+ filepath = self._replace_prefix(filepath)
121
+ return self._client.size(filepath)
122
+
123
+ def get(self, filepath: Union[str, Path], offset: Optional[int] = None, size: Optional[int] = None) -> bytes:
124
+ """Read bytes from a given ``filepath`` with 'rb' mode in range [offset, offset + size).
125
+
126
+ Args:
127
+ filepath (str or Path): Path to read data.
128
+ offset (int, optional): Read offset in bytes (0-index). Defaults to 0.
129
+ size (int, optional): Read size in bytes. Defaults to the file size.
130
+
131
+ Returns:
132
+ bytes: Return bytes read from filepath.
133
+
134
+ Examples:
135
+ >>> backend = Boto3Backend()
136
+ >>> filepath = 's3://path/of/file'
137
+ >>> backend.get(filepath)
138
+ b'hello world'
139
+ """
140
+ filepath = self._map_path(filepath)
141
+ filepath = self._format_path(filepath)
142
+ filepath = self._replace_prefix(filepath)
143
+ value = self._client.get(filepath=filepath, offset=offset, size=size)
144
+ return value
145
+
146
+ def get_text(
147
+ self,
148
+ filepath: Union[str, Path],
149
+ encoding: str = "utf-8",
150
+ ) -> str:
151
+ """Read text from a given ``filepath`` with 'r' mode.
152
+
153
+ Args:
154
+ filepath (str or Path): Path to read data.
155
+ encoding (str): The encoding format used to open the ``filepath``.
156
+ Defaults to 'utf-8'.
157
+
158
+ Returns:
159
+ str: Expected text reading from ``filepath``.
160
+
161
+ Examples:
162
+ >>> backend = Boto3Backend()
163
+ >>> filepath = 's3://path/of/file'
164
+ >>> backend.get_text(filepath)
165
+ 'hello world'
166
+ """
167
+ return str(self.get(filepath), encoding=encoding)
168
+
169
+ def put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path]) -> None:
170
+ """Write bytes to a given ``filepath``.
171
+
172
+ Args:
173
+ obj (bytes): Data to be saved.
174
+ filepath (str or Path): Path to write data.
175
+
176
+ Examples:
177
+ >>> backend = Boto3Backend()
178
+ >>> filepath = 's3://path/of/file'
179
+ >>> backend.put(b'hello world', filepath)
180
+ """
181
+ filepath = self._map_path(filepath)
182
+ filepath = self._format_path(filepath)
183
+ filepath = self._replace_prefix(filepath)
184
+ self._client.put(obj, filepath)
185
+
186
+ def fast_put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path], num_processes: int = 32) -> None:
187
+ """Write bytes to a given ``filepath`` with multiple processes and async"""
188
+ assert num_processes > 1
189
+ filepath = self._map_path(filepath)
190
+ filepath = self._format_path(filepath)
191
+ filepath = self._replace_prefix(filepath)
192
+ self._client.fast_put(obj, filepath, num_processes=num_processes)
193
+
194
+ def put_text(
195
+ self,
196
+ obj: str,
197
+ filepath: Union[str, Path],
198
+ encoding: str = "utf-8",
199
+ ) -> None:
200
+ """Write text to a given ``filepath``.
201
+
202
+ Args:
203
+ obj (str): Data to be written.
204
+ filepath (str or Path): Path to write data.
205
+ encoding (str): The encoding format used to encode the ``obj``.
206
+ Defaults to 'utf-8'.
207
+
208
+ Examples:
209
+ >>> backend = Boto3Backend()
210
+ >>> filepath = 's3://path/of/file'
211
+ >>> backend.put_text('hello world', filepath)
212
+ """
213
+ self.put(bytes(obj, encoding=encoding), filepath)
214
+
215
+ def exists(self, filepath: Union[str, Path]) -> bool:
216
+ """Check whether a file path exists.
217
+
218
+ Args:
219
+ filepath (str or Path): Path to be checked whether exists.
220
+
221
+ Returns:
222
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
223
+
224
+ Examples:
225
+ >>> backend = Boto3Backend()
226
+ >>> filepath = 's3://path/of/file'
227
+ >>> backend.exists(filepath)
228
+ True
229
+ """
230
+ if not (has_method(self._client, "contains") and has_method(self._client, "isdir")):
231
+ raise NotImplementedError(
232
+ "Current version of Boto3 Python SDK has not supported "
233
+ "the `contains` and `isdir` methods, please use a higher"
234
+ "version or dev branch instead."
235
+ )
236
+
237
+ filepath = self._map_path(filepath)
238
+ filepath = self._format_path(filepath)
239
+ filepath = self._replace_prefix(filepath)
240
+ return self._client.contains(filepath) or self._client.isdir(filepath)
241
+
242
+ def isdir(self, filepath: Union[str, Path]) -> bool:
243
+ """Check whether a file path is a directory.
244
+
245
+ Args:
246
+ filepath (str or Path): Path to be checked whether it is a
247
+ directory.
248
+
249
+ Returns:
250
+ bool: Return ``True`` if ``filepath`` points to a directory,
251
+ ``False`` otherwise.
252
+
253
+ Examples:
254
+ >>> backend = Boto3Backend()
255
+ >>> filepath = 's3://path/of/dir'
256
+ >>> backend.isdir(filepath)
257
+ True
258
+ """
259
+ if not has_method(self._client, "isdir"):
260
+ raise NotImplementedError(
261
+ "Current version of Boto3 Python SDK has not supported "
262
+ "the `isdir` method, please use a higher version or dev"
263
+ " branch instead."
264
+ )
265
+
266
+ filepath = self._map_path(filepath)
267
+ filepath = self._format_path(filepath)
268
+ filepath = self._replace_prefix(filepath)
269
+ return self._client.isdir(filepath)
270
+
271
+ def isfile(self, filepath: Union[str, Path]) -> bool:
272
+ """Check whether a file path is a file.
273
+
274
+ Args:
275
+ filepath (str or Path): Path to be checked whether it is a file.
276
+
277
+ Returns:
278
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
279
+ otherwise.
280
+
281
+ Examples:
282
+ >>> backend = Boto3Backend()
283
+ >>> filepath = 's3://path/of/file'
284
+ >>> backend.isfile(filepath)
285
+ True
286
+ """
287
+ if not has_method(self._client, "contains"):
288
+ raise NotImplementedError(
289
+ "Current version of Boto3 Python SDK has not supported "
290
+ "the `contains` method, please use a higher version or "
291
+ "dev branch instead."
292
+ )
293
+
294
+ filepath = self._map_path(filepath)
295
+ filepath = self._format_path(filepath)
296
+ filepath = self._replace_prefix(filepath)
297
+ return self._client.contains(filepath)
298
+
299
+ def join_path(
300
+ self,
301
+ filepath: Union[str, Path],
302
+ *filepaths: Union[str, Path],
303
+ ) -> str:
304
+ r"""Concatenate all file paths.
305
+
306
+ Join one or more filepath components intelligently. The return value
307
+ is the concatenation of filepath and any members of \*filepaths.
308
+
309
+ Args:
310
+ filepath (str or Path): Path to be concatenated.
311
+
312
+ Returns:
313
+ str: The result after concatenation.
314
+
315
+ Examples:
316
+ >>> backend = Boto3Backend()
317
+ >>> filepath = 's3://path/of/file'
318
+ >>> backend.join_path(filepath, 'another/path')
319
+ 's3://path/of/file/another/path'
320
+ >>> backend.join_path(filepath, '/another/path')
321
+ 's3://path/of/file/another/path'
322
+ """
323
+ filepath = self._format_path(self._map_path(filepath))
324
+ if filepath.endswith("/"):
325
+ filepath = filepath[:-1]
326
+ formatted_paths = [filepath]
327
+ for path in filepaths:
328
+ formatted_path = self._format_path(self._map_path(path))
329
+ formatted_paths.append(formatted_path.lstrip("/"))
330
+
331
+ return "/".join(formatted_paths)
332
+
333
+ @contextmanager
334
+ def get_local_path(
335
+ self,
336
+ filepath: Union[str, Path],
337
+ ) -> Generator[Union[str, Path], None, None]:
338
+ """Download a file from ``filepath`` to a local temporary directory,
339
+ and return the temporary path.
340
+
341
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
342
+ can be called with ``with`` statement, and when exists from the
343
+ ``with`` statement, the temporary path will be released.
344
+
345
+ Args:
346
+ filepath (str or Path): Download a file from ``filepath``.
347
+
348
+ Yields:
349
+ Iterable[str]: Only yield one temporary path.
350
+
351
+ Examples:
352
+ >>> backend = Boto3Backend()
353
+ >>> # After existing from the ``with`` clause,
354
+ >>> # the path will be removed
355
+ >>> filepath = 's3://path/of/file'
356
+ >>> with backend.get_local_path(filepath) as path:
357
+ ... # do something here
358
+ """
359
+ assert self.isfile(filepath)
360
+ try:
361
+ f = tempfile.NamedTemporaryFile(delete=False)
362
+ f.write(self.get(filepath))
363
+ f.close()
364
+ yield f.name
365
+ finally:
366
+ os.remove(f.name)
367
+
368
+ def copyfile(
369
+ self,
370
+ src: Union[str, Path],
371
+ dst: Union[str, Path],
372
+ ) -> str:
373
+ """Copy a file src to dst and return the destination file.
374
+
375
+ src and dst should have the same prefix. If dst specifies a directory,
376
+ the file will be copied into dst using the base filename from src. If
377
+ dst specifies a file that already exists, it will be replaced.
378
+
379
+ Args:
380
+ src (str or Path): A file to be copied.
381
+ dst (str or Path): Copy file to dst.
382
+
383
+ Returns:
384
+ str: The destination file.
385
+
386
+ Raises:
387
+ SameFileError: If src and dst are the same file, a SameFileError
388
+ will be raised.
389
+
390
+ Examples:
391
+ >>> backend = Boto3Backend()
392
+ >>> # dst is a file
393
+ >>> src = 's3://path/of/file'
394
+ >>> dst = 's3://path/of/file1'
395
+ >>> backend.copyfile(src, dst)
396
+ 's3://path/of/file1'
397
+
398
+ >>> # dst is a directory
399
+ >>> dst = 's3://path/of/dir'
400
+ >>> backend.copyfile(src, dst)
401
+ 's3://path/of/dir/file'
402
+ """
403
+ src = self._format_path(self._map_path(src))
404
+ dst = self._format_path(self._map_path(dst))
405
+ if self.isdir(dst):
406
+ dst = self.join_path(dst, src.split("/")[-1])
407
+
408
+ if src == dst:
409
+ raise SameFileError("src and dst should not be same")
410
+
411
+ self.put(self.get(src), dst)
412
+ return dst
413
+
414
+ def copytree(
415
+ self,
416
+ src: Union[str, Path],
417
+ dst: Union[str, Path],
418
+ ) -> str:
419
+ """Recursively copy an entire directory tree rooted at src to a
420
+ directory named dst and return the destination directory.
421
+
422
+ src and dst should have the same prefix.
423
+
424
+ Args:
425
+ src (str or Path): A directory to be copied.
426
+ dst (str or Path): Copy directory to dst.
427
+ backend_args (dict, optional): Arguments to instantiate the
428
+ prefix of uri corresponding backend. Defaults to None.
429
+
430
+ Returns:
431
+ str: The destination directory.
432
+
433
+ Raises:
434
+ FileExistsError: If dst had already existed, a FileExistsError will
435
+ be raised.
436
+
437
+ Examples:
438
+ >>> backend = Boto3Backend()
439
+ >>> src = 's3://path/of/dir'
440
+ >>> dst = 's3://path/of/dir1'
441
+ >>> backend.copytree(src, dst)
442
+ 's3://path/of/dir1'
443
+ """
444
+ src = self._format_path(self._map_path(src))
445
+ dst = self._format_path(self._map_path(dst))
446
+
447
+ if self.exists(dst):
448
+ raise FileExistsError("dst should not exist")
449
+
450
+ for path in self.list_dir_or_file(src, list_dir=False, recursive=True):
451
+ src_path = self.join_path(src, path)
452
+ dst_path = self.join_path(dst, path)
453
+ self.put(self.get(src_path), dst_path)
454
+
455
+ return dst
456
+
457
+ def copyfile_from_local(
458
+ self,
459
+ src: Union[str, Path],
460
+ dst: Union[str, Path],
461
+ ) -> str:
462
+ """Upload a local file src to dst and return the destination file.
463
+
464
+ Args:
465
+ src (str or Path): A local file to be copied.
466
+ dst (str or Path): Copy file to dst.
467
+ backend_args (dict, optional): Arguments to instantiate the
468
+ prefix of uri corresponding backend. Defaults to None.
469
+
470
+ Returns:
471
+ str: If dst specifies a directory, the file will be copied into dst
472
+ using the base filename from src.
473
+
474
+ Examples:
475
+ >>> backend = Boto3Backend()
476
+ >>> # dst is a file
477
+ >>> src = 'path/of/your/file'
478
+ >>> dst = 's3://path/of/file1'
479
+ >>> backend.copyfile_from_local(src, dst)
480
+ 's3://path/of/file1'
481
+
482
+ >>> # dst is a directory
483
+ >>> dst = 's3://path/of/dir'
484
+ >>> backend.copyfile_from_local(src, dst)
485
+ 's3://path/of/dir/file'
486
+ """
487
+ dst = self._format_path(self._map_path(dst))
488
+ if self.isdir(dst):
489
+ dst = self.join_path(dst, os.path.basename(src))
490
+
491
+ with open(src, "rb") as f:
492
+ self.put(f.read(), dst)
493
+
494
+ return dst
495
+
496
+ def copytree_from_local(
497
+ self,
498
+ src: Union[str, Path],
499
+ dst: Union[str, Path],
500
+ ) -> str:
501
+ """Recursively copy an entire directory tree rooted at src to a
502
+ directory named dst and return the destination directory.
503
+
504
+ Args:
505
+ src (str or Path): A local directory to be copied.
506
+ dst (str or Path): Copy directory to dst.
507
+
508
+ Returns:
509
+ str: The destination directory.
510
+
511
+ Raises:
512
+ FileExistsError: If dst had already existed, a FileExistsError will
513
+ be raised.
514
+
515
+ Examples:
516
+ >>> backend = Boto3Backend()
517
+ >>> src = 'path/of/your/dir'
518
+ >>> dst = 's3://path/of/dir1'
519
+ >>> backend.copytree_from_local(src, dst)
520
+ 's3://path/of/dir1'
521
+ """
522
+ dst = self._format_path(self._map_path(dst))
523
+ if self.exists(dst):
524
+ raise FileExistsError("dst should not exist")
525
+
526
+ src = str(src)
527
+
528
+ for cur_dir, _, files in os.walk(src):
529
+ for f in files:
530
+ src_path = os.path.join(cur_dir, f)
531
+ dst_path = self.join_path(dst, src_path.replace(src, ""))
532
+ self.copyfile_from_local(src_path, dst_path)
533
+
534
+ return dst
535
+
536
+ def copyfile_to_local(
537
+ self,
538
+ src: Union[str, Path],
539
+ dst: Union[str, Path],
540
+ dst_type: str, # Choose from ["file", "dir"]
541
+ ) -> Union[str, Path]:
542
+ """Copy the file src to local dst and return the destination file.
543
+
544
+ If dst specifies a directory, the file will be copied into dst using
545
+ the base filename from src. If dst specifies a file that already
546
+ exists, it will be replaced.
547
+
548
+ Args:
549
+ src (str or Path): A file to be copied.
550
+ dst (str or Path): Copy file to to local dst.
551
+
552
+ Returns:
553
+ str: If dst specifies a directory, the file will be copied into dst
554
+ using the base filename from src.
555
+
556
+ Examples:
557
+ >>> backend = Boto3Backend()
558
+ >>> # dst is a file
559
+ >>> src = 's3://path/of/file'
560
+ >>> dst = 'path/of/your/file'
561
+ >>> backend.copyfile_to_local(src, dst)
562
+ 'path/of/your/file'
563
+
564
+ >>> # dst is a directory
565
+ >>> dst = 'path/of/your/dir'
566
+ >>> backend.copyfile_to_local(src, dst)
567
+ 'path/of/your/dir/file'
568
+ """
569
+ assert dst_type in ["file", "dir"]
570
+ # There is no good way to detect whether dst is a directory or a file, so we make dst_type required
571
+ if dst_type == "dir":
572
+ basename = os.path.basename(src)
573
+ if isinstance(dst, str):
574
+ dst = os.path.join(dst, basename)
575
+ else:
576
+ assert isinstance(dst, Path)
577
+ dst = dst / basename
578
+
579
+ # Create parent directory if it doesn't exist
580
+ parent_dir = os.path.dirname(dst)
581
+ os.makedirs(parent_dir, exist_ok=True)
582
+
583
+ try:
584
+ with open(dst, "wb") as f:
585
+ data = self.get(src)
586
+ f.write(data)
587
+ except Exception as e:
588
+ log.error(f"Failed to write file: {e}")
589
+ raise
590
+
591
+ return dst
592
+
593
+ def copytree_to_local(
594
+ self,
595
+ src: Union[str, Path],
596
+ dst: Union[str, Path],
597
+ ) -> Union[str, Path]:
598
+ """Recursively copy an entire directory tree rooted at src to a local
599
+ directory named dst and return the destination directory.
600
+
601
+ Args:
602
+ src (str or Path): A directory to be copied.
603
+ dst (str or Path): Copy directory to local dst.
604
+ backend_args (dict, optional): Arguments to instantiate the
605
+ prefix of uri corresponding backend. Defaults to None.
606
+
607
+ Returns:
608
+ str: The destination directory.
609
+
610
+ Examples:
611
+ >>> backend = Boto3Backend()
612
+ >>> src = 's3://path/of/dir'
613
+ >>> dst = 'path/of/your/dir'
614
+ >>> backend.copytree_to_local(src, dst)
615
+ 'path/of/your/dir'
616
+ """
617
+ for path in self.list_dir_or_file(src, list_dir=False, recursive=True):
618
+ dst_path = os.path.join(dst, path)
619
+ mkdir_or_exist(os.path.dirname(dst_path))
620
+ with open(dst_path, "wb") as f:
621
+ f.write(self.get(self.join_path(src, path)))
622
+
623
+ return dst
624
+
625
+ def remove(self, filepath: Union[str, Path]) -> None:
626
+ """Remove a file.
627
+
628
+ Args:
629
+ filepath (str or Path): Path to be removed.
630
+
631
+ Raises:
632
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
633
+ will be raised.
634
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
635
+ will be raised.
636
+
637
+ Examples:
638
+ >>> backend = Boto3Backend()
639
+ >>> filepath = 's3://path/of/file'
640
+ >>> backend.remove(filepath)
641
+ """
642
+ if not has_method(self._client, "delete"):
643
+ raise NotImplementedError(
644
+ "Current version of Boto3 Python SDK has not supported "
645
+ "the `delete` method, please use a higher version or dev "
646
+ "branch instead."
647
+ )
648
+
649
+ if not self.exists(filepath):
650
+ raise FileNotFoundError(f"filepath {filepath} does not exist")
651
+
652
+ if self.isdir(filepath):
653
+ raise IsADirectoryError("filepath should be a file")
654
+
655
+ filepath = self._map_path(filepath)
656
+ filepath = self._format_path(filepath)
657
+ filepath = self._replace_prefix(filepath)
658
+ self._client.delete(filepath)
659
+
660
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
661
+ """Recursively delete a directory tree.
662
+
663
+ Args:
664
+ dir_path (str or Path): A directory to be removed.
665
+
666
+ Examples:
667
+ >>> backend = Boto3Backend()
668
+ >>> dir_path = 's3://path/of/dir'
669
+ >>> backend.rmtree(dir_path)
670
+ """
671
+ for path in self.list_dir_or_file(dir_path, list_dir=False, recursive=True):
672
+ filepath = self.join_path(dir_path, path)
673
+ self.remove(filepath)
674
+
675
+ def copy_if_symlink_fails(
676
+ self,
677
+ src: Union[str, Path],
678
+ dst: Union[str, Path],
679
+ ) -> bool:
680
+ """Create a symbolic link pointing to src named dst.
681
+
682
+ Directly copy src to dst because PetrelBacekend does not support create
683
+ a symbolic link.
684
+
685
+ Args:
686
+ src (str or Path): A file or directory to be copied.
687
+ dst (str or Path): Copy a file or directory to dst.
688
+ backend_args (dict, optional): Arguments to instantiate the
689
+ prefix of uri corresponding backend. Defaults to None.
690
+
691
+ Returns:
692
+ bool: Return False because Boto3Backend does not support create
693
+ a symbolic link.
694
+
695
+ Examples:
696
+ >>> backend = Boto3Backend()
697
+ >>> src = 's3://path/of/file'
698
+ >>> dst = 's3://path/of/your/file'
699
+ >>> backend.copy_if_symlink_fails(src, dst)
700
+ False
701
+ >>> src = 's3://path/of/dir'
702
+ >>> dst = 's3://path/of/your/dir'
703
+ >>> backend.copy_if_symlink_fails(src, dst)
704
+ False
705
+ """
706
+ if self.isfile(src):
707
+ self.copyfile(src, dst)
708
+ else:
709
+ self.copytree(src, dst)
710
+ return False
711
+
712
+ def list_dir(self, dir_path: Union[str, Path]):
713
+ """List all folders in an S3 bucket with a given prefix.
714
+
715
+ Args:
716
+ dir_path (str | Path): Path of the directory.
717
+
718
+ Examples:
719
+ >>> backend = Boto3Backend()
720
+ >>> dir_path = 's3://path/of/dir'
721
+ >>> backend.list_dir(dir_path)
722
+ """
723
+ dir_path = self._map_path(dir_path)
724
+ dir_path = self._format_path(dir_path)
725
+ dir_path = self._replace_prefix(dir_path)
726
+ return self._client.ls_dir(dir_path)
727
+
728
+ def list_dir_or_file( # pylint: disable=too-many-arguments
729
+ self,
730
+ dir_path: Union[str, Path],
731
+ list_dir: bool = True,
732
+ list_file: bool = True,
733
+ suffix: Optional[Union[str, tuple[str]]] = None,
734
+ recursive: bool = False,
735
+ ) -> Iterator[str]:
736
+ """Scan a directory to find the interested directories or files in
737
+ arbitrary order.
738
+
739
+ Note:
740
+ Boto3 has no concept of directories but it simulates the directory
741
+ hierarchy in the filesystem through public prefixes. In addition,
742
+ if the returned path ends with '/', it means the path is a public
743
+ prefix which is a logical directory.
744
+
745
+ Note:
746
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
747
+ In addition, the returned path of directory will not contains the
748
+ suffix '/' which is consistent with other backends.
749
+
750
+ Args:
751
+ dir_path (str | Path): Path of the directory.
752
+ list_dir (bool): List the directories. Defaults to True.
753
+ list_file (bool): List the path of files. Defaults to True.
754
+ suffix (str or tuple[str], optional): File suffix
755
+ that we are interested in. Defaults to None.
756
+ recursive (bool): If set to True, recursively scan the
757
+ directory. Defaults to False.
758
+
759
+ Yields:
760
+ Iterable[str]: A relative path to ``dir_path``.
761
+
762
+ Examples:
763
+ >>> backend = Boto3Backend()
764
+ >>> dir_path = 's3://path/of/dir'
765
+ >>> # list those files and directories in current directory
766
+ >>> for file_path in backend.list_dir_or_file(dir_path):
767
+ ... print(file_path)
768
+ >>> # only list files
769
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_dir=False):
770
+ ... print(file_path)
771
+ >>> # only list directories
772
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_file=False):
773
+ ... print(file_path)
774
+ >>> # only list files ending with specified suffixes
775
+ >>> for file_path in backend.list_dir_or_file(dir_path, suffix='.txt'):
776
+ ... print(file_path)
777
+ >>> # list all files and directory recursively
778
+ >>> for file_path in backend.list_dir_or_file(dir_path, recursive=True):
779
+ ... print(file_path)
780
+ """ # noqa: E501
781
+ if not has_method(self._client, "list"):
782
+ raise NotImplementedError(
783
+ "Current version of Boto3 Python SDK has not supported "
784
+ "the `list` method, please use a higher version or dev"
785
+ " branch instead."
786
+ )
787
+
788
+ dir_path = self._map_path(dir_path)
789
+ dir_path = self._format_path(dir_path)
790
+ dir_path = self._replace_prefix(dir_path)
791
+ if list_dir and suffix is not None:
792
+ raise TypeError("`list_dir` should be False when `suffix` is not None")
793
+
794
+ if list_dir and not list_file and not recursive:
795
+ raise TypeError(
796
+ "Please use `list_dir` instead of `list_dir_or_file` when you only want to list the first level directories."
797
+ )
798
+
799
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
800
+ raise TypeError("`suffix` must be a string or tuple of strings")
801
+
802
+ # Boto3's simulated directory hierarchy assumes that directory paths
803
+ # should end with `/`
804
+ if not dir_path.endswith("/"):
805
+ dir_path += "/"
806
+
807
+ root = dir_path
808
+
809
+ def _list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive):
810
+ # Keep track of directories we've already yielded to avoid duplicates
811
+ yielded_dirs = set() if list_dir else None
812
+
813
+ for path in self._client.list(dir_path):
814
+ # All paths returned by S3 list are file paths, never directory paths
815
+ absolute_path = self.join_path(dir_path, path)
816
+ rel_path = absolute_path[len(root) :]
817
+
818
+ # If we want directories, extract directory prefixes from file paths
819
+ # boto3 client actually never return dir, it only return file paths
820
+ if list_dir and "/" in rel_path:
821
+ if not recursive:
822
+ # Non-recursive: only yield immediate child directory (first level)
823
+ first_slash_pos = rel_path.find("/")
824
+ immediate_child_dir = rel_path[:first_slash_pos]
825
+
826
+ if immediate_child_dir not in yielded_dirs:
827
+ yielded_dirs.add(immediate_child_dir)
828
+ yield immediate_child_dir
829
+ else:
830
+ # Recursive: yield all directory levels
831
+ path_parts = rel_path.split("/")[:-1] # Exclude filename
832
+ current_dir = ""
833
+ for part in path_parts:
834
+ if current_dir:
835
+ current_dir += "/" + part
836
+ else:
837
+ current_dir = part
838
+
839
+ if current_dir not in yielded_dirs:
840
+ yielded_dirs.add(current_dir)
841
+ yield current_dir
842
+
843
+ # Handle file listing
844
+ if (suffix is None or rel_path.endswith(suffix)) and list_file:
845
+ yield rel_path
846
+
847
+ return _list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive)
848
+
849
+ def generate_presigned_url(self, url: str, client_method: str = "get_object", expires_in: int = 3600) -> str:
850
+ """Generate the presigned url of video stream which can be passed to
851
+ mmcv.VideoReader. Now only work on Boto3 backend.
852
+
853
+ Note:
854
+ Now only work on Boto3 backend.
855
+
856
+ Args:
857
+ url (str): Url of video stream.
858
+ client_method (str): Method of client, 'get_object' or
859
+ 'put_object'. Default: 'get_object'.
860
+ expires_in (int): expires, in seconds. Default: 3600.
861
+
862
+ Returns:
863
+ str: Generated presigned url.
864
+ """
865
+ raise NotImplementedError("generate_presigned_url is not supported in Boto3Backend")
866
+ return self._client.generate_presigned_url(url, client_method, expires_in)
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/boto3_client.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import asyncio
17
+ import concurrent.futures
18
+ import io
19
+ import os
20
+ import time
21
+ from collections.abc import Generator
22
+ from math import ceil
23
+ from multiprocessing import shared_memory
24
+ from typing import Any, Optional
25
+
26
+ import boto3
27
+ import numpy as np
28
+ from botocore.config import Config as S3Config
29
+ from botocore.exceptions import ClientError
30
+
31
+ import cosmos_policy._src.imaginaire.utils.easy_io.backends.auto_auth as auto
32
+ from cosmos_policy._src.imaginaire.utils import log
33
+ from cosmos_policy._src.imaginaire.utils.env_parsers.cred_env_parser import CRED_ENVS
34
+
35
+ try:
36
+ # pyrefly: ignore # import-error
37
+ import aioboto3
38
+
39
+ # pyrefly: ignore # import-error
40
+ import aioboto3.session
41
+
42
+ # pyrefly: ignore # import-error
43
+ from aiobotocore.config import AioConfig
44
+
45
+ # pyrefly: ignore # import-error
46
+ from aiobotocore.session import AioSession
47
+ except ImportError:
48
+ aioboto3 = None
49
+ AioSession = None
50
+
51
+ MAX_RETRIES = 5
52
+ RETRY_DELAY = 1 # seconds
53
+
54
+
55
+ async def upload_single_part_async(
56
+ s3: AioSession, bucket: str, key: str, part_number: int, data: bytes, upload_id: str
57
+ ) -> dict[str, Any]:
58
+ """
59
+ Uploads a single part of a file asynchronously to S3.
60
+
61
+ Args:
62
+ s3 (S3): The S3 client.
63
+ bucket (str): The S3 bucket name.
64
+ key (str): The S3 key (file path).
65
+ part_number (int): The part number of the upload.
66
+ data (bytes): The data to upload.
67
+ upload_id (str): The upload ID for the multipart upload.
68
+
69
+ Returns:
70
+ dict[str, Any]: A dictionary containing the part number and ETag.
71
+ """
72
+ for attempt in range(MAX_RETRIES):
73
+ try:
74
+ response = await s3.upload_part(
75
+ Bucket=bucket, Key=key, PartNumber=part_number, UploadId=upload_id, Body=data
76
+ )
77
+ return {"PartNumber": part_number, "ETag": response["ETag"]}
78
+ except (ClientError, asyncio.TimeoutError, Exception) as e:
79
+ log.warning(f"Attempt {attempt + 1} failed for part {part_number}: {str(e)}", rank0_only=False)
80
+ if attempt < MAX_RETRIES - 1:
81
+ await asyncio.sleep(RETRY_DELAY * (2**attempt)) # Exponential backoff
82
+ else:
83
+ log.error(f"Failed to upload part {part_number} after {MAX_RETRIES} attempts", rank0_only=False)
84
+ raise
85
+
86
+
87
+ async def upload_parts_async(
88
+ part_size: int,
89
+ part_numbers: range,
90
+ upload_id: str,
91
+ data: bytes,
92
+ bucket: str,
93
+ key: str,
94
+ client_config: dict[str, Any],
95
+ ) -> list[dict[str, Any]]:
96
+ """
97
+ Uploads multiple parts of a file asynchronously to S3.
98
+
99
+ Args:
100
+ part_size (int): The size of each part in bytes.
101
+ part_numbers (range): The range of part numbers to upload.
102
+ upload_id (str): The upload ID for the multipart upload.
103
+ data (bytes): The data to upload.
104
+ bucket (str): The S3 bucket name.
105
+ key (str): The S3 key (file path).
106
+ client_config (dict[str, Any]): The S3 client configuration.
107
+
108
+ Returns:
109
+ list[dict[str, Any]]: A list of dictionaries containing part numbers and ETags.
110
+ """
111
+ session = aioboto3.Session()
112
+ config = AioConfig(retries={"max_attempts": 3, "mode": "adaptive"}, connect_timeout=5, read_timeout=10)
113
+ start_idx = part_numbers[0]
114
+ async with session.client("s3", config=config, **client_config) as s3:
115
+ tasks = []
116
+ for part_number in part_numbers:
117
+ start = (part_number - start_idx) * part_size
118
+ end = min(start + part_size, len(data))
119
+ part_data = data[start:end]
120
+ tasks.append(upload_single_part_async(s3, bucket, key, part_number + 1, part_data, upload_id))
121
+
122
+ results = await asyncio.gather(*tasks, return_exceptions=True)
123
+
124
+ successful_parts = []
125
+ failed_parts = []
126
+ for part_number, result in enumerate(results, start=start_idx + 1):
127
+ if isinstance(result, Exception):
128
+ failed_parts.append(part_number)
129
+ else:
130
+ successful_parts.append(result)
131
+
132
+ if failed_parts:
133
+ log.error(f"Failed to upload parts: {failed_parts}", rank0_only=False)
134
+ raise Exception(f"Failed to upload {len(failed_parts)} parts")
135
+
136
+ successful_parts.sort(key=lambda part: part["PartNumber"])
137
+ return successful_parts
138
+
139
+
140
+ def upload_parts_to_s3(args: tuple[range, str, int, bytes, str, str, dict[str, Any]]) -> list[dict[str, Any]]:
141
+ """
142
+ Uploads parts of a file to S3 using a new event loop.
143
+
144
+ Args:
145
+ args (tuple[range, str, int, bytes, str, str, dict[str, Any]]): The arguments for uploading parts, including:
146
+ part_numbers (range): The range of part numbers to upload.
147
+ upload_id (str): The upload ID for the multipart upload.
148
+ part_size (int): The size of each part in bytes.
149
+ data (bytes): The data to upload.
150
+ bucket (str): The S3 bucket name.
151
+ key (str): The S3 key (file path).
152
+ client_config (dict[str, Any]): The S3 client configuration.
153
+
154
+ Returns:
155
+ list[dict[str, Any]]: A list of dictionaries containing part numbers and ETags.
156
+ """
157
+ part_numbers, upload_id, part_size, data, bucket, key, client_config = args
158
+ loop = asyncio.new_event_loop()
159
+ asyncio.set_event_loop(loop)
160
+ parts = loop.run_until_complete(
161
+ upload_parts_async(part_size, part_numbers, upload_id, data, bucket, key, client_config)
162
+ )
163
+ loop.close()
164
+ return parts
165
+
166
+
167
+ async def download_single_part_async(
168
+ s3, bucket: str, key: str, part_number: int, start: int, end: int, shm_name: str, part_size: int
169
+ ) -> None:
170
+ """
171
+ Downloads a single part of a file asynchronously and writes it to shared memory.
172
+
173
+ Args:
174
+ s3 (S3): The S3 client.
175
+ bucket (str): The S3 bucket name.
176
+ key (str): The S3 key (file path).
177
+ part_number (int): The part number.
178
+ start (int): The start byte of the part.
179
+ end (int): The end byte of the part.
180
+ shm_name (str): The name of the shared memory block.
181
+ part_size (int): The size of each part in bytes.
182
+ """
183
+ for attempt in range(MAX_RETRIES):
184
+ try:
185
+ range_header = f"bytes={start}-{end}"
186
+ response = await s3.get_object(Bucket=bucket, Key=key, Range=range_header)
187
+ data = await response["Body"].read()
188
+
189
+ shm = shared_memory.SharedMemory(name=shm_name)
190
+ offset = part_number * part_size
191
+ shm.buf[offset : offset + len(data)] = data
192
+ shm.close()
193
+ return
194
+ except (ClientError, asyncio.TimeoutError, Exception) as e:
195
+ log.warning(f"Attempt {attempt + 1} failed for part {part_number}: {str(e)}", rank0_only=False)
196
+ if attempt < MAX_RETRIES - 1:
197
+ await asyncio.sleep(RETRY_DELAY * (2**attempt)) # Exponential backoff
198
+ else:
199
+ log.error(f"Failed to download part {part_number} after {MAX_RETRIES} attempts", rank0_only=False)
200
+ raise
201
+
202
+
203
+ async def download_parts_async(
204
+ part_size: int, part_numbers: range, bucket: str, key: str, client_config: dict[str, Any], shm_name: str
205
+ ) -> None:
206
+ """
207
+ Downloads multiple parts of a file asynchronously and writes them to shared memory.
208
+
209
+ Args:
210
+ part_size (int): The size of each part in bytes.
211
+ part_numbers (range): The range of part numbers to download.
212
+ bucket (str): The S3 bucket name.
213
+ key (str): The S3 key (file path).
214
+ client_config (dict[str, Any]): The S3 client configuration.
215
+ shm_name (str): The name of the shared memory block.
216
+ """
217
+ session = aioboto3.Session()
218
+ config = AioConfig(retries={"max_attempts": 5, "mode": "adaptive"}, connect_timeout=10, read_timeout=30)
219
+ async with session.client("s3", config=config, **client_config) as s3:
220
+ tasks = [
221
+ download_single_part_async(
222
+ s3,
223
+ bucket,
224
+ key,
225
+ part_number,
226
+ part_number * part_size,
227
+ (part_number + 1) * part_size - 1,
228
+ shm_name,
229
+ part_size,
230
+ )
231
+ for part_number in part_numbers
232
+ ]
233
+ results = await asyncio.gather(*tasks, return_exceptions=True)
234
+ failed_parts = [part for part, result in zip(part_numbers, results) if isinstance(result, Exception)]
235
+
236
+ if failed_parts:
237
+ log.error(f"Failed to download parts: {failed_parts}", rank0_only=False)
238
+ raise Exception(f"Failed to download {len(failed_parts)} parts")
239
+
240
+
241
+ def download_parts_to_s3(args: tuple[range, int, str, str, dict[str, Any], str]) -> bytes:
242
+ """
243
+ Downloads parts of a file using a new event loop.
244
+
245
+ Args:
246
+ args (tuple[range, int, str, str, dict[str, Any]]): The arguments for downloading parts, including:
247
+ part_numbers (range): The range of part numbers to download.
248
+ part_size (int): The size of each part in bytes.
249
+ bucket (str): The S3 bucket name.
250
+ key (str): The S3 key (file path).
251
+ client_config (dict[str, Any]): The S3 client configuration.
252
+
253
+ Returns:
254
+ bytes: The combined file data from all downloaded parts.
255
+ """
256
+ part_numbers, part_size, bucket, key, client_config, shm_name = args
257
+ loop = asyncio.new_event_loop()
258
+ asyncio.set_event_loop(loop)
259
+ loop.run_until_complete(download_parts_async(part_size, part_numbers, bucket, key, client_config, shm_name))
260
+ loop.close()
261
+
262
+
263
+ class Boto3Client:
264
+ """
265
+ This class:
266
+
267
+ - Provides higher-level S3 operations.
268
+ - Serves as a wrapper around boto3.client in order to make boto3.client serializable.
269
+ - It's required to use spawn method of creating DataLoader workers,
270
+ which is in turn required to avoid segfaults when using Triton,
271
+ e.g. for torch.compile or custom kernels.
272
+ """
273
+
274
+ def __init__(
275
+ self,
276
+ s3_credential_path: str,
277
+ max_attempt: int = 3,
278
+ ):
279
+ self.max_attempt: int = max_attempt
280
+ assert s3_credential_path, "s3_credential_path is required"
281
+ assert os.path.exists(s3_credential_path) or CRED_ENVS.APP_ENV in [
282
+ "prod",
283
+ "dev",
284
+ "stg",
285
+ ], f"Credential file not found: {s3_credential_path}"
286
+
287
+ # Keep track of S3 client constructor parameters so it can be recreated when pickling.
288
+ with auto.open_auth(s3_credential_path, "r") as f:
289
+ self._s3_cred_info = auto.json_load_auth(f)
290
+ self._s3_config = S3Config(
291
+ signature_version="s3v4",
292
+ s3={"addressing_style": "virtual"},
293
+ response_checksum_validation="when_required",
294
+ request_checksum_calculation="when_required",
295
+ )
296
+ self._init_client()
297
+ self._mc_kv_store = None
298
+
299
+ def _init_client(self):
300
+ """Initialize the S3 client."""
301
+ self._client = boto3.client("s3", **self._s3_cred_info, config=self._s3_config)
302
+
303
+ def __getstate__(self):
304
+ state = self.__dict__.copy()
305
+ # S3 client isn't pickleable.
306
+ del state["_client"]
307
+ return state
308
+
309
+ def __setstate__(self, state: dict[str, Any]):
310
+ self.__dict__.update(state)
311
+ self._init_client()
312
+
313
+ def size(self, filepath: str) -> int:
314
+ filepath = self._check_path(filepath)
315
+
316
+ if self._mc_kv_store and self._mc_kv_store.available:
317
+ if self._mc_kv_store.has(filepath):
318
+ return len(self._mc_kv_store.get(filepath))
319
+
320
+ attempt: int = 0
321
+ while attempt < self.max_attempt:
322
+ try:
323
+ return self._client.head_object(
324
+ Bucket=filepath.split("/")[0],
325
+ Key="/".join(filepath.split("/")[1:]),
326
+ )["ContentLength"]
327
+ except ClientError as e:
328
+ if e.response["Error"]["Code"] == "404":
329
+ raise # Object does not exist.
330
+ else:
331
+ attempt += 1
332
+ log.error(f"Attempt {attempt} failed for {filepath}: {e}", rank0_only=False)
333
+ if attempt >= self.max_attempt:
334
+ raise # Re-raise the exception after max attempt
335
+ time.sleep(2) # Wait for 2 seconds before retrying
336
+ except Exception as e:
337
+ attempt += 1
338
+ log.error(f"Attempt {attempt} failed for {filepath}: due to an unexpected error: {e}", rank0_only=False)
339
+ if attempt >= self.max_attempt:
340
+ raise # Re-raise the exception after max attempt
341
+ time.sleep(2) # Wait for 2 seconds before retrying
342
+
343
+ raise ConnectionError("Unable to head {} from. {} attempts tried.".format(filepath, attempt))
344
+
345
+ def get(self, filepath: str, offset: Optional[int] = None, size: Optional[int] = None) -> bytes:
346
+ raw_filepath = filepath
347
+ filepath = self._check_path(filepath)
348
+
349
+ read_offset: Optional[int] = None
350
+ read_size: Optional[int] = None
351
+ byte_range: Optional[str] = None
352
+ if offset is not None or size is not None:
353
+ read_offset = offset or 0
354
+ assert read_offset >= 0, "Read offset must be ≥ 0"
355
+
356
+ # Try not to incur a remote call to get the file size. This can heavily slow down ranged reads.
357
+ #
358
+ # This means we won't always validate the read offset or read size against the file size.
359
+ read_size = size or (self.size(filepath=raw_filepath) - read_offset)
360
+ assert read_size >= 1, "Read size must be ≥ 1 or read offset must be < file size"
361
+
362
+ byte_range = f"bytes={read_offset}-{read_offset + read_size - 1}"
363
+
364
+ if self._mc_kv_store and self._mc_kv_store.available:
365
+ if self._mc_kv_store.has(filepath):
366
+ chunk: bytes = self._mc_kv_store.get(filepath)
367
+ if read_offset is not None and read_size is not None:
368
+ return chunk[read_offset : read_offset + read_size]
369
+ else:
370
+ return chunk
371
+
372
+ attempt = 0
373
+ while attempt < self.max_attempt:
374
+ try:
375
+ buffer = io.BytesIO()
376
+ if byte_range is None:
377
+ self._client.download_fileobj(
378
+ Bucket=filepath.split("/")[0],
379
+ Key="/".join(filepath.split("/")[1:]),
380
+ Fileobj=buffer,
381
+ )
382
+ else:
383
+ # The boto S3 Transfer Manager doesn't support ranged reads yet.
384
+ #
385
+ # https://github.com/boto/boto3/issues/1215
386
+ # https://github.com/boto/s3transfer/issues/248
387
+ resp = self._client.get_object(
388
+ Bucket=filepath.split("/")[0],
389
+ Key="/".join(filepath.split("/")[1:]),
390
+ Range=byte_range,
391
+ )
392
+ buffer.write(resp["Body"].read())
393
+ buffer.seek(0)
394
+ # Only cache full reads.
395
+ if byte_range is None:
396
+ if self._mc_kv_store and self._mc_kv_store.available:
397
+ self._mc_kv_store.put(filepath, buffer.read())
398
+ buffer.seek(0)
399
+
400
+ return buffer.read()
401
+ except Exception as e:
402
+ attempt += 1
403
+ log.error(f"Got an exception: attempt={attempt} - {e} - {filepath}", rank0_only=False)
404
+
405
+ raise ConnectionError("Unable to read {} from. {} attempts tried.".format(filepath, attempt))
406
+
407
+ def put(self, obj, filepath):
408
+ filepath = self._check_path(filepath)
409
+ bucket_name = filepath.split("/")[0]
410
+ key = "/".join(filepath.split("/")[1:])
411
+ attempt = 0
412
+ while attempt < self.max_attempt:
413
+ try:
414
+ # If obj is a string path to a local file, use upload_file instead
415
+ if isinstance(obj, str) and os.path.isfile(obj):
416
+ self._client.upload_file(Filename=obj, Bucket=bucket_name, Key=key)
417
+ return
418
+ if isinstance(obj, io.BytesIO):
419
+ obj.seek(0)
420
+ self._client.upload_fileobj(obj, Bucket=bucket_name, Key=key)
421
+ return
422
+ if isinstance(obj, bytes):
423
+ self._client.put_object(Body=obj, Bucket=bucket_name, Key=key)
424
+ return
425
+ else:
426
+ raise ValueError("Unsupported object type for upload")
427
+ except ClientError as e:
428
+ attempt += 1
429
+ log.error(f"Got an exception: attempt={attempt} - {e} - {filepath}", rank0_only=False)
430
+
431
+ raise ConnectionError("Unable to write {} to. {} attempts tried.".format(filepath, attempt))
432
+
433
+ def fast_put(self, obj, filepath, num_processes: int = 32):
434
+ assert aioboto3 is not None, "aioboto3 is required for fast_put"
435
+ original_filepath = filepath
436
+ filepath = self._check_path(filepath)
437
+ bucket = filepath.split("/")[0]
438
+ key = "/".join(filepath.split("/")[1:])
439
+ part_size = 16 * 1024 * 1024 # 16 MB part size
440
+
441
+ if isinstance(obj, bytes):
442
+ data = obj
443
+ elif isinstance(obj, str) and os.path.isfile(obj):
444
+ with open(obj, "rb") as f:
445
+ data = f.read()
446
+ elif isinstance(obj, io.BytesIO):
447
+ obj.seek(0)
448
+ data = obj.read()
449
+ else:
450
+ raise ValueError("Unsupported object type for upload")
451
+
452
+ file_size = len(data)
453
+ if file_size <= part_size * num_processes:
454
+ return self.put(data, original_filepath)
455
+ num_parts = ceil(file_size / part_size)
456
+ upload_id = self._client.create_multipart_upload(Bucket=bucket, Key=key)["UploadId"]
457
+
458
+ part_numbers = np.array_split(np.arange(num_parts), num_processes)
459
+
460
+ with concurrent.futures.ProcessPoolExecutor(max_workers=num_processes) as executor:
461
+ args = []
462
+ for i in range(num_processes):
463
+ cur_parts = part_numbers[i].tolist()
464
+ cur_data = data[cur_parts[0] * part_size : min(cur_parts[-1] * part_size + part_size, file_size)]
465
+ args.append((cur_parts, upload_id, part_size, cur_data, bucket, key, self._s3_cred_info))
466
+ results = executor.map(upload_parts_to_s3, args)
467
+ parts = []
468
+ for result in results:
469
+ parts.extend(result)
470
+
471
+ parts = sorted(parts, key=lambda part: part["PartNumber"])
472
+ self._client.complete_multipart_upload(
473
+ Bucket=bucket, Key=key, UploadId=upload_id, MultipartUpload={"Parts": parts}
474
+ )
475
+
476
+ def contains(self, filepath: str, max_retries=10) -> bool:
477
+ """
478
+ Checks if the specified object exists in the S3 bucket with retry logic for errors.
479
+
480
+ Args:
481
+ filepath (str): The s3 path of the file to check, must start with "s3://".
482
+
483
+ Returns:
484
+ bool: True if the object exists in the S3 bucket, False otherwise.
485
+
486
+ Raises:
487
+ ClientError: If an error response other than "404 Not Found" is returned from the S3 service.
488
+ """
489
+ filepath = self._check_path(filepath)
490
+ bucket = filepath.split("/")[0]
491
+ key = "/".join(filepath.split("/")[1:])
492
+
493
+ retries = 0
494
+ while retries < max_retries:
495
+ try:
496
+ # Try to check if the object exists
497
+ self._client.head_object(Bucket=bucket, Key=key)
498
+ return True # Object exists
499
+ except ClientError as e:
500
+ if e.response["Error"]["Code"] == "404":
501
+ return False # Object does not exist
502
+ else:
503
+ retries += 1
504
+ print(f"Attempt {retries} failed with error: {e}")
505
+ if retries >= max_retries:
506
+ raise # Re-raise the exception if max retries are reached
507
+ time.sleep(2) # Wait for 2 seconds before retrying
508
+ except Exception as e:
509
+ retries += 1
510
+ print(f"Attempt {retries} failed due to an unexpected error: {e}")
511
+ if retries >= max_retries:
512
+ raise # Re-raise the exception if max retries are reached
513
+ time.sleep(2) # Wait for 2 seconds before retrying
514
+
515
+ def isdir(self, filepath: str, max_retries=10) -> bool:
516
+ """
517
+ Determines if the specified path corresponds to a directory in S3 with retry logic.
518
+
519
+ A directory in S3 is implied if there are any objects stored with the given prefix,
520
+ which means this function checks for the existence of any objects at or under the specified path.
521
+
522
+ Args:
523
+ filepath (str): The s3 path to check, must start with "s3://".
524
+
525
+ Returns:
526
+ bool: True if the specified path corresponds to a directory in S3, False otherwise.
527
+ Directories in S3 are not physical entities but are implied by object keys.
528
+
529
+ Raises:
530
+ ClientError: An error from the S3 API that isn't related to the absence of the directory
531
+ (logged but not raised further).
532
+ """
533
+ filepath = self._check_path(filepath)
534
+ if not filepath.endswith("/"):
535
+ filepath += "/"
536
+
537
+ bucket = filepath.split("/")[0]
538
+ prefix = "/".join(filepath.split("/")[1:])
539
+
540
+ retries = 0
541
+ while retries < max_retries:
542
+ try:
543
+ # Try to check if any objects exist with the given prefix (i.e., directory in S3)
544
+ resp = self._client.list_objects_v2(Bucket=bucket, Prefix=prefix, Delimiter="/", MaxKeys=1)
545
+ # Check if any content or prefixes exist under the given path
546
+ return "CommonPrefixes" in resp or "Contents" in resp
547
+ except ClientError as e:
548
+ retries += 1
549
+ log.error(f"Attempt {retries} failed: {e}", rank0_only=False)
550
+ if retries >= max_retries:
551
+ return False # Return False if maximum retries are reached
552
+ time.sleep(2) # Wait for 2 seconds before retrying
553
+ except Exception as e:
554
+ retries += 1
555
+ log.error(f"Attempt {retries} failed due to an unexpected error: {e}", rank0_only=False)
556
+ if retries >= max_retries:
557
+ return False # Return False if maximum retries are reached
558
+ time.sleep(2) # Wait for 2 seconds before retrying
559
+
560
+ def delete(self, filepath):
561
+ filepath = self._check_path(filepath)
562
+ self._client.delete_object(Bucket=filepath.split("/")[0], Key="/".join(filepath.split("/")[1:]))
563
+
564
+ def ls_dir(self, filepath: str) -> Generator[str, None, None]:
565
+ """
566
+ List all folders in an S3 bucket with a given prefix.
567
+
568
+ Args:
569
+ filepath (str): The S3 path of the folder to list.
570
+
571
+ Yields:
572
+ str: The keys of the folders in the S3 bucket.
573
+ """
574
+ filepath = self._check_path(filepath)
575
+ bucket = filepath.split("/")[0]
576
+ prefix = "/".join(filepath.split("/")[1:])
577
+ continuation_token = None
578
+ if prefix and not prefix.endswith("/"):
579
+ prefix += "/"
580
+
581
+ while True:
582
+ if continuation_token:
583
+ resp = self._client.list_objects_v2(
584
+ Bucket=bucket, Prefix=prefix, Delimiter="/", ContinuationToken=continuation_token
585
+ )
586
+ else:
587
+ resp = self._client.list_objects_v2(Bucket=bucket, Prefix=prefix, Delimiter="/")
588
+
589
+ if "CommonPrefixes" in resp:
590
+ for item in resp["CommonPrefixes"]:
591
+ yield item["Prefix"][len(prefix) :]
592
+
593
+ # Check if there are more keys to retrieve
594
+ if resp.get("IsTruncated"): # If IsTruncated is True, there are more keys
595
+ continuation_token = resp.get("NextContinuationToken")
596
+ else:
597
+ break
598
+
599
+ def list(self, filepath: str, exclude_prefix: Optional[str] = None) -> Generator[str, None, None]:
600
+ """
601
+ List all keys in an S3 bucket with a given prefix, excluding files that start with
602
+ specified prefix.
603
+
604
+ Args:
605
+ filepath (str): The S3 path of the file to list.
606
+ exclude_prefix (str): Files starting with this prefix will be excluded from results.
607
+ Defaults to "real".
608
+
609
+ Yields:
610
+ str: The keys of the files in the S3 bucket that don't start with exclude_prefix.
611
+ """
612
+ filepath = self._check_path(filepath)
613
+ bucket = filepath.split("/")[0]
614
+ prefix = "/".join(filepath.split("/")[1:])
615
+
616
+ continuation_token = None
617
+
618
+ while True:
619
+ if continuation_token:
620
+ resp = self._client.list_objects_v2(Bucket=bucket, Prefix=prefix, ContinuationToken=continuation_token)
621
+ else:
622
+ resp = self._client.list_objects_v2(Bucket=bucket, Prefix=prefix)
623
+
624
+ if "Contents" in resp:
625
+ for item in resp["Contents"]:
626
+ key = item["Key"][len(prefix) :]
627
+ # Skip files that start with the excluded prefix
628
+ if exclude_prefix is None or not key.startswith(exclude_prefix):
629
+ yield key
630
+
631
+ # Check if there are more keys to retrieve
632
+ if resp.get("IsTruncated"): # If IsTruncated is True, there are more keys
633
+ continuation_token = resp.get("NextContinuationToken")
634
+ else:
635
+ break
636
+
637
+ def _check_path(self, filepath: str):
638
+ assert filepath.startswith("s3://")
639
+ filepath = filepath[5:]
640
+ return filepath
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/http_backend.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import os
18
+ import tempfile
19
+ from collections.abc import Generator, Iterator
20
+ from contextlib import contextmanager
21
+ from pathlib import Path
22
+ from typing import Optional, Union
23
+ from urllib.request import Request, urlopen
24
+
25
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.base_backend import BaseStorageBackend
26
+
27
+
28
+ class HTTPBackend(BaseStorageBackend):
29
+ """HTTP and HTTPS storage bachend."""
30
+
31
+ def size(self, filepath: Union[str, Path]) -> int:
32
+ """Get the file size in bytes for a given ``filepath``.
33
+
34
+ Args:
35
+ filepath (str or Path): Path to get file size in bytes.
36
+
37
+ Returns:
38
+ int: File size in bytes for filepath.
39
+
40
+ Examples:
41
+ >>> backend = HTTPBackend()
42
+ >>> filepath = 'http://path/of/file'
43
+ >>> backend.size(filepath) # file containing 'hello world'
44
+ 11
45
+ """
46
+ request = Request(url=str(filepath), method="HEAD")
47
+ with urlopen(request) as response:
48
+ if response.status == 200:
49
+ return int(response.headers["Content-Length"])
50
+ else:
51
+ raise RuntimeError(f"Unexpected response: {response}")
52
+
53
+ def get(self, filepath: Union[str, Path], offset: Optional[int] = None, size: Optional[int] = None) -> bytes:
54
+ """Read bytes from a given ``filepath`` with 'rb' mode in range [offset, offset + size).
55
+
56
+ Args:
57
+ filepath (str): Path to read data.
58
+ offset (int, optional): Read offset in bytes (0-index). Defaults to 0.
59
+ size (int, optional): Read size in bytes. Defaults to the file size.
60
+
61
+ Returns:
62
+ bytes: Expected bytes object.
63
+
64
+ Examples:
65
+ >>> backend = HTTPBackend()
66
+ >>> backend.get('http://path/of/file')
67
+ b'hello world'
68
+ """
69
+ request = Request(url=str(filepath), method="GET")
70
+ if offset is not None or size is not None:
71
+ read_offset = offset or 0
72
+ assert read_offset >= 0, "Read offset must be ≥ 0"
73
+
74
+ # Try not to incur a remote call to get the file size. This can heavily slow down ranged reads.
75
+ #
76
+ # This means we won't always validate the read offset or read size against the file size.
77
+ read_size = size or (self.size(filepath=filepath) - read_offset)
78
+ assert read_size >= 1, "Read size must be ≥ 1 or read offset must be < file size"
79
+
80
+ request.add_header("Range", f"bytes={read_offset}-{read_offset + read_size - 1}")
81
+ with urlopen(request) as response:
82
+ if response.status in {200, 206}:
83
+ return response.read()
84
+ else:
85
+ raise RuntimeError(f"Unexpected response: {response}")
86
+
87
+ def get_text(self, filepath: Union[str, Path], encoding: str = "utf-8") -> str:
88
+ """Read text from a given ``filepath``.
89
+
90
+ Args:
91
+ filepath (str): Path to read data.
92
+ encoding (str): The encoding format used to open the ``filepath``.
93
+ Defaults to 'utf-8'.
94
+
95
+ Returns:
96
+ str: Expected text reading from ``filepath``.
97
+
98
+ Examples:
99
+ >>> backend = HTTPBackend()
100
+ >>> backend.get_text('http://path/of/file')
101
+ 'hello world'
102
+ """
103
+ return self.get(filepath=filepath).decode(encoding)
104
+
105
+ def put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path]) -> None:
106
+ raise NotImplementedError(f"put not supported in {self.name}")
107
+
108
+ def put_text(self, obj: str, filepath: Union[str, Path], encoding: str = "utf-8") -> None:
109
+ raise NotImplementedError(f"put_text not supported in {self.name}")
110
+
111
+ def exists(self, filepath: Union[str, Path]) -> bool:
112
+ request = Request(url=str(filepath), method="HEAD")
113
+ with urlopen(request) as response:
114
+ if response.status == 404:
115
+ return False
116
+ elif response.status == 200:
117
+ return True
118
+ else:
119
+ raise RuntimeError(f"Unexpected response: {response}")
120
+
121
+ def isdir(self, filepath: Union[str, Path]) -> bool:
122
+ raise NotImplementedError(f"isdir not supported in {self.name}")
123
+
124
+ def isfile(self, filepath: Union[str, Path]) -> bool:
125
+ raise NotImplementedError(f"isfile not supported in {self.name}")
126
+
127
+ def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str:
128
+ raise NotImplementedError(f"join_path not supported in {self.name}")
129
+
130
+ @contextmanager
131
+ def get_local_path(self, filepath: Union[str, Path]) -> Generator[Union[str, Path], None, None]:
132
+ """Download a file from ``filepath`` to a local temporary directory,
133
+ and return the temporary path.
134
+
135
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
136
+ can be called with ``with`` statement, and when exists from the
137
+ ``with`` statement, the temporary path will be released.
138
+
139
+ Args:
140
+ filepath (str): Download a file from ``filepath``.
141
+
142
+ Yields:
143
+ Iterable[str]: Only yield one temporary path.
144
+
145
+ Examples:
146
+ >>> backend = HTTPBackend()
147
+ >>> # After existing from the ``with`` clause,
148
+ >>> # the path will be removed
149
+ >>> with backend.get_local_path('http://path/of/file') as path:
150
+ ... # do something here
151
+ """
152
+ try:
153
+ f = tempfile.NamedTemporaryFile(delete=False)
154
+ f.write(self.get(filepath))
155
+ f.close()
156
+ yield f.name
157
+ finally:
158
+ os.remove(f.name)
159
+
160
+ def copyfile(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
161
+ raise NotImplementedError(f"copyfile not supported in {self.name}")
162
+
163
+ def copytree(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
164
+ raise NotImplementedError(f"copytree not supported in {self.name}")
165
+
166
+ def copyfile_from_local(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
167
+ raise NotImplementedError(f"copyfile_from_local not supported in {self.name}")
168
+
169
+ def copytree_from_local(self, src: Union[str, Path], dst: Union[str, Path]) -> str:
170
+ raise NotImplementedError(f"copytree_from_local not supported in {self.name}")
171
+
172
+ def copyfile_to_local(self, src: Union[str, Path], dst: Union[str, Path], dst_type: str) -> Union[str, Path]:
173
+ raise NotImplementedError(f"copyfile_to_local not supported in {self.name}")
174
+
175
+ def copytree_to_local(self, src: Union[str, Path], dst: Union[str, Path]) -> Union[str, Path]:
176
+ raise NotImplementedError(f"copytree_to_local not supported in {self.name}")
177
+
178
+ def remove(self, filepath: Union[str, Path]) -> None:
179
+ raise NotImplementedError(f"remove not supported in {self.name}")
180
+
181
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
182
+ raise NotImplementedError(f"rmtree not supported in {self.name}")
183
+
184
+ def copy_if_symlink_fails(self, src: Union[str, Path], dst: Union[str, Path]) -> bool:
185
+ raise NotImplementedError(f"copy_if_symlink_fails not supported in {self.name}")
186
+
187
+ def list_dir(self, dir_path: Union[str, Path]) -> Generator[str, None, None]:
188
+ raise NotImplementedError(f"list_dir not supported in {self.name}")
189
+
190
+ def list_dir_or_file( # pylint: disable=too-many-arguments
191
+ self,
192
+ dir_path: Union[str, Path],
193
+ list_dir: bool = True,
194
+ list_file: bool = True,
195
+ suffix: Optional[Union[str, tuple[str]]] = None,
196
+ recursive: bool = False,
197
+ ) -> Iterator[str]:
198
+ raise NotImplementedError(f"list_dir_or_file not supported in {self.name}")
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/local_backend.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import io
17
+ import os
18
+ import os.path as osp
19
+ import shutil
20
+ from collections.abc import Generator, Iterator
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+ from typing import Optional, Union
24
+
25
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.base_backend import BaseStorageBackend, mkdir_or_exist
26
+
27
+
28
+ class LocalBackend(BaseStorageBackend):
29
+ """Raw local storage backend."""
30
+
31
+ _allow_symlink = True
32
+
33
+ def size(self, filepath: Union[str, Path]) -> int:
34
+ """Get the file size in bytes for a given ``filepath``.
35
+
36
+ Args:
37
+ filepath (str or Path): Path to get file size in bytes.
38
+
39
+ Returns:
40
+ int: File size in bytes for filepath.
41
+
42
+ Examples:
43
+ >>> backend = LocalBackend()
44
+ >>> filepath = '/path/of/file'
45
+ >>> backend.size(filepath) # file containing 'hello world'
46
+ 11
47
+ """
48
+ return osp.getsize(filepath)
49
+
50
+ def get(self, filepath: Union[str, Path], offset: Optional[int] = None, size: Optional[int] = None) -> bytes:
51
+ """Read bytes from a given ``filepath`` with 'rb' mode.
52
+
53
+ Args:
54
+ filepath (str or Path): Path to read data.
55
+ offset (int, optional): Read offset in bytes (0-index). Defaults to 0.
56
+ size (int, optional): Read size in bytes. Defaults to the file size.
57
+
58
+ Returns:
59
+ bytes: Expected bytes object.
60
+
61
+ Examples:
62
+ >>> backend = LocalBackend()
63
+ >>> filepath = '/path/of/file'
64
+ >>> backend.get(filepath)
65
+ b'hello world'
66
+ """
67
+ read_offset: Optional[int] = None
68
+ read_size: Optional[int] = None
69
+ if offset is not None or size is not None:
70
+ read_offset = offset or 0
71
+ assert read_offset >= 0, "Read offset must be ≥ 0"
72
+
73
+ read_size = size or (self.size(filepath=filepath) - read_offset)
74
+ assert read_size >= 1, "Read size must be ≥ 1 or read offset must be < file size"
75
+
76
+ with open(filepath, "rb") as f:
77
+ if read_offset is not None:
78
+ f.seek(read_offset)
79
+ value = f.read(read_size)
80
+ return value
81
+
82
+ def get_text(self, filepath: Union[str, Path], encoding: str = "utf-8") -> str:
83
+ """Read text from a given ``filepath`` with 'r' mode.
84
+
85
+ Args:
86
+ filepath (str or Path): Path to read data.
87
+ encoding (str): The encoding format used to open the ``filepath``.
88
+ Defaults to 'utf-8'.
89
+
90
+ Returns:
91
+ str: Expected text reading from ``filepath``.
92
+
93
+ Examples:
94
+ >>> backend = LocalBackend()
95
+ >>> filepath = '/path/of/file'
96
+ >>> backend.get_text(filepath)
97
+ 'hello world'
98
+ """
99
+ with open(filepath, encoding=encoding) as f:
100
+ text = f.read()
101
+ return text
102
+
103
+ def put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path]) -> None:
104
+ """Write bytes to a given ``filepath`` with 'wb' mode.
105
+
106
+ Note:
107
+ ``put`` will create a directory if the directory of
108
+ ``filepath`` does not exist.
109
+
110
+ Args:
111
+ obj (bytes): Data to be written.
112
+ filepath (str or Path): Path to write data.
113
+
114
+ Examples:
115
+ >>> backend = LocalBackend()
116
+ >>> filepath = '/path/of/file'
117
+ >>> backend.put(b'hello world', filepath)
118
+ """
119
+ mkdir_or_exist(osp.dirname(filepath))
120
+ if isinstance(obj, io.BytesIO):
121
+ obj.seek(0)
122
+ obj = obj.getvalue()
123
+ with open(filepath, "wb") as f:
124
+ f.write(obj)
125
+
126
+ def put_text(self, obj: str, filepath: Union[str, Path], encoding: str = "utf-8") -> None:
127
+ """Write text to a given ``filepath`` with 'w' mode.
128
+
129
+ Note:
130
+ ``put_text`` will create a directory if the directory of
131
+ ``filepath`` does not exist.
132
+
133
+ Args:
134
+ obj (str): Data to be written.
135
+ filepath (str or Path): Path to write data.
136
+ encoding (str): The encoding format used to open the ``filepath``.
137
+ Defaults to 'utf-8'.
138
+
139
+ Examples:
140
+ >>> backend = LocalBackend()
141
+ >>> filepath = '/path/of/file'
142
+ >>> backend.put_text('hello world', filepath)
143
+ """
144
+ mkdir_or_exist(osp.dirname(filepath))
145
+ with open(filepath, "w", encoding=encoding) as f:
146
+ f.write(obj)
147
+
148
+ def exists(self, filepath: Union[str, Path]) -> bool:
149
+ """Check whether a file path exists.
150
+
151
+ Args:
152
+ filepath (str or Path): Path to be checked whether exists.
153
+
154
+ Returns:
155
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
156
+
157
+ Examples:
158
+ >>> backend = LocalBackend()
159
+ >>> filepath = '/path/of/file'
160
+ >>> backend.exists(filepath)
161
+ True
162
+ """
163
+ return osp.exists(filepath)
164
+
165
+ def isdir(self, filepath: Union[str, Path]) -> bool:
166
+ """Check whether a file path is a directory.
167
+
168
+ Args:
169
+ filepath (str or Path): Path to be checked whether it is a
170
+ directory.
171
+
172
+ Returns:
173
+ bool: Return ``True`` if ``filepath`` points to a directory,
174
+ ``False`` otherwise.
175
+
176
+ Examples:
177
+ >>> backend = LocalBackend()
178
+ >>> filepath = '/path/of/dir'
179
+ >>> backend.isdir(filepath)
180
+ True
181
+ """
182
+ return osp.isdir(filepath)
183
+
184
+ def isfile(self, filepath: Union[str, Path]) -> bool:
185
+ """Check whether a file path is a file.
186
+
187
+ Args:
188
+ filepath (str or Path): Path to be checked whether it is a file.
189
+
190
+ Returns:
191
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
192
+ otherwise.
193
+
194
+ Examples:
195
+ >>> backend = LocalBackend()
196
+ >>> filepath = '/path/of/file'
197
+ >>> backend.isfile(filepath)
198
+ True
199
+ """
200
+ return osp.isfile(filepath)
201
+
202
+ def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str:
203
+ r"""Concatenate all file paths.
204
+
205
+ Join one or more filepath components intelligently. The return value
206
+ is the concatenation of filepath and any members of \*filepaths.
207
+
208
+ Args:
209
+ filepath (str or Path): Path to be concatenated.
210
+
211
+ Returns:
212
+ str: The result of concatenation.
213
+
214
+ Examples:
215
+ >>> backend = LocalBackend()
216
+ >>> filepath1 = '/path/of/dir1'
217
+ >>> filepath2 = 'dir2'
218
+ >>> filepath3 = 'path/of/file'
219
+ >>> backend.join_path(filepath1, filepath2, filepath3)
220
+ '/path/of/dir/dir2/path/of/file'
221
+ """
222
+ # TODO, if filepath or filepaths are Path, should return Path
223
+ return osp.join(filepath, *filepaths)
224
+
225
+ @contextmanager
226
+ def get_local_path(
227
+ self,
228
+ filepath: Union[str, Path],
229
+ ) -> Generator[Union[str, Path], None, None]:
230
+ """Only for unified API and do nothing.
231
+
232
+ Args:
233
+ filepath (str or Path): Path to be read data.
234
+ backend_args (dict, optional): Arguments to instantiate the
235
+ corresponding backend. Defaults to None.
236
+
237
+ Examples:
238
+ >>> backend = LocalBackend()
239
+ >>> with backend.get_local_path('s3://bucket/abc.jpg') as path:
240
+ ... # do something here
241
+ """
242
+ yield filepath
243
+
244
+ def copyfile(
245
+ self,
246
+ src: Union[str, Path],
247
+ dst: Union[str, Path],
248
+ ) -> str:
249
+ """Copy a file src to dst and return the destination file.
250
+
251
+ src and dst should have the same prefix. If dst specifies a directory,
252
+ the file will be copied into dst using the base filename from src. If
253
+ dst specifies a file that already exists, it will be replaced.
254
+
255
+ Args:
256
+ src (str or Path): A file to be copied.
257
+ dst (str or Path): Copy file to dst.
258
+
259
+ Returns:
260
+ str: The destination file.
261
+
262
+ Raises:
263
+ SameFileError: If src and dst are the same file, a SameFileError
264
+ will be raised.
265
+
266
+ Examples:
267
+ >>> backend = LocalBackend()
268
+ >>> # dst is a file
269
+ >>> src = '/path/of/file'
270
+ >>> dst = '/path1/of/file1'
271
+ >>> # src will be copied to '/path1/of/file1'
272
+ >>> backend.copyfile(src, dst)
273
+ '/path1/of/file1'
274
+
275
+ >>> # dst is a directory
276
+ >>> dst = '/path1/of/dir'
277
+ >>> # src will be copied to '/path1/of/dir/file'
278
+ >>> backend.copyfile(src, dst)
279
+ '/path1/of/dir/file'
280
+ """
281
+ return shutil.copy(src, dst)
282
+
283
+ def copytree(
284
+ self,
285
+ src: Union[str, Path],
286
+ dst: Union[str, Path],
287
+ ) -> str:
288
+ """Recursively copy an entire directory tree rooted at src to a
289
+ directory named dst and return the destination directory.
290
+
291
+ src and dst should have the same prefix and dst must not already exist.
292
+
293
+ TODO: Whether to support dirs_exist_ok parameter.
294
+
295
+ Args:
296
+ src (str or Path): A directory to be copied.
297
+ dst (str or Path): Copy directory to dst.
298
+
299
+ Returns:
300
+ str: The destination directory.
301
+
302
+ Raises:
303
+ FileExistsError: If dst had already existed, a FileExistsError will
304
+ be raised.
305
+
306
+ Examples:
307
+ >>> backend = LocalBackend()
308
+ >>> src = '/path/of/dir1'
309
+ >>> dst = '/path/of/dir2'
310
+ >>> backend.copytree(src, dst)
311
+ '/path/of/dir2'
312
+ """
313
+ return shutil.copytree(src, dst)
314
+
315
+ def copyfile_from_local(
316
+ self,
317
+ src: Union[str, Path],
318
+ dst: Union[str, Path],
319
+ ) -> str:
320
+ """Copy a local file src to dst and return the destination file. Same
321
+ as :meth:`copyfile`.
322
+
323
+ Args:
324
+ src (str or Path): A local file to be copied.
325
+ dst (str or Path): Copy file to dst.
326
+
327
+ Returns:
328
+ str: If dst specifies a directory, the file will be copied into dst
329
+ using the base filename from src.
330
+
331
+ Raises:
332
+ SameFileError: If src and dst are the same file, a SameFileError
333
+ will be raised.
334
+
335
+ Examples:
336
+ >>> backend = LocalBackend()
337
+ >>> # dst is a file
338
+ >>> src = '/path/of/file'
339
+ >>> dst = '/path1/of/file1'
340
+ >>> # src will be copied to '/path1/of/file1'
341
+ >>> backend.copyfile_from_local(src, dst)
342
+ '/path1/of/file1'
343
+
344
+ >>> # dst is a directory
345
+ >>> dst = '/path1/of/dir'
346
+ >>> # src will be copied to
347
+ >>> backend.copyfile_from_local(src, dst)
348
+ '/path1/of/dir/file'
349
+ """
350
+ return self.copyfile(src, dst)
351
+
352
+ def copytree_from_local(
353
+ self,
354
+ src: Union[str, Path],
355
+ dst: Union[str, Path],
356
+ ) -> str:
357
+ """Recursively copy an entire directory tree rooted at src to a
358
+ directory named dst and return the destination directory. Same as
359
+ :meth:`copytree`.
360
+
361
+ Args:
362
+ src (str or Path): A local directory to be copied.
363
+ dst (str or Path): Copy directory to dst.
364
+
365
+ Returns:
366
+ str: The destination directory.
367
+
368
+ Examples:
369
+ >>> backend = LocalBackend()
370
+ >>> src = '/path/of/dir1'
371
+ >>> dst = '/path/of/dir2'
372
+ >>> backend.copytree_from_local(src, dst)
373
+ '/path/of/dir2'
374
+ """
375
+ return self.copytree(src, dst)
376
+
377
+ def copyfile_to_local(
378
+ self,
379
+ src: Union[str, Path],
380
+ dst: Union[str, Path],
381
+ dst_type: Optional[str] = None,
382
+ ) -> str:
383
+ """Copy the file src to local dst and return the destination file. Same
384
+ as :meth:`copyfile`.
385
+
386
+ If dst specifies a directory, the file will be copied into dst using
387
+ the base filename from src. If dst specifies a file that already
388
+ exists, it will be replaced.
389
+
390
+ Args:
391
+ src (str or Path): A file to be copied.
392
+ dst (str or Path): Copy file to to local dst.
393
+
394
+ Returns:
395
+ str: If dst specifies a directory, the file will be copied into dst
396
+ using the base filename from src.
397
+
398
+ Examples:
399
+ >>> backend = LocalBackend()
400
+ >>> # dst is a file
401
+ >>> src = '/path/of/file'
402
+ >>> dst = '/path1/of/file1'
403
+ >>> # src will be copied to '/path1/of/file1'
404
+ >>> backend.copyfile_to_local(src, dst)
405
+ '/path1/of/file1'
406
+
407
+ >>> # dst is a directory
408
+ >>> dst = '/path1/of/dir'
409
+ >>> # src will be copied to
410
+ >>> backend.copyfile_to_local(src, dst)
411
+ '/path1/of/dir/file'
412
+ """
413
+ return self.copyfile(src, dst)
414
+
415
+ def copytree_to_local(
416
+ self,
417
+ src: Union[str, Path],
418
+ dst: Union[str, Path],
419
+ ) -> str:
420
+ """Recursively copy an entire directory tree rooted at src to a local
421
+ directory named dst and return the destination directory.
422
+
423
+ Args:
424
+ src (str or Path): A directory to be copied.
425
+ dst (str or Path): Copy directory to local dst.
426
+ backend_args (dict, optional): Arguments to instantiate the
427
+ prefix of uri corresponding backend. Defaults to None.
428
+
429
+ Returns:
430
+ str: The destination directory.
431
+
432
+ Examples:
433
+ >>> backend = LocalBackend()
434
+ >>> src = '/path/of/dir1'
435
+ >>> dst = '/path/of/dir2'
436
+ >>> backend.copytree_from_local(src, dst)
437
+ '/path/of/dir2'
438
+ """
439
+ return self.copytree(src, dst)
440
+
441
+ def remove(self, filepath: Union[str, Path]) -> None:
442
+ """Remove a file.
443
+
444
+ Args:
445
+ filepath (str or Path): Path to be removed.
446
+
447
+ Raises:
448
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
449
+ will be raised.
450
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
451
+ will be raised.
452
+
453
+ Examples:
454
+ >>> backend = LocalBackend()
455
+ >>> filepath = '/path/of/file'
456
+ >>> backend.remove(filepath)
457
+ """
458
+ if not self.exists(filepath):
459
+ raise FileNotFoundError(f"filepath {filepath} does not exist")
460
+
461
+ if self.isdir(filepath):
462
+ raise IsADirectoryError("filepath should be a file")
463
+
464
+ os.remove(filepath)
465
+
466
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
467
+ """Recursively delete a directory tree.
468
+
469
+ Args:
470
+ dir_path (str or Path): A directory to be removed.
471
+
472
+ Examples:
473
+ >>> dir_path = '/path/of/dir'
474
+ >>> backend.rmtree(dir_path)
475
+ """
476
+ shutil.rmtree(dir_path)
477
+
478
+ def copy_if_symlink_fails(
479
+ self,
480
+ src: Union[str, Path],
481
+ dst: Union[str, Path],
482
+ ) -> bool:
483
+ """Create a symbolic link pointing to src named dst.
484
+
485
+ If failed to create a symbolic link pointing to src, directly copy src
486
+ to dst instead.
487
+
488
+ Args:
489
+ src (str or Path): Create a symbolic link pointing to src.
490
+ dst (str or Path): Create a symbolic link named dst.
491
+
492
+ Returns:
493
+ bool: Return True if successfully create a symbolic link pointing
494
+ to src. Otherwise, return False.
495
+
496
+ Examples:
497
+ >>> backend = LocalBackend()
498
+ >>> src = '/path/of/file'
499
+ >>> dst = '/path1/of/file1'
500
+ >>> backend.copy_if_symlink_fails(src, dst)
501
+ True
502
+ >>> src = '/path/of/dir'
503
+ >>> dst = '/path1/of/dir1'
504
+ >>> backend.copy_if_symlink_fails(src, dst)
505
+ True
506
+ """
507
+ try:
508
+ os.symlink(src, dst)
509
+ return True
510
+ except Exception:
511
+ if self.isfile(src):
512
+ self.copyfile(src, dst)
513
+ else:
514
+ self.copytree(src, dst)
515
+ return False
516
+
517
+ def list_dir(self, dir_path: Union[str, Path]) -> Generator[str, None, None]:
518
+ """List all folders in a storage location with a given prefix.
519
+
520
+ Args:
521
+ dir_path (str | Path): Path of the directory.
522
+
523
+ Examples:
524
+ >>> backend = LocalBackend()
525
+ >>> dir_path = 'path/of/dir'
526
+ >>> list(backend.list_dir(dir_path))
527
+ ['subdir1/', 'subdir2/']
528
+ """
529
+ for entry in os.scandir(dir_path):
530
+ if entry.is_dir():
531
+ yield f"{entry.name}/"
532
+
533
+ def list_dir_or_file(
534
+ self,
535
+ dir_path: Union[str, Path],
536
+ list_dir: bool = True,
537
+ list_file: bool = True,
538
+ suffix: Optional[Union[str, tuple[str]]] = None,
539
+ recursive: bool = False,
540
+ ) -> Iterator[str]:
541
+ """Scan a directory to find the interested directories or files in
542
+ arbitrary order.
543
+
544
+ Note:
545
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
546
+
547
+ Args:
548
+ dir_path (str or Path): Path of the directory.
549
+ list_dir (bool): List the directories. Defaults to True.
550
+ list_file (bool): List the path of files. Defaults to True.
551
+ suffix (str or tuple[str], optional): File suffix that we are
552
+ interested in. Defaults to None.
553
+ recursive (bool): If set to True, recursively scan the directory.
554
+ Defaults to False.
555
+
556
+ Yields:
557
+ Iterable[str]: A relative path to ``dir_path``.
558
+
559
+ Examples:
560
+ >>> backend = LocalBackend()
561
+ >>> dir_path = '/path/of/dir'
562
+ >>> # list those files and directories in current directory
563
+ >>> for file_path in backend.list_dir_or_file(dir_path):
564
+ ... print(file_path)
565
+ >>> # only list files
566
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_dir=False):
567
+ ... print(file_path)
568
+ >>> # only list directories
569
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_file=False):
570
+ ... print(file_path)
571
+ >>> # only list files ending with specified suffixes
572
+ >>> for file_path in backend.list_dir_or_file(dir_path, suffix='.txt'):
573
+ ... print(file_path)
574
+ >>> # list all files and directory recursively
575
+ >>> for file_path in backend.list_dir_or_file(dir_path, recursive=True):
576
+ ... print(file_path)
577
+ """ # noqa: E501
578
+ if list_dir and suffix is not None:
579
+ raise TypeError("`suffix` should be None when `list_dir` is True")
580
+
581
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
582
+ raise TypeError("`suffix` must be a string or tuple of strings")
583
+
584
+ root = dir_path
585
+
586
+ def _list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive):
587
+ for entry in os.scandir(dir_path):
588
+ if not entry.name.startswith(".") and entry.is_file():
589
+ rel_path = osp.relpath(entry.path, root)
590
+ if (suffix is None or rel_path.endswith(suffix)) and list_file:
591
+ yield rel_path
592
+ elif osp.isdir(entry.path):
593
+ if list_dir:
594
+ rel_dir = osp.relpath(entry.path, root)
595
+ yield rel_dir
596
+ if recursive:
597
+ yield from _list_dir_or_file(entry.path, list_dir, list_file, suffix, recursive)
598
+
599
+ return _list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive)
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/msc_backend.py ADDED
@@ -0,0 +1,911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import copy
17
+ import io
18
+ import os
19
+ import re
20
+ import tempfile
21
+ from collections.abc import Generator, Iterator
22
+ from contextlib import contextmanager
23
+ from pathlib import Path
24
+ from shutil import SameFileError
25
+ from typing import Any, Optional, Union
26
+ from urllib.parse import urlparse
27
+
28
+ from multistorageclient import StorageClient, StorageClientConfig
29
+ from multistorageclient.types import Range
30
+
31
+ import cosmos_policy._src.imaginaire.utils.easy_io.backends.auto_auth as auto
32
+ from cosmos_policy._src.imaginaire.utils import log
33
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.base_backend import BaseStorageBackend, mkdir_or_exist
34
+
35
+ # {scheme}://
36
+ _URL_PREFIX_REGEX = r"[a-zA-Z0-9+.-]*:\/\/"
37
+
38
+
39
+ class MSCBackend(BaseStorageBackend):
40
+ """Multi-Storage Client (MSC) backend.
41
+
42
+ Uses MSC storage clients instead of MSC shortcuts.
43
+
44
+ URL file paths (e.g. 's3://path/of/file') are handled transparently. Using URL file paths
45
+ as input will return URL file path outputs when appropriate to match Boto3Backend behavior.
46
+
47
+ **If using URL file paths, the storage provider's base path option must be empty!**
48
+
49
+ Get/put concurrency can be set for certain providers in the MSC configuration file.
50
+
51
+ Examples:
52
+ >>> backend = MSCBackend()
53
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
54
+ >>> backend.get(filepath)
55
+ """
56
+
57
+ _storage_client: StorageClient
58
+ _path_mapping: dict[str, str]
59
+
60
+ def __init__(
61
+ self,
62
+ config_path: Optional[str] = "credentials/msc_config.yaml",
63
+ profile: Optional[str] = None,
64
+ s3_credential_path: Optional[str] = None,
65
+ path_mapping: Optional[dict[str, str]] = None,
66
+ ):
67
+ """Initialize a backend.
68
+
69
+ Args:
70
+ config_path (str, optional): MSC config path (e.g. ``credentials/msc_config.yaml``).
71
+ profile (str, optional): MSC profile from the MSC config to use.
72
+ Mutually exclusive with ``s3_credential_path``.
73
+ s3_credential_path (str, optional): Legacy Boto3 config path (e.g. ``credentials/s3_training.secret``).
74
+ Translated into an MSC profile that's merged with the MSC config at ``config_path`` with:
75
+
76
+ - The profile name set to ``s3_credential_path`` verbatim.
77
+ - The storage and credentials provider types determined by the file contents.
78
+
79
+ Mutually exclusive with ``profile``.
80
+ path_mapping (dict, optional): Path mapping dict from src path to dst path.
81
+ When ``path_mapping={'src': 'dst'}``, ``src`` in ``filepath`` will be replaced by ``dst``.
82
+ Doesn't apply to the local path in ``copy{file,tree}_{from,to}_local`` methods.
83
+ """
84
+ if all(_ is None for _ in (profile, s3_credential_path)) or all(
85
+ _ is not None for _ in (profile, s3_credential_path)
86
+ ):
87
+ raise ValueError("Must specify exactly one of profile or s3_credential_path")
88
+
89
+ msc_config_dict: dict[str, Any] = {}
90
+
91
+ # Use an existing MSC config file as the base MSC config.
92
+ if config_path is not None:
93
+ config_dict, _ = StorageClientConfig.read_msc_config(config_file_paths=[config_path])
94
+ if config_dict is None:
95
+ log.info(f"No MSC config at {config_path}, using empty base MSC config", rank0_only=False)
96
+ else:
97
+ msc_config_dict = config_dict
98
+
99
+ # Create an MSC profile from the legacy Boto3 config.
100
+ if s3_credential_path is not None:
101
+ with auto.open_auth(s3_credential_path, "r") as unloaded_legacy_boto3_config:
102
+ legacy_boto3_config = auto.json_load_auth(unloaded_legacy_boto3_config)
103
+ if len(legacy_boto3_config) > 0:
104
+ profile = s3_credential_path
105
+
106
+ # Merge with any existing profiles.
107
+ msc_config_dict["profiles"] = msc_config_dict.get("profiles", {})
108
+ # Merge with the existing profile, replacing `storage_provider` and `credentials_provider` completely.
109
+ msc_config_dict["profiles"][profile] = msc_config_dict["profiles"].get(profile, {})
110
+
111
+ storage_provider_type: str = "s3"
112
+ parsed_endpoint_url = urlparse(legacy_boto3_config["endpoint_url"])
113
+ # Handle regional SwiftStack endpoints.
114
+ if parsed_endpoint_url.hostname.endswith(".s8k.io"):
115
+ storage_provider_type = "s8k"
116
+ # Handle global and regional GCS endpoints.
117
+ elif parsed_endpoint_url.hostname.startswith("storage.") and parsed_endpoint_url.hostname.endswith(
118
+ ".googleapis.com"
119
+ ):
120
+ storage_provider_type = "gcs_s3"
121
+
122
+ msc_config_dict["profiles"][profile]["storage_provider"] = {
123
+ "type": storage_provider_type,
124
+ "options": {
125
+ "base_path": "",
126
+ "endpoint_url": legacy_boto3_config["endpoint_url"],
127
+ "region_name": legacy_boto3_config["region_name"],
128
+ },
129
+ }
130
+
131
+ if all(_ in legacy_boto3_config for _ in ("aws_access_key_id", "aws_secret_access_key")):
132
+ msc_config_dict["profiles"][profile]["credentials_provider"] = {
133
+ "type": "S3Credentials",
134
+ "options": {
135
+ "access_key": legacy_boto3_config["aws_access_key_id"],
136
+ "secret_key": legacy_boto3_config["aws_secret_access_key"],
137
+ },
138
+ }
139
+ else:
140
+ raise ValueError("Cannot create profile from empty legacy Boto3 config")
141
+
142
+ assert profile is not None, "Failed to resolve MSC profile"
143
+
144
+ # easy_io needs backend args to be JSON-serializable for backend instance cache keys.
145
+ #
146
+ # StorageClientConfig isn't, so we need to construct it here instead of receiving one.
147
+ self._storage_client = StorageClient(
148
+ config=StorageClientConfig.from_dict(config_dict=msc_config_dict, profile=profile)
149
+ )
150
+
151
+ assert isinstance(path_mapping, dict) or path_mapping is None
152
+ # Make a deep copy of the path mapping to prevent external mutation.
153
+ self._path_mapping = {} if path_mapping is None else copy.deepcopy(path_mapping)
154
+ for src, dst in self._path_mapping.items():
155
+ log.info(f"Path mapping: {src} -> {dst}", rank0_only=False)
156
+
157
+ def _translate_filepath(self, filepath: Union[str, Path], translate_url: bool = True) -> str:
158
+ """Translate a `filepath` to a string.
159
+
160
+ Paths are of the form 'path/to/file' (path form) or '{protocol}://path/to/file' (URL form).
161
+
162
+ Args:
163
+ filepath (str): File path to be translated.
164
+ translate_url (bool): Strip '{scheme}://' prefixes. Needed for paths passed directly to MSC storage clients.
165
+ """
166
+ assert isinstance(filepath, (str, Path))
167
+
168
+ # Change to a POSIX path string.
169
+ if isinstance(filepath, str):
170
+ # If the ``filepath`` is concatenated by ``os.path.join`` in a Windows
171
+ # environment, the ``filepath`` will be the format of 'prefix\file.txt'.
172
+ filepath = re.sub(r"\\+", "/", filepath)
173
+ elif isinstance(filepath, Path):
174
+ # These should only be filesystem paths (e.g. '/path/of/file').
175
+ # URL paths (e.g. ``Path('s3://profile/path/of/file')``) collapse '://' to ':/'.
176
+ filepath = filepath.as_posix()
177
+ else:
178
+ raise ValueError(f"Unhandled filepath type: {type(filepath)}")
179
+
180
+ # Remap path.
181
+ #
182
+ # If there's multiple matching srcs, use the longest src (i.e. the most specific).
183
+ longest_src: str = ""
184
+ for src in self._path_mapping.keys():
185
+ if filepath.startswith(src) and len(src) > len(longest_src):
186
+ longest_src = src
187
+ if len(longest_src) > 0:
188
+ filepath = filepath.replace(longest_src, self._path_mapping[longest_src], 1)
189
+
190
+ # Optionally strip URL prefix then return.
191
+ #
192
+ # Don't use urlparse in case filepath is an invalid URL.
193
+ return re.sub(rf"^{_URL_PREFIX_REGEX}", "", filepath) if translate_url else filepath
194
+
195
+ def size(self, filepath: Union[str, Path]) -> int:
196
+ """Get the file size in bytes for a given ``filepath``.
197
+
198
+ Args:
199
+ filepath (str or Path): Path to get file size in bytes.
200
+
201
+ Returns:
202
+ int: File size in bytes for filepath.
203
+
204
+ Examples:
205
+ >>> backend = MSCBackend()
206
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
207
+ >>> backend.size(filepath) # file containing "hello world"
208
+ 11
209
+ """
210
+ path = self._translate_filepath(filepath=filepath)
211
+ return self._storage_client.info(path=path, strict=False).content_length
212
+
213
+ def get(self, filepath: Union[str, Path], offset: Optional[int] = None, size: Optional[int] = None) -> bytes:
214
+ """Read bytes from a given ``filepath`` with 'rb' mode in range [offset, offset + size).
215
+
216
+ Args:
217
+ filepath (str or Path): Path to read data.
218
+ offset (int, optional): Read offset in bytes (0-index). Defaults to 0.
219
+ size (int, optional): Read size in bytes. Defaults to the file size.
220
+
221
+ Returns:
222
+ bytes: Return bytes read from filepath.
223
+
224
+ Examples:
225
+ >>> backend = MSCBackend()
226
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
227
+ >>> backend.get(filepath)
228
+ b'hello world'
229
+ """
230
+ path = self._translate_filepath(filepath=filepath)
231
+ byte_range: Optional[Range] = None
232
+ if offset is not None or size is not None:
233
+ read_offset = offset or 0
234
+ assert read_offset >= 0, "Read offset must be ≥ 0"
235
+
236
+ # Try not to incur a remote call to get the file size. This can heavily slow down ranged reads.
237
+ #
238
+ # This means we won't always validate the read offset or read size against the file size.
239
+ read_size = size or (self.size(filepath=filepath) - read_offset)
240
+ assert read_size >= 1, "Read size must be ≥ 1 or read offset must be < file size"
241
+
242
+ byte_range = Range(offset=read_offset, size=read_size)
243
+
244
+ if byte_range is None:
245
+ buffer = io.BytesIO()
246
+ # `StorageClient.read()` defers to `StorageProvider.get_object()` while
247
+ # `StorageClient.download_file()` defers to `StorageProvider.download_file()`.
248
+ #
249
+ # Currently, only `StorageProvider.download_file()` supports parallel downloads
250
+ # in some storage providers (e.g. boto S3 transfer manager for S3 storage providers)
251
+ # so it's often much faster.
252
+ self._storage_client.download_file(remote_path=path, local_path=buffer)
253
+ buffer.seek(0)
254
+ return buffer.read()
255
+ else:
256
+ return self._storage_client.read(path=path, byte_range=byte_range)
257
+
258
+ def get_text(
259
+ self,
260
+ filepath: Union[str, Path],
261
+ encoding: str = "utf-8",
262
+ ) -> str:
263
+ """Read text from a given ``filepath`` with 'r' mode.
264
+
265
+ Args:
266
+ filepath (str or Path): Path to read data.
267
+ encoding (str): The encoding format used to open the ``filepath``.
268
+ Defaults to 'utf-8'.
269
+
270
+ Returns:
271
+ str: Expected text reading from ``filepath``.
272
+
273
+ Examples:
274
+ >>> backend = MSCBackend()
275
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
276
+ >>> backend.get_text(filepath)
277
+ 'hello world'
278
+ """
279
+ return str(self.get(filepath=filepath), encoding=encoding)
280
+
281
+ def put(self, obj: Union[bytes, io.BytesIO], filepath: Union[str, Path]) -> None:
282
+ """Write bytes to a given ``filepath``.
283
+
284
+ Args:
285
+ obj (bytes): Data to be saved.
286
+ filepath (str or Path): Path to write data.
287
+
288
+ Examples:
289
+ >>> backend = MSCBackend()
290
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
291
+ >>> backend.put(b"hello world", filepath)
292
+ """
293
+ path = self._translate_filepath(filepath=filepath)
294
+ buffer = io.BytesIO()
295
+ if isinstance(obj, bytes):
296
+ buffer.write(obj)
297
+ buffer.seek(0)
298
+ elif isinstance(obj, io.BytesIO):
299
+ buffer = obj
300
+ else:
301
+ raise ValueError(f"Unhandled obj type: {type(obj)}")
302
+ # `StorageClient.write()` defers to `StorageProvider.put_object()` while
303
+ # `StorageClient.upload_file()` defers to `StorageProvider.upload_file()`.
304
+ #
305
+ # Currently, only `StorageProvider.upload_file()` supports parallel uploads
306
+ # in some storage providers (e.g. boto S3 transfer manager for S3 storage providers)
307
+ # so it's often much faster.
308
+ self._storage_client.upload_file(remote_path=path, local_path=buffer)
309
+
310
+ def put_text(
311
+ self,
312
+ obj: str,
313
+ filepath: Union[str, Path],
314
+ encoding: str = "utf-8",
315
+ ) -> None:
316
+ """Write text to a given ``filepath``.
317
+
318
+ Args:
319
+ obj (str): Data to be written.
320
+ filepath (str or Path): Path to write data.
321
+ encoding (str): The encoding format used to encode the ``obj``.
322
+ Defaults to 'utf-8'.
323
+
324
+ Examples:
325
+ >>> backend = MSCBackend()
326
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
327
+ >>> backend.put_text("hello world", filepath)
328
+ """
329
+ self.put(obj=bytes(obj, encoding=encoding), filepath=filepath)
330
+
331
+ def exists(self, filepath: Union[str, Path]) -> bool:
332
+ """Check whether a file path exists.
333
+
334
+ Args:
335
+ filepath (str or Path): Path to be checked whether exists.
336
+
337
+ Returns:
338
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
339
+
340
+ Examples:
341
+ >>> backend = MSCBackend()
342
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
343
+ >>> backend.exists(filepath)
344
+ True
345
+ """
346
+ path = self._translate_filepath(filepath=filepath)
347
+ try:
348
+ # Include directories and files.
349
+ self._storage_client.info(path=path, strict=True)
350
+ return True
351
+ except FileNotFoundError:
352
+ return False
353
+
354
+ def isdir(self, filepath: Union[str, Path]) -> bool:
355
+ """Check whether a file path is a directory.
356
+
357
+ Args:
358
+ filepath (str or Path): Path to be checked whether it is a
359
+ directory.
360
+
361
+ Returns:
362
+ bool: Return ``True`` if ``filepath`` points to a directory,
363
+ ``False`` otherwise.
364
+
365
+ Examples:
366
+ >>> backend = MSCBackend()
367
+ >>> filepath = "path/of/dir" # or "s3://path/of/file"
368
+ >>> backend.isdir(filepath)
369
+ True
370
+ """
371
+ path = self._translate_filepath(filepath=filepath)
372
+ try:
373
+ # Include directories and files.
374
+ metadata = self._storage_client.info(path=path, strict=True)
375
+ return metadata.type == "directory"
376
+ except FileNotFoundError:
377
+ return False
378
+
379
+ def isfile(self, filepath: Union[str, Path]) -> bool:
380
+ """Check whether a file path is a file.
381
+
382
+ Args:
383
+ filepath (str or Path): Path to be checked whether it is a file.
384
+
385
+ Returns:
386
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
387
+ otherwise.
388
+
389
+ Examples:
390
+ >>> backend = MSCBackend()
391
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
392
+ >>> backend.isfile(filepath)
393
+ True
394
+ """
395
+ path = self._translate_filepath(filepath=filepath)
396
+ try:
397
+ return self._storage_client.is_file(path=path)
398
+ except FileNotFoundError:
399
+ return False
400
+
401
+ def join_path(
402
+ self,
403
+ filepath: Union[str, Path],
404
+ *filepaths: Union[str, Path],
405
+ ) -> str:
406
+ r"""Concatenate all file paths.
407
+
408
+ Join one or more filepath components intelligently. The return value
409
+ is the concatenation of filepath and any members of \*filepaths.
410
+
411
+ Args:
412
+ filepath (str or Path): Path to be concatenated.
413
+
414
+ Returns:
415
+ str: The result after concatenation.
416
+
417
+ Examples:
418
+ >>> backend = MSCBackend()
419
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
420
+ >>> backend.join_path(filepath, "another/path")
421
+ 'path/of/file/another/path' # or "s3://path/of/file/another/path"
422
+ >>> backend.join_path(filepath, "/another/path")
423
+ 'path/of/file/another/path' # or "s3://path/of/file/another/path"
424
+ """
425
+ filepath = self._translate_filepath(filepath=filepath, translate_url=False)
426
+ if filepath.endswith("/") and not filepath.endswith("://"):
427
+ filepath = filepath[:-1]
428
+ formatted_paths = [filepath]
429
+ for path in filepaths:
430
+ formatted_path = self._translate_filepath(filepath=path)
431
+ formatted_paths.append(formatted_path.lstrip("/"))
432
+
433
+ return "/".join(formatted_paths)
434
+
435
+ @contextmanager
436
+ def get_local_path(
437
+ self,
438
+ filepath: Union[str, Path],
439
+ ) -> Generator[Union[str, Path], None, None]:
440
+ """Download a file from ``filepath`` to a local temporary directory,
441
+ and return the temporary path.
442
+
443
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
444
+ can be called with ``with`` statement, and when exists from the
445
+ ``with`` statement, the temporary path will be released.
446
+
447
+ Args:
448
+ filepath (str or Path): Download a file from ``filepath``.
449
+
450
+ Yields:
451
+ Iterable[str]: Only yield one temporary path.
452
+
453
+ Examples:
454
+ >>> backend = MSCBackend()
455
+ >>> # After existing from the ``with`` clause,
456
+ >>> # the path will be removed
457
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
458
+ >>> with backend.get_local_path(filepath) as path:
459
+ ... # do something here
460
+ """
461
+ assert self.isfile(filepath=filepath)
462
+ try:
463
+ f = tempfile.NamedTemporaryFile(delete=False)
464
+ f.write(self.get(filepath=filepath))
465
+ f.close()
466
+ yield f.name
467
+ finally:
468
+ os.remove(f.name)
469
+
470
+ def copyfile(
471
+ self,
472
+ src: Union[str, Path],
473
+ dst: Union[str, Path],
474
+ ) -> str:
475
+ """Copy a file src to dst and return the destination file.
476
+
477
+ If dst specifies a file that already exists, it will be replaced.
478
+
479
+ Args:
480
+ src (str or Path): A file to be copied.
481
+ dst (str or Path): Copy file to dst.
482
+
483
+ Returns:
484
+ str: The destination file.
485
+
486
+ Raises:
487
+ SameFileError: If src and dst are the same file, a SameFileError
488
+ will be raised.
489
+
490
+ Examples:
491
+ >>> backend = MSCBackend()
492
+ >>> # dst is a file
493
+ >>> src = "path/of/file" # or "s3://path/of/file"
494
+ >>> dst = "path/of/file1" # or "s3://path/of/file1"
495
+ >>> backend.copyfile(src, dst)
496
+ 'path/of/file1' # or "s3://path/of/file1"
497
+
498
+ >>> # dst is a directory
499
+ >>> dst = "path/of/dir" # or "s3://path/of/dir"
500
+ >>> backend.copyfile(src, dst)
501
+ 'path/of/dir/file' # or "s3://path/of/dir/file"
502
+ """
503
+ if not self.isfile(filepath=src):
504
+ raise FileNotFoundError("src does not exist or is not a file")
505
+ if self.isdir(filepath=dst):
506
+ dst = self.join_path(dst, self._translate_filepath(filepath=src).split("/")[-1])
507
+ if self._translate_filepath(filepath=src) == self._translate_filepath(filepath=dst):
508
+ raise SameFileError("src and dst should not be same")
509
+
510
+ self.put(obj=self.get(filepath=src), filepath=dst)
511
+
512
+ return self._translate_filepath(filepath=dst, translate_url=False)
513
+
514
+ def copytree(
515
+ self,
516
+ src: Union[str, Path],
517
+ dst: Union[str, Path],
518
+ ) -> str:
519
+ """Recursively copy an entire directory tree rooted at src to a
520
+ directory named dst and return the destination directory.
521
+
522
+ Args:
523
+ src (str or Path): A directory to be copied.
524
+ dst (str or Path): Copy directory to dst.
525
+
526
+ Returns:
527
+ str: The destination directory.
528
+
529
+ Raises:
530
+ FileExistsError: If dst had already existed, a FileExistsError will
531
+ be raised.
532
+
533
+ Examples:
534
+ >>> backend = MSCBackend()
535
+ >>> src = "path/of/dir" # or "s3://path/of/dir"
536
+ >>> dst = "path/of/dir1" # or "s3://path/of/dir1"
537
+ >>> backend.copytree(src, dst)
538
+ 'path/of/dir1' # or "s3://path/of/dir1"
539
+ """
540
+ if not self.isdir(filepath=src):
541
+ raise FileNotFoundError("src does not exist or is not a directory")
542
+ if self.exists(filepath=dst):
543
+ raise FileExistsError("dst should not exist")
544
+
545
+ for path in self.list_dir_or_file(src, list_dir=False, recursive=True):
546
+ src_path = self.join_path(src, path)
547
+ dst_path = self.join_path(dst, path)
548
+ self.put(obj=self.get(filepath=src_path), filepath=dst_path)
549
+
550
+ return self._translate_filepath(filepath=dst, translate_url=False)
551
+
552
+ def copyfile_from_local(
553
+ self,
554
+ src: Union[str, Path],
555
+ dst: Union[str, Path],
556
+ ) -> str:
557
+ """Upload a local file src to dst and return the destination file.
558
+
559
+ Args:
560
+ src (str or Path): A local file to be copied.
561
+ dst (str or Path): Copy file to dst.
562
+
563
+ Returns:
564
+ str: If dst specifies a directory, the file will be copied into dst
565
+ using the base filename from src.
566
+
567
+ Examples:
568
+ >>> backend = MSCBackend()
569
+ >>> # dst is a file
570
+ >>> src = "path/of/your/file"
571
+ >>> dst = "path/of/file1" # or "s3://path/of/file1"
572
+ >>> backend.copyfile_from_local(src, dst)
573
+ 'path/of/file1' # or "s3://path/of/file1"
574
+
575
+ >>> # dst is a directory
576
+ >>> dst = "path/of/dir"
577
+ >>> backend.copyfile_from_local(src, dst)
578
+ 'path/of/dir/file' # or "s3://path/of/dir/file"
579
+ """
580
+ if self.isdir(filepath=dst):
581
+ dst = self.join_path(dst, os.path.basename(src))
582
+
583
+ with open(src, "rb") as f:
584
+ self.put(obj=f.read(), filepath=dst)
585
+
586
+ return self._translate_filepath(filepath=dst, translate_url=False)
587
+
588
+ def copytree_from_local(
589
+ self,
590
+ src: Union[str, Path],
591
+ dst: Union[str, Path],
592
+ ) -> str:
593
+ """Recursively copy an entire directory tree rooted at src to a
594
+ directory named dst and return the destination directory.
595
+
596
+ Args:
597
+ src (str or Path): A local directory to be copied.
598
+ dst (str or Path): Copy directory to dst.
599
+
600
+ Returns:
601
+ str: The destination directory.
602
+
603
+ Raises:
604
+ FileExistsError: If dst had already existed, a FileExistsError will
605
+ be raised.
606
+
607
+ Examples:
608
+ >>> backend = MSCBackend()
609
+ >>> src = "path/of/your/dir"
610
+ >>> dst = "path/of/dir1" # or "s3://path/of/dir1"
611
+ >>> backend.copytree_from_local(src, dst)
612
+ 'path/of/dir1' # or "s3://path/of/dir1"
613
+ """
614
+ if self.exists(filepath=dst):
615
+ raise FileExistsError("dst should not exist")
616
+
617
+ src = str(src)
618
+
619
+ for cur_dir, _, files in os.walk(src):
620
+ for f in files:
621
+ src_path = os.path.join(cur_dir, f)
622
+ dst_path = self.join_path(dst, src_path.replace(src, ""))
623
+ self.copyfile_from_local(src=src_path, dst=dst_path)
624
+
625
+ return self._translate_filepath(filepath=dst, translate_url=False)
626
+
627
+ def copyfile_to_local(
628
+ self,
629
+ src: Union[str, Path],
630
+ dst: Union[str, Path],
631
+ dst_type: str, # Choose from ["file", "dir"]
632
+ ) -> Union[str, Path]:
633
+ """Copy the file src to local dst and return the destination file.
634
+
635
+ If dst specifies a directory, the file will be copied into dst using
636
+ the base filename from src. If dst specifies a file that already
637
+ exists, it will be replaced.
638
+
639
+ Args:
640
+ src (str or Path): A file to be copied.
641
+ dst (str or Path): Copy file to to local dst.
642
+
643
+ Returns:
644
+ str: If dst specifies a directory, the file will be copied into dst
645
+ using the base filename from src.
646
+
647
+ Examples:
648
+ >>> backend = MSCBackend()
649
+ >>> # dst is a file
650
+ >>> src = "path/of/file" # or "s3://path/of/file"
651
+ >>> dst = "path/of/your/file"
652
+ >>> backend.copyfile_to_local(src, dst)
653
+ 'path/of/your/file'
654
+
655
+ >>> # dst is a directory
656
+ >>> dst = "path/of/your/dir"
657
+ >>> backend.copyfile_to_local(src, dst)
658
+ 'path/of/your/dir/file'
659
+ """
660
+ assert dst_type in ["file", "dir"]
661
+ # There is no good way to detect whether dst is a directory or a file, so we make dst_type required
662
+ if dst_type == "dir":
663
+ basename = os.path.basename(self._translate_filepath(filepath=src))
664
+ if isinstance(dst, str):
665
+ dst = os.path.join(dst, basename)
666
+ else:
667
+ assert isinstance(dst, Path)
668
+ dst = dst / basename
669
+
670
+ # Create parent directory if it doesn't exist
671
+ parent_dir = os.path.dirname(dst)
672
+ os.makedirs(parent_dir, exist_ok=True)
673
+
674
+ try:
675
+ with open(dst, "wb") as f:
676
+ data = self.get(filepath=src)
677
+ f.write(data)
678
+ except Exception as e:
679
+ log.error(f"Failed to write file: {e}")
680
+ raise
681
+
682
+ return dst
683
+
684
+ def copytree_to_local(
685
+ self,
686
+ src: Union[str, Path],
687
+ dst: Union[str, Path],
688
+ ) -> Union[str, Path]:
689
+ """Recursively copy an entire directory tree rooted at src to a local
690
+ directory named dst and return the destination directory.
691
+
692
+ Args:
693
+ src (str or Path): A directory to be copied.
694
+ dst (str or Path): Copy directory to local dst.
695
+
696
+ Returns:
697
+ str: The destination directory.
698
+
699
+ Examples:
700
+ >>> backend = MSCBackend()
701
+ >>> src = "path/of/dir" # or "s3://path/of/dir"
702
+ >>> dst = "path/of/your/dir"
703
+ >>> backend.copytree_to_local(src, dst)
704
+ 'path/of/your/dir'
705
+ """
706
+ for path in self.list_dir_or_file(dir_path=src, list_dir=False, recursive=True):
707
+ dst_path = os.path.join(dst, path)
708
+ mkdir_or_exist(os.path.dirname(dst_path))
709
+ with open(dst_path, "wb") as f:
710
+ f.write(self.get(filepath=self.join_path(src, path)))
711
+
712
+ return dst
713
+
714
+ def remove(self, filepath: Union[str, Path]) -> None:
715
+ """Remove a file.
716
+
717
+ Args:
718
+ filepath (str or Path): Path to be removed.
719
+
720
+ Raises:
721
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
722
+ will be raised.
723
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
724
+ will be raised.
725
+
726
+ Examples:
727
+ >>> backend = MSCBackend()
728
+ >>> filepath = "path/of/file" # or "s3://path/of/file"
729
+ >>> backend.remove(filepath)
730
+ """
731
+ if not self.exists(filepath=filepath):
732
+ raise FileNotFoundError(f"filepath {filepath} does not exist")
733
+
734
+ if self.isdir(filepath=filepath):
735
+ raise IsADirectoryError("filepath should be a file")
736
+
737
+ self._storage_client.delete(path=self._translate_filepath(filepath=filepath), recursive=False)
738
+
739
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
740
+ """Recursively delete a directory tree.
741
+
742
+ Args:
743
+ dir_path (str or Path): A directory to be removed.
744
+
745
+ Examples:
746
+ >>> backend = MSCBackend()
747
+ >>> dir_path = "path/of/dir" # or "s3://path/of/dir"
748
+ >>> backend.rmtree(dir_path)
749
+ """
750
+ self._storage_client.delete(path=self._translate_filepath(filepath=dir_path), recursive=True)
751
+
752
+ def copy_if_symlink_fails(
753
+ self,
754
+ src: Union[str, Path],
755
+ dst: Union[str, Path],
756
+ ) -> bool:
757
+ """Create a symbolic link pointing to src named dst.
758
+
759
+ Directly copy src to dst because MSCBackend does not support creating
760
+ a symbolic link.
761
+
762
+ Args:
763
+ src (str or Path): A file or directory to be copied.
764
+ dst (str or Path): Copy a file or directory to dst.
765
+
766
+ Returns:
767
+ bool: Return False because MSCBackend does not support create
768
+ a symbolic link.
769
+
770
+ Examples:
771
+ >>> backend = MSCBackend()
772
+ >>> src = "path/of/file" # or "s3://path/of/file"
773
+ >>> dst = "path/of/your/file" # or "s3://path/of/your/file"
774
+ >>> backend.copy_if_symlink_fails(src, dst)
775
+ False
776
+ >>> src = "path/of/dir" # or "s3://path/of/dir"
777
+ >>> dst = "path/of/your/dir" # or "s3://path/of/your/dir"
778
+ >>> backend.copy_if_symlink_fails(src, dst)
779
+ False
780
+ """
781
+ if self.isfile(filepath=src):
782
+ self.copyfile(src=src, dst=dst)
783
+ else:
784
+ self.copytree(src=src, dst=dst)
785
+ return False
786
+
787
+ def list_dir(self, dir_path: Union[str, Path]) -> Generator[str, None, None]:
788
+ """List all folders in a storage location with a given prefix.
789
+
790
+ Args:
791
+ dir_path (str | Path): Path of the directory.
792
+
793
+ Examples:
794
+ >>> backend = MSCBackend()
795
+ >>> dir_path = "path/of/dir" # or "s3://path/of/dir"
796
+ >>> list(backend.list_dir(dir_path))
797
+ ["subdir1/", "subdir2/"]
798
+ """
799
+ path = self._translate_filepath(filepath=dir_path).removesuffix("/") + "/"
800
+ for metadata in self._storage_client.list(path=path, include_directories=True, include_url_prefix=False):
801
+ if metadata.type == "directory":
802
+ yield metadata.key.removeprefix(path).removesuffix("/") + "/"
803
+
804
+ def list_dir_or_file( # pylint: disable=too-many-arguments
805
+ self,
806
+ dir_path: Union[str, Path],
807
+ list_dir: bool = True,
808
+ list_file: bool = True,
809
+ suffix: Optional[Union[str, tuple[str]]] = None,
810
+ recursive: bool = False,
811
+ ) -> Iterator[str]:
812
+ """Scan a directory to find the interested directories or files in
813
+ arbitrary order.
814
+
815
+ Note:
816
+ Most object stores have no concept of directories but it simulates
817
+ the directory hierarchy in the filesystem through public prefixes.
818
+ In addition, if the returned path ends with '/', it means the path
819
+ is a public prefix which is a logical directory.
820
+
821
+ Note:
822
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
823
+ In addition, the returned path of directory will not contains the
824
+ suffix '/' which is consistent with other backends.
825
+
826
+ Args:
827
+ dir_path (str | Path): Path of the directory.
828
+ list_dir (bool): List the directories. Defaults to True.
829
+ list_file (bool): List the path of files. Defaults to True.
830
+ suffix (str or tuple[str], optional): File suffix
831
+ that we are interested in. Defaults to None.
832
+ recursive (bool): If set to True, recursively scan the
833
+ directory. Defaults to False.
834
+
835
+ Yields:
836
+ Iterable[str]: A relative path to ``dir_path``.
837
+
838
+ Examples:
839
+ >>> backend = MSCBackend()
840
+ >>> dir_path = "path/of/dir" # or "s3://path/of/dir"
841
+ >>> # list those files and directories in current directory
842
+ >>> list(backend.list_dir_or_file(dir_path))
843
+ ["file.txt", "subdir", "subdir/cat.png", "subdir/subsubdir/dog.jpg"]
844
+ >>> # only list files
845
+ >>> list(backend.list_dir_or_file(dir_path, list_dir=False))
846
+ ["file.txt", "subdir/cat.png", "subdir/subsubdir/dog.jpg"]
847
+ >>> # only list directories
848
+ >>> list(backend.list_dir_or_file(dir_path, list_file=False))
849
+ ["subdir"]
850
+ >>> # only list files ending with specified suffixes
851
+ >>> list(backend.list_dir_or_file(dir_path, suffix=".txt"))
852
+ ["file.txt"]
853
+ >>> # list all files and directory recursively
854
+ >>> list(backend.list_dir_or_file(dir_path, recursive=True))
855
+ ["file.txt", "subdir", "subdir/cat.png", "subdir/subsubdir", "subdir/subsubdir/dog.png"]
856
+ """
857
+ dir_path = self._translate_filepath(filepath=dir_path).removesuffix("/") + "/"
858
+
859
+ if list_dir and suffix is not None:
860
+ raise TypeError("`list_dir` should be False when `suffix` is not None")
861
+
862
+ if list_dir and not list_file and not recursive:
863
+ raise TypeError(
864
+ "Please use `list_dir` instead of `list_dir_or_file` "
865
+ "when you only want to list the first level directories."
866
+ )
867
+
868
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
869
+ raise TypeError("`suffix` must be a string or tuple of strings")
870
+
871
+ yielded_subdir_paths: set[str] = set()
872
+ # In the MSC, the `include_directories` option switches between flat and hierarchical for both files and "directories".
873
+ #
874
+ # In the Boto3Backend, however, the `recursive` option only applies to "directories" (seems like a bug).
875
+ #
876
+ # Construct directories from file paths to match the Boto3Backend behavior.
877
+ #
878
+ # If this behavior needs to be fixed, switch to `include_directories=(not recursive)` and adjust metadata processing.
879
+ for metadata in self._storage_client.list(path=dir_path, include_directories=False, include_url_prefix=False):
880
+ # Only files should be returned with `include_directories=False`, but just in case.
881
+ if metadata.type == "file":
882
+ rel_path: str = metadata.key.removeprefix(dir_path)
883
+ if list_dir:
884
+ rel_path_fragments = rel_path.split("/")
885
+ if len(rel_path_fragments) > 1:
886
+ for i in range(len(rel_path_fragments) - 1 if recursive else 1):
887
+ subdir_path = "/".join(rel_path_fragments[: i + 1])
888
+ if subdir_path not in yielded_subdir_paths:
889
+ yielded_subdir_paths.add(subdir_path)
890
+ yield subdir_path
891
+ if list_file:
892
+ if suffix is None or rel_path.endswith(suffix):
893
+ yield rel_path
894
+
895
+ def generate_presigned_url(self, url: str, client_method: str = "get_object", expires_in: int = 3600) -> str:
896
+ """Generate the presigned url of video stream which can be passed to
897
+ mmcv.VideoReader. Now only work on Boto3 backend.
898
+
899
+ Note:
900
+ Now only work on Boto3 backend.
901
+
902
+ Args:
903
+ url (str): Url of video stream.
904
+ client_method (str): Method of client, 'get_object' or
905
+ 'put_object'. Default: 'get_object'.
906
+ expires_in (int): expires, in seconds. Default: 3600.
907
+
908
+ Returns:
909
+ str: Generated presigned url.
910
+ """
911
+ raise NotImplementedError("generate_presigned_url is not supported in MSCBackend")
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/backends/registry_utils.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ from typing import Optional, Type, Union
18
+
19
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.base_backend import BaseStorageBackend
20
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.http_backend import HTTPBackend
21
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.local_backend import LocalBackend
22
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends.msc_backend import MSCBackend
23
+
24
+ backends: dict = {}
25
+ prefix_to_backends: dict = {}
26
+
27
+
28
+ def _register_backend(
29
+ name: str,
30
+ backend: Type[BaseStorageBackend],
31
+ force: bool = False,
32
+ prefixes: Union[str, list, tuple, None] = None,
33
+ ):
34
+ """Register a backend.
35
+
36
+ Args:
37
+ name (str): The name of the registered backend.
38
+ backend (BaseStorageBackend): The backend class to be registered,
39
+ which must be a subclass of :class:`BaseStorageBackend`.
40
+ force (bool): Whether to override the backend if the name has already
41
+ been registered. Defaults to False.
42
+ prefixes (str or list[str] or tuple[str], optional): The prefix
43
+ of the registered storage backend. Defaults to None.
44
+ """
45
+ global backends, prefix_to_backends
46
+
47
+ if not isinstance(name, str):
48
+ raise TypeError(f"the backend name should be a string, but got {type(name)}")
49
+
50
+ if not inspect.isclass(backend):
51
+ raise TypeError(f"backend should be a class, but got {type(backend)}")
52
+ if not issubclass(backend, BaseStorageBackend):
53
+ raise TypeError(f"backend {backend} is not a subclass of BaseStorageBackend")
54
+
55
+ if name in backends and not force:
56
+ raise ValueError(
57
+ f'{name} is already registered as a storage backend, add "force=True" if you want to override it'
58
+ )
59
+ backends[name] = backend
60
+
61
+ if prefixes is not None:
62
+ if isinstance(prefixes, str):
63
+ prefixes = [prefixes]
64
+ else:
65
+ assert isinstance(prefixes, (list, tuple))
66
+
67
+ for prefix in prefixes:
68
+ if prefix in prefix_to_backends and not force:
69
+ raise ValueError(
70
+ f'{prefix} is already registered as a storage backend, add "force=True" if you want to override it'
71
+ )
72
+
73
+ prefix_to_backends[prefix] = backend
74
+
75
+
76
+ def register_backend(
77
+ name: str,
78
+ backend: Optional[Type[BaseStorageBackend]] = None,
79
+ force: bool = False,
80
+ prefixes: Union[str, list, tuple, None] = None,
81
+ ):
82
+ """Register a backend.
83
+
84
+ Args:
85
+ name (str): The name of the registered backend.
86
+ backend (class, optional): The backend class to be registered,
87
+ which must be a subclass of :class:`BaseStorageBackend`.
88
+ When this method is used as a decorator, backend is None.
89
+ Defaults to None.
90
+ force (bool): Whether to override the backend if the name has already
91
+ been registered. Defaults to False.
92
+ prefixes (str or list[str] or tuple[str], optional): The prefix
93
+ of the registered storage backend. Defaults to None.
94
+
95
+ This method can be used as a normal method or a decorator.
96
+
97
+ Examples:
98
+
99
+ >>> class NewBackend(BaseStorageBackend):
100
+ ... def get(self, filepath):
101
+ ... return filepath
102
+ ...
103
+ ... def get_text(self, filepath):
104
+ ... return filepath
105
+ >>> register_backend('new', NewBackend)
106
+
107
+ >>> @register_backend('new')
108
+ ... class NewBackend(BaseStorageBackend):
109
+ ... def get(self, filepath):
110
+ ... return filepath
111
+ ...
112
+ ... def get_text(self, filepath):
113
+ ... return filepath
114
+ """
115
+ if backend is not None:
116
+ _register_backend(name, backend, force=force, prefixes=prefixes)
117
+ return
118
+
119
+ def _register(backend_cls):
120
+ _register_backend(name, backend_cls, force=force, prefixes=prefixes)
121
+ return backend_cls
122
+
123
+ return _register
124
+
125
+
126
+ register_backend("local", LocalBackend, prefixes="")
127
+ # To avoid breaking backward Compatibility, 's3' is also used as a
128
+ # prefix for MSCBackend
129
+ register_backend("s3", MSCBackend, prefixes=["s3"])
130
+ register_backend("http", HTTPBackend, prefixes=["http", "https"])
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/easy_io.py ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import warnings
18
+ from contextlib import contextmanager
19
+ from io import BytesIO, StringIO
20
+ from pathlib import Path
21
+ from typing import IO, Any, Generator, Iterator, Optional, Tuple, Union
22
+
23
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends import backends, prefix_to_backends
24
+ from cosmos_policy._src.imaginaire.utils.easy_io.file_client import FileClient
25
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers import file_handlers
26
+
27
+ backend_instances: dict = {}
28
+
29
+
30
+ def is_filepath(filepath):
31
+ return isinstance(filepath, (str, Path))
32
+
33
+
34
+ def _parse_uri_prefix(uri: Union[str, Path]) -> str:
35
+ """Parse the prefix of uri.
36
+
37
+ Args:
38
+ uri (str or Path): Uri to be parsed that contains the file prefix.
39
+
40
+ Examples:
41
+ >>> _parse_uri_prefix('/home/path/of/your/file')
42
+ ''
43
+ >>> _parse_uri_prefix('s3://path/of/your/file')
44
+ 's3'
45
+ >>> _parse_uri_prefix('clusterName:s3://path/of/your/file')
46
+ 's3'
47
+
48
+ Returns:
49
+ str: Return the prefix of uri if the uri contains '://'. Otherwise,
50
+ return ''.
51
+ """
52
+ assert is_filepath(uri)
53
+ uri = str(uri)
54
+ # if uri does not contains '://', the uri will be handled by
55
+ # LocalBackend by default
56
+ if "://" not in uri:
57
+ return ""
58
+ else:
59
+ prefix, _ = uri.split("://")
60
+ # In the case of Boto3Backend, the prefix may contain the cluster
61
+ # name like clusterName:s3://path/of/your/file
62
+ if ":" in prefix:
63
+ _, prefix = prefix.split(":")
64
+ return prefix
65
+
66
+
67
+ def _get_file_backend(prefix: str, backend_args: dict):
68
+ """Return a file backend based on the prefix or backend_args.
69
+
70
+ Args:
71
+ prefix (str): Prefix of uri.
72
+ backend_args (dict): Arguments to instantiate the corresponding
73
+ backend.
74
+ """
75
+ # backend name has a higher priority
76
+ if "backend" in backend_args:
77
+ # backend_args should not be modified
78
+ backend_args_bak = backend_args.copy()
79
+ backend_name = backend_args_bak.pop("backend")
80
+ backend = backends[backend_name](**backend_args_bak)
81
+ else:
82
+ backend = prefix_to_backends[prefix](**backend_args)
83
+ return backend
84
+
85
+
86
+ def set_s3_backend(
87
+ key: str = "s3:{}",
88
+ backend_args: Optional[dict] = None,
89
+ ):
90
+ """register s3 backend.
91
+
92
+ Args:
93
+ key str: The key to register the s3 backend. Defaults to s3.
94
+ backend_args (dict, optional): Arguments to instantiate the
95
+ corresponding backend. Defaults to None.
96
+ """
97
+ global backend_instances
98
+ if backend_args is None:
99
+ backend_args = {}
100
+ backend = _get_file_backend(key, backend_args)
101
+ backend_instances[key] = backend
102
+ return backend
103
+
104
+
105
+ def get_file_backend(
106
+ uri: Union[str, Path, None] = None,
107
+ *,
108
+ backend_args: Optional[dict] = None,
109
+ enable_singleton: bool = False,
110
+ backend_key: Optional[str] = None,
111
+ ):
112
+ """Return a file backend based on the prefix of uri or backend_args.
113
+
114
+ Args:
115
+ uri (str or Path): Uri to be parsed that contains the file prefix.
116
+ backend_args (dict, optional): Arguments to instantiate the
117
+ corresponding backend. Defaults to None.
118
+ enable_singleton (bool): Whether to enable the singleton pattern.
119
+ If it is True, the backend created will be reused if the
120
+ signature is same with the previous one. Defaults to False.
121
+ backend_key: str: The key to register the backend. Defaults to None.
122
+
123
+ Returns:
124
+ BaseStorageBackend: Instantiated Backend object.
125
+
126
+ Examples:
127
+ >>> # get file backend based on the prefix of uri
128
+ >>> uri = 's3://path/of/your/file'
129
+ >>> backend = get_file_backend(uri)
130
+ >>> # get file backend based on the backend_args
131
+ >>> backend = get_file_backend(backend_args={'backend': 's3'})
132
+ >>> # backend name has a higher priority if 'backend' in backend_args
133
+ >>> backend = get_file_backend(uri, backend_args={'backend': 's3'})
134
+ """
135
+ global backend_instances
136
+ if backend_key is not None:
137
+ if backend_key in backend_instances:
138
+ return backend_instances[backend_key]
139
+
140
+ if backend_args is None:
141
+ backend_args = {}
142
+
143
+ if uri is None and "backend" not in backend_args and backend_key is None:
144
+ raise ValueError('uri should not be None when "backend" does not exist in backend_args and backend_key is None')
145
+
146
+ if uri is not None:
147
+ prefix = _parse_uri_prefix(uri)
148
+ else:
149
+ prefix = ""
150
+
151
+ if enable_singleton:
152
+ unique_key = f"{prefix}:{json.dumps(backend_args)}"
153
+ if unique_key in backend_instances:
154
+ return backend_instances[unique_key]
155
+
156
+ backend = _get_file_backend(prefix, backend_args)
157
+ backend_instances[unique_key] = backend
158
+ if backend_key is not None:
159
+ backend_instances[backend_key] = backend
160
+ return backend
161
+ else:
162
+ backend = _get_file_backend(prefix, backend_args)
163
+ return backend
164
+
165
+
166
+ def size(
167
+ filepath: Union[str, Path],
168
+ backend_args: Optional[dict] = None,
169
+ backend_key: Optional[str] = None,
170
+ ) -> int:
171
+ """Get the file size in bytes for a given ``filepath``.
172
+
173
+ Args:
174
+ filepath (str or Path): Path to get file size in bytes.
175
+
176
+ Returns:
177
+ int: File size in bytes for filepath.
178
+
179
+ Examples:
180
+ >>> filepath = 'path/of/file'
181
+ >>> size(filepath) # file containing 'hello world'
182
+ 11
183
+ """
184
+ backend = get_file_backend(
185
+ filepath,
186
+ backend_args=backend_args,
187
+ enable_singleton=True,
188
+ backend_key=backend_key,
189
+ )
190
+ return backend.size(filepath)
191
+
192
+
193
+ def get(
194
+ filepath: Union[str, Path],
195
+ offset: Optional[int] = None,
196
+ size: Optional[int] = None,
197
+ backend_args: Optional[dict] = None,
198
+ backend_key: Optional[str] = None,
199
+ ) -> bytes:
200
+ """Read bytes from a given ``filepath`` with 'rb' mode in range [offset, offset + size).
201
+
202
+ Args:
203
+ filepath (str or Path): Path to read data.
204
+ offset (int, optional): Read offset in bytes (0-index). Defaults to 0.
205
+ size (int, optional): Read size in bytes. Defaults to the file size.
206
+ backend_args (dict, optional): Arguments to instantiate the
207
+ corresponding backend. Defaults to None.
208
+ backend_key (str, optional): The key to get the backend from register.
209
+
210
+ Returns:
211
+ bytes: Expected bytes object.
212
+
213
+ Examples:
214
+ >>> filepath = '/path/of/file'
215
+ >>> get(filepath)
216
+ b'hello world'
217
+ """
218
+ backend = get_file_backend(
219
+ filepath,
220
+ backend_args=backend_args,
221
+ enable_singleton=True,
222
+ backend_key=backend_key,
223
+ )
224
+ return backend.get(filepath, offset=offset, size=size)
225
+
226
+
227
+ def get_text(
228
+ filepath: Union[str, Path],
229
+ encoding="utf-8",
230
+ backend_args: Optional[dict] = None,
231
+ backend_key: Optional[str] = None,
232
+ ) -> str:
233
+ """Read text from a given ``filepath`` with 'r' mode.
234
+
235
+ Args:
236
+ filepath (str or Path): Path to read data.
237
+ encoding (str): The encoding format used to open the ``filepath``.
238
+ Defaults to 'utf-8'.
239
+ backend_args (dict, optional): Arguments to instantiate the
240
+ corresponding backend. Defaults to None.
241
+ backend_key (str, optional): The key to get the backend from register.
242
+
243
+ Returns:
244
+ str: Expected text reading from ``filepath``.
245
+
246
+ Examples:
247
+ >>> filepath = '/path/of/file'
248
+ >>> get_text(filepath)
249
+ 'hello world'
250
+ """
251
+ backend = get_file_backend(
252
+ filepath,
253
+ backend_args=backend_args,
254
+ enable_singleton=True,
255
+ backend_key=backend_key,
256
+ )
257
+ return backend.get_text(filepath, encoding)
258
+
259
+
260
+ def put(
261
+ obj: bytes,
262
+ filepath: Union[str, Path],
263
+ backend_args: Optional[dict] = None,
264
+ backend_key: Optional[str] = None,
265
+ ) -> None:
266
+ """Write bytes to a given ``filepath`` with 'wb' mode.
267
+
268
+ Note:
269
+ ``put`` should create a directory if the directory of
270
+ ``filepath`` does not exist.
271
+
272
+ Args:
273
+ obj (bytes): Data to be written.
274
+ filepath (str or Path): Path to write data.
275
+ backend_args (dict, optional): Arguments to instantiate the
276
+ corresponding backend. Defaults to None.
277
+ backend_key (str, optional): The key to get the backend from register.
278
+
279
+ Examples:
280
+ >>> filepath = '/path/of/file'
281
+ >>> put(b'hello world', filepath)
282
+ """
283
+ backend = get_file_backend(
284
+ filepath,
285
+ backend_args=backend_args,
286
+ enable_singleton=True,
287
+ backend_key=backend_key,
288
+ )
289
+ backend.put(obj, filepath)
290
+
291
+
292
+ def put_text(
293
+ obj: str,
294
+ filepath: Union[str, Path],
295
+ backend_args: Optional[dict] = None,
296
+ backend_key: Optional[str] = None,
297
+ ) -> None:
298
+ """Write text to a given ``filepath`` with 'w' mode.
299
+
300
+ Note:
301
+ ``put_text`` should create a directory if the directory of
302
+ ``filepath`` does not exist.
303
+
304
+ Args:
305
+ obj (str): Data to be written.
306
+ filepath (str or Path): Path to write data.
307
+ encoding (str, optional): The encoding format used to open the
308
+ ``filepath``. Defaults to 'utf-8'.
309
+ backend_args (dict, optional): Arguments to instantiate the
310
+ corresponding backend. Defaults to None.
311
+ backend_key (str, optional): The key to get the backend from register.
312
+
313
+ Examples:
314
+ >>> filepath = '/path/of/file'
315
+ >>> put_text('hello world', filepath)
316
+ """
317
+ backend = get_file_backend(
318
+ filepath,
319
+ backend_args=backend_args,
320
+ enable_singleton=True,
321
+ backend_key=backend_key,
322
+ )
323
+ backend.put_text(obj, filepath)
324
+
325
+
326
+ def exists(
327
+ filepath: Union[str, Path],
328
+ backend_args: Optional[dict] = None,
329
+ backend_key: Optional[str] = None,
330
+ ) -> bool:
331
+ """Check whether a file path exists.
332
+
333
+ Args:
334
+ filepath (str or Path): Path to be checked whether exists.
335
+ backend_args (dict, optional): Arguments to instantiate the
336
+ corresponding backend. Defaults to None.
337
+ backend_key (str, optional): The key to get the backend from register.
338
+
339
+ Returns:
340
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
341
+
342
+ Examples:
343
+ >>> filepath = '/path/of/file'
344
+ >>> exists(filepath)
345
+ True
346
+ """
347
+ backend = get_file_backend(
348
+ filepath,
349
+ backend_args=backend_args,
350
+ enable_singleton=True,
351
+ backend_key=backend_key,
352
+ )
353
+ return backend.exists(filepath)
354
+
355
+
356
+ def isdir(
357
+ filepath: Union[str, Path],
358
+ backend_args: Optional[dict] = None,
359
+ backend_key: Optional[str] = None,
360
+ ) -> bool:
361
+ """Check whether a file path is a directory.
362
+
363
+ Args:
364
+ filepath (str or Path): Path to be checked whether it is a
365
+ directory.
366
+ backend_args (dict, optional): Arguments to instantiate the
367
+ corresponding backend. Defaults to None.
368
+ backend_key (str, optional): The key to get the backend from register.
369
+
370
+ Returns:
371
+ bool: Return ``True`` if ``filepath`` points to a directory,
372
+ ``False`` otherwise.
373
+
374
+ Examples:
375
+ >>> filepath = '/path/of/dir'
376
+ >>> isdir(filepath)
377
+ True
378
+ """
379
+ backend = get_file_backend(
380
+ filepath,
381
+ backend_args=backend_args,
382
+ enable_singleton=True,
383
+ backend_key=backend_key,
384
+ )
385
+ return backend.isdir(filepath)
386
+
387
+
388
+ def isfile(
389
+ filepath: Union[str, Path],
390
+ backend_args: Optional[dict] = None,
391
+ backend_key: Optional[str] = None,
392
+ ) -> bool:
393
+ """Check whether a file path is a file.
394
+
395
+ Args:
396
+ filepath (str or Path): Path to be checked whether it is a file.
397
+ backend_args (dict, optional): Arguments to instantiate the
398
+ corresponding backend. Defaults to None.
399
+ backend_key (str, optional): The key to get the backend from register.
400
+
401
+ Returns:
402
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
403
+ otherwise.
404
+
405
+ Examples:
406
+ >>> filepath = '/path/of/file'
407
+ >>> isfile(filepath)
408
+ True
409
+ """
410
+ backend = get_file_backend(
411
+ filepath,
412
+ backend_args=backend_args,
413
+ enable_singleton=True,
414
+ backend_key=backend_key,
415
+ )
416
+ return backend.isfile(filepath)
417
+
418
+
419
+ def join_path(
420
+ filepath: Union[str, Path],
421
+ *filepaths: Union[str, Path],
422
+ backend_args: Optional[dict] = None,
423
+ backend_key: Optional[str] = None,
424
+ ) -> Union[str, Path]:
425
+ r"""Concatenate all file paths.
426
+
427
+ Join one or more filepath components intelligently. The return value
428
+ is the concatenation of filepath and any members of \*filepaths.
429
+
430
+ Args:
431
+ filepath (str or Path): Path to be concatenated.
432
+ *filepaths (str or Path): Other paths to be concatenated.
433
+ backend_args (dict, optional): Arguments to instantiate the
434
+ corresponding backend. Defaults to None.
435
+ backend_key (str, optional): The key to get the backend from register.
436
+
437
+ Returns:
438
+ str: The result of concatenation.
439
+
440
+ Examples:
441
+ >>> filepath1 = '/path/of/dir1'
442
+ >>> filepath2 = 'dir2'
443
+ >>> filepath3 = 'path/of/file'
444
+ >>> join_path(filepath1, filepath2, filepath3)
445
+ '/path/of/dir/dir2/path/of/file'
446
+ """
447
+ backend = get_file_backend(
448
+ filepath,
449
+ backend_args=backend_args,
450
+ enable_singleton=True,
451
+ backend_key=backend_key,
452
+ )
453
+ return backend.join_path(filepath, *filepaths)
454
+
455
+
456
+ @contextmanager
457
+ def get_local_path(
458
+ filepath: Union[str, Path],
459
+ backend_args: Optional[dict] = None,
460
+ backend_key: Optional[str] = None,
461
+ ) -> Generator[Union[str, Path], None, None]:
462
+ """Download data from ``filepath`` and write the data to local path.
463
+
464
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
465
+ can be called with ``with`` statement, and when exists from the
466
+ ``with`` statement, the temporary path will be released.
467
+
468
+ Note:
469
+ If the ``filepath`` is a local path, just return itself and it will
470
+ not be released (removed).
471
+
472
+ Args:
473
+ filepath (str or Path): Path to be read data.
474
+ backend_args (dict, optional): Arguments to instantiate the
475
+ corresponding backend. Defaults to None.
476
+
477
+ Yields:
478
+ Iterable[str]: Only yield one path.
479
+
480
+ Examples:
481
+ >>> with get_local_path('s3://bucket/abc.jpg') as path:
482
+ ... # do something here
483
+ """
484
+ backend = get_file_backend(
485
+ filepath,
486
+ backend_args=backend_args,
487
+ enable_singleton=True,
488
+ backend_key=backend_key,
489
+ )
490
+ with backend.get_local_path(str(filepath)) as local_path:
491
+ yield local_path
492
+
493
+
494
+ def copyfile(
495
+ src: Union[str, Path],
496
+ dst: Union[str, Path],
497
+ backend_args: Optional[dict] = None,
498
+ backend_key: Optional[str] = None,
499
+ ) -> Union[str, Path]:
500
+ """Copy a file src to dst and return the destination file.
501
+
502
+ src and dst should have the same prefix. If dst specifies a directory,
503
+ the file will be copied into dst using the base filename from src. If
504
+ dst specifies a file that already exists, it will be replaced.
505
+
506
+ Args:
507
+ src (str or Path): A file to be copied.
508
+ dst (str or Path): Copy file to dst.
509
+ backend_args (dict, optional): Arguments to instantiate the
510
+ corresponding backend. Defaults to None.
511
+
512
+ Returns:
513
+ str: The destination file.
514
+
515
+ Raises:
516
+ SameFileError: If src and dst are the same file, a SameFileError will
517
+ be raised.
518
+
519
+ Examples:
520
+ >>> # dst is a file
521
+ >>> src = '/path/of/file'
522
+ >>> dst = '/path1/of/file1'
523
+ >>> # src will be copied to '/path1/of/file1'
524
+ >>> copyfile(src, dst)
525
+ '/path1/of/file1'
526
+
527
+ >>> # dst is a directory
528
+ >>> dst = '/path1/of/dir'
529
+ >>> # src will be copied to '/path1/of/dir/file'
530
+ >>> copyfile(src, dst)
531
+ '/path1/of/dir/file'
532
+ """
533
+ backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
534
+ return backend.copyfile(src, dst)
535
+
536
+
537
+ def copytree(
538
+ src: Union[str, Path],
539
+ dst: Union[str, Path],
540
+ backend_args: Optional[dict] = None,
541
+ backend_key: Optional[str] = None,
542
+ ) -> Union[str, Path]:
543
+ """Recursively copy an entire directory tree rooted at src to a directory
544
+ named dst and return the destination directory.
545
+
546
+ src and dst should have the same prefix and dst must not already exist.
547
+
548
+ Args:
549
+ src (str or Path): A directory to be copied.
550
+ dst (str or Path): Copy directory to dst.
551
+ backend_args (dict, optional): Arguments to instantiate the
552
+ corresponding backend. Defaults to None.
553
+ backend_key (str, optional): The key to get the backend from register.
554
+
555
+ Returns:
556
+ str: The destination directory.
557
+
558
+ Raises:
559
+ FileExistsError: If dst had already existed, a FileExistsError will be
560
+ raised.
561
+
562
+ Examples:
563
+ >>> src = '/path/of/dir1'
564
+ >>> dst = '/path/of/dir2'
565
+ >>> copytree(src, dst)
566
+ '/path/of/dir2'
567
+ """
568
+ backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
569
+ return backend.copytree(src, dst)
570
+
571
+
572
+ def copyfile_from_local(
573
+ src: Union[str, Path],
574
+ dst: Union[str, Path],
575
+ backend_args: Optional[dict] = None,
576
+ backend_key: Optional[str] = None,
577
+ ) -> Union[str, Path]:
578
+ """Copy a local file src to dst and return the destination file.
579
+
580
+ Note:
581
+ If the backend is the instance of LocalBackend, it does the same
582
+ thing with :func:`copyfile`.
583
+
584
+ Args:
585
+ src (str or Path): A local file to be copied.
586
+ dst (str or Path): Copy file to dst.
587
+ backend_args (dict, optional): Arguments to instantiate the
588
+ corresponding backend. Defaults to None.
589
+
590
+ Returns:
591
+ str: If dst specifies a directory, the file will be copied into dst
592
+ using the base filename from src.
593
+
594
+ Examples:
595
+ >>> # dst is a file
596
+ >>> src = '/path/of/file'
597
+ >>> dst = 's3://openmmlab/mmengine/file1'
598
+ >>> # src will be copied to 's3://openmmlab/mmengine/file1'
599
+ >>> copyfile_from_local(src, dst)
600
+ s3://openmmlab/mmengine/file1
601
+
602
+ >>> # dst is a directory
603
+ >>> dst = 's3://openmmlab/mmengine'
604
+ >>> # src will be copied to 's3://openmmlab/mmengine/file''
605
+ >>> copyfile_from_local(src, dst)
606
+ 's3://openmmlab/mmengine/file'
607
+ """
608
+ backend = get_file_backend(dst, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
609
+ return backend.copyfile_from_local(src, dst)
610
+
611
+
612
+ def copytree_from_local(
613
+ src: Union[str, Path],
614
+ dst: Union[str, Path],
615
+ backend_args: Optional[dict] = None,
616
+ backend_key: Optional[str] = None,
617
+ ) -> Union[str, Path]:
618
+ """Recursively copy an entire directory tree rooted at src to a directory
619
+ named dst and return the destination directory.
620
+
621
+ Note:
622
+ If the backend is the instance of LocalBackend, it does the same
623
+ thing with :func:`copytree`.
624
+
625
+ Args:
626
+ src (str or Path): A local directory to be copied.
627
+ dst (str or Path): Copy directory to dst.
628
+ backend_args (dict, optional): Arguments to instantiate the
629
+ corresponding backend. Defaults to None.
630
+
631
+ Returns:
632
+ str: The destination directory.
633
+
634
+ Examples:
635
+ >>> src = '/path/of/dir'
636
+ >>> dst = 's3://openmmlab/mmengine/dir'
637
+ >>> copyfile_from_local(src, dst)
638
+ 's3://openmmlab/mmengine/dir'
639
+ """
640
+ backend = get_file_backend(dst, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
641
+ return backend.copytree_from_local(src, dst)
642
+
643
+
644
+ def copyfile_to_local(
645
+ src: Union[str, Path],
646
+ dst: Union[str, Path],
647
+ dst_type: str, # Choose from ["file", "dir"]
648
+ backend_args: Optional[dict] = None,
649
+ backend_key: Optional[str] = None,
650
+ ) -> Union[str, Path]:
651
+ """Copy the file src to local dst and return the destination file.
652
+
653
+ If dst specifies a directory, the file will be copied into dst using
654
+ the base filename from src. If dst specifies a file that already
655
+ exists, it will be replaced.
656
+
657
+ Note:
658
+ If the backend is the instance of LocalBackend, it does the same
659
+ thing with :func:`copyfile`.
660
+
661
+ Args:
662
+ src (str or Path): A file to be copied.
663
+ dst (str or Path): Copy file to to local dst.
664
+ backend_args (dict, optional): Arguments to instantiate the
665
+ corresponding backend. Defaults to None.
666
+
667
+ Returns:
668
+ str: If dst specifies a directory, the file will be copied into dst
669
+ using the base filename from src.
670
+
671
+ Examples:
672
+ >>> # dst is a file
673
+ >>> src = 's3://openmmlab/mmengine/file'
674
+ >>> dst = '/path/of/file'
675
+ >>> # src will be copied to '/path/of/file'
676
+ >>> copyfile_to_local(src, dst)
677
+ '/path/of/file'
678
+
679
+ >>> # dst is a directory
680
+ >>> dst = '/path/of/dir'
681
+ >>> # src will be copied to '/path/of/dir/file'
682
+ >>> copyfile_to_local(src, dst)
683
+ '/path/of/dir/file'
684
+ """
685
+ assert dst_type in ["file", "dir"]
686
+ Path(dst).parent.mkdir(parents=True, exist_ok=True)
687
+ backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
688
+ return backend.copyfile_to_local(src, dst, dst_type=dst_type)
689
+
690
+
691
+ def copytree_to_local(
692
+ src: Union[str, Path],
693
+ dst: Union[str, Path],
694
+ backend_args: Optional[dict] = None,
695
+ backend_key: Optional[str] = None,
696
+ ) -> Union[str, Path]:
697
+ """Recursively copy an entire directory tree rooted at src to a local
698
+ directory named dst and return the destination directory.
699
+
700
+ Note:
701
+ If the backend is the instance of LocalBackend, it does the same
702
+ thing with :func:`copytree`.
703
+
704
+ Args:
705
+ src (str or Path): A directory to be copied.
706
+ dst (str or Path): Copy directory to local dst.
707
+ backend_args (dict, optional): Arguments to instantiate the
708
+ corresponding backend. Defaults to None.
709
+
710
+ Returns:
711
+ str: The destination directory.
712
+
713
+ Examples:
714
+ >>> src = 's3://openmmlab/mmengine/dir'
715
+ >>> dst = '/path/of/dir'
716
+ >>> copytree_to_local(src, dst)
717
+ '/path/of/dir'
718
+ """
719
+ Path(dst).parent.mkdir(parents=True, exist_ok=True)
720
+ backend = get_file_backend(dst, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
721
+ return backend.copytree_to_local(src, dst)
722
+
723
+
724
+ def remove(
725
+ filepath: Union[str, Path],
726
+ backend_args: Optional[dict] = None,
727
+ backend_key: Optional[str] = None,
728
+ ) -> None:
729
+ """Remove a file.
730
+
731
+ Args:
732
+ filepath (str, Path): Path to be removed.
733
+ backend_args (dict, optional): Arguments to instantiate the
734
+ corresponding backend. Defaults to None.
735
+
736
+ Raises:
737
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
738
+ will be raised.
739
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
740
+ will be raised.
741
+
742
+ Examples:
743
+ >>> filepath = '/path/of/file'
744
+ >>> remove(filepath)
745
+ """
746
+ backend = get_file_backend(
747
+ filepath,
748
+ backend_args=backend_args,
749
+ enable_singleton=True,
750
+ backend_key=backend_key,
751
+ )
752
+ backend.remove(filepath)
753
+
754
+
755
+ def rmtree(
756
+ dir_path: Union[str, Path],
757
+ backend_args: Optional[dict] = None,
758
+ backend_key: Optional[str] = None,
759
+ ) -> None:
760
+ """Recursively delete a directory tree.
761
+
762
+ Args:
763
+ dir_path (str or Path): A directory to be removed.
764
+ backend_args (dict, optional): Arguments to instantiate the
765
+ corresponding backend. Defaults to None.
766
+
767
+ Examples:
768
+ >>> dir_path = '/path/of/dir'
769
+ >>> rmtree(dir_path)
770
+ """
771
+ backend = get_file_backend(
772
+ dir_path,
773
+ backend_args=backend_args,
774
+ enable_singleton=True,
775
+ backend_key=backend_key,
776
+ )
777
+ backend.rmtree(dir_path)
778
+
779
+
780
+ def copy_if_symlink_fails(
781
+ src: Union[str, Path],
782
+ dst: Union[str, Path],
783
+ backend_args: Optional[dict] = None,
784
+ backend_key: Optional[str] = None,
785
+ ) -> bool:
786
+ """Create a symbolic link pointing to src named dst.
787
+
788
+ If failed to create a symbolic link pointing to src, directory copy src to
789
+ dst instead.
790
+
791
+ Args:
792
+ src (str or Path): Create a symbolic link pointing to src.
793
+ dst (str or Path): Create a symbolic link named dst.
794
+ backend_args (dict, optional): Arguments to instantiate the
795
+ corresponding backend. Defaults to None.
796
+
797
+ Returns:
798
+ bool: Return True if successfully create a symbolic link pointing to
799
+ src. Otherwise, return False.
800
+
801
+ Examples:
802
+ >>> src = '/path/of/file'
803
+ >>> dst = '/path1/of/file1'
804
+ >>> copy_if_symlink_fails(src, dst)
805
+ True
806
+ >>> src = '/path/of/dir'
807
+ >>> dst = '/path1/of/dir1'
808
+ >>> copy_if_symlink_fails(src, dst)
809
+ True
810
+ """
811
+ backend = get_file_backend(src, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
812
+ return backend.copy_if_symlink_fails(src, dst)
813
+
814
+
815
+ def list_dir(
816
+ dir_path: Union[str, Path],
817
+ backend_args: Optional[dict] = None,
818
+ backend_key: Optional[str] = None,
819
+ ):
820
+ """List all folders in an S3 bucket with a given prefix.
821
+
822
+ Args:
823
+ dir_path (str | Path): Path of the directory.
824
+
825
+ Examples:
826
+ >>> dir_path = '/path/of/dir'
827
+ >>> for file_path in list_dir(dir_path):
828
+ ... print(file_path)
829
+ """
830
+ if not dir_path.endswith("/"):
831
+ dir_path += "/"
832
+ backend = get_file_backend(
833
+ dir_path,
834
+ backend_args=backend_args,
835
+ enable_singleton=True,
836
+ backend_key=backend_key,
837
+ )
838
+
839
+ return backend.list_dir(dir_path)
840
+
841
+
842
+ def list_dir_or_file(
843
+ dir_path: Union[str, Path],
844
+ list_dir: bool = True,
845
+ list_file: bool = True,
846
+ suffix: Optional[Union[str, Tuple[str]]] = None,
847
+ recursive: bool = False,
848
+ backend_args: Optional[dict] = None,
849
+ backend_key: Optional[str] = None,
850
+ ) -> Iterator[str]:
851
+ """Scan a directory to find the interested directories or files in
852
+ arbitrary order.
853
+
854
+ Note:
855
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
856
+
857
+ Args:
858
+ dir_path (str or Path): Path of the directory.
859
+ list_dir (bool): List the directories. Defaults to True.
860
+ list_file (bool): List the path of files. Defaults to True.
861
+ suffix (str or tuple[str], optional): File suffix that we are
862
+ interested in. Defaults to None.
863
+ recursive (bool): If set to True, recursively scan the directory.
864
+ Defaults to False.
865
+ backend_args (dict, optional): Arguments to instantiate the
866
+ corresponding backend. Defaults to None.
867
+
868
+ Yields:
869
+ Iterable[str]: A relative path to ``dir_path``.
870
+
871
+ Examples:
872
+ >>> dir_path = '/path/of/dir'
873
+ >>> for file_path in list_dir_or_file(dir_path):
874
+ ... print(file_path)
875
+ >>> # list those files and directories in current directory
876
+ >>> for file_path in list_dir_or_file(dir_path):
877
+ ... print(file_path)
878
+ >>> # only list files
879
+ >>> for file_path in list_dir_or_file(dir_path, list_dir=False):
880
+ ... print(file_path)
881
+ >>> # only list directories
882
+ >>> for file_path in list_dir_or_file(dir_path, list_file=False):
883
+ ... print(file_path)
884
+ >>> # only list files ending with specified suffixes
885
+ >>> for file_path in list_dir_or_file(dir_path, suffix='.txt'):
886
+ ... print(file_path)
887
+ >>> # list all files and directory recursively
888
+ >>> for file_path in list_dir_or_file(dir_path, recursive=True):
889
+ ... print(file_path)
890
+ """
891
+ backend = get_file_backend(
892
+ dir_path,
893
+ backend_args=backend_args,
894
+ enable_singleton=True,
895
+ backend_key=backend_key,
896
+ )
897
+ yield from backend.list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive)
898
+
899
+
900
+ def generate_presigned_url(
901
+ url: str,
902
+ client_method: str = "get_object",
903
+ expires_in: int = 3600,
904
+ backend_args: Optional[dict] = None,
905
+ backend_key: Optional[str] = None,
906
+ ) -> str:
907
+ """Generate the presigned url of video stream which can be passed to
908
+ mmcv.VideoReader. Now only work on s3 backend.
909
+
910
+ Note:
911
+ Now only work on s3 backend.
912
+
913
+ Args:
914
+ url (str): Url of video stream.
915
+ client_method (str): Method of client, 'get_object' or
916
+ 'put_object'. Defaults to 'get_object'.
917
+ expires_in (int): expires, in seconds. Defaults to 3600.
918
+ backend_args (dict, optional): Arguments to instantiate the
919
+ corresponding backend. Defaults to None.
920
+
921
+ Returns:
922
+ str: Generated presigned url.
923
+ """
924
+ backend = get_file_backend(url, backend_args=backend_args, enable_singleton=True, backend_key=backend_key)
925
+ return backend.generate_presigned_url(url, client_method, expires_in)
926
+
927
+
928
+ def load(
929
+ file: Union[str, Path, IO[Any]],
930
+ file_format: Optional[str] = None,
931
+ file_client_args: Optional[dict] = None,
932
+ fast_backend: bool = False,
933
+ backend_args: Optional[dict] = None,
934
+ backend_key: Optional[str] = None,
935
+ **kwargs,
936
+ ):
937
+ """Load data from json/yaml/pickle files.
938
+
939
+ This method provides a unified api for loading data from serialized files.
940
+
941
+ ``load`` supports loading data from serialized files those can be storaged
942
+ in different backends.
943
+
944
+ Args:
945
+ file (str or :obj:`Path` or file-like object): Filename or a file-like
946
+ object.
947
+ file_format (str, optional): If not specified, the file format will be
948
+ inferred from the file extension, otherwise use the specified one.
949
+ Currently supported formats include "json", "yaml/yml" and
950
+ "pickle/pkl".
951
+ file_client_args (dict, optional): Arguments to instantiate a
952
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
953
+ Defaults to None. It will be deprecated in future. Please use
954
+ ``backend_args`` instead.
955
+ fast_backend: bool: Whether to use multiprocess. Defaults to False.
956
+ backend_args (dict, optional): Arguments to instantiate the
957
+ prefix of uri corresponding backend. Defaults to None.
958
+ New in v0.2.0.
959
+
960
+ Examples:
961
+ >>> load('/path/of/your/file') # file is storaged in disk
962
+ >>> load('https://path/of/your/file') # file is storaged in Internet
963
+ >>> load('s3://path/of/your/file') # file is storaged in s3
964
+
965
+ Returns:
966
+ The content from the file.
967
+ """
968
+ if isinstance(file, Path):
969
+ file = str(file)
970
+ if file_format is None and isinstance(file, str):
971
+ file_format = file.split(".")[-1]
972
+ # convert file_format to lower case
973
+ file_format = file_format.lower()
974
+ if file_format not in file_handlers:
975
+ raise TypeError(f"Unsupported format: {file_format}")
976
+
977
+ if file_client_args is not None:
978
+ warnings.warn(
979
+ '"file_client_args" will be deprecated in future. Please use "backend_args" instead',
980
+ DeprecationWarning,
981
+ )
982
+ if backend_args is not None:
983
+ raise ValueError('"file_client_args and "backend_args" cannot be set at the same time.')
984
+
985
+ handler = file_handlers[file_format]
986
+ if isinstance(file, str):
987
+ if file_client_args is not None:
988
+ file_client = FileClient.infer_client(file_client_args, file)
989
+ file_backend = file_client
990
+ else:
991
+ file_backend = get_file_backend(
992
+ file,
993
+ backend_args=backend_args,
994
+ backend_key=backend_key,
995
+ enable_singleton=True,
996
+ )
997
+
998
+ if handler.str_like:
999
+ with StringIO(file_backend.get_text(file)) as f:
1000
+ obj = handler.load_from_fileobj(f, **kwargs)
1001
+ else:
1002
+ if fast_backend:
1003
+ if hasattr(file_backend, "fast_get"):
1004
+ with BytesIO(file_backend.fast_get(file)) as f:
1005
+ obj = handler.load_from_fileobj(f, **kwargs)
1006
+ else:
1007
+ warnings.warn(
1008
+ f"fast_backend is not supported by the backend, type {type(file_backend)} fallback to normal get"
1009
+ )
1010
+ with BytesIO(file_backend.get(file)) as f:
1011
+ obj = handler.load_from_fileobj(f, **kwargs)
1012
+ else:
1013
+ with BytesIO(file_backend.get(file)) as f:
1014
+ obj = handler.load_from_fileobj(f, **kwargs)
1015
+ elif hasattr(file, "read"):
1016
+ obj = handler.load_from_fileobj(file, **kwargs)
1017
+ else:
1018
+ raise TypeError('"file" must be a filepath str or a file-object')
1019
+ return obj
1020
+
1021
+
1022
+ def dump(
1023
+ obj: Any,
1024
+ file: Union[str, Path, IO[Any], None] = None,
1025
+ file_format: Optional[str] = None,
1026
+ file_client_args: Optional[dict] = None,
1027
+ fast_backend: bool = False,
1028
+ backend_args: Optional[dict] = None,
1029
+ backend_key: Optional[str] = None,
1030
+ **kwargs,
1031
+ ):
1032
+ """Dump data to json/yaml/pickle strings or files.
1033
+
1034
+ This method provides a unified api for dumping data as strings or to files,
1035
+ and also supports custom arguments for each file format.
1036
+
1037
+ ``dump`` supports dumping data as strings or to files which is saved to
1038
+ different backends.
1039
+
1040
+ Args:
1041
+ obj (any): The python object to be dumped.
1042
+ file (str or :obj:`Path` or file-like object, optional): If not
1043
+ specified, then the object is dumped to a str, otherwise to a file
1044
+ specified by the filename or file-like object.
1045
+ file_format (str, optional): Same as :func:`load`.
1046
+ file_client_args (dict, optional): Arguments to instantiate a
1047
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
1048
+ Defaults to None. It will be deprecated in future. Please use
1049
+ ``backend_args`` instead.
1050
+ fast_backend: bool: Whether to use multiprocess. Defaults to False.
1051
+ backend_args (dict, optional): Arguments to instantiate the
1052
+ prefix of uri corresponding backend. Defaults to None.
1053
+ New in v0.2.0.
1054
+ backend_key: str: The key to register the backend. Defaults to None.
1055
+
1056
+ Examples:
1057
+ >>> dump('hello world', '/path/of/your/file') # disk
1058
+ >>> dump('hello world', 's3://path/of/your/file') # ceph or s3
1059
+
1060
+ Returns:
1061
+ bool: True for success, False otherwise.
1062
+ """
1063
+ if isinstance(file, Path):
1064
+ file = str(file)
1065
+ if file_format is None:
1066
+ if isinstance(file, str):
1067
+ file_format = file.split(".")[-1]
1068
+ elif file is None:
1069
+ raise ValueError("file_format must be specified since file is None")
1070
+ # convert file_format to lower case
1071
+ file_format = file_format.lower()
1072
+ if file_format not in file_handlers:
1073
+ raise TypeError(f"Unsupported format: {file_format}")
1074
+
1075
+ if file_client_args is not None:
1076
+ warnings.warn(
1077
+ '"file_client_args" will be deprecated in future. Please use "backend_args" instead',
1078
+ DeprecationWarning,
1079
+ )
1080
+ if backend_args is not None:
1081
+ raise ValueError('"file_client_args" and "backend_args" cannot be set at the same time.')
1082
+
1083
+ handler = file_handlers[file_format]
1084
+ if file is None:
1085
+ return handler.dump_to_str(obj, **kwargs)
1086
+ elif isinstance(file, str):
1087
+ if file_client_args is not None:
1088
+ file_client = FileClient.infer_client(file_client_args, file)
1089
+ file_backend = file_client
1090
+ else:
1091
+ file_backend = get_file_backend(
1092
+ file,
1093
+ backend_args=backend_args,
1094
+ backend_key=backend_key,
1095
+ enable_singleton=True,
1096
+ )
1097
+
1098
+ if handler.str_like:
1099
+ with StringIO() as f:
1100
+ handler.dump_to_fileobj(obj, f, **kwargs)
1101
+ file_backend.put_text(f.getvalue(), file)
1102
+ else:
1103
+ with BytesIO() as f:
1104
+ handler.dump_to_fileobj(obj, f, **kwargs)
1105
+ if fast_backend:
1106
+ if hasattr(file_backend, "fast_put"):
1107
+ file_backend.fast_put(f, file)
1108
+ else:
1109
+ warnings.warn("fast_backend is not supported by the backend, fallback to normal put")
1110
+ file_backend.put(f, file)
1111
+ else:
1112
+ file_backend.put(f, file)
1113
+ elif hasattr(file, "write"):
1114
+ handler.dump_to_fileobj(obj, file, **kwargs)
1115
+ else:
1116
+ raise TypeError('"file" must be a filename str or a file-object')
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/file_client.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ from contextlib import contextmanager
18
+ from pathlib import Path
19
+ from typing import Any, Generator, Iterator, Optional, Tuple, Union
20
+
21
+ from cosmos_policy._src.imaginaire.utils.easy_io.backends import (
22
+ BaseStorageBackend,
23
+ HTTPBackend,
24
+ LocalBackend,
25
+ MSCBackend,
26
+ )
27
+
28
+
29
+ def is_filepath(filepath):
30
+ return isinstance(filepath, (str, Path))
31
+
32
+
33
+ class HardDiskBackend(LocalBackend):
34
+ """Raw hard disks storage backend."""
35
+
36
+ @property
37
+ def name(self):
38
+ return self.__class__.__name__
39
+
40
+
41
+ class FileClient:
42
+ """A general file client to access files in different backends.
43
+
44
+ The client loads a file or text in a specified backend from its path
45
+ and returns it as a binary or text file. There are two ways to choose a
46
+ backend, the name of backend and the prefix of path. Although both of them
47
+ can be used to choose a storage backend, ``backend`` has a higher priority
48
+ that is if they are all set, the storage backend will be chosen by the
49
+ backend argument. If they are all `None`, the disk backend will be chosen.
50
+ Note that It can also register other backend accessor with a given name,
51
+ prefixes, and backend class. In addition, We use the singleton pattern to
52
+ avoid repeated object creation. If the arguments are the same, the same
53
+ object will be returned.
54
+
55
+ Warning:
56
+ `FileClient` will be deprecated in future. Please use io functions
57
+ in https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io
58
+
59
+ Args:
60
+ backend (str, optional): The storage backend type. Options are "disk",
61
+ "memcached", "lmdb", "http" and "s3". Defaults to None.
62
+ prefix (str, optional): The prefix of the registered storage backend.
63
+ Options are "s3", "http", "https". Defaults to None.
64
+
65
+ Examples:
66
+ >>> # only set backend
67
+ >>> file_client = FileClient(backend='s3')
68
+ >>> # only set prefix
69
+ >>> file_client = FileClient(prefix='s3')
70
+ >>> # set both backend and prefix but use backend to choose client
71
+ >>> file_client = FileClient(backend='s3', prefix='s3')
72
+ >>> # if the arguments are the same, the same object is returned
73
+ >>> file_client1 = FileClient(backend='s3')
74
+ >>> file_client1 is file_client
75
+ True
76
+
77
+ Attributes:
78
+ client (:obj:`BaseStorageBackend`): The backend object.
79
+ """
80
+
81
+ _backends = {
82
+ "disk": HardDiskBackend,
83
+ "s3": MSCBackend,
84
+ "http": HTTPBackend,
85
+ "msc": MSCBackend,
86
+ }
87
+
88
+ _prefix_to_backends: dict = {
89
+ "s3": MSCBackend,
90
+ "http": HTTPBackend,
91
+ "https": HTTPBackend,
92
+ }
93
+
94
+ _instances: dict = {}
95
+
96
+ client: Any
97
+
98
+ def __new__(cls, backend=None, prefix=None, **kwargs):
99
+ if backend is None and prefix is None:
100
+ backend = "disk"
101
+ if backend is not None and backend not in cls._backends:
102
+ raise ValueError(
103
+ f"Backend {backend} is not supported. Currently supported ones are {list(cls._backends.keys())}"
104
+ )
105
+ if prefix is not None and prefix not in cls._prefix_to_backends:
106
+ raise ValueError(
107
+ f"prefix {prefix} is not supported. Currently supported ones are {list(cls._prefix_to_backends.keys())}"
108
+ )
109
+
110
+ # concatenate the arguments to a unique key for determining whether
111
+ # objects with the same arguments were created
112
+ arg_key = f"{backend}:{prefix}"
113
+ for key, value in kwargs.items():
114
+ arg_key += f":{key}:{value}"
115
+
116
+ # if a backend was overridden, it will create a new object
117
+ if arg_key in cls._instances:
118
+ _instance = cls._instances[arg_key]
119
+ else:
120
+ # create a new object and put it to _instance
121
+ _instance = super().__new__(cls)
122
+ if backend is not None:
123
+ _instance.client = cls._backends[backend](**kwargs)
124
+ else:
125
+ _instance.client = cls._prefix_to_backends[prefix](**kwargs)
126
+
127
+ cls._instances[arg_key] = _instance
128
+
129
+ return _instance
130
+
131
+ @property
132
+ def name(self):
133
+ return self.client.name
134
+
135
+ @property
136
+ def allow_symlink(self):
137
+ return self.client.allow_symlink
138
+
139
+ @staticmethod
140
+ def parse_uri_prefix(uri: Union[str, Path]) -> Optional[str]:
141
+ """Parse the prefix of a uri.
142
+
143
+ Args:
144
+ uri (str | Path): Uri to be parsed that contains the file prefix.
145
+
146
+ Examples:
147
+ >>> FileClient.parse_uri_prefix('s3://path/of/your/file')
148
+ 's3'
149
+
150
+ Returns:
151
+ str | None: Return the prefix of uri if the uri contains '://' else
152
+ ``None``.
153
+ """
154
+ assert is_filepath(uri)
155
+ uri = str(uri)
156
+ if "://" not in uri:
157
+ return None
158
+ else:
159
+ prefix, _ = uri.split("://")
160
+ # In the case of MSCBackend, the prefix may contains the cluster
161
+ # name like clusterName:s3
162
+ if ":" in prefix:
163
+ _, prefix = prefix.split(":")
164
+ return prefix
165
+
166
+ @classmethod
167
+ def infer_client(
168
+ cls,
169
+ file_client_args: Optional[dict] = None,
170
+ uri: Optional[Union[str, Path]] = None,
171
+ ) -> "FileClient":
172
+ """Infer a suitable file client based on the URI and arguments.
173
+
174
+ Args:
175
+ file_client_args (dict, optional): Arguments to instantiate a
176
+ FileClient. Defaults to None.
177
+ uri (str | Path, optional): Uri to be parsed that contains the file
178
+ prefix. Defaults to None.
179
+
180
+ Examples:
181
+ >>> uri = 's3://path/of/your/file'
182
+ >>> file_client = FileClient.infer_client(uri=uri)
183
+ >>> file_client_args = {'backend': 's3'}
184
+ >>> file_client = FileClient.infer_client(file_client_args)
185
+
186
+ Returns:
187
+ FileClient: Instantiated FileClient object.
188
+ """
189
+ assert file_client_args is not None or uri is not None
190
+ if file_client_args is None:
191
+ file_prefix = cls.parse_uri_prefix(uri) # type: ignore
192
+ return cls(prefix=file_prefix)
193
+ else:
194
+ return cls(**file_client_args)
195
+
196
+ @classmethod
197
+ def _register_backend(cls, name, backend, force=False, prefixes=None):
198
+ if not isinstance(name, str):
199
+ raise TypeError(f"the backend name should be a string, but got {type(name)}")
200
+ if not inspect.isclass(backend):
201
+ raise TypeError(f"backend should be a class but got {type(backend)}")
202
+ if not issubclass(backend, BaseStorageBackend):
203
+ raise TypeError(f"backend {backend} is not a subclass of BaseStorageBackend")
204
+ if not force and name in cls._backends:
205
+ raise KeyError(
206
+ f'{name} is already registered as a storage backend, add "force=True" if you want to override it'
207
+ )
208
+
209
+ if name in cls._backends and force:
210
+ for arg_key, instance in list(cls._instances.items()):
211
+ if isinstance(instance.client, cls._backends[name]):
212
+ cls._instances.pop(arg_key)
213
+ cls._backends[name] = backend
214
+
215
+ if prefixes is not None:
216
+ if isinstance(prefixes, str):
217
+ prefixes = [prefixes]
218
+ else:
219
+ assert isinstance(prefixes, (list, tuple))
220
+ for prefix in prefixes:
221
+ if prefix not in cls._prefix_to_backends:
222
+ cls._prefix_to_backends[prefix] = backend
223
+ elif (prefix in cls._prefix_to_backends) and force:
224
+ overridden_backend = cls._prefix_to_backends[prefix]
225
+ for arg_key, instance in list(cls._instances.items()):
226
+ if isinstance(instance.client, overridden_backend):
227
+ cls._instances.pop(arg_key)
228
+ else:
229
+ raise KeyError(
230
+ f"{prefix} is already registered as a storage backend,"
231
+ ' add "force=True" if you want to override it'
232
+ )
233
+
234
+ @classmethod
235
+ def register_backend(cls, name, backend=None, force=False, prefixes=None):
236
+ """Register a backend to FileClient.
237
+
238
+ This method can be used as a normal class method or a decorator.
239
+
240
+ .. code-block:: python
241
+
242
+ class NewBackend(BaseStorageBackend):
243
+
244
+ def get(self, filepath):
245
+ return filepath
246
+
247
+ def get_text(self, filepath):
248
+ return filepath
249
+
250
+ FileClient.register_backend('new', NewBackend)
251
+
252
+ or
253
+
254
+ .. code-block:: python
255
+
256
+ @FileClient.register_backend('new')
257
+ class NewBackend(BaseStorageBackend):
258
+
259
+ def get(self, filepath):
260
+ return filepath
261
+
262
+ def get_text(self, filepath):
263
+ return filepath
264
+
265
+ Args:
266
+ name (str): The name of the registered backend.
267
+ backend (class, optional): The backend class to be registered,
268
+ which must be a subclass of :class:`BaseStorageBackend`.
269
+ When this method is used as a decorator, backend is None.
270
+ Defaults to None.
271
+ force (bool, optional): Whether to override the backend if the name
272
+ has already been registered. Defaults to False.
273
+ prefixes (str or list[str] or tuple[str], optional): The prefixes
274
+ of the registered storage backend. Defaults to None.
275
+ `New in version 1.3.15.`
276
+ """
277
+ if backend is not None:
278
+ cls._register_backend(name, backend, force=force, prefixes=prefixes)
279
+ return
280
+
281
+ def _register(backend_cls):
282
+ cls._register_backend(name, backend_cls, force=force, prefixes=prefixes)
283
+ return backend_cls
284
+
285
+ return _register
286
+
287
+ def get(self, filepath: Union[str, Path]) -> Union[bytes, memoryview]:
288
+ """Read data from a given ``filepath`` with 'rb' mode.
289
+
290
+ Note:
291
+ There are two types of return values for ``get``, one is ``bytes``
292
+ and the other is ``memoryview``. The advantage of using memoryview
293
+ is that you can avoid copying, and if you want to convert it to
294
+ ``bytes``, you can use ``.tobytes()``.
295
+
296
+ Args:
297
+ filepath (str or Path): Path to read data.
298
+
299
+ Returns:
300
+ bytes | memoryview: Expected bytes object or a memory view of the
301
+ bytes object.
302
+ """
303
+ return self.client.get(filepath)
304
+
305
+ def get_text(self, filepath: Union[str, Path], encoding="utf-8") -> str:
306
+ """Read data from a given ``filepath`` with 'r' mode.
307
+
308
+ Args:
309
+ filepath (str or Path): Path to read data.
310
+ encoding (str): The encoding format used to open the ``filepath``.
311
+ Defaults to 'utf-8'.
312
+
313
+ Returns:
314
+ str: Expected text reading from ``filepath``.
315
+ """
316
+ return self.client.get_text(filepath, encoding)
317
+
318
+ def put(self, obj: bytes, filepath: Union[str, Path]) -> None:
319
+ """Write data to a given ``filepath`` with 'wb' mode.
320
+
321
+ Note:
322
+ ``put`` should create a directory if the directory of ``filepath``
323
+ does not exist.
324
+
325
+ Args:
326
+ obj (bytes): Data to be written.
327
+ filepath (str or Path): Path to write data.
328
+ """
329
+ self.client.put(obj, filepath)
330
+
331
+ def put_text(self, obj: str, filepath: Union[str, Path]) -> None:
332
+ """Write data to a given ``filepath`` with 'w' mode.
333
+
334
+ Note:
335
+ ``put_text`` should create a directory if the directory of
336
+ ``filepath`` does not exist.
337
+
338
+ Args:
339
+ obj (str): Data to be written.
340
+ filepath (str or Path): Path to write data.
341
+ encoding (str, optional): The encoding format used to open the
342
+ `filepath`. Defaults to 'utf-8'.
343
+ """
344
+ self.client.put_text(obj, filepath)
345
+
346
+ def remove(self, filepath: Union[str, Path]) -> None:
347
+ """Remove a file.
348
+
349
+ Args:
350
+ filepath (str, Path): Path to be removed.
351
+ """
352
+ self.client.remove(filepath)
353
+
354
+ def exists(self, filepath: Union[str, Path]) -> bool:
355
+ """Check whether a file path exists.
356
+
357
+ Args:
358
+ filepath (str or Path): Path to be checked whether exists.
359
+
360
+ Returns:
361
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
362
+ """
363
+ return self.client.exists(filepath)
364
+
365
+ def isdir(self, filepath: Union[str, Path]) -> bool:
366
+ """Check whether a file path is a directory.
367
+
368
+ Args:
369
+ filepath (str or Path): Path to be checked whether it is a
370
+ directory.
371
+
372
+ Returns:
373
+ bool: Return ``True`` if ``filepath`` points to a directory,
374
+ ``False`` otherwise.
375
+ """
376
+ return self.client.isdir(filepath)
377
+
378
+ def isfile(self, filepath: Union[str, Path]) -> bool:
379
+ """Check whether a file path is a file.
380
+
381
+ Args:
382
+ filepath (str or Path): Path to be checked whether it is a file.
383
+
384
+ Returns:
385
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
386
+ otherwise.
387
+ """
388
+ return self.client.isfile(filepath)
389
+
390
+ def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str:
391
+ r"""Concatenate all file paths.
392
+
393
+ Join one or more filepath components intelligently. The return value
394
+ is the concatenation of filepath and any members of \*filepaths.
395
+
396
+ Args:
397
+ filepath (str or Path): Path to be concatenated.
398
+
399
+ Returns:
400
+ str: The result of concatenation.
401
+ """
402
+ return self.client.join_path(filepath, *filepaths)
403
+
404
+ @contextmanager
405
+ def get_local_path(self, filepath: Union[str, Path]) -> Generator[Union[str, Path], None, None]:
406
+ """Download data from ``filepath`` and write the data to local path.
407
+
408
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
409
+ can be called with ``with`` statement, and when exists from the
410
+ ``with`` statement, the temporary path will be released.
411
+
412
+ Note:
413
+ If the ``filepath`` is a local path, just return itself.
414
+
415
+ .. warning::
416
+ ``get_local_path`` is an experimental interface that may change in
417
+ the future.
418
+
419
+ Args:
420
+ filepath (str or Path): Path to be read data.
421
+
422
+ Examples:
423
+ >>> file_client = FileClient(prefix='s3')
424
+ >>> with file_client.get_local_path('s3://bucket/abc.jpg') as path:
425
+ ... # do something here
426
+
427
+ Yields:
428
+ Iterable[str]: Only yield one path.
429
+ """
430
+ with self.client.get_local_path(str(filepath)) as local_path:
431
+ yield local_path
432
+
433
+ def list_dir_or_file( # pylint: disable=too-many-arguments
434
+ self,
435
+ dir_path: Union[str, Path],
436
+ list_dir: bool = True,
437
+ list_file: bool = True,
438
+ suffix: Optional[Union[str, Tuple[str]]] = None,
439
+ recursive: bool = False,
440
+ ) -> Iterator[str]:
441
+ """Scan a directory to find the interested directories or files in
442
+ arbitrary order.
443
+
444
+ Note:
445
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
446
+
447
+ Args:
448
+ dir_path (str | Path): Path of the directory.
449
+ list_dir (bool): List the directories. Defaults to True.
450
+ list_file (bool): List the path of files. Defaults to True.
451
+ suffix (str or tuple[str], optional): File suffix
452
+ that we are interested in. Defaults to None.
453
+ recursive (bool): If set to True, recursively scan the
454
+ directory. Defaults to False.
455
+
456
+ Yields:
457
+ Iterable[str]: A relative path to ``dir_path``.
458
+ """
459
+ yield from self.client.list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive)
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/handlers/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers.base import BaseFileHandler
17
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers.json_handler import JsonHandler
18
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers.pickle_handler import PickleHandler
19
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers.registry_utils import file_handlers, register_handler
20
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers.yaml_handler import YamlHandler
21
+
22
+ __all__ = [
23
+ "BaseFileHandler",
24
+ "JsonHandler",
25
+ "PickleHandler",
26
+ "YamlHandler",
27
+ "register_handler",
28
+ "file_handlers",
29
+ ]
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/handlers/base.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from abc import ABCMeta, abstractmethod
17
+
18
+
19
+ class BaseFileHandler(metaclass=ABCMeta):
20
+ # `str_like` is a flag to indicate whether the type of file object is
21
+ # str-like object or bytes-like object. Pickle only processes bytes-like
22
+ # objects but json only processes str-like object. If it is str-like
23
+ # object, `StringIO` will be used to process the buffer.
24
+ str_like = True
25
+
26
+ @abstractmethod
27
+ def load_from_fileobj(self, file, **kwargs):
28
+ pass
29
+
30
+ @abstractmethod
31
+ def dump_to_fileobj(self, obj, file, **kwargs):
32
+ pass
33
+
34
+ @abstractmethod
35
+ def dump_to_str(self, obj, **kwargs):
36
+ pass
37
+
38
+ def load_from_path(self, filepath, mode="r", **kwargs):
39
+ with open(filepath, mode) as f:
40
+ return self.load_from_fileobj(f, **kwargs)
41
+
42
+ def dump_to_path(self, obj, filepath, mode="w", **kwargs):
43
+ with open(filepath, mode) as f:
44
+ self.dump_to_fileobj(obj, f, **kwargs)
REGEN-main/cosmos_policy/_src/imaginaire/utils/easy_io/handlers/byte_handler.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import IO
17
+
18
+ from cosmos_policy._src.imaginaire.utils.easy_io.handlers.base import BaseFileHandler
19
+
20
+
21
+ class ByteHandler(BaseFileHandler):
22
+ str_like = False
23
+
24
+ def load_from_fileobj(self, file: IO[bytes], **kwargs):
25
+ file.seek(0)
26
+ # extra all bytes and return
27
+ return file.read()
28
+
29
+ def dump_to_fileobj(
30
+ self,
31
+ obj: bytes,
32
+ file: IO[bytes],
33
+ **kwargs,
34
+ ):
35
+ # write all bytes to file
36
+ file.write(obj)
37
+
38
+ def dump_to_str(self, obj, **kwargs):
39
+ raise NotImplementedError