sedpack 0.2.1__cp315-cp315-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 (56) hide show
  1. sedpack/__init__.py +33 -0
  2. sedpack/_sedpack_rs.cp315-win_amd64.pyd +0 -0
  3. sedpack/io/__init__.py +29 -0
  4. sedpack/io/compress.py +110 -0
  5. sedpack/io/dataset.py +106 -0
  6. sedpack/io/dataset_base.py +159 -0
  7. sedpack/io/dataset_filler.py +373 -0
  8. sedpack/io/dataset_iteration.py +657 -0
  9. sedpack/io/dataset_iteration_tf.py +242 -0
  10. sedpack/io/dataset_writing.py +315 -0
  11. sedpack/io/errors.py +36 -0
  12. sedpack/io/file_info.py +197 -0
  13. sedpack/io/flatbuffer/__init__.py +20 -0
  14. sedpack/io/flatbuffer/iterate.py +236 -0
  15. sedpack/io/flatbuffer/shard.fbs +23 -0
  16. sedpack/io/flatbuffer/shardfile/Attribute.py +114 -0
  17. sedpack/io/flatbuffer/shardfile/Example.py +105 -0
  18. sedpack/io/flatbuffer/shardfile/Shard.py +117 -0
  19. sedpack/io/flatbuffer/shardfile/__init__.py +0 -0
  20. sedpack/io/flatbuffer/unit_tests/shard_writer_flatbuffer_test_schema/NumPyVectorTest.py +582 -0
  21. sedpack/io/flatbuffer/unit_tests/shard_writer_flatbuffer_test_schema/__init__.py +0 -0
  22. sedpack/io/flatbuffer/unit_tests/shard_writer_flatbuffer_test_schema.fbs +34 -0
  23. sedpack/io/iteration/__init__.py +22 -0
  24. sedpack/io/iteration/rust_batched_generator.py +190 -0
  25. sedpack/io/iteration/rust_generator.py +231 -0
  26. sedpack/io/itertools/__init__.py +27 -0
  27. sedpack/io/itertools/itertools.py +228 -0
  28. sedpack/io/itertools/lazy_pool.py +219 -0
  29. sedpack/io/merge_shard_infos.py +117 -0
  30. sedpack/io/metadata.py +171 -0
  31. sedpack/io/npz/__init__.py +20 -0
  32. sedpack/io/npz/iterate_npz.py +195 -0
  33. sedpack/io/shard/__init__.py +22 -0
  34. sedpack/io/shard/get_shard_writer.py +41 -0
  35. sedpack/io/shard/iterate_shard_base.py +70 -0
  36. sedpack/io/shard/shard.py +84 -0
  37. sedpack/io/shard/shard_writer_base.py +100 -0
  38. sedpack/io/shard/shard_writer_flatbuffer.py +314 -0
  39. sedpack/io/shard/shard_writer_np.py +169 -0
  40. sedpack/io/shard/shard_writer_tfrec.py +97 -0
  41. sedpack/io/shard_file_metadata.py +200 -0
  42. sedpack/io/shard_info_iterator/__init__.py +22 -0
  43. sedpack/io/shard_info_iterator/balanced_iterator.py +280 -0
  44. sedpack/io/shard_info_iterator/cached_shard_info_iterator.py +166 -0
  45. sedpack/io/shard_info_iterator/shard_info_iterator.py +109 -0
  46. sedpack/io/tfrec/__init__.py +20 -0
  47. sedpack/io/tfrec/read.py +101 -0
  48. sedpack/io/tfrec/tfdata.py +187 -0
  49. sedpack/io/types.py +92 -0
  50. sedpack/io/utils.py +199 -0
  51. sedpack/py.typed +0 -0
  52. sedpack-0.2.1.dist-info/METADATA +118 -0
  53. sedpack-0.2.1.dist-info/RECORD +56 -0
  54. sedpack-0.2.1.dist-info/WHEEL +4 -0
  55. sedpack-0.2.1.dist-info/licenses/LICENSE +202 -0
  56. sedpack-0.2.1.dist-info/sboms/sedpack_rs.cyclonedx.json +4759 -0
sedpack/__init__.py ADDED
@@ -0,0 +1,33 @@
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
+ Version format: MAJOR.MINOR.PATCH (see https://pypi.org/project/semver/ for
17
+ more possibilities).
18
+ """
19
+
20
+ from importlib.metadata import version, PackageNotFoundError
21
+
22
+ # The version of this package is defined by rust/Cargo.toml and dynamically
23
+ # deduced by Maturin (see
24
+ # https://www.maturin.rs/metadata.html#dynamic-metadata). To ensure
25
+ # compatibility with existing code we dynamically set the __version__ attribute
26
+ # here.
27
+ try:
28
+ # When package is installed use the version.
29
+ __version__ = version("sedpack") # pylint: disable=invalid-name
30
+ except PackageNotFoundError:
31
+ # Package is not installed. The Rust part of this package is probably not
32
+ # going to work in this case (the Rust binding would be probably missing).
33
+ __version__ = "0.0.7-dev" # pylint: disable=invalid-name
Binary file
sedpack/io/__init__.py ADDED
@@ -0,0 +1,29 @@
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, DatasetFillerContext
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
+ "DatasetFillerContext",
27
+ "DatasetStructure",
28
+ "Metadata",
29
+ ]
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,106 @@
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_iteration_tf import DatasetIterationTF
22
+ from sedpack.io.dataset_writing import DatasetWriting
23
+ from sedpack.io.errors import DatasetExistsError
24
+ from sedpack.io.metadata import DatasetInfo, DatasetStructure, Metadata
25
+
26
+
27
+ class Dataset(
28
+ DatasetIteration,
29
+ DatasetIterationTF,
30
+ DatasetWriting,
31
+ ):
32
+ """Dataset class."""
33
+
34
+ def __init__(self,
35
+ path: Union[str, Path],
36
+ create_dataset: bool = False) -> None:
37
+ """Class for saving and loading a database.
38
+
39
+ Args:
40
+
41
+ path (Union[str, Path]): Path from where to load the dataset (a
42
+ directory -- for instance
43
+ "/home/user_name/datasets/my_awesome_dataset").
44
+
45
+ create_dataset (bool): Are we creating a new dataset? Defaults to
46
+ False which is used when (down-)loading a dataset.
47
+
48
+ Raises:
49
+
50
+ ValueError if the dataset was created using a newer version of the
51
+ sedpack than the one trying to load it. See
52
+ sedpack.__version__ docstring.
53
+
54
+ FileNotFoundError if `create_dataset` is False and the
55
+ `dataset_info.json` file does not exist.
56
+ """
57
+ dataset_info: DatasetInfo
58
+ if create_dataset:
59
+ # Default DatasetInfo.
60
+ dataset_info = DatasetInfo()
61
+ else:
62
+ # Load the information.
63
+ dataset_info = DatasetBase._load(Path(path))
64
+
65
+ super().__init__(path=path, dataset_info=dataset_info)
66
+
67
+ @staticmethod
68
+ def create(
69
+ path: Union[str, Path],
70
+ metadata: Metadata,
71
+ dataset_structure: DatasetStructure,
72
+ ) -> "Dataset":
73
+ """Create an empty dataset to be filled using the `filler` or
74
+ `write_multiprocessing` API.
75
+
76
+ Args:
77
+
78
+ path (Union[str, Path]): Path where the dataset gets saved (a
79
+ directory -- for instance
80
+ "/home/user_name/datasets/my_awesome_dataset").
81
+
82
+ metadata (Metadata): Information about this dataset.
83
+
84
+ dataset_structure (DatasetStructure): Structure of saved records.
85
+
86
+ Raises: DatasetExistsError if creating this object would overwrite the
87
+ corresponding config file.
88
+ """
89
+ # Create a new object.
90
+ dataset = Dataset(path=Path(path), create_dataset=True)
91
+
92
+ # Do not overwrite an existing dataset.
93
+ if Dataset._get_config_path(dataset.path).is_file():
94
+ # Raise if the dataset already exists.
95
+ raise DatasetExistsError(dataset.path)
96
+
97
+ # Create a new dataset directory if needed.
98
+ dataset.path.mkdir(parents=True, exist_ok=True)
99
+
100
+ # Fill metadata and structure parameters.
101
+ dataset.metadata = metadata
102
+ dataset.dataset_structure = dataset_structure
103
+
104
+ # Write empty config.
105
+ dataset.write_config(updated_infos=[])
106
+ return dataset
@@ -0,0 +1,159 @@
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.metadata import DatasetInfo, DatasetStructure, Metadata
23
+ from sedpack.io.shard_file_metadata import ShardInfo
24
+ from sedpack.io.shard_info_iterator import ShardInfoIterator
25
+ from sedpack.io.types import SplitT
26
+
27
+
28
+ class DatasetBase:
29
+ """Base class for the dataset. Holds information and allows iteration over
30
+ ShardInfo.
31
+ """
32
+
33
+ def __init__(self, path: Union[str, Path],
34
+ dataset_info: DatasetInfo) -> None:
35
+ """Initialize the data.
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
+ # Ensure pathlib Path.
44
+ self.path: Path = Path(path)
45
+ try:
46
+ # Expand user directory.
47
+ self.path = self.path.expanduser()
48
+ except RuntimeError:
49
+ # Expansion failed we assume that the path was not supposed to be
50
+ # expanded.
51
+ pass
52
+ # Resolve the dataset root path to avoid problems when checking if
53
+ # another path is relative to it.
54
+ self.path = self.path.resolve()
55
+
56
+ # Default DatasetInfo.
57
+ self._dataset_info = dataset_info
58
+
59
+ self._logger = logging.getLogger("sedpack.io.Dataset")
60
+
61
+ @staticmethod
62
+ def _load(path: Path) -> DatasetInfo:
63
+ """Load a dataset from a config file.
64
+
65
+ Args:
66
+
67
+ path (Path): The path to the dataset.
68
+
69
+ Raises:
70
+
71
+ ValueError if the dataset was created using a newer version of the
72
+ sedpack than the one trying to load it. See
73
+ sedpack.__version__ docstring.
74
+
75
+ FileNotFoundError if the `dataset_info.json` file does not exist.
76
+
77
+ Returns: A DatasetInfo object representing the dataset metadata.
78
+ """
79
+ dataset_info = DatasetInfo.model_validate_json(
80
+ DatasetBase._get_config_path(path).read_text(encoding="utf-8"))
81
+
82
+ # Check that the library version (version of this software) is not
83
+ # lower than what was used to capture the dataset.
84
+ if semver.Version.parse(dataset_info.metadata.sedpack_version).compare(
85
+ sedpack.__version__) > 0:
86
+ raise ValueError(f"Dataset-lib module is outdated, "
87
+ f"sedpack_version: {sedpack.__version__}, "
88
+ f"but dataset was created using: "
89
+ f"{dataset_info.metadata.sedpack_version}")
90
+
91
+ return dataset_info
92
+
93
+ @staticmethod
94
+ def _get_config_path(path: Path, relative: bool = False) -> Path:
95
+ """Get the dataset config path.
96
+
97
+ Args:
98
+
99
+ path (Path): The dataset path.
100
+
101
+ relative (bool): Return only relative to `path`. Defaults to False.
102
+
103
+ Returns: A path to the config.
104
+ """
105
+ relative_path: Path = Path("dataset_info.json")
106
+ if relative:
107
+ return relative_path
108
+ return path / relative_path
109
+
110
+ @property
111
+ def metadata(self) -> Metadata:
112
+ """Return the metadata of this dataset.
113
+ """
114
+ return self._dataset_info.metadata
115
+
116
+ @metadata.setter
117
+ def metadata(self, value: Metadata) -> None:
118
+ """Set the metadata of this dataset.
119
+ """
120
+ self._dataset_info.metadata = value
121
+
122
+ @property
123
+ def dataset_info(self) -> DatasetInfo:
124
+ """Get the dataset information.
125
+ """
126
+ return self._dataset_info
127
+
128
+ @property
129
+ def dataset_structure(self) -> DatasetStructure:
130
+ """Return the structure of this dataset.
131
+ """
132
+ return self._dataset_info.dataset_structure
133
+
134
+ @dataset_structure.setter
135
+ def dataset_structure(self, value: DatasetStructure) -> None:
136
+ self._dataset_info.dataset_structure = value
137
+
138
+ def shard_info_iterator(self, split: SplitT | None) -> Iterator[ShardInfo]:
139
+ """Iterate all `ShardInfo` in the split.
140
+
141
+ Args:
142
+
143
+ split (SplitT | None): Which split to iterate shard information from.
144
+ If None then all splits are iterated.
145
+
146
+ Raises: ValueError when the split is not present. A split not being
147
+ present is different from there not being any shard.
148
+ """
149
+ if split:
150
+ if split not in self._dataset_info.splits:
151
+ # Split not present.
152
+ raise ValueError(f"There is no shard in {split}.")
153
+
154
+ return ShardInfoIterator(
155
+ dataset_path=self.path,
156
+ dataset_info=self.dataset_info,
157
+ split=split,
158
+ repeat=False,
159
+ )