# Builder classes

## Builder classes

### Builders

🤗 Datasets relies on two main classes during the dataset building process: [DatasetBuilder](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DatasetBuilder) and [BuilderConfig](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.BuilderConfig).

#### class datasets.DatasetBuilder

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L216)

( cache\_dir: typing.Optional\[str] = Nonedataset\_name: typing.Optional\[str] = Noneconfig\_name: typing.Optional\[str] = Nonehash: typing.Optional\[str] = Nonebase\_path: typing.Optional\[str] = Noneinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonetoken: typing.Union\[bool, str, NoneType] = Noneuse\_auth\_token = 'deprecated'repo\_id: typing.Optional\[str] = Nonedata\_files: typing.Union\[str, list, dict, datasets.data\_files.DataFilesDict, NoneType] = Nonedata\_dir: typing.Optional\[str] = Nonestorage\_options: typing.Optional\[dict] = Nonewriter\_batch\_size: typing.Optional\[int] = Nonename = 'deprecated'\*\*config\_kwargs )

Parameters

* **cache\_dir** (`str`, *optional*) — Directory to cache data. Defaults to `"~/.cache/huggingface/datasets"`.
* **dataset\_name** (`str`, *optional*) — Name of the dataset, if different from the builder name. Useful for packaged builders like csv, imagefolder, audiofolder, etc. to reflect the difference between datasets that use the same packaged builder.
* **config\_name** (`str`, *optional*) — Name of the dataset configuration. It affects the data generated on disk. Different configurations will have their own subdirectories and versions. If not provided, the default configuration is used (if it exists).

  Added in 2.3.0

  Parameter `name` was renamed to `config_name`.
* **hash** (`str`, *optional*) — Hash specific to the dataset code. Used to update the caching directory when the dataset loading script code is updated (to avoid reusing old data). The typical caching directory (defined in `self._relative_data_dir`) is `name/version/hash/`.
* **base\_path** (`str`, *optional*) — Base path for relative paths that are used to download files. This can be a remote URL.
* **features** ([Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features), *optional*) — Features types to use with this dataset. It can be used to change the [Features](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Features) types of a dataset, for example.
* **token** (`str` or `bool`, *optional*) — String or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, will get token from `"~/.huggingface"`.
* **repo\_id** (`str`, *optional*) — ID of the dataset repository. Used to distinguish builders with the same name but not coming from the same namespace, for example “squad” and “lhoestq/squad” repo IDs. In the latter, the builder name would be “lhoestq\_\_\_squad”.
* **data\_files** (`str` or `Sequence` or `Mapping`, *optional*) — Path(s) to source data file(s). For builders like “csv” or “json” that need the user to specify data files. They can be either local or remote files. For convenience, you can use a `DataFilesDict`.
* **data\_dir** (`str`, *optional*) — Path to directory containing source data file(s). Use only if `data_files` is not passed, in which case it is equivalent to passing `os.path.join(data_dir, "**")` as `data_files`. For builders that require manual download, it must be the path to the local directory containing the manually downloaded data.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the dataset file-system backend, if any.
* **writer\_batch\_size** (`int`, *optional*) — Batch size used by the ArrowWriter. It defines the number of samples that are kept in memory before writing them and also the length of the arrow chunks. None means that the ArrowWriter will use its default value.
* **name** (`str`) — Configuration name for the dataset.

  Deprecated in 2.3.0

  Use `config_name` instead.
* \***\*config\_kwargs** (additional keyword arguments) — Keyword arguments to be passed to the corresponding builder configuration class, set on the class attribute [DatasetBuilder.BUILDER\_CONFIG\_CLASS](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.BuilderConfig). The builder configuration class is [BuilderConfig](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.BuilderConfig) or a subclass of it.

Abstract base class for all datasets.

`DatasetBuilder` has 3 key methods:

* `DatasetBuilder.info`: Documents the dataset, including feature names, types, shapes, version, splits, citation, etc.
* [DatasetBuilder.download\_and\_prepare()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DatasetBuilder.download_and_prepare): Downloads the source data and writes it to disk.
* [DatasetBuilder.as\_dataset()](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DatasetBuilder.as_dataset): Generates a [Dataset](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/main_classes#datasets.Dataset).

Some `DatasetBuilder`s expose multiple variants of the dataset by defining a [BuilderConfig](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.BuilderConfig) subclass and accepting a config object (or name) on construction. Configurable datasets expose a pre-defined set of configurations in `DatasetBuilder.builder_configs()`.

**as\_dataset**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L1111)

( split: typing.Optional\[datasets.splits.Split] = Nonerun\_post\_process = Trueverification\_mode: typing.Union\[datasets.utils.info\_utils.VerificationMode, str, NoneType] = Noneignore\_verifications = 'deprecated'in\_memory = False )

Parameters

* **split** (`datasets.Split`) — Which subset of the data to return.
* **run\_post\_process** (`bool`, defaults to `True`) — Whether to run post-processing dataset transforms and/or add indexes.
* **verification\_mode** ([VerificationMode](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.VerificationMode) or `str`, defaults to `BASIC_CHECKS`) — Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/…).

  Added in 2.9.1
* **ignore\_verifications** (`bool`, defaults to `False`) — Whether to ignore the verifications of the downloaded/processed dataset information (checksums/size/splits/…).

  Deprecated in 2.9.1

  `ignore_verifications` was deprecated in version 2.9.1 and will be removed in 3.0.0. Please use `verification_mode` instead.
* **in\_memory** (`bool`, defaults to `False`) — Whether to copy the data in-memory.

Return a Dataset for the specified split.

Example:

Copied

```
>>> from datasets import load_dataset_builder
>>> builder = load_dataset_builder('rotten_tomatoes')
>>> builder.download_and_prepare()
>>> ds = builder.as_dataset(split='train')
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 8530
})
```

**download\_and\_prepare**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L693)

( output\_dir: typing.Optional\[str] = Nonedownload\_config: typing.Optional\[datasets.download.download\_config.DownloadConfig] = Nonedownload\_mode: typing.Union\[datasets.download.download\_manager.DownloadMode, str, NoneType] = Noneverification\_mode: typing.Union\[datasets.utils.info\_utils.VerificationMode, str, NoneType] = Noneignore\_verifications = 'deprecated'try\_from\_hf\_gcs: bool = Truedl\_manager: typing.Optional\[datasets.download.download\_manager.DownloadManager] = Nonebase\_path: typing.Optional\[str] = Noneuse\_auth\_token = 'deprecated'file\_format: str = 'arrow'max\_shard\_size: typing.Union\[str, int, NoneType] = Nonenum\_proc: typing.Optional\[int] = Nonestorage\_options: typing.Optional\[dict] = None\*\*download\_and\_prepare\_kwargs )

Parameters

* **output\_dir** (`str`, *optional*) — Output directory for the dataset. Default to this builder’s `cache_dir`, which is inside `~/.cache/huggingface/datasets` by default.

  Added in 2.5.0
* **download\_config** (`DownloadConfig`, *optional*) — Specific download configuration parameters.
* **download\_mode** ([DownloadMode](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.DownloadMode) or `str`, *optional*) — Select the download/generate mode, default to `REUSE_DATASET_IF_EXISTS`.
* **verification\_mode** ([VerificationMode](https://huggingface.co/docs/datasets/v2.14.5/en/package_reference/builder_classes#datasets.VerificationMode) or `str`, defaults to `BASIC_CHECKS`) — Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/…).

  Added in 2.9.1
* **ignore\_verifications** (`bool`, defaults to `False`) — Ignore the verifications of the downloaded/processed dataset information (checksums/size/splits/…).

  Deprecated in 2.9.1

  `ignore_verifications` was deprecated in version 2.9.1 and will be removed in 3.0.0. Please use `verification_mode` instead.
* **try\_from\_hf\_gcs** (`bool`) — If `True`, it will try to download the already prepared dataset from the HF Google cloud storage.
* **dl\_manager** (`DownloadManager`, *optional*) — Specific `DownloadManger` to use.
* **base\_path** (`str`, *optional*) — Base path for relative paths that are used to download files. This can be a remote url. If not specified, the value of the `base_path` attribute (`self.base_path`) will be used instead.
* **use\_auth\_token** (`Union[str, bool]`, *optional*) — Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If True, or not specified, will get token from \~/.huggingface.

  Deprecated in 2.7.1

  Pass `use_auth_token` to `load_dataset_builder` instead.
* **file\_format** (`str`, *optional*) — Format of the data files in which the dataset will be written. Supported formats: “arrow”, “parquet”. Default to “arrow” format. If the format is “parquet”, then image and audio data are embedded into the Parquet files instead of pointing to local files.

  Added in 2.5.0
* **max\_shard\_size** (`Union[str, int]`, *optional*) — Maximum number of bytes written per shard, default is “500MB”. The size is based on uncompressed data size, so in practice your shard files may be smaller than `max_shard_size` thanks to Parquet compression for example.

  Added in 2.5.0
* **num\_proc** (`int`, *optional*, defaults to `None`) — Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default.

  Added in 2.7.0
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the caching file-system backend, if any.

  Added in 2.5.0
* \***\*download\_and\_prepare\_kwargs** (additional keyword arguments) — Keyword arguments.

Downloads and prepares dataset for reading.

Example:

Download and prepare the dataset as Arrow files that can be loaded as a Dataset using `builder.as_dataset()`:

Copied

```
>>> from datasets import load_dataset_builder
>>> builder = load_dataset_builder("rotten_tomatoes")
>>> builder.download_and_prepare()
```

Download and prepare the dataset as sharded Parquet files locally:

Copied

```
>>> from datasets import load_dataset_builder
>>> builder = load_dataset_builder("rotten_tomatoes")
>>> builder.download_and_prepare("./output_dir", file_format="parquet")
```

Download and prepare the dataset as sharded Parquet files in a cloud storage:

Copied

```
>>> from datasets import load_dataset_builder
>>> storage_options = {"key": aws_access_key_id, "secret": aws_secret_access_key}
>>> builder = load_dataset_builder("rotten_tomatoes")
>>> builder.download_and_prepare("s3://my-bucket/my_rotten_tomatoes", storage_options=storage_options, file_format="parquet")
```

**get\_all\_exported\_dataset\_infos**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L479)

( )

Empty dict if doesn’t exist

Example:

Copied

```
>>> from datasets import load_dataset_builder
>>> ds_builder = load_dataset_builder('rotten_tomatoes')
>>> ds_builder.get_all_exported_dataset_infos()
{'default': DatasetInfo(description="Movie Review Dataset.
a dataset of containing 5,331 positive and 5,331 negative processed
s from Rotten Tomatoes movie reviews. This data was first used in Bo
 Lillian Lee, ``Seeing stars: Exploiting class relationships for
t categorization with respect to rating scales.'', Proceedings of the
5.
ion='@InProceedings{Pang+Lee:05a,
 =       {Bo Pang and Lillian Lee},
=        {Seeing stars: Exploiting class relationships for sentiment
          categorization with respect to rating scales},
tle =    {Proceedings of the ACL},
         2005

age='http://www.cs.cornell.edu/people/pabo/movie-review-data/', license='', features={'text': Value(dtype='string', id=None), 'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None)}, post_processed=None, supervised_keys=SupervisedKeysData(input='', output=''), task_templates=[TextClassification(task='text-classification', text_column='text', label_column='label')], builder_name='rotten_tomatoes_movie_review', config_name='default', version=1.0.0, splits={'train': SplitInfo(name='train', num_bytes=1074810, num_examples=8530, dataset_name='rotten_tomatoes_movie_review'), 'validation': SplitInfo(name='validation', num_bytes=134679, num_examples=1066, dataset_name='rotten_tomatoes_movie_review'), 'test': SplitInfo(name='test', num_bytes=135972, num_examples=1066, dataset_name='rotten_tomatoes_movie_review')}, download_checksums={'https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz': {'num_bytes': 487770, 'checksum': 'a05befe52aafda71d458d188a1c54506a998b1308613ba76bbda2e5029409ce9'}}, download_size=487770, post_processing_size=None, dataset_size=1345461, size_in_bytes=1833231)}
```

**get\_exported\_dataset\_info**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L494)

( )

Empty `DatasetInfo` if doesn’t exist

Example:

Copied

```
>>> from datasets import load_dataset_builder
>>> ds_builder = load_dataset_builder('rotten_tomatoes')
>>> ds_builder.get_exported_dataset_info()
DatasetInfo(description="Movie Review Dataset.
a dataset of containing 5,331 positive and 5,331 negative processed
s from Rotten Tomatoes movie reviews. This data was first used in Bo
 Lillian Lee, ``Seeing stars: Exploiting class relationships for
t categorization with respect to rating scales.'', Proceedings of the
5.
ion='@InProceedings{Pang+Lee:05a,
 =       {Bo Pang and Lillian Lee},
=        {Seeing stars: Exploiting class relationships for sentiment
          categorization with respect to rating scales},
tle =    {Proceedings of the ACL},
         2005

age='http://www.cs.cornell.edu/people/pabo/movie-review-data/', license='', features={'text': Value(dtype='string', id=None), 'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None)}, post_processed=None, supervised_keys=SupervisedKeysData(input='', output=''), task_templates=[TextClassification(task='text-classification', text_column='text', label_column='label')], builder_name='rotten_tomatoes_movie_review', config_name='default', version=1.0.0, splits={'train': SplitInfo(name='train', num_bytes=1074810, num_examples=8530, dataset_name='rotten_tomatoes_movie_review'), 'validation': SplitInfo(name='validation', num_bytes=134679, num_examples=1066, dataset_name='rotten_tomatoes_movie_review'), 'test': SplitInfo(name='test', num_bytes=135972, num_examples=1066, dataset_name='rotten_tomatoes_movie_review')}, download_checksums={'https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz': {'num_bytes': 487770, 'checksum': 'a05befe52aafda71d458d188a1c54506a998b1308613ba76bbda2e5029409ce9'}}, download_size=487770, post_processing_size=None, dataset_size=1345461, size_in_bytes=1833231)
```

**get\_imported\_module\_dir**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L685)

( )

Return the path of the module of this class or subclass.

#### class datasets.GeneratorBasedBuilder

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L1461)

( cache\_dir: typing.Optional\[str] = Nonedataset\_name: typing.Optional\[str] = Noneconfig\_name: typing.Optional\[str] = Nonehash: typing.Optional\[str] = Nonebase\_path: typing.Optional\[str] = Noneinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonetoken: typing.Union\[bool, str, NoneType] = Noneuse\_auth\_token = 'deprecated'repo\_id: typing.Optional\[str] = Nonedata\_files: typing.Union\[str, list, dict, datasets.data\_files.DataFilesDict, NoneType] = Nonedata\_dir: typing.Optional\[str] = Nonestorage\_options: typing.Optional\[dict] = Nonewriter\_batch\_size: typing.Optional\[int] = Nonename = 'deprecated'\*\*config\_kwargs )

Base class for datasets with data generation based on dict generators.

`GeneratorBasedBuilder` is a convenience class that abstracts away much of the data writing and reading of `DatasetBuilder`. It expects subclasses to implement generators of feature dictionaries across the dataset splits (`_split_generators`). See the method docstrings for details.

#### class datasets.BeamBasedBuilder

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L1970)

( \*argsbeam\_runner = Nonebeam\_options = None\*\*kwargs )

Beam-based Builder.

#### class datasets.ArrowBasedBuilder

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L1729)

( cache\_dir: typing.Optional\[str] = Nonedataset\_name: typing.Optional\[str] = Noneconfig\_name: typing.Optional\[str] = Nonehash: typing.Optional\[str] = Nonebase\_path: typing.Optional\[str] = Noneinfo: typing.Optional\[datasets.info.DatasetInfo] = Nonefeatures: typing.Optional\[datasets.features.features.Features] = Nonetoken: typing.Union\[bool, str, NoneType] = Noneuse\_auth\_token = 'deprecated'repo\_id: typing.Optional\[str] = Nonedata\_files: typing.Union\[str, list, dict, datasets.data\_files.DataFilesDict, NoneType] = Nonedata\_dir: typing.Optional\[str] = Nonestorage\_options: typing.Optional\[dict] = Nonewriter\_batch\_size: typing.Optional\[int] = Nonename = 'deprecated'\*\*config\_kwargs )

Base class for datasets with data generation based on Arrow loading functions (CSV/JSON/Parquet).

#### class datasets.BuilderConfig

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L108)

( name: str = 'default'version: typing.Union\[str, datasets.utils.version.Version, NoneType] = 0.0.0data\_dir: typing.Optional\[str] = Nonedata\_files: typing.Optional\[datasets.data\_files.DataFilesDict] = Nonedescription: typing.Optional\[str] = None )

Parameters

* **name** (`str`, defaults to `default`) — The name of the configuration.
* **version** (`Version` or `str`, defaults to `0.0.0`) — The version of the configuration.
* **data\_dir** (`str`, *optional*) — Path to the directory containing the source data.
* **data\_files** (`str` or `Sequence` or `Mapping`, *optional*) — Path(s) to source data file(s).
* **description** (`str`, *optional*) — A human description of the configuration.

Base class for `DatasetBuilder` data configuration.

`DatasetBuilder` subclasses with data configuration options should subclass `BuilderConfig` and add their own properties.

**create\_config\_id**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/builder.py#L151)

( config\_kwargs: dictcustom\_features: typing.Optional\[datasets.features.features.Features] = None )

The config id is used to build the cache directory. By default it is equal to the config name. However the name of a config is not sufficient to have a unique identifier for the dataset being generated since it doesn’t take into account:

* the config kwargs that can be used to overwrite attributes
* the custom features used to write the dataset
* the data\_files for json/text/csv/pandas datasets

Therefore the config id is just the config name with an optional suffix based on these.

### Download

#### class datasets.DownloadManager

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L254)

( dataset\_name: typing.Optional\[str] = Nonedata\_dir: typing.Optional\[str] = Nonedownload\_config: typing.Optional\[datasets.download.download\_config.DownloadConfig] = Nonebase\_path: typing.Optional\[str] = Nonerecord\_checksums = True )

**download**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L401)

( url\_or\_urls ) → `str` or `list` or `dict`

Parameters

* **url\_or\_urls** (`str` or `list` or `dict`) — URL or `list` or `dict` of URLs to download. Each URL is a `str`.

Returns

`str` or `list` or `dict`

The downloaded paths matching the given input `url_or_urls`.

Download given URL(s).

By default, only one process is used for download. Pass customized `download_config.num_proc` to change this behavior.

Example:

Copied

```
>>> downloaded_files = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
```

**download\_and\_extract**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L549)

( url\_or\_urls ) → extracted\_path(s)

Parameters

* **url\_or\_urls** (`str` or `list` or `dict`) — URL or `list` or `dict` of URLs to download and extract. Each URL is a `str`.

Returns

extracted\_path(s)

`str`, extracted paths of given URL(s).

Download and extract given `url_or_urls`.

Is roughly equivalent to:

Copied

```
extracted_paths = dl_manager.extract(dl_manager.download(url_or_urls))
```

**download\_custom**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L352)

( url\_or\_urlscustom\_download ) → downloaded\_path(s)

Parameters

* **url\_or\_urls** (`str` or `list` or `dict`) — URL or `list` or `dict` of URLs to download and extract. Each URL is a `str`.
* **custom\_download** (`Callable[src_url, dst_path]`) — The source URL and destination path. For example `tf.io.gfile.copy`, that lets you download from Google storage.

Returns

downloaded\_path(s)

`str`, The downloaded paths matching the given input `url_or_urls`.

Download given urls(s) by calling `custom_download`.

Example:

Copied

```
>>> downloaded_files = dl_manager.download_custom('s3://my-bucket/data.zip', custom_download_for_my_private_bucket)
```

**extract**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L500)

( path\_or\_pathsnum\_proc = 'deprecated' ) → extracted\_path(s)

Parameters

* **path\_or\_paths** (path or `list` or `dict`) — Path of file to extract. Each path is a `str`.
* **num\_proc** (`int`) — Use multi-processing if `num_proc` > 1 and the length of `path_or_paths` is larger than `num_proc`.

  Deprecated in 2.6.2

  Pass `DownloadConfig(num_proc=<num_proc>)` to the initializer instead.

Returns

extracted\_path(s)

`str`, The extracted paths matching the given input path\_or\_paths.

Extract given path(s).

Example:

Copied

```
>>> downloaded_files = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> extracted_files = dl_manager.extract(downloaded_files)
```

**iter\_archive**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L456)

( path\_or\_buf: typing.Union\[str, \_io.BufferedReader] ) → `tuple[str, io.BufferedReader]`

Parameters

* **path\_or\_buf** (`str` or `io.BufferedReader`) — Archive path or archive binary file object.

Yields

`tuple[str, io.BufferedReader]`

Iterate over files within an archive.

Example:

Copied

```
>>> archive = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> files = dl_manager.iter_archive(archive)
```

**iter\_files**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L481)

( paths: typing.Union\[str, typing.List\[str]] ) → `str`

Parameters

* **paths** (`str` or `list` of `str`) — Root paths.

Yields

`str`

Iterate over file paths.

Example:

Copied

```
>>> files = dl_manager.download_and_extract('https://huggingface.co/datasets/beans/resolve/main/data/train.zip')
>>> files = dl_manager.iter_files(files)
```

**ship\_files\_with\_pipeline**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L301)

( downloaded\_path\_or\_pathspipeline )

Parameters

* **downloaded\_path\_or\_paths** (`str` or `list[str]` or `dict[str, str]`) — Nested structure containing the downloaded path(s).
* **pipeline** (`utils.beam_utils.BeamPipeline`) — Apache Beam Pipeline.

Ship the files using Beam FileSystems to the pipeline temp dir.

#### class datasets.StreamingDownloadManager

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/streaming_download_manager.py#L943)

( dataset\_name: typing.Optional\[str] = Nonedata\_dir: typing.Optional\[str] = Nonedownload\_config: typing.Optional\[datasets.download.download\_config.DownloadConfig] = Nonebase\_path: typing.Optional\[str] = None )

Download manager that uses the ”::” separator to navigate through (possibly remote) compressed archives. Contrary to the regular `DownloadManager`, the `download` and `extract` methods don’t actually download nor extract data, but they rather return the path or url that could be opened using the `xopen` function which extends the built-in `open` function to stream data from remote files.

**download**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/streaming_download_manager.py#L969)

( url\_or\_urls ) → url(s)

Parameters

* **url\_or\_urls** (`str` or `list` or `dict`) — URL(s) of files to stream data from. Each url is a `str`.

Returns

url(s)

(`str` or `list` or `dict`), URL(s) to stream data from matching the given input url\_or\_urls.

Normalize URL(s) of files to stream data from. This is the lazy version of `DownloadManager.download` for streaming.

Example:

Copied

```
>>> downloaded_files = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
```

**download\_and\_extract**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/streaming_download_manager.py#L1045)

( url\_or\_urls ) → url(s)

Parameters

* **url\_or\_urls** (`str` or `list` or `dict`) — URL(s) to stream from data from. Each url is a `str`.

Returns

url(s)

(`str` or `list` or `dict`), URL(s) to stream data from matching the given input `url_or_urls`.

Prepare given `url_or_urls` for streaming (add extraction protocol).

This is the lazy version of `DownloadManager.download_and_extract` for streaming.

Is equivalent to:

Copied

```
urls = dl_manager.extract(dl_manager.download(url_or_urls))
```

**extract**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/streaming_download_manager.py#L996)

( url\_or\_urls ) → url(s)

Parameters

* **url\_or\_urls** (`str` or `list` or `dict`) — URL(s) of files to stream data from. Each url is a `str`.

Returns

url(s)

(`str` or `list` or `dict`), URL(s) to stream data from matching the given input `url_or_urls`.

Add extraction protocol for given url(s) for streaming.

This is the lazy version of `DownloadManager.extract` for streaming.

Example:

Copied

```
>>> downloaded_files = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> extracted_files = dl_manager.extract(downloaded_files)
```

**iter\_archive**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/streaming_download_manager.py#L1065)

( urlpath\_or\_buf: typing.Union\[str, \_io.BufferedReader] ) → `tuple[str, io.BufferedReader]`

Parameters

* **urlpath\_or\_buf** (`str` or `io.BufferedReader`) — Archive path or archive binary file object.

Yields

`tuple[str, io.BufferedReader]`

Iterate over files within an archive.

Example:

Copied

```
>>> archive = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> files = dl_manager.iter_archive(archive)
```

**iter\_files**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/streaming_download_manager.py#L1090)

( urlpaths: typing.Union\[str, typing.List\[str]] ) → str

Parameters

* **urlpaths** (`str` or `list` of `str`) — Root paths.

Yields

str

Iterate over files.

Example:

Copied

```
>>> files = dl_manager.download_and_extract('https://huggingface.co/datasets/beans/resolve/main/data/train.zip')
>>> files = dl_manager.iter_files(files)
```

#### class datasets.DownloadConfig

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_config.py#L11)

( cache\_dir: typing.Union\[str, pathlib.Path, NoneType] = Noneforce\_download: bool = Falseresume\_download: bool = Falselocal\_files\_only: bool = Falseproxies: typing.Optional\[typing.Dict] = Noneuser\_agent: typing.Optional\[str] = Noneextract\_compressed\_file: bool = Falseforce\_extract: bool = Falsedelete\_extracted: bool = Falseuse\_etag: bool = Truenum\_proc: typing.Optional\[int] = Nonemax\_retries: int = 1token: typing.Union\[str, bool, NoneType] = Noneuse\_auth\_token: dataclasses.InitVar\[typing.Union\[str, bool, NoneType]] = 'deprecated'ignore\_url\_params: bool = Falsestorage\_options: typing.Dict\[str, typing.Any] = \<factory>download\_desc: typing.Optional\[str] = None )

Parameters

* **cache\_dir** (`str` or `Path`, *optional*) — Specify a cache directory to save the file to (overwrite the default cache dir).
* **force\_download** (`bool`, defaults to `False`) — If `True`, re-dowload the file even if it’s already cached in the cache dir.
* **resume\_download** (`bool`, defaults to `False`) — If `True`, resume the download if an incompletely received file is found.
* **proxies** (`dict`, *optional*) —
* **user\_agent** (`str`, *optional*) — Optional string or dict that will be appended to the user-agent on remote requests.
* **extract\_compressed\_file** (`bool`, defaults to `False`) — If `True` and the path point to a zip or tar file, extract the compressed file in a folder along the archive.
* **force\_extract** (`bool`, defaults to `False`) — If `True` when `extract_compressed_file` is `True` and the archive was already extracted, re-extract the archive and override the folder where it was extracted.
* **delete\_extracted** (`bool`, defaults to `False`) — Whether to delete (or keep) the extracted files.
* **use\_etag** (`bool`, defaults to `True`) — Whether to use the ETag HTTP response header to validate the cached files.
* **num\_proc** (`int`, *optional*) — The number of processes to launch to download the files in parallel.
* **max\_retries** (`int`, default to `1`) — The number of times to retry an HTTP request if it fails.
* **token** (`str` or `bool`, *optional*) — Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, or not specified, will get token from `~/.huggingface`.
* **use\_auth\_token** (`str` or `bool`, *optional*) — Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, or not specified, will get token from `~/.huggingface`.

  Deprecated in 2.14.0

  `use_auth_token` was deprecated in favor of `token` in version 2.14.0 and will be removed in 3.0.0.
* **ignore\_url\_params** (`bool`, defaults to `False`) — Whether to strip all query parameters and fragments from the download URL before using it for caching the file.
* **storage\_options** (`dict`, *optional*) — Key/value pairs to be passed on to the dataset file-system backend, if any.
* **download\_desc** (`str`, *optional*) — A description to be displayed alongside with the progress bar while downloading the files.

Configuration for our cached path manager.

#### class datasets.DownloadMode

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/download/download_manager.py#L76)

( valuenames = Nonemodule = Nonequalname = Nonetype = Nonestart = 1 )

`Enum` for how to treat pre-existing downloads and data.

The default mode is `REUSE_DATASET_IF_EXISTS`, which will reuse both raw downloads and the prepared dataset if they exist.

The generations modes:

|                                     | Downloads | Dataset |
| ----------------------------------- | --------- | ------- |
| `REUSE_DATASET_IF_EXISTS` (default) | Reuse     | Reuse   |
| `REUSE_CACHE_IF_EXISTS`             | Reuse     | Fresh   |
| `FORCE_REDOWNLOAD`                  | Fresh     | Fresh   |

### Verification

#### class datasets.VerificationMode

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/utils/info_utils.py#L13)

( valuenames = Nonemodule = Nonequalname = Nonetype = Nonestart = 1 )

`Enum` that specifies which verification checks to run.

The default mode is `BASIC_CHECKS`, which will perform only rudimentary checks to avoid slowdowns when generating/downloading a dataset for the first time.

The verification modes:

|                          | Verification checks                                                          |
| ------------------------ | ---------------------------------------------------------------------------- |
| `ALL_CHECKS`             | Split checks, uniqueness of the keys yielded in case of the GeneratorBuilder |
|                          | and the validity (number of files, checksums, etc.) of downloaded files      |
| `BASIC_CHECKS` (default) | Same as `ALL_CHECKS` but without checking downloaded files                   |
| `NO_CHECKS`              | None                                                                         |

### Splits

#### class datasets.SplitGenerator

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/splits.py#L602)

( name: strgen\_kwargs: typing.Dict = \<factory> )

Parameters

* **name** (`str`) — Name of the `Split` for which the generator will create the examples.
* \***\*gen\_kwargs** (additional keyword arguments) — Keyword arguments to forward to the `DatasetBuilder._generate_examples` method of the builder.

Defines the split information for the generator.

This should be used as returned value of `GeneratorBasedBuilder._split_generators`. See `GeneratorBasedBuilder._split_generators` for more info and example of usage.

Example:

Copied

```
>>> datasets.SplitGenerator(
...     name=datasets.Split.TRAIN,
...     gen_kwargs={"split_key": "train", "files": dl_manager.download_and_extract(url)},
... )
```

#### class datasets.Split

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/splits.py#L405)

( name )

`Enum` for dataset splits.

Datasets are typically split into different subsets to be used at various stages of training and evaluation.

* `TRAIN`: the training data.
* `VALIDATION`: the validation data. If present, this is typically used as evaluation data while iterating on a model (e.g. changing hyperparameters, model architecture, etc.).
* `TEST`: the testing data. This is the data to report metrics on. Typically you do not want to use this during model iteration as you may overfit to it.
* `ALL`: the union of all defined dataset splits.

All splits, including compositions inherit from `datasets.SplitBase`.

See the [guide](https://huggingface.co/docs/datasets/load_hub#splits) on splits for more information.

Example:

Copied

```
>>> datasets.SplitGenerator(
...     name=datasets.Split.TRAIN,
...     gen_kwargs={"split_key": "train", "files": dl_manager.download_and extract(url)},
... ),
... datasets.SplitGenerator(
...     name=datasets.Split.VALIDATION,
...     gen_kwargs={"split_key": "validation", "files": dl_manager.download_and extract(url)},
... ),
... datasets.SplitGenerator(
...     name=datasets.Split.TEST,
...     gen_kwargs={"split_key": "test", "files": dl_manager.download_and extract(url)},
... )
```

#### class datasets.NamedSplit

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/splits.py#L313)

( name )

Descriptor corresponding to a named split (train, test, …).

Example:

Each descriptor can be composed with other using addition or slice:

Copied

```
split = datasets.Split.TRAIN.subsplit(datasets.percent[0:25]) + datasets.Split.TEST
```

The resulting split will correspond to 25% of the train split merged with 100% of the test split.

A split cannot be added twice, so the following will fail:

Copied

```
split = (
        datasets.Split.TRAIN.subsplit(datasets.percent[:25]) +
        datasets.Split.TRAIN.subsplit(datasets.percent[75:])
)  # Error
split = datasets.Split.TEST + datasets.Split.ALL  # Error
```

The slices can be applied only one time. So the following are valid:

Copied

```
split = (
        datasets.Split.TRAIN.subsplit(datasets.percent[:25]) +
        datasets.Split.TEST.subsplit(datasets.percent[:50])
)
split = (datasets.Split.TRAIN + datasets.Split.TEST).subsplit(datasets.percent[:50])
```

But this is not valid:

Copied

```
train = datasets.Split.TRAIN
test = datasets.Split.TEST
split = train.subsplit(datasets.percent[:25]).subsplit(datasets.percent[:25])
split = (train.subsplit(datasets.percent[:25]) + test).subsplit(datasets.percent[:50])
```

#### class datasets.NamedSplitAll

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/splits.py#L390)

( )

Split corresponding to the union of all defined dataset splits.

#### class datasets.ReadInstruction

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_reader.py#L489)

( split\_namerounding = Nonefrom\_ = Noneto = Noneunit = None )

Reading instruction for a dataset.

Examples:

Copied

```
# The following lines are equivalent:
ds = datasets.load_dataset('mnist', split='test[:33%]')
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction.from_spec('test[:33%]'))
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction('test', to=33, unit='%'))
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction(
'test', from_=0, to=33, unit='%'))

# The following lines are equivalent:
ds = datasets.load_dataset('mnist', split='test[:33%]+train[1:-1]')
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction.from_spec(
'test[:33%]+train[1:-1]'))
ds = datasets.load_dataset('mnist', split=(
datasets.ReadInstruction('test', to=33, unit='%') +
datasets.ReadInstruction('train', from_=1, to=-1, unit='abs')))

# The following lines are equivalent:
ds = datasets.load_dataset('mnist', split='test[:33%](pct1_dropremainder)')
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction.from_spec(
'test[:33%](pct1_dropremainder)'))
ds = datasets.load_dataset('mnist', split=datasets.ReadInstruction(
'test', from_=0, to=33, unit='%', rounding="pct1_dropremainder"))

# 10-fold validation:
tests = datasets.load_dataset(
'mnist',
[datasets.ReadInstruction('train', from_=k, to=k+10, unit='%')
for k in range(0, 100, 10)])
trains = datasets.load_dataset(
'mnist',
[datasets.ReadInstruction('train', to=k, unit='%') + datasets.ReadInstruction('train', from_=k+10, unit='%')
for k in range(0, 100, 10)])
```

**from\_spec**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_reader.py#L569)

( spec )

Parameters

* **spec** (`str`) — Split(s) + optional slice(s) to read + optional rounding if percents are used as the slicing unit. A slice can be specified, using absolute numbers (`int`) or percentages (`int`).

Creates a `ReadInstruction` instance out of a string spec.

Examples:

Copied

```
test: test split.
test + validation: test split + validation split.
test[10:]: test split, minus its first 10 records.
test[:10%]: first 10% records of test split.
test[:20%](pct1_dropremainder): first 10% records, rounded with the pct1_dropremainder rounding.
test[:-5%]+train[40%:60%]: first 95% of test + middle 20% of train.
```

**to\_absolute**

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/arrow_reader.py#L641)

( name2len )

Parameters

* **name2len** (`dict`) — Associating split names to number of examples.

Translate instruction into a list of absolute instructions.

Those absolute instructions are then to be added together.

### Version

#### class datasets.Version

[\<source>](https://github.com/huggingface/datasets/blob/2.14.5/src/datasets/utils/version.py#L30)

( version\_str: strdescription: typing.Optional\[str] = Nonemajor: typing.Union\[str, int, NoneType] = Noneminor: typing.Union\[str, int, NoneType] = Nonepatch: typing.Union\[str, int, NoneType] = None )

Parameters

* **version\_str** (`str`) — The dataset version.
* **description** (`str`) — A description of what is new in this version.
* **major** (`str`) —
* **minor** (`str`) —
* **patch** (`str`) —

Dataset version `MAJOR.MINOR.PATCH`.

Example:

Copied

```
>>> VERSION = datasets.Version("1.0.0")
```
