-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathdataset_builder.py
1975 lines (1716 loc) · 73.9 KB
/
dataset_builder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2024 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DatasetBuilder base class."""
from __future__ import annotations
import abc
import collections
from collections.abc import Sequence
import dataclasses
import functools
import inspect
import json
import os
import sys
from typing import Any, ClassVar, Dict, Iterable, Iterator, List, Optional, Tuple, Type, Union
from absl import logging
from etils import epy
from tensorflow_datasets.core.utils.lazy_imports_utils import apache_beam as beam
from tensorflow_datasets.core.utils.lazy_imports_utils import tensorflow as tf
from tensorflow_datasets.core.utils.lazy_imports_utils import tree
with epy.lazy_imports():
# pylint: disable=g-import-not-at-top
from etils import epath
import importlib_resources
import termcolor
from tensorflow_datasets.core import constants
from tensorflow_datasets.core import dataset_info
from tensorflow_datasets.core import dataset_metadata
from tensorflow_datasets.core import decode
from tensorflow_datasets.core import download
from tensorflow_datasets.core import file_adapters
from tensorflow_datasets.core import lazy_imports_lib
from tensorflow_datasets.core import logging as tfds_logging
from tensorflow_datasets.core import naming
from tensorflow_datasets.core import reader as reader_lib
from tensorflow_datasets.core import registered
from tensorflow_datasets.core import split_builder as split_builder_lib
from tensorflow_datasets.core import splits as splits_lib
from tensorflow_datasets.core import tf_compat
from tensorflow_datasets.core import units
from tensorflow_datasets.core import utils
from tensorflow_datasets.core import writer as writer_lib
from tensorflow_datasets.core.data_sources import array_record
from tensorflow_datasets.core.data_sources import parquet
from tensorflow_datasets.core.proto import dataset_info_pb2
from tensorflow_datasets.core.utils import file_utils
from tensorflow_datasets.core.utils import gcs_utils
from tensorflow_datasets.core.utils import read_config as read_config_lib
from tensorflow_datasets.core.utils import type_utils
# pylint: enable=g-import-not-at-top
ListOrTreeOrElem = type_utils.ListOrTreeOrElem
Tree = type_utils.Tree
TreeDict = type_utils.TreeDict
VersionOrStr = Union[utils.Version, str]
FORCE_REDOWNLOAD = download.GenerateMode.FORCE_REDOWNLOAD
REUSE_CACHE_IF_EXISTS = download.GenerateMode.REUSE_CACHE_IF_EXISTS
REUSE_DATASET_IF_EXISTS = download.GenerateMode.REUSE_DATASET_IF_EXISTS
UPDATE_DATASET_INFO = download.GenerateMode.UPDATE_DATASET_INFO
GCS_HOSTED_MSG = """\
Dataset %s is hosted on GCS. It will automatically be downloaded to your
local data directory. If you'd instead prefer to read directly from our public
GCS bucket (recommended if you're running on GCP), you can instead pass
`try_gcs=True` to `tfds.load` or set `data_dir=gs://tfds-data/datasets`.
"""
@dataclasses.dataclass(eq=False)
class BuilderConfig:
"""Base class for `DatasetBuilder` data configuration.
DatasetBuilder subclasses with data configuration options should subclass
`BuilderConfig` and add their own properties.
Attributes:
name: The name of the config.
version: The version of the config.
release_notes: A dictionary associating versions to changes.
supported_versions: A list of versions which this Builder Config supports.
description: a human description of the config.
tags: [Experimental] a list of freeform tags applying to the config. This is
not used by TFDS, but can be retrieved later from a ConfigBuilder
instance.
"""
# TODO(py3.10): Should update dataclass to be:
# * Frozen (https://bugs.python.org/issue32953)
# * Kwargs-only (https://bugs.python.org/issue33129)
name: str
version: VersionOrStr | None = None
release_notes: Dict[str, str] | None = None
supported_versions: list[VersionOrStr] = dataclasses.field(
default_factory=list
)
description: str | None = None
tags: list[str] = dataclasses.field(default_factory=list)
@classmethod
def from_dataset_info(
cls,
info_proto: dataset_info_pb2.DatasetInfo,
) -> BuilderConfig | None:
"""Instantiates a BuilderConfig from the given proto.
Args:
info_proto: DatasetInfo proto which documents the requested dataset
config, including its name, version, and features.
Returns:
A BuilderConfig for the requested config.
"""
if not info_proto.config_name:
return None
return BuilderConfig(
name=info_proto.config_name,
description=info_proto.config_description,
version=info_proto.version,
release_notes=info_proto.release_notes or {},
tags=info_proto.config_tags or [],
)
def _get_builder_datadir_path(builder_cls: Type[Any]) -> epath.Path:
"""Returns the path to ConfigBuilder data dir.
Args:
builder_cls: a Builder class.
Returns:
The path to directory where the config data files of `builders_cls` can be
read from. e.g. "/usr/lib/[...]/tensorflow_datasets/datasets/foo".
"""
pkg_names = builder_cls.__module__.split(".")
# -1 to remove the xxx.py python file.
return epath.resource_path(pkg_names[0]).joinpath(*pkg_names[1:-1])
class DatasetBuilder(registered.RegisteredDataset):
"""Abstract base class for all datasets.
`DatasetBuilder` has 3 key methods:
* `DatasetBuilder.info`: documents the dataset, including feature
names, types, and shapes, version, splits, citation, etc.
* `DatasetBuilder.download_and_prepare`: downloads the source data
and writes it to disk.
* `DatasetBuilder.as_dataset`: builds an input pipeline using
`tf.data.Dataset`s.
**Configuration**: Some `DatasetBuilder`s expose multiple variants of the
dataset by defining a `tfds.core.BuilderConfig` subclass and accepting a
config object (or name) on construction. Configurable datasets expose a
pre-defined set of configurations in `DatasetBuilder.builder_configs`.
Typical `DatasetBuilder` usage:
```python
mnist_builder = tfds.builder("mnist")
mnist_info = mnist_builder.info
mnist_builder.download_and_prepare()
datasets = mnist_builder.as_dataset()
train_dataset, test_dataset = datasets["train"], datasets["test"]
assert isinstance(train_dataset, tf.data.Dataset)
# And then the rest of your input pipeline
train_dataset = train_dataset.repeat().shuffle(1024).batch(128)
train_dataset = train_dataset.prefetch(2)
features = tf.compat.v1.data.make_one_shot_iterator(train_dataset).get_next()
image, label = features['image'], features['label']
```
"""
# Semantic version of the dataset (ex: tfds.core.Version('1.2.0'))
VERSION: Optional[utils.Version] = None
# Release notes
# Metadata only used for documentation. Should be a dict[version,description]
# Multi-lines are automatically dedent
RELEASE_NOTES: ClassVar[Dict[str, str]] = {}
# List dataset versions which can be loaded using current code.
# Data can only be prepared with canonical VERSION or above.
SUPPORTED_VERSIONS: list[utils.Version] = []
# Named configurations that modify the data generated by download_and_prepare.
BUILDER_CONFIGS = []
# Name of the builder config that should be used in case the user doesn't
# specify a config when loading a dataset. If None, then the first config in
# `BUILDER_CONFIGS` is used.
DEFAULT_BUILDER_CONFIG_NAME: Optional[str] = None
# Must be set for datasets that use 'manual_dir' functionality - the ones
# that require users to do additional steps to download the data
# (this is usually due to some external regulations / rules).
#
# This field should contain a string with user instructions, including
# the list of files that should be present. It will be
# displayed in the dataset documentation.
MANUAL_DOWNLOAD_INSTRUCTIONS = None
# Optional max number of simultaneous downloads. Setting this value will
# override download config settings if necessary.
MAX_SIMULTANEOUS_DOWNLOADS: Optional[int] = None
# If not set, pkg_dir_path is inferred. However, if user of class knows better
# then this can be set directly before init, to avoid heuristic inferences.
# Example: `imported_builder_cls` function in `registered.py` module sets it.
pkg_dir_path: Optional[epath.Path] = None
# Holds information on versions and configs that should not be used.
BLOCKED_VERSIONS: ClassVar[Optional[utils.BlockedVersions]] = None
@classmethod
def _get_pkg_dir_path(cls) -> epath.Path:
"""Returns class pkg_dir_path, infer it first if not set."""
# We use cls.__dict__.get to check whether `pkg_dir_path` attribute has been
# set on the class, and not on a parent class. If we were accessing the
# attribute directly, a dataset Builder inheriting from another would read
# its metadata from its parent directory (which would be wrong).
if cls.pkg_dir_path is None:
cls.pkg_dir_path = _get_builder_datadir_path(cls)
return cls.pkg_dir_path
@classmethod
def get_metadata(cls) -> dataset_metadata.DatasetMetadata:
"""Returns metadata (README, CITATIONS, ...) specified in config files.
The config files are read from the same package where the DatasetBuilder has
been defined, so those metadata might be wrong for legacy builders.
"""
return dataset_metadata.load(cls._get_pkg_dir_path())
@tfds_logging.builder_init()
def __init__(
self,
*,
data_dir: epath.PathLike | None = None,
config: None | str | BuilderConfig = None,
version: None | str | utils.Version = None,
**kwargs,
):
"""Constructs a DatasetBuilder.
Callers must pass arguments as keyword arguments.
Args:
data_dir: directory to read/write data. Defaults to the value of the
environment variable TFDS_DATA_DIR, if set, otherwise falls back to
"~/tensorflow_datasets".
config: `tfds.core.BuilderConfig` or `str` name, optional configuration
for the dataset that affects the data generated on disk. Different
`builder_config`s will have their own subdirectories and versions.
version: Optional version at which to load the dataset. An error is raised
if specified version cannot be satisfied. Eg: '1.2.3', '1.2.*'. The
special value "experimental_latest" will use the highest version, even
if not default. This is not recommended unless you know what you are
doing, as the version could be broken.
""" # fmt: skip
if data_dir:
data_dir = os.fspath(data_dir) # Pathlib -> str
# For pickling:
self._original_state = dict(
data_dir=data_dir, config=config, version=version
)
# To do the work:
self._builder_config = self._create_builder_config(config, version=version)
# Extract code version (VERSION or config)
self._version = self._pick_version(version)
# Compute the base directory (for download) and dataset/version directory.
self._data_dir_root, self._data_dir = self._build_data_dir(data_dir)
# If the dataset info is available, use it.
if dataset_info.dataset_info_path(self.data_path).exists():
self.info.read_from_directory(self._data_dir)
else: # Use the code version (do not restore data)
self.info.initialize_from_bucket()
@utils.classproperty
@classmethod
@utils.memoize()
def code_path(cls) -> Optional[epath.Path]:
"""Returns the path to the file where the Dataset class is located.
Note: As the code can be run inside zip file. The returned value is
a `Path` by default. Use `tfds.core.utils.to_write_path()` to cast
the path into `Path`.
Returns:
path: pathlib.Path like abstraction
"""
modules = cls.__module__.split(".")
if len(modules) >= 2: # Filter `__main__`, `python my_dataset.py`,...
# If the dataset can be loaded from a module, use this to support zipapp.
# Note: `utils.resource_path` will return either `zipfile.Path` (for
# zipapp) or `pathlib.Path`.
try:
path = epath.resource_path(modules[0])
except TypeError: # Module is not a package
pass
else:
# For dynamically added modules, `importlib.resources` returns
# `pathlib.Path('.')` rather than the real path, so filter those by
# checking for `parts`.
# Check for `zipfile.Path` (`ResourcePath`) or
# `importlib_resources.abc.Traversable` (e.g. `MultiplexedPath`) as they
# do not have `.parts`.
if (
isinstance(path, epath.resource_utils.ResourcePath)
or isinstance(path, importlib_resources.abc.Traversable)
or path.parts
):
modules[-1] += ".py"
return path.joinpath(*modules[1:])
# Otherwise, fallback to `pathlib.Path`. For non-zipapp, it should be
# equivalent to the above return.
try:
filepath = inspect.getfile(cls)
except (TypeError, OSError): # Module is not a package
# Could happen when the class is defined in Colab.
return None
else:
return epath.Path(filepath)
def __getstate__(self):
return self._original_state
def __setstate__(self, state):
self.__init__(**state)
@functools.cached_property
def canonical_version(self) -> utils.Version:
return canonical_version_for_config(self, self._builder_config)
@functools.cached_property
def supported_versions(self):
if self._builder_config and self._builder_config.supported_versions:
return self._builder_config.supported_versions
else:
return self.SUPPORTED_VERSIONS
@functools.cached_property
def versions(self) -> List[utils.Version]:
"""Versions (canonical + availables), in preference order."""
return [
utils.Version(v) if isinstance(v, str) else v
for v in [self.canonical_version] + self.supported_versions
]
def _pick_version(
self, requested_version: str | utils.Version | None
) -> utils.Version:
"""Returns utils.Version instance, or raise AssertionError."""
# Validate that `canonical_version` is correctly defined
assert self.canonical_version
# If requested_version is of type utils.Version, convert to its string
# representation. This is necessary to properly execute the equality check
# with "experimental_latest".
if isinstance(requested_version, utils.Version):
requested_version = str(requested_version)
if requested_version == "experimental_latest":
return max(self.versions)
for version in self.versions:
if requested_version is None or version.match(requested_version):
return version
available_versions = [str(v) for v in self.versions]
msg = "Dataset {} cannot be loaded at version {}, only: {}.".format(
self.name, requested_version, ", ".join(available_versions)
)
raise AssertionError(msg)
@property
def version(self) -> utils.Version:
return self._version
@property
def release_notes(self) -> Dict[str, str]:
if self.builder_config and self.builder_config.release_notes:
return self.builder_config.release_notes
else:
return self.RELEASE_NOTES
@property
def blocked_versions(self) -> utils.BlockedVersions | None:
return self.BLOCKED_VERSIONS
@property
def data_dir_root(self) -> epath.Path:
"""Returns the root directory where all TFDS datasets are stored.
Note that this is different from `data_dir`, which includes the dataset
name, config, and version. For example, if `data_dir` is
`/data/tfds/my_dataset/my_config/1.2.3`, then `data_dir_root` is
`/data/tfds`.
Returns:
the root directory where all TFDS datasets are stored.
"""
return epath.Path(self._data_dir_root)
@property
def data_dir(self) -> str:
"""Returns the directory where this version + config is stored.
Note that this is different from `data_dir_root`. For example, if
`data_dir_root` is `/data/tfds`, then `data_dir` would be
`/data/tfds/my_dataset/my_config/1.2.3`.
Returns:
the directory where this version + config is stored.
"""
return self._data_dir
@property
def data_path(self) -> epath.Path:
"""Returns the path where this version + config is stored."""
# Instead, should make `_data_dir` be Path everywhere
return epath.Path(self.data_dir)
@utils.classproperty
@classmethod
def _checksums_path(cls) -> Optional[epath.Path]:
"""Returns the checksums path."""
# Used:
# * To load the checksums (in url_infos)
# * To save the checksums (in DownloadManager)
if not cls.code_path:
return None
new_path = cls.code_path.parent / constants.CHECKSUMS_FILENAME
# Checksums of legacy datasets are located in a separate dir.
legacy_path = utils.tfds_path() / "url_checksums" / f"{cls.name}.txt"
if (
# zipfile.Path does not have `.parts`. Additionally, `os.fspath`
# will extract the file, so use `str`.
"tensorflow_datasets" in str(new_path)
and legacy_path.exists()
and not new_path.exists()
):
return legacy_path
else:
return new_path
@utils.classproperty
@classmethod
@functools.lru_cache(maxsize=None)
def url_infos(cls) -> Optional[Dict[str, download.checksums.UrlInfo]]:
"""Load `UrlInfo` from the given path."""
# Note: If the dataset is downloaded with `record_checksums=True`, urls
# might be updated but `url_infos` won't as it is memoized.
# Search for the url_info file.
checksums_path = cls._checksums_path
# If url_info file is found, load the urls
if checksums_path and checksums_path.exists():
return download.checksums.load_url_infos(checksums_path)
else:
return None
@property
@tfds_logging.builder_info()
# Warning: This unbounded cache is required for correctness. See b/238762111.
@functools.lru_cache(maxsize=None)
def info(self) -> dataset_info.DatasetInfo:
"""`tfds.core.DatasetInfo` for this builder."""
# Ensure .info hasn't been called before versioning is set-up
# Otherwise, backward compatibility cannot be guaranteed as some code will
# depend on the code version instead of the restored data version
if not getattr(self, "_version", None):
# Message for developers creating new dataset. Will trigger if they are
# using .info in the constructor before calling super().__init__
raise AssertionError(
"Info should not been called before version has been defined. "
"Otherwise, the created .info may not match the info version from "
"the restored dataset."
)
info = self._info()
if not isinstance(info, dataset_info.DatasetInfo):
raise TypeError(
"DatasetBuilder._info should returns `tfds.core.DatasetInfo`, not "
f" {type(info)}."
)
return info
@utils.classproperty
@classmethod
def default_builder_config(cls) -> Optional[BuilderConfig]:
return _get_default_config(
builder_configs=cls.BUILDER_CONFIGS,
default_config_name=cls.DEFAULT_BUILDER_CONFIG_NAME,
)
def get_default_builder_config(self) -> Optional[BuilderConfig]:
"""Returns the default builder config if there is one.
Note that for dataset builders that cannot use the `cls.BUILDER_CONFIGS`, we
need a method that uses the instance to get `BUILDER_CONFIGS` and
`DEFAULT_BUILDER_CONFIG_NAME`.
Returns:
the default builder config if there is one
"""
return _get_default_config(
builder_configs=self.BUILDER_CONFIGS,
default_config_name=self.DEFAULT_BUILDER_CONFIG_NAME,
)
def get_reference(
self,
namespace: Optional[str] = None,
) -> naming.DatasetReference:
"""Returns a reference to the dataset produced by this dataset builder.
Includes the config if specified, the version, and the data_dir that should
contain this dataset.
Arguments:
namespace: if this dataset is a community dataset, and therefore has a
namespace, then the namespace must be provided such that it can be set
in the reference. Note that a dataset builder is not aware that it is
part of a namespace.
Returns:
a reference to this instantiated builder.
"""
if self.builder_config:
config = self.builder_config.name
else:
config = None
return naming.DatasetReference(
dataset_name=self.name,
namespace=namespace,
config=config,
version=self.version,
data_dir=self.data_dir_root,
)
def get_file_spec(self, split: str) -> str:
"""Returns the file spec of the split."""
split_info: splits_lib.SplitInfo = self.info.splits[split]
return split_info.file_spec(self.info.file_format)
def is_prepared(self) -> bool:
"""Returns whether this dataset is already downloaded and prepared."""
return self.data_path.exists()
def is_blocked(self) -> utils.IsBlocked:
"""Returns whether this builder (version, config) is blocked."""
config_name = self.builder_config.name if self.builder_config else None
if blocked_versions := self.blocked_versions:
return blocked_versions.is_blocked(
version=self.version, config=config_name
)
return utils.IsBlocked(False)
def assert_is_not_blocked(self) -> None:
"""Checks that the dataset is not blocked."""
config_name = self.builder_config.name if self.builder_config else None
if blocked_versions := self.blocked_versions:
is_blocked = blocked_versions.is_blocked(
version=self.version, config=config_name
)
if is_blocked.result:
raise utils.DatasetVariantBlockedError(is_blocked.blocked_msg)
@tfds_logging.download_and_prepare()
def download_and_prepare(
self,
*,
download_dir: epath.PathLike | None = None,
download_config: download.DownloadConfig | None = None,
file_format: str | file_adapters.FileFormat | None = None,
permissions: file_utils.Permissions = file_utils.Permissions(mode=0o775),
) -> None:
"""Downloads and prepares dataset for reading.
Args:
download_dir: directory where downloaded files are stored. Defaults to
"~/tensorflow-datasets/downloads".
download_config: `tfds.download.DownloadConfig`, further configuration for
downloading and preparing dataset.
file_format: optional `str` or `file_adapters.FileFormat`, format of the
record files in which the dataset will be written.
permissions: permissions to set on the generated folder and files.
Defaults to 0o775 instead of gFile's default 0o750.
Raises:
IOError: if there is not enough disk space available.
RuntimeError: when the config cannot be found.
DatasetBlockedError: if the given version, or combination of version and
config, has been marked as blocked in the builder's BLOCKED_VERSIONS.
"""
self.assert_is_not_blocked()
download_config = download_config or download.DownloadConfig()
data_path = self.data_path
data_exists = data_path.exists()
if download_config.download_mode == UPDATE_DATASET_INFO:
self._update_dataset_info()
return
if data_exists and download_config.download_mode == REUSE_DATASET_IF_EXISTS:
logging.info("Reusing dataset %s (%s)", self.name, self.data_dir)
return
elif data_exists and download_config.download_mode == REUSE_CACHE_IF_EXISTS:
logging.info(
"Deleting pre-existing dataset %s (%s)", self.name, self.data_dir
)
data_path.rmtree() # Delete pre-existing data.
data_exists = data_path.exists()
if self.version.tfds_version_to_prepare:
available_to_prepare = ", ".join(
str(v) for v in self.versions if not v.tfds_version_to_prepare
)
raise AssertionError(
"The version of the dataset you are trying to use ({}:{}) can only "
"be generated using TFDS code synced @ {} or earlier. Either sync to "
"that version of TFDS to first prepare the data or use another "
"version of the dataset (available for `download_and_prepare`: "
"{}).".format(
self.name,
self.version,
self.version.tfds_version_to_prepare,
available_to_prepare,
)
)
# Only `cls.VERSION` or `experimental_latest` versions can be generated.
# Otherwise, users may accidentally generate an old version using the
# code from newer versions.
installable_versions = {
str(v) for v in (self.canonical_version, max(self.versions))
}
if str(self.version) not in installable_versions:
msg = (
"The version of the dataset you are trying to use ({}) is too "
"old for this version of TFDS so cannot be generated."
).format(self.info.full_name)
if self.version.tfds_version_to_prepare:
msg += (
"{} can only be generated using TFDS code synced @ {} or earlier "
"Either sync to that version of TFDS to first prepare the data or "
"use another version of the dataset. "
).format(self.version, self.version.tfds_version_to_prepare)
else:
msg += (
"Either sync to a previous version of TFDS to first prepare the "
"data or use another version of the dataset. "
)
msg += "Available for `download_and_prepare`: {}".format(
list(sorted(installable_versions))
)
raise ValueError(msg)
# Currently it's not possible to overwrite the data because it would
# conflict with versioning: If the last version has already been generated,
# it will always be reloaded and data_dir will be set at construction.
if data_exists:
raise ValueError(
"Trying to overwrite an existing dataset {} at {}. A dataset with "
"the same version {} already exists. If the dataset has changed, "
"please update the version number.".format(
self.name, self.data_dir, self.version
)
)
logging.info("Generating dataset %s (%s)", self.name, self.data_dir)
if not utils.has_sufficient_disk_space(
self.info.dataset_size + self.info.download_size,
directory=os.fspath(self.data_dir_root),
):
raise IOError(
"Not enough disk space. Needed: {} (download: {}, generated: {})"
.format(
self.info.dataset_size + self.info.download_size,
self.info.download_size,
self.info.dataset_size,
)
)
self._log_download_bytes()
dl_manager = self._make_download_manager(
download_dir=download_dir,
download_config=download_config,
)
# Maybe save the `builder_cls` metadata common to all builder configs.
if self.BUILDER_CONFIGS:
default_builder_config = self.get_default_builder_config()
if default_builder_config is None:
raise RuntimeError(
"Could not find default builder config while there "
"are builder configs!"
)
_save_default_config_name(
# `data_dir/ds_name/config/version/` -> `data_dir/ds_name/`
common_dir=self.data_path.parent.parent,
default_config_name=default_builder_config.name,
)
# If the file format was specified, set it in the info such that it is used
# to generate the files.
if file_format:
self.info.set_file_format(file_format, override=True)
# Create a tmp dir and rename to self.data_dir on successful exit.
with utils.incomplete_dir(
dirname=self.data_dir, permissions=permissions
) as tmp_data_dir:
# Temporarily assign _data_dir to tmp_data_dir to avoid having to forward
# it to every sub function.
with utils.temporary_assignment(self, "_data_dir", tmp_data_dir):
if (
download_config.try_download_gcs
and gcs_utils.is_dataset_on_gcs(self.info.full_name)
and self.info.file_format == file_adapters.FileFormat.TFRECORD
):
logging.info(GCS_HOSTED_MSG, self.name)
gcs_utils.download_gcs_dataset(
dataset_name=self.info.full_name, local_dataset_dir=self.data_dir
)
self.info.read_from_directory(self.data_dir)
else:
self._download_and_prepare(
dl_manager=dl_manager,
download_config=download_config,
)
# NOTE: If modifying the lines below to put additional information in
# DatasetInfo, you'll likely also want to update
# DatasetInfo.read_from_directory to possibly restore these attributes
# when reading from package data.
self.info.download_size = dl_manager.downloaded_size
# Write DatasetInfo to disk, even if we haven't computed statistics.
self.info.write_to_directory(self.data_dir)
# The generated DatasetInfo contains references to `tmp_data_dir`
self.info.update_data_dir(self.data_dir)
# Clean up incomplete files from preempted workers.
deleted_incomplete_files = []
for f in self.data_path.glob(f"*{constants.INCOMPLETE_PREFIX}*"):
if utils.is_incomplete_file(f):
deleted_incomplete_files.append(os.fspath(f))
f.unlink()
if deleted_incomplete_files:
logging.info(
"Deleted %d incomplete files. A small selection: %s",
len(deleted_incomplete_files),
"\n".join(deleted_incomplete_files[:3]),
)
self._log_download_done()
# Execute post download and prepare hook if it exists.
self._post_download_and_prepare_hook()
def _post_download_and_prepare_hook(self) -> None:
"""Hook to be executed after download and prepare.
Override this in custom dataset builders to execute custom logic after
download and prepare.
"""
pass
def _update_dataset_info(self) -> None:
"""Updates the `dataset_info.json` file in the dataset dir."""
info_file = self.data_path / constants.DATASET_INFO_FILENAME
if not info_file.exists():
raise AssertionError(f"To update {info_file}, it must already exist.")
new_info = self.info
new_info.read_from_directory(self.data_path)
new_info.write_to_directory(self.data_path, all_metadata=False)
@tfds_logging.as_data_source()
def as_data_source(
self,
split: Optional[Tree[splits_lib.SplitArg]] = None,
*,
decoders: Optional[TreeDict[decode.partial_decode.DecoderArg]] = None,
deserialize_method: decode.DeserializeMethod = decode.DeserializeMethod.DESERIALIZE_AND_DECODE,
) -> ListOrTreeOrElem[Sequence[Any]]:
"""Constructs an `ArrayRecordDataSource`.
Args:
split: Which split of the data to load (e.g. `'train'`, `'test'`,
`['train', 'test']`, `'train[80%:]'`,...). See our [split API
guide](https://www.tensorflow.org/datasets/splits). If `None`, will
return all splits in a `Dict[Split, Sequence]`.
decoders: Nested dict of `Decoder` objects which allow to customize the
decoding. The structure should match the feature structure, but only
customized feature keys need to be present. See [the
guide](https://github.com/tensorflow/datasets/blob/master/docs/decode.md)
for more info.
deserialize_method: Whether the read examples should be deserialized
and/or decoded. If not specified, it'll deserialize the data and decode
the features. Decoding is only supported if the examples are tf
examples. Note that if the deserialize_method method is other than
PARSE_AND_DECODE, then the `decoders` argument is ignored.
Returns:
`Sequence` if `split`,
`dict<key: tfds.Split, value: Sequence>` otherwise.
Raises:
NotImplementedError if the data was not generated using ArrayRecords.
"""
self.assert_is_not_blocked()
# By default, return all splits
if split is None:
split = {s: s for s in self.info.splits}
info = self.info
random_access_formats = file_adapters.FileFormat.with_random_access()
random_access_formats_msg = " or ".join(
[f.value for f in random_access_formats]
)
unsupported_format_msg = (
f"Random access data source for file format {info.file_format} is not"
" supported. Possible root causes:\n\t* You have to run"
" download_and_prepare with"
f" file_format={random_access_formats_msg}.\n\t* The dataset is already"
f" prepared at {self.data_dir} in the {info.file_format} format. Either"
" choose another data_dir or delete the data."
)
available_formats = info.available_file_formats()
if not available_formats:
raise ValueError(
"Dataset info file format is not set! For random access, one of the"
f" following formats is required: {random_access_formats_msg}"
)
suitable_formats = available_formats.intersection(random_access_formats)
if suitable_formats:
chosen_format = suitable_formats.pop()
logging.info(
"Found random access formats: %s. Chose to use %s. Overriding file"
" format in the dataset info.",
", ".join([f.name for f in suitable_formats]),
chosen_format,
)
# Change the dataset info to read from a random access format.
info.set_file_format(
chosen_format, override=True, override_if_initialized=True
)
else:
raise NotImplementedError(unsupported_format_msg)
# Create a dataset for each of the given splits
def build_single_data_source(split: str) -> Sequence[Any]:
if info.file_format is None:
raise ValueError(
"Dataset info file format is not set! For random access, one of the"
f" following formats is required: {random_access_formats_msg}"
)
match info.file_format:
case file_adapters.FileFormat.ARRAY_RECORD:
return array_record.ArrayRecordDataSource(
info,
split=split,
decoders=decoders,
deserialize_method=deserialize_method,
)
case file_adapters.FileFormat.PARQUET:
return parquet.ParquetDataSource(
info,
split=split,
decoders=decoders,
deserialize_method=deserialize_method,
)
case _:
raise NotImplementedError(unsupported_format_msg)
all_ds = tree.map_structure(build_single_data_source, split)
return all_ds
@tfds_logging.as_dataset()
def as_dataset(
self,
split: Optional[Tree[splits_lib.SplitArg]] = None,
*,
batch_size: Optional[int] = None,
shuffle_files: bool = False,
decoders: Optional[TreeDict[decode.partial_decode.DecoderArg]] = None,
read_config: Optional[read_config_lib.ReadConfig] = None,
as_supervised: bool = False,
):
# pylint: disable=line-too-long
"""Constructs a `tf.data.Dataset`.
Callers must pass arguments as keyword arguments.
The output types vary depending on the parameters. Examples:
```python
builder = tfds.builder('imdb_reviews')
builder.download_and_prepare()
# Default parameters: Returns the dict of tf.data.Dataset
ds_all_dict = builder.as_dataset()
assert isinstance(ds_all_dict, dict)
print(ds_all_dict.keys()) # ==> ['test', 'train', 'unsupervised']
assert isinstance(ds_all_dict['test'], tf.data.Dataset)
# Each dataset (test, train, unsup.) consists of dictionaries
# {'label': <tf.Tensor: .. dtype=int64, numpy=1>,
# 'text': <tf.Tensor: .. dtype=string, numpy=b"I've watched the movie ..">}
# {'label': <tf.Tensor: .. dtype=int64, numpy=1>,
# 'text': <tf.Tensor: .. dtype=string, numpy=b'If you love Japanese ..'>}
# With as_supervised: tf.data.Dataset only contains (feature, label) tuples
ds_all_supervised = builder.as_dataset(as_supervised=True)
assert isinstance(ds_all_supervised, dict)
print(ds_all_supervised.keys()) # ==> ['test', 'train', 'unsupervised']
assert isinstance(ds_all_supervised['test'], tf.data.Dataset)
# Each dataset (test, train, unsup.) consists of tuples (text, label)
# (<tf.Tensor: ... dtype=string, numpy=b"I've watched the movie ..">,
# <tf.Tensor: ... dtype=int64, numpy=1>)
# (<tf.Tensor: ... dtype=string, numpy=b"If you love Japanese ..">,
# <tf.Tensor: ... dtype=int64, numpy=1>)
# Same as above plus requesting a particular split
ds_test_supervised = builder.as_dataset(as_supervised=True, split='test')
assert isinstance(ds_test_supervised, tf.data.Dataset)
# The dataset consists of tuples (text, label)
# (<tf.Tensor: ... dtype=string, numpy=b"I've watched the movie ..">,
# <tf.Tensor: ... dtype=int64, numpy=1>)
# (<tf.Tensor: ... dtype=string, numpy=b"If you love Japanese ..">,
# <tf.Tensor: ... dtype=int64, numpy=1>)
```
Args:
split: Which split of the data to load (e.g. `'train'`, `'test'`,
`['train', 'test']`, `'train[80%:]'`,...). See our [split API
guide](https://www.tensorflow.org/datasets/splits). If `None`, will
return all splits in a `Dict[Split, tf.data.Dataset]`.
batch_size: `int`, batch size. Note that variable-length features will be
0-padded if `batch_size` is set. Users that want more custom behavior
should use `batch_size=None` and use the `tf.data` API to construct a
custom pipeline. If `batch_size == -1`, will return feature dictionaries
of the whole dataset with `tf.Tensor`s instead of a `tf.data.Dataset`.
shuffle_files: `bool`, whether to shuffle the input files. Defaults to
`False`.
decoders: Nested dict of `Decoder` objects which allow to customize the
decoding. The structure should match the feature structure, but only
customized feature keys need to be present. See [the
guide](https://github.com/tensorflow/datasets/blob/master/docs/decode.md)
for more info.
read_config: `tfds.ReadConfig`, Additional options to configure the input
pipeline (e.g. seed, num parallel reads,...).
as_supervised: `bool`, if `True`, the returned `tf.data.Dataset` will have
a 2-tuple structure `(input, label)` according to
`builder.info.supervised_keys`. If `False`, the default, the returned
`tf.data.Dataset` will have a dictionary with all the features.
Returns:
`tf.data.Dataset`, or if `split=None`, `dict<key: tfds.Split, value:
tf.data.Dataset>`.
If `batch_size` is -1, will return feature dictionaries containing
the entire dataset in `tf.Tensor`s instead of a `tf.data.Dataset`.
"""
self.assert_is_not_blocked()
# pylint: enable=line-too-long
if not self.data_path.exists():
raise AssertionError(
"Dataset %s: could not find data in %s. Please make sure to call "
"dataset_builder.download_and_prepare(), or pass download=True to "
"tfds.load() before trying to access the tf.data.Dataset object."
% (self.name, self.data_dir_root)
)