sedpack 0.1.2__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. sedpack/__init__.py +21 -0
  2. sedpack/_sedpack_rs.cp313-win_amd64.pyd +0 -0
  3. sedpack/io/__init__.py +28 -0
  4. sedpack/io/compress.py +110 -0
  5. sedpack/io/dataset.py +104 -0
  6. sedpack/io/dataset_base.py +165 -0
  7. sedpack/io/dataset_filler.py +309 -0
  8. sedpack/io/dataset_iteration.py +927 -0
  9. sedpack/io/dataset_writing.py +293 -0
  10. sedpack/io/errors.py +36 -0
  11. sedpack/io/file_info.py +54 -0
  12. sedpack/io/flatbuffer/__init__.py +20 -0
  13. sedpack/io/flatbuffer/iterate.py +174 -0
  14. sedpack/io/flatbuffer/shard.fbs +23 -0
  15. sedpack/io/flatbuffer/shardfile/Attribute.py +115 -0
  16. sedpack/io/flatbuffer/shardfile/Example.py +105 -0
  17. sedpack/io/flatbuffer/shardfile/Shard.py +117 -0
  18. sedpack/io/flatbuffer/shardfile/__init__.py +0 -0
  19. sedpack/io/flatbuffer/unit_tests/shard_writer_flatbuffer_test_schema/NumPyVectorTest.py +582 -0
  20. sedpack/io/flatbuffer/unit_tests/shard_writer_flatbuffer_test_schema/__init__.py +0 -0
  21. sedpack/io/flatbuffer/unit_tests/shard_writer_flatbuffer_test_schema.fbs +34 -0
  22. sedpack/io/itertools/__init__.py +27 -0
  23. sedpack/io/itertools/itertools.py +223 -0
  24. sedpack/io/itertools/lazy_pool.py +219 -0
  25. sedpack/io/merge_shard_infos.py +117 -0
  26. sedpack/io/metadata.py +153 -0
  27. sedpack/io/npz/__init__.py +20 -0
  28. sedpack/io/npz/iterate_npz.py +79 -0
  29. sedpack/io/shard/__init__.py +22 -0
  30. sedpack/io/shard/get_shard_writer.py +41 -0
  31. sedpack/io/shard/iterate_shard_base.py +70 -0
  32. sedpack/io/shard/shard.py +98 -0
  33. sedpack/io/shard/shard_writer_base.py +92 -0
  34. sedpack/io/shard/shard_writer_flatbuffer.py +242 -0
  35. sedpack/io/shard/shard_writer_np.py +99 -0
  36. sedpack/io/shard/shard_writer_tfrec.py +95 -0
  37. sedpack/io/shard_file_metadata.py +200 -0
  38. sedpack/io/tfrec/__init__.py +20 -0
  39. sedpack/io/tfrec/read.py +100 -0
  40. sedpack/io/tfrec/tfdata.py +168 -0
  41. sedpack/io/types.py +74 -0
  42. sedpack/io/utils.py +152 -0
  43. sedpack/py.typed +0 -0
  44. sedpack-0.1.2.dist-info/METADATA +101 -0
  45. sedpack-0.1.2.dist-info/RECORD +47 -0
  46. sedpack-0.1.2.dist-info/WHEEL +4 -0
  47. sedpack-0.1.2.dist-info/licenses/LICENSE +202 -0
sedpack/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ # Copyright 2023 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Dataset library.
15
+
16
+ Format: MAJOR.MINOR.PATCH (see https://pypi.org/project/semver/ for more
17
+ possibilities)
18
+ """
19
+ # The version of this package is defined by rust/Cargo.toml but mypy does not
20
+ # see that.
21
+ __version__ = "0.0.7"
Binary file
sedpack/io/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ # Copyright 2023-2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Dataset creation and usage."""
15
+
16
+ from sedpack.io.dataset import Dataset
17
+ from sedpack.io.dataset_filler import DatasetFiller
18
+ from sedpack.io.metadata import Attribute
19
+ from sedpack.io.metadata import DatasetStructure
20
+ from sedpack.io.metadata import Metadata
21
+
22
+ __all__ = [
23
+ "Attribute",
24
+ "Dataset",
25
+ "DatasetFiller",
26
+ "DatasetStructure",
27
+ "Metadata",
28
+ ]
sedpack/io/compress.py ADDED
@@ -0,0 +1,110 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Open a file with specified compression.
15
+ """
16
+
17
+ import bz2
18
+ import gzip
19
+ import lzma
20
+
21
+ import lz4.frame
22
+ import zstandard as zstd
23
+
24
+ from sedpack.io.types import CompressionT
25
+
26
+
27
+ class CompressedFile:
28
+ """Provide an easy open function for dealing with compressed files.
29
+ """
30
+
31
+ def __init__(self, compression_type: CompressionT) -> None:
32
+ """Initialize a compressed file opening.
33
+
34
+ compression_type (CompressionT): The type of compression. Note that ZIP
35
+ is not supported yet.
36
+ """
37
+ self.compression_type: CompressionT = compression_type
38
+
39
+ if compression_type in ["ZIP"]:
40
+ # Zip is a container meaning we open something.zip and inside that
41
+ # we open file(-s). This requires more work on the context manager
42
+ # side. Not implementing yet.
43
+ raise NotImplementedError(f"Compression {compression_type} is not "
44
+ f"supported yet by CompressedFile")
45
+
46
+ @staticmethod
47
+ def supported_compressions() -> list[CompressionT]:
48
+ """Return a list of supported compression types.
49
+ """
50
+ return [
51
+ "",
52
+ "BZ2",
53
+ "GZIP",
54
+ "LZMA",
55
+ "LZ4",
56
+ "ZLIB",
57
+ "ZSTD",
58
+ ]
59
+
60
+ def compress(self, data: bytes) -> bytes:
61
+ """Compression.
62
+
63
+ Args:
64
+
65
+ data (bytes): Content to compress.
66
+
67
+ Returns: the compressed data.
68
+ """
69
+ match self.compression_type:
70
+ case "":
71
+ return data
72
+ case "GZIP" | "ZLIB":
73
+ return gzip.compress(data, compresslevel=9)
74
+ case "BZ2":
75
+ return bz2.compress(data, compresslevel=9)
76
+ case "LZMA":
77
+ return lzma.compress(data)
78
+ case "LZ4":
79
+ return lz4.frame.compress(data) # type: ignore[no-any-return]
80
+ case "ZSTD":
81
+ return zstd.compress(data)
82
+ case _:
83
+ raise NotImplementedError(f"CompressedFile does not implement "
84
+ f"{self.compression_type} yet.")
85
+
86
+ def decompress(self, data: bytes) -> bytes:
87
+ """Decompression.
88
+
89
+ Args:
90
+
91
+ data (bytes): Content of the file to be decompressed.
92
+
93
+ Returns: the decompressed data.
94
+ """
95
+ match self.compression_type:
96
+ case "":
97
+ return data
98
+ case "GZIP" | "ZLIB":
99
+ return gzip.decompress(data)
100
+ case "BZ2":
101
+ return bz2.decompress(data)
102
+ case "LZMA":
103
+ return lzma.decompress(data)
104
+ case "LZ4":
105
+ return lz4.frame.decompress(data) # type: ignore[no-any-return]
106
+ case "ZSTD":
107
+ return zstd.decompress(data)
108
+ case _:
109
+ raise NotImplementedError(f"CompressedFile does not implement "
110
+ f"{self.compression_type} yet.")
sedpack/io/dataset.py ADDED
@@ -0,0 +1,104 @@
1
+ # Copyright 2023-2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Build and load tensorFlow dataset Record wrapper"""
15
+
16
+ from pathlib import Path
17
+ from typing import Union
18
+
19
+ from sedpack.io.dataset_base import DatasetBase
20
+ from sedpack.io.dataset_iteration import DatasetIteration
21
+ from sedpack.io.dataset_writing import DatasetWriting
22
+ from sedpack.io.errors import DatasetExistsError
23
+ from sedpack.io.metadata import DatasetInfo, DatasetStructure, Metadata
24
+
25
+
26
+ class Dataset(
27
+ DatasetIteration,
28
+ DatasetWriting,
29
+ ):
30
+ """Dataset class."""
31
+
32
+ def __init__(self,
33
+ path: Union[str, Path],
34
+ create_dataset: bool = False) -> None:
35
+ """Class for saving and loading a database.
36
+
37
+ Args:
38
+
39
+ path (Union[str, Path]): Path from where to load the dataset (a
40
+ directory -- for instance
41
+ "/home/user_name/datasets/my_awesome_dataset").
42
+
43
+ create_dataset (bool): Are we creating a new dataset? Defaults to
44
+ False which is used when (down-)loading a dataset.
45
+
46
+ Raises:
47
+
48
+ ValueError if the dataset was created using a newer version of the
49
+ sedpack than the one trying to load it. See
50
+ sedpack.__version__ docstring.
51
+
52
+ FileNotFoundError if `create_dataset` is False and the
53
+ `dataset_info.json` file does not exist.
54
+ """
55
+ dataset_info: DatasetInfo
56
+ if create_dataset:
57
+ # Default DatasetInfo.
58
+ dataset_info = DatasetInfo()
59
+ else:
60
+ # Load the information.
61
+ dataset_info = DatasetBase._load(Path(path))
62
+
63
+ super().__init__(path=path, dataset_info=dataset_info)
64
+
65
+ @staticmethod
66
+ def create(
67
+ path: Union[str, Path],
68
+ metadata: Metadata,
69
+ dataset_structure: DatasetStructure,
70
+ ) -> "Dataset":
71
+ """Create an empty dataset to be filled using the `filler` or
72
+ `write_multiprocessing` API.
73
+
74
+ Args:
75
+
76
+ path (Union[str, Path]): Path where the dataset gets saved (a
77
+ directory -- for instance
78
+ "/home/user_name/datasets/my_awesome_dataset").
79
+
80
+ metadata (Metadata): Information about this dataset.
81
+
82
+ dataset_structure (DatasetStructure): Structure of saved records.
83
+
84
+ Raises: DatasetExistsError if creating this object would overwrite the
85
+ corresponding config file.
86
+ """
87
+ # Create a new object.
88
+ dataset = Dataset(path=Path(path), create_dataset=True)
89
+
90
+ # Do not overwrite an existing dataset.
91
+ if Dataset._get_config_path(dataset.path).is_file():
92
+ # Raise if the dataset already exists.
93
+ raise DatasetExistsError(dataset.path)
94
+
95
+ # Create a new dataset directory if needed.
96
+ dataset.path.mkdir(parents=True, exist_ok=True)
97
+
98
+ # Fill metadata and structure parameters.
99
+ dataset.metadata = metadata
100
+ dataset.dataset_structure = dataset_structure
101
+
102
+ # Write empty config.
103
+ dataset.write_config(updated_infos=[])
104
+ return dataset
@@ -0,0 +1,165 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Base class for a dataset."""
15
+ import logging
16
+ from pathlib import Path
17
+ import semver
18
+
19
+ from typing import Iterator, Union
20
+
21
+ import sedpack
22
+ from sedpack.io.shard_file_metadata import ShardInfo, ShardsList, ShardListInfo
23
+ from sedpack.io.types import SplitT
24
+ from sedpack.io.metadata import DatasetInfo, DatasetStructure, Metadata
25
+
26
+
27
+ class DatasetBase:
28
+ """Base class for the dataset. Holds information and allows iteration over
29
+ ShardInfo.
30
+ """
31
+
32
+ def __init__(self, path: Union[str, Path],
33
+ dataset_info: DatasetInfo) -> None:
34
+ """Initialize the data.
35
+
36
+ Args:
37
+
38
+ path (Union[str, Path]): Path from where to load the dataset (a
39
+ directory -- for instance
40
+ "/home/user_name/datasets/my_awesome_dataset").
41
+ """
42
+ # Ensure pathlib Path.
43
+ self.path: Path = Path(path)
44
+ try:
45
+ # Expand user directory.
46
+ self.path = self.path.expanduser()
47
+ except RuntimeError:
48
+ # Expansion failed we assume that the path was not supposed to be
49
+ # expanded.
50
+ pass
51
+ # Resolve the dataset root path to avoid problems when checking if
52
+ # another path is relative to it.
53
+ self.path = self.path.resolve()
54
+
55
+ # Default DatasetInfo.
56
+ self._dataset_info = dataset_info
57
+
58
+ self._logger = logging.getLogger("sedpack.io.Dataset")
59
+
60
+ @staticmethod
61
+ def _load(path: Path) -> DatasetInfo:
62
+ """Load a dataset from a config file.
63
+
64
+ Args:
65
+
66
+ path (Path): The path to the dataset.
67
+
68
+ Raises:
69
+
70
+ ValueError if the dataset was created using a newer version of the
71
+ sedpack than the one trying to load it. See
72
+ sedpack.__version__ docstring.
73
+
74
+ FileNotFoundError if the `dataset_info.json` file does not exist.
75
+
76
+ Returns: A DatasetInfo object representing the dataset metadata.
77
+ """
78
+ dataset_info = DatasetInfo.model_validate_json(
79
+ DatasetBase._get_config_path(path).read_text(encoding="utf-8"))
80
+
81
+ # Check that the library version (version of this software) is not
82
+ # lower than what was used to capture the dataset.
83
+ if semver.Version.parse(dataset_info.metadata.sedpack_version).compare(
84
+ sedpack.__version__) > 0:
85
+ raise ValueError(f"Dataset-lib module is outdated, "
86
+ f"sedpack_version: {sedpack.__version__}, "
87
+ f"but dataset was created using: "
88
+ f"{dataset_info.metadata.sedpack_version}")
89
+
90
+ return dataset_info
91
+
92
+ @staticmethod
93
+ def _get_config_path(path: Path, relative: bool = False) -> Path:
94
+ """Get the dataset config path.
95
+
96
+ Args:
97
+
98
+ path (Path): The dataset path.
99
+
100
+ relative (bool): Return only relative to `path`. Defaults to False.
101
+
102
+ Returns: A path to the config.
103
+ """
104
+ relative_path: Path = Path("dataset_info.json")
105
+ if relative:
106
+ return relative_path
107
+ return path / relative_path
108
+
109
+ @property
110
+ def metadata(self) -> Metadata:
111
+ """Return the metadata of this dataset.
112
+ """
113
+ return self._dataset_info.metadata
114
+
115
+ @metadata.setter
116
+ def metadata(self, value: Metadata) -> None:
117
+ """Set the metadata of this dataset.
118
+ """
119
+ self._dataset_info.metadata = value
120
+
121
+ @property
122
+ def dataset_structure(self) -> DatasetStructure:
123
+ """Return the structure of this dataset.
124
+ """
125
+ return self._dataset_info.dataset_structure
126
+
127
+ @dataset_structure.setter
128
+ def dataset_structure(self, value: DatasetStructure) -> None:
129
+ self._dataset_info.dataset_structure = value
130
+
131
+ def _shard_info_iterator(
132
+ self, shard_list_info: ShardListInfo) -> Iterator[ShardInfo]:
133
+ """Recursively yield `ShardInfo` from the whole directory tree.
134
+ """
135
+ shard_list: ShardsList = ShardsList.model_validate_json(
136
+ (self.path /
137
+ shard_list_info.shard_list_info_file.file_path).read_text())
138
+
139
+ yield from shard_list.shard_files
140
+
141
+ for child in shard_list.children_shard_lists:
142
+ yield from self._shard_info_iterator(child)
143
+
144
+ def shard_info_iterator(self, split: SplitT | None) -> Iterator[ShardInfo]:
145
+ """Iterate all `ShardInfo` in the split.
146
+
147
+ Args:
148
+
149
+ split (SplitT | None): Which split to iterate shard information from.
150
+ If None then all splits are iterated.
151
+
152
+ Raises: ValueError when the split is not present. A split not being
153
+ present is different from there not being any shard.
154
+ """
155
+ if split:
156
+ if split not in self._dataset_info.splits:
157
+ # Split not present.
158
+ raise ValueError(f"There is no shard in {split}.")
159
+
160
+ shard_list_info: ShardListInfo = self._dataset_info.splits[split]
161
+
162
+ yield from self._shard_info_iterator(shard_list_info)
163
+ else:
164
+ for shard_list_info in self._dataset_info.splits.values():
165
+ yield from self._shard_info_iterator(shard_list_info)