repo_id
stringlengths
15
89
file_path
stringlengths
27
180
content
stringlengths
1
2.23M
__index_level_0__
int64
0
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/stream.mdx
# Stream Dataset streaming lets you work with a dataset without downloading it. The data is streamed as you iterate over the dataset. This is especially helpful when: - You don't want to wait for an extremely large dataset to download. - The dataset size exceeds the amount of available disk space on your computer. - You want to quickly explore just a few samples of a dataset. <div class="flex justify-center"> <img class="block dark:hidden" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/streaming.gif"/> <img class="hidden dark:block" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/streaming-dark.gif"/> </div> For example, the English split of the [oscar-corpus/OSCAR-2201](https://huggingface.co/datasets/oscar-corpus/OSCAR-2201) dataset is 1.2 terabytes, but you can use it instantly with streaming. Stream a dataset by setting `streaming=True` in [`load_dataset`] as shown below: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('oscar-corpus/OSCAR-2201', 'en', split='train', streaming=True) >>> print(next(iter(dataset))) {'id': 0, 'text': 'Founded in 2015, Golden Bees is a leading programmatic recruitment platform dedicated to employers, HR agencies and job boards. The company has developed unique HR-custom technologies and predictive algorithms to identify and attract the best candidates for a job opportunity.', ... ``` Dataset streaming also lets you work with a dataset made of local files without doing any conversion. In this case, the data is streamed from the local files as you iterate over the dataset. This is especially helpful when: - You don't want to wait for an extremely large local dataset to be converted to Arrow. - The converted files size would exceed the amount of available disk space on your computer. - You want to quickly explore just a few samples of a dataset. For example, you can stream a local dataset of hundreds of compressed JSONL files like [oscar-corpus/OSCAR-2201](https://huggingface.co/datasets/oscar-corpus/OSCAR-2201) to use it instantly: ```py >>> from datasets import load_dataset >>> data_files = {'train': 'path/to/OSCAR-2201/compressed/en_meta/*.jsonl.gz'} >>> dataset = load_dataset('json', data_files=data_files, split='train', streaming=True) >>> print(next(iter(dataset))) {'id': 0, 'text': 'Founded in 2015, Golden Bees is a leading programmatic recruitment platform dedicated to employers, HR agencies and job boards. The company has developed unique HR-custom technologies and predictive algorithms to identify and attract the best candidates for a job opportunity.', ... ``` Loading a dataset in streaming mode creates a new dataset type instance (instead of the classic [`Dataset`] object), known as an [`IterableDataset`]. This special type of dataset has its own set of processing methods shown below. <Tip> An [`IterableDataset`] is useful for iterative jobs like training a model. You shouldn't use a [`IterableDataset`] for jobs that require random access to examples because you have to iterate all over it using a for loop. Getting the last example in an iterable dataset would require you to iterate over all the previous examples. You can find more details in the [Dataset vs. IterableDataset guide](./about_mapstyle_vs_iterable). </Tip> ## Convert from a Dataset If you have an existing [`Dataset`] object, you can convert it to an [`IterableDataset`] with the [`~Dataset.to_iterable_dataset`] function. This is actually faster than setting the `streaming=True` argument in [`load_dataset`] because the data is streamed from local files. ```py >>> from datasets import load_dataset # faster 🐇 >>> dataset = load_dataset("food101") >>> iterable_dataset = dataset.to_iterable_dataset() # slower 🐢 >>> iterable_dataset = load_dataset("food101", streaming=True) ``` The [`~Dataset.to_iterable_dataset`] function supports sharding when the [`IterableDataset`] is instantiated. This is useful when working with big datasets, and you'd like to shuffle the dataset or to enable fast parallel loading with a PyTorch DataLoader. ```py >>> import torch >>> from datasets import load_dataset >>> dataset = load_dataset("food101") >>> iterable_dataset = dataset.to_iterable_dataset(num_shards=64) # shard the dataset >>> iterable_dataset = iterable_dataset.shuffle(buffer_size=10_000) # shuffles the shards order and use a shuffle buffer when you start iterating dataloader = torch.utils.data.DataLoader(iterable_dataset, num_workers=4) # assigns 64 / 4 = 16 shards from the shuffled list of shards to each worker when you start iterating ``` ## Shuffle Like a regular [`Dataset`] object, you can also shuffle a [`IterableDataset`] with [`IterableDataset.shuffle`]. The `buffer_size` argument controls the size of the buffer to randomly sample examples from. Let's say your dataset has one million examples, and you set the `buffer_size` to ten thousand. [`IterableDataset.shuffle`] will randomly select examples from the first ten thousand examples in the buffer. Selected examples in the buffer are replaced with new examples. By default, the buffer size is 1,000. ```py >>> from datasets import load_dataset >>> dataset = load_dataset('oscar', "unshuffled_deduplicated_en", split='train', streaming=True) >>> shuffled_dataset = dataset.shuffle(seed=42, buffer_size=10_000) ``` <Tip> [`IterableDataset.shuffle`] will also shuffle the order of the shards if the dataset is sharded into multiple files. </Tip> ## Reshuffle Sometimes you may want to reshuffle the dataset after each epoch. This will require you to set a different seed for each epoch. Use [`IterableDataset.set_epoch`] in between epochs to tell the dataset what epoch you're on. Your seed effectively becomes: `initial seed + current epoch`. ```py >>> for epoch in range(epochs): ... shuffled_dataset.set_epoch(epoch) ... for example in shuffled_dataset: ... ... ``` ## Split dataset You can split your dataset one of two ways: - [`IterableDataset.take`] returns the first `n` examples in a dataset: ```py >>> dataset = load_dataset('oscar', "unshuffled_deduplicated_en", split='train', streaming=True) >>> dataset_head = dataset.take(2) >>> list(dataset_head) [{'id': 0, 'text': 'Mtendere Village was...'}, {'id': 1, 'text': 'Lily James cannot fight the music...'}] ``` - [`IterableDataset.skip`] omits the first `n` examples in a dataset and returns the remaining examples: ```py >>> train_dataset = shuffled_dataset.skip(1000) ``` <Tip warning={true}> `take` and `skip` prevent future calls to `shuffle` because they lock in the order of the shards. You should `shuffle` your dataset before splitting it. </Tip> <a id='interleave_datasets'></a> ## Interleave [`interleave_datasets`] can combine an [`IterableDataset`] with other datasets. The combined dataset returns alternating examples from each of the original datasets. ```py >>> from datasets import interleave_datasets >>> en_dataset = load_dataset('oscar', "unshuffled_deduplicated_en", split='train', streaming=True, trust_remote_code=True) >>> fr_dataset = load_dataset('oscar', "unshuffled_deduplicated_fr", split='train', streaming=True, trust_remote_code=True) >>> multilingual_dataset = interleave_datasets([en_dataset, fr_dataset]) >>> list(multilingual_dataset.take(2)) [{'text': 'Mtendere Village was inspired by the vision...'}, {'text': "Média de débat d'idées, de culture et de littérature..."}] ``` Define sampling probabilities from each of the original datasets for more control over how each of them are sampled and combined. Set the `probabilities` argument with your desired sampling probabilities: ```py >>> multilingual_dataset_with_oversampling = interleave_datasets([en_dataset, fr_dataset], probabilities=[0.8, 0.2], seed=42) >>> list(multilingual_dataset_with_oversampling.take(2)) [{'text': 'Mtendere Village was inspired by the vision...'}, {'text': 'Lily James cannot fight the music...'}] ``` Around 80% of the final dataset is made of the `en_dataset`, and 20% of the `fr_dataset`. You can also specify the `stopping_strategy`. The default strategy, `first_exhausted`, is a subsampling strategy, i.e the dataset construction is stopped as soon one of the dataset runs out of samples. You can specify `stopping_strategy=all_exhausted` to execute an oversampling strategy. In this case, the dataset construction is stopped as soon as every samples in every dataset has been added at least once. In practice, it means that if a dataset is exhausted, it will return to the beginning of this dataset until the stop criterion has been reached. Note that if no sampling probabilities are specified, the new dataset will have `max_length_datasets*nb_dataset samples`. ## Rename, remove, and cast The following methods allow you to modify the columns of a dataset. These methods are useful for renaming or removing columns and changing columns to a new set of features. ### Rename Use [`IterableDataset.rename_column`] when you need to rename a column in your dataset. Features associated with the original column are actually moved under the new column name, instead of just replacing the original column in-place. Provide [`IterableDataset.rename_column`] with the name of the original column, and the new column name: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('mc4', 'en', streaming=True, split='train', trust_remote_code=True) >>> dataset = dataset.rename_column("text", "content") ``` ### Remove When you need to remove one or more columns, give [`IterableDataset.remove_columns`] the name of the column to remove. Remove more than one column by providing a list of column names: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('mc4', 'en', streaming=True, split='train', trust_remote_code=True) >>> dataset = dataset.remove_columns('timestamp') ``` ### Cast [`IterableDataset.cast`] changes the feature type of one or more columns. This method takes your new `Features` as its argument. The following sample code shows how to change the feature types of `ClassLabel` and `Value`: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('glue', 'mrpc', split='train', streaming=True) >>> dataset.features {'sentence1': Value(dtype='string', id=None), 'sentence2': Value(dtype='string', id=None), 'label': ClassLabel(num_classes=2, names=['not_equivalent', 'equivalent'], names_file=None, id=None), 'idx': Value(dtype='int32', id=None)} >>> from datasets import ClassLabel, Value >>> new_features = dataset.features.copy() >>> new_features["label"] = ClassLabel(names=['negative', 'positive']) >>> new_features["idx"] = Value('int64') >>> dataset = dataset.cast(new_features) >>> dataset.features {'sentence1': Value(dtype='string', id=None), 'sentence2': Value(dtype='string', id=None), 'label': ClassLabel(num_classes=2, names=['negative', 'positive'], names_file=None, id=None), 'idx': Value(dtype='int64', id=None)} ``` <Tip> Casting only works if the original feature type and new feature type are compatible. For example, you can cast a column with the feature type `Value('int32')` to `Value('bool')` if the original column only contains ones and zeros. </Tip> Use [`IterableDataset.cast_column`] to change the feature type of just one column. Pass the column name and its new feature type as arguments: ```py >>> dataset.features {'audio': Audio(sampling_rate=44100, mono=True, id=None)} >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) >>> dataset.features {'audio': Audio(sampling_rate=16000, mono=True, id=None)} ``` ## Map Similar to the [`Dataset.map`] function for a regular [`Dataset`], 🤗 Datasets features [`IterableDataset.map`] for processing an [`IterableDataset`]. [`IterableDataset.map`] applies processing on-the-fly when examples are streamed. It allows you to apply a processing function to each example in a dataset, independently or in batches. This function can even create new rows and columns. The following example demonstrates how to tokenize a [`IterableDataset`]. The function needs to accept and output a `dict`: ```py >>> def add_prefix(example): ... example['text'] = 'My text: ' + example['text'] ... return example ``` Next, apply this function to the dataset with [`IterableDataset.map`]: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('oscar', 'unshuffled_deduplicated_en', streaming=True, split='train', trust_remote_code=True) >>> updated_dataset = dataset.map(add_prefix) >>> list(updated_dataset.take(3)) [{'id': 0, 'text': 'My text: Mtendere Village was inspired by...'}, {'id': 1, 'text': 'My text: Lily James cannot fight the music...'}, {'id': 2, 'text': 'My text: "I\'d love to help kickstart...'}] ``` Let's take a look at another example, except this time, you will remove a column with [`IterableDataset.map`]. When you remove a column, it is only removed after the example has been provided to the mapped function. This allows the mapped function to use the content of the columns before they are removed. Specify the column to remove with the `remove_columns` argument in [`IterableDataset.map`]: ```py >>> updated_dataset = dataset.map(add_prefix, remove_columns=["id"]) >>> list(updated_dataset.take(3)) [{'text': 'My text: Mtendere Village was inspired by...'}, {'text': 'My text: Lily James cannot fight the music...'}, {'text': 'My text: "I\'d love to help kickstart...'}] ``` ### Batch processing [`IterableDataset.map`] also supports working with batches of examples. Operate on batches by setting `batched=True`. The default batch size is 1000, but you can adjust it with the `batch_size` argument. This opens the door to many interesting applications such as tokenization, splitting long sentences into shorter chunks, and data augmentation. #### Tokenization ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> dataset = load_dataset("mc4", "en", streaming=True, split="train", trust_remote_code=True) >>> tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased') >>> def encode(examples): ... return tokenizer(examples['text'], truncation=True, padding='max_length') >>> dataset = dataset.map(encode, batched=True, remove_columns=["text", "timestamp", "url"]) >>> next(iter(dataset)) {'input_ids': [101, 8466, 1018, 1010, 4029, 2475, 2062, 18558, 3100, 2061, ...,1106, 3739, 102], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ..., 1, 1]} ``` <Tip> See other examples of batch processing in the [batched map processing](./process#batch-processing) documentation. They work the same for iterable datasets. </Tip> ### Filter You can filter rows in the dataset based on a predicate function using [`Dataset.filter`]. It returns rows that match a specified condition: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('oscar', 'unshuffled_deduplicated_en', streaming=True, split='train', trust_remote_code=True) >>> start_with_ar = dataset.filter(lambda example: example['text'].startswith('Ar')) >>> next(iter(start_with_ar)) {'id': 4, 'text': 'Are you looking for Number the Stars (Essential Modern Classics)?...'} ``` [`Dataset.filter`] can also filter by indices if you set `with_indices=True`: ```py >>> even_dataset = dataset.filter(lambda example, idx: idx % 2 == 0, with_indices=True) >>> list(even_dataset.take(3)) [{'id': 0, 'text': 'Mtendere Village was inspired by the vision of Chief Napoleon Dzombe, ...'}, {'id': 2, 'text': '"I\'d love to help kickstart continued development! And 0 EUR/month...'}, {'id': 4, 'text': 'Are you looking for Number the Stars (Essential Modern Classics)? Normally, ...'}] ``` ## Stream in a training loop [`IterableDataset`] can be integrated into a training loop. First, shuffle the dataset: <frameworkcontent> <pt> ```py >>> seed, buffer_size = 42, 10_000 >>> dataset = dataset.shuffle(seed, buffer_size=buffer_size) ``` Lastly, create a simple training loop and start training: ```py >>> import torch >>> from torch.utils.data import DataLoader >>> from transformers import AutoModelForMaskedLM, DataCollatorForLanguageModeling >>> from tqdm import tqdm >>> dataset = dataset.with_format("torch") >>> dataloader = DataLoader(dataset, collate_fn=DataCollatorForLanguageModeling(tokenizer)) >>> device = 'cuda' if torch.cuda.is_available() else 'cpu' >>> model = AutoModelForMaskedLM.from_pretrained("distilbert-base-uncased") >>> model.train().to(device) >>> optimizer = torch.optim.AdamW(params=model.parameters(), lr=1e-5) >>> for epoch in range(3): ... dataset.set_epoch(epoch) ... for i, batch in enumerate(tqdm(dataloader, total=5)): ... if i == 5: ... break ... batch = {k: v.to(device) for k, v in batch.items()} ... outputs = model(**batch) ... loss = outputs[0] ... loss.backward() ... optimizer.step() ... optimizer.zero_grad() ... if i % 10 == 0: ... print(f"loss: {loss}") ``` </pt> </frameworkcontent> <!-- TODO: Write the TF content! -->
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/nlp_load.mdx
# Load text data This guide shows you how to load text datasets. To learn how to load any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./loading">general loading guide</a>. Text files are one of the most common file types for storing a dataset. By default, 🤗 Datasets samples a text file line by line to build the dataset. ```py >>> from datasets import load_dataset >>> dataset = load_dataset("text", data_files={"train": ["my_text_1.txt", "my_text_2.txt"], "test": "my_test_file.txt"}) # Load from a directory >>> dataset = load_dataset("text", data_dir="path/to/text/dataset") ``` To sample a text file by paragraph or even an entire document, use the `sample_by` parameter: ```py # Sample by paragraph >>> dataset = load_dataset("text", data_files={"train": "my_train_file.txt", "test": "my_test_file.txt"}, sample_by="paragraph") # Sample by document >>> dataset = load_dataset("text", data_files={"train": "my_train_file.txt", "test": "my_test_file.txt"}, sample_by="document") ``` You can also use grep patterns to load specific files: ```py >>> from datasets import load_dataset >>> c4_subset = load_dataset("allenai/c4", data_files="en/c4-train.0000*-of-01024.json.gz") ``` To load remote text files via HTTP, pass the URLs instead: ```py >>> dataset = load_dataset("text", data_files="https://huggingface.co/datasets/lhoestq/test/resolve/main/some_text.txt") ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_dataset_load.mdx
# Build and load Nearly every deep learning workflow begins with loading a dataset, which makes it one of the most important steps. With 🤗 Datasets, there are more than 900 datasets available to help you get started with your NLP task. All you have to do is call: [`load_dataset`] to take your first step. This function is a true workhorse in every sense because it builds and loads every dataset you use. ## ELI5: `load_dataset` Let's begin with a basic Explain Like I'm Five. A dataset is a directory that contains: - Some data files in generic formats (JSON, CSV, Parquet, text, etc.) - A dataset card named `README.md` that contains documentation about the dataset as well as a YAML header to define the datasets tags and configurations - An optional dataset script if it requires some code to read the data files. This is sometimes used to load files of specific formats and structures. The [`load_dataset`] function fetches the requested dataset locally or from the Hugging Face Hub. The Hub is a central repository where all the Hugging Face datasets and models are stored. If the dataset only contains data files, then [`load_dataset`] automatically infers how to load the data files from their extensions (json, csv, parquet, txt, etc.). Under the hood, 🤗 Datasets will use an appropriate [`DatasetBuilder`] based on the data files format. There exist one builder per data file format in 🤗 Datasets: * [`datasets.packaged_modules.text.Text`] for text * [`datasets.packaged_modules.csv.Csv`] for CSV and TSV * [`datasets.packaged_modules.json.Json`] for JSON and JSONL * [`datasets.packaged_modules.parquet.Parquet`] for Parquet * [`datasets.packaged_modules.arrow.Arrow`] for Arrow (streaming file format) * [`datasets.packaged_modules.sql.Sql`] for SQL databases * [`datasets.packaged_modules.imagefolder.ImageFolder`] for image folders * [`datasets.packaged_modules.audiofolder.AudioFolder`] for audio folders If the dataset has a dataset script, then it downloads and imports it from the Hugging Face Hub. Code in the dataset script defines a custom [`DatasetBuilder`] the dataset information (description, features, URL to the original files, etc.), and tells 🤗 Datasets how to generate and display examples from it. <Tip> Read the [Share](./upload_dataset) section to learn more about how to share a dataset. This section also provides a step-by-step guide on how to write your own dataset loading script! </Tip> 🤗 Datasets downloads the dataset files from the original URL, generates the dataset and caches it in an Arrow table on your drive. If you've downloaded the dataset before, then 🤗 Datasets will reload it from the cache to save you the trouble of downloading it again. Now that you have a high-level understanding about how datasets are built, let's take a closer look at the nuts and bolts of how all this works. ## Building a dataset When you load a dataset for the first time, 🤗 Datasets takes the raw data file and builds it into a table of rows and typed columns. There are two main classes responsible for building a dataset: [`BuilderConfig`] and [`DatasetBuilder`]. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/builderconfig.png"/> </div> ### BuilderConfig[[datasets-builderconfig]] [`BuilderConfig`] is the configuration class of [`DatasetBuilder`]. The [`BuilderConfig`] contains the following basic attributes about a dataset: | Attribute | Description | |---------------|--------------------------------------------------------------| | `name` | Short name of the dataset. | | `version` | Dataset version identifier. | | `data_dir` | Stores the path to a local folder containing the data files. | | `data_files` | Stores paths to local data files. | | `description` | Description of the dataset. | If you want to add additional attributes to your dataset such as the class labels, you can subclass the base [`BuilderConfig`] class. There are two ways to populate the attributes of a [`BuilderConfig`] class or subclass: - Provide a list of predefined [`BuilderConfig`] class (or subclass) instances in the datasets [`DatasetBuilder.BUILDER_CONFIGS`] attribute. - When you call [`load_dataset`], any keyword arguments that are not specific to the method will be used to set the associated attributes of the [`BuilderConfig`] class. This will override the predefined attributes if a specific configuration was selected. You can also set the [`DatasetBuilder.BUILDER_CONFIG_CLASS`] to any custom subclass of [`BuilderConfig`]. ### DatasetBuilder[[datasets-datasetbuilder]] [`DatasetBuilder`] accesses all the attributes inside [`BuilderConfig`] to build the actual dataset. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/datasetbuilder.png"/> </div> There are three main methods in [`DatasetBuilder`]: 1. [`DatasetBuilder._info`] is in charge of defining the dataset attributes. When you call `dataset.info`, 🤗 Datasets returns the information stored here. Likewise, the [`Features`] are also specified here. Remember, the [`Features`] are like the skeleton of the dataset. It provides the names and types of each column. 2. [`DatasetBuilder._split_generator`] downloads or retrieves the requested data files, organizes them into splits, and defines specific arguments for the generation process. This method has a [`DownloadManager`] that downloads files or fetches them from your local filesystem. Within the [`DownloadManager`], there is a [`DownloadManager.download_and_extract`] method that accepts a dictionary of URLs to the original data files, and downloads the requested files. Accepted inputs include: a single URL or path, or a list/dictionary of URLs or paths. Any compressed file types like TAR, GZIP and ZIP archives will be automatically extracted. Once the files are downloaded, [`SplitGenerator`] organizes them into splits. The [`SplitGenerator`] contains the name of the split, and any keyword arguments that are provided to the [`DatasetBuilder._generate_examples`] method. The keyword arguments can be specific to each split, and typically comprise at least the local path to the data files for each split. 3. [`DatasetBuilder._generate_examples`] reads and parses the data files for a split. Then it yields dataset examples according to the format specified in the `features` from [`DatasetBuilder._info`]. The input of [`DatasetBuilder._generate_examples`] is actually the `filepath` provided in the keyword arguments of the last method. The dataset is generated with a Python generator, which doesn't load all the data in memory. As a result, the generator can handle large datasets. However, before the generated samples are flushed to the dataset file on disk, they are stored in an `ArrowWriter` buffer. This means the generated samples are written by batch. If your dataset samples consumes a lot of memory (images or videos), then make sure to specify a low value for the `DEFAULT_WRITER_BATCH_SIZE` attribute in [`DatasetBuilder`]. We recommend not exceeding a size of 200 MB. ## Maintaining integrity To ensure a dataset is complete, [`load_dataset`] will perform a series of tests on the downloaded files to make sure everything is there. This way, you don't encounter any surprises when your requested dataset doesn't get generated as expected. [`load_dataset`] verifies: - The number of splits in the generated `DatasetDict`. - The number of samples in each split of the generated `DatasetDict`. - The list of downloaded files. - The SHA256 checksums of the downloaded files (disabled by defaut). If the dataset doesn't pass the verifications, it is likely that the original host of the dataset made some changes in the data files. <Tip> If it is your own dataset, you'll need to recompute the information above and update the `README.md` file in your dataset repository. Take a look at this [section](dataset_script#optional-generate-dataset-metadata) to learn how to generate and update this metadata. </Tip> In this case, an error is raised to alert that the dataset has changed. To ignore the error, one needs to specify `verification_mode="no_checks"` in [`load_dataset`]. Anytime you see a verification error, feel free to open a discussion or pull request in the corresponding dataset "Community" tab, so that the integrity checks for that dataset are updated. ## Security The dataset repositories on the Hub are scanned for malware, see more information [here](https://huggingface.co/docs/hub/security#malware-scanning). Moreover the datasets without a namespace (originally contributed on our GitHub repository) have all been reviewed by our maintainers. The code of these datasets is considered **safe**. It concerns datasets that are not under a namespace, e.g. "squad" or "glue", unlike the other datasets that are named "username/dataset_name" or "org/dataset_name".
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_map_batch.mdx
# Batch mapping Combining the utility of [`Dataset.map`] with batch mode is very powerful. It allows you to speed up processing, and freely control the size of the generated dataset. ## Need for speed The primary objective of batch mapping is to speed up processing. Often times, it is faster to work with batches of data instead of single examples. Naturally, batch mapping lends itself to tokenization. For example, the 🤗 [Tokenizers](https://huggingface.co/docs/tokenizers/python/latest/) library works faster with batches because it parallelizes the tokenization of all the examples in a batch. ## Input size != output size The ability to control the size of the generated dataset can be leveraged for many interesting use-cases. In the How-to [map](#map) section, there are examples of using batch mapping to: - Split long sentences into shorter chunks. - Augment a dataset with additional tokens. It is helpful to understand how this works, so you can come up with your own ways to use batch mapping. At this point, you may be wondering how you can control the size of the generated dataset. The answer is: **the mapped function does not have to return an output batch of the same size**. In other words, your mapped function input can be a batch of size `N` and return a batch of size `M`. The output `M` can be greater than or less than `N`. This means you can concatenate your examples, divide it up, and even add more examples! However, remember that all values in the output dictionary must contain the **same number of elements** as the other fields in the output dictionary. Otherwise, it is not possible to define the number of examples in the output returned by the mapped function. The number can vary between successive batches processed by the mapped function. For a single batch though, all values of the output dictionary should have the same length (i.e., the number of elements). For example, from a dataset of 1 column and 3 rows, if you use `map` to return a new column with twice as many rows, then you will have an error. In this case, you end up with one column with 3 rows, and one column with 6 rows. As you can see, the table will not be valid: ```py >>> from datasets import Dataset >>> dataset = Dataset.from_dict({"a": [0, 1, 2]}) >>> dataset.map(lambda batch: {"b": batch["a"] * 2}, batched=True) # new column with 6 elements: [0, 1, 2, 0, 1, 2] 'ArrowInvalid: Column 1 named b expected length 3 but got length 6' ``` To make it valid, you have to drop one of the columns: ```py >>> from datasets import Dataset >>> dataset = Dataset.from_dict({"a": [0, 1, 2]}) >>> dataset_with_duplicates = dataset.map(lambda batch: {"b": batch["a"] * 2}, remove_columns=["a"], batched=True) >>> len(dataset_with_duplicates) 6 ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/installation.md
# Installation Before you start, you'll need to setup your environment and install the appropriate packages. 🤗 Datasets is tested on **Python 3.7+**. <Tip> If you want to use 🤗 Datasets with TensorFlow or PyTorch, you'll need to install them separately. Refer to the [TensorFlow installation page](https://www.tensorflow.org/install/pip#tensorflow-2-packages-are-available) or the [PyTorch installation page](https://pytorch.org/get-started/locally/#start-locally) for the specific install command for your framework. </Tip> ## Virtual environment You should install 🤗 Datasets in a [virtual environment](https://docs.python.org/3/library/venv.html) to keep things tidy and avoid dependency conflicts. 1. Create and navigate to your project directory: ```bash mkdir ~/my-project cd ~/my-project ``` 2. Start a virtual environment inside your directory: ```bash python -m venv .env ``` 3. Activate and deactivate the virtual environment with the following commands: ```bash # Activate the virtual environment source .env/bin/activate # Deactivate the virtual environment source .env/bin/deactivate ``` Once you've created your virtual environment, you can install 🤗 Datasets in it. ## pip The most straightforward way to install 🤗 Datasets is with pip: ```bash pip install datasets ``` Run the following command to check if 🤗 Datasets has been properly installed: ```bash python -c "from datasets import load_dataset; print(load_dataset('squad', split='train')[0])" ``` This command downloads version 1 of the [Stanford Question Answering Dataset (SQuAD)](https://rajpurkar.github.io/SQuAD-explorer/), loads the training split, and prints the first training example. You should see: ```python {'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']}, 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', 'id': '5733be284776f41900661182', 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?', 'title': 'University_of_Notre_Dame'} ``` ## Audio To work with audio datasets, you need to install the [`Audio`] feature as an extra dependency: ```bash pip install datasets[audio] ``` <Tip warning={true}> To decode mp3 files, you need to have at least version 1.1.0 of the `libsndfile` system library. Usually, it's bundled with the python [`soundfile`](https://github.com/bastibe/python-soundfile) package, which is installed as an extra audio dependency for 🤗 Datasets. For Linux, the required version of `libsndfile` is bundled with `soundfile` starting from version 0.12.0. You can run the following command to determine which version of `libsndfile` is being used by `soundfile`: ```bash python -c "import soundfile; print(soundfile.__libsndfile_version__)" ``` </Tip> ## Vision To work with image datasets, you need to install the [`Image`] feature as an extra dependency: ```bash pip install datasets[vision] ``` ## source Building 🤗 Datasets from source lets you make changes to the code base. To install from the source, clone the repository and install with the following commands: ```bash git clone https://github.com/huggingface/datasets.git cd datasets pip install -e . ``` Again, you can check if 🤗 Datasets was properly installed with the following command: ```bash python -c "from datasets import load_dataset; print(load_dataset('squad', split='train')[0])" ``` ## conda 🤗 Datasets can also be installed from conda, a package management system: ```bash conda install -c huggingface -c conda-forge datasets ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/troubleshoot.mdx
# Troubleshooting This guide aims to provide you the tools and knowledge required to navigate some common issues. If the suggestions listed in this guide do not cover your such situation, please refer to the [Asking for Help](#asking-for-help) section to learn where to find help with your specific issue. ## Issues when uploading datasets with `push_to_hub` ### Authentication issues If you are experiencing authentication issues when sharing a dataset on 🤗 Hub using [`Dataset.push_to_hub`] and a Hugging Face access token: * Make sure that the Hugging Face token you're using to authenticate yourself is a token with **write** permission. * On OSX, it may help to clean up all the huggingface.co passwords on your keychain access, as well as reconfigure `git config --global credential.helper osxkeychain`, before using `huggingface-cli login`. Alternatively, you can use SSH keys to authenticate yourself - read more in the [🤗 Hub documentation](https://huggingface.co/docs/hub/security-git-ssh). ### Lost connection on large dataset upload When uploading large datasets to Hub, if the number of dataset shards is large, it can create too many commits for the Hub in a short period. This will result in a connection error. The connection error can also be caused by a HTTP 500 error returned by AWS S3 bucket that Hub uses internally. In either situation, you can re-run [`Dataset.push_to_hub`] to proceed with the dataset upload. Hub will check the SHAs of already uploaded shards to avoid reuploading them. We are working on making upload process more robust to transient errors, so updating to the latest library version is always a good idea. ### `Too Many Requests` Uploading large datasets via `push_to_hub()` can result in an error: ```bash HfHubHTTPError: 429 Client Error: Too Many Requests for url: ... You have exceeded our hourly quotas for action: commit. We invite you to retry later. ``` If you encounter this issue, you need to upgrade the `datasets` library to the latest version (or at least `2.15.0`). ## Issues when creating datasets from custom data ### Loading images and audio from a folder When creating a dataset from a folder, one of the most common issues is that the file structure does not follow the expected format, or there's an issue with the metadata file. Learn more about required folder structure in corresponding documentation pages: * [AudioFolder](https://huggingface.co/docs/datasets/audio_dataset#audiofolder) * [ImageFolder](https://huggingface.co/docs/datasets/image_dataset#imagefolder) ### Pickling issues #### Pickling issues when using `Dataset.from_generator` When creating a dataset, [`IterableDataset.from_generator`] and [`Dataset.from_generator`] expect a "picklable" generator function. This is required to hash the function using [`pickle`](https://docs.python.org/3/library/pickle.html) to be able to cache the dataset on disk. While generator functions are generally "picklable", note that generator objects are not. So if you're using a generator object, you will encounter a `TypeError` like this: ```bash TypeError: cannot pickle 'generator' object ``` This error can also occur when using a generator function that uses a global object that is not "picklable", such as a DB connection, for example. If that's the case, you can initialize such object directly inside the generator function to avoid this error. #### Pickling issues with `Dataset.map` Pickling errors can also happen in the multiprocess [`Dataset.map`] - objects are pickled to be passed to child processes. If the objects used in the transformation are not picklable, it's not possible to cache the result of `map`, which leads to an error being raised. Here are some ways to address this issue: * A universal solution to pickle issues is to make sure the objects (or generator classes) are pickable manually by implementing `__getstate__` / `__setstate__` / `__reduce__`. * You can also provide your own unique hash in `map` with the `new_fingerprint` argument. * You can also disable caching by calling `datasets.disable_caching()`, however, this is undesirable - [read more about importance of cache](cache) ## Asking for help If the above troubleshooting advice did not help you resolve your issue, reach out for help to the community and the team. ### Forums Ask for help on the Hugging Face forums - post your question in the [🤗Datasets category](https://discuss.huggingface.co/c/datasets/10) Make sure to write a descriptive post with relevant context about your setup and reproducible code to maximize the likelihood that your problem is solved! ### Discord Post a question on [Discord](http://hf.co/join/discord), and let the team and the community help you. ### Community Discussions on 🤗 Hub If you are facing issues creating a custom dataset with a script on Hub, you can ask the Hugging Face team for help by opening a discussion in the Community tab of your dataset with this message: ```text # Dataset rewiew request for <Dataset name> ## Description <brief description of the dataset> ## Files to review - file1 - file2 - ... cc @lhoestq @polinaeterna @mariosasko @albertvillanova ``` ### GitHub Issues Finally, if you suspect to have found a bug related to the library itself, create an Issue on the 🤗 Datasets [GitHub repository](https://github.com/huggingface/datasets/issues). Include context regarding the bug: code snippet to reproduce, details about your environment and data, etc. to help us figure out what's wrong and how we can fix it.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_arrow.md
# Datasets 🤝 Arrow ## What is Arrow? [Arrow](https://arrow.apache.org/) enables large amounts of data to be processed and moved quickly. It is a specific data format that stores data in a columnar memory layout. This provides several significant advantages: * Arrow's standard format allows [zero-copy reads](https://en.wikipedia.org/wiki/Zero-copy) which removes virtually all serialization overhead. * Arrow is language-agnostic so it supports different programming languages. * Arrow is column-oriented so it is faster at querying and processing slices or columns of data. * Arrow allows for copy-free hand-offs to standard machine learning tools such as NumPy, Pandas, PyTorch, and TensorFlow. * Arrow supports many, possibly nested, column types. ## Memory-mapping 🤗 Datasets uses Arrow for its local caching system. It allows datasets to be backed by an on-disk cache, which is memory-mapped for fast lookup. This architecture allows for large datasets to be used on machines with relatively small device memory. For example, loading the full English Wikipedia dataset only takes a few MB of RAM: ```python >>> import os; import psutil; import timeit >>> from datasets import load_dataset # Process.memory_info is expressed in bytes, so convert to megabytes >>> mem_before = psutil.Process(os.getpid()).memory_info().rss / (1024 * 1024) >>> wiki = load_dataset("wikipedia", "20220301.en", split="train") >>> mem_after = psutil.Process(os.getpid()).memory_info().rss / (1024 * 1024) >>> print(f"RAM memory used: {(mem_after - mem_before)} MB") RAM memory used: 50 MB ``` This is possible because the Arrow data is actually memory-mapped from disk, and not loaded in memory. Memory-mapping allows access to data on disk, and leverages virtual memory capabilities for fast lookups. ## Performance Iterating over a memory-mapped dataset using Arrow is fast. Iterating over Wikipedia on a laptop gives you speeds of 1-3 Gbit/s: ```python >>> s = """batch_size = 1000 ... for batch in wiki.iter(batch_size): ... ... ... """ >>> elapsed_time = timeit.timeit(stmt=s, number=1, globals=globals()) >>> print(f"Time to iterate over the {wiki.dataset_size >> 30} GB dataset: {elapsed_time:.1f} sec, " ... f"ie. {float(wiki.dataset_size >> 27)/elapsed_time:.1f} Gb/s") Time to iterate over the 18 GB dataset: 31.8 sec, ie. 4.8 Gb/s ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/share.mdx
# Share a dataset using the CLI At Hugging Face, we are on a mission to democratize good Machine Learning and we believe in the value of open source. That's why we designed 🤗 Datasets so that anyone can share a dataset with the greater ML community. There are currently thousands of datasets in over 100 languages in the Hugging Face Hub, and the Hugging Face team always welcomes new contributions! Dataset repositories offer features such as: - Free dataset hosting - Dataset versioning - Commit history and diffs - Metadata for discoverability - Dataset cards for documentation, licensing, limitations, etc. This guide will show you how to share a dataset that can be easily accessed by anyone. <a id='upload_dataset_repo'></a> ## Add a dataset You can share your dataset with the community with a dataset repository on the Hugging Face Hub. It can also be a private dataset if you want to control who has access to it. In a dataset repository, you can host all your data files and [configure your dataset](./repository_structure#define-your-splits-in-yaml) to define which file goes to which split. The following formats are supported: CSV, TSV, JSON, JSON lines, text, Parquet, Arrow, SQLite. Many kinds of compressed file types are also supported: GZ, BZ2, LZ4, LZMA or ZSTD. For example, your dataset can be made of `.json.gz` files. On the other hand, if your dataset is not in a supported format or if you want more control over how your dataset is loaded, you can write your own dataset script. When loading a dataset from the Hub, all the files in the supported formats are loaded, following the [repository structure](./repository_structure). However if there's a dataset script, it is downloaded and executed to download and prepare the dataset instead. For more information on how to load a dataset from the Hub, take a look at the [load a dataset from the Hub](./load_hub) tutorial. ### Create the repository Sharing a community dataset will require you to create an account on [hf.co](https://huggingface.co/join) if you don't have one yet. You can directly create a [new dataset repository](https://huggingface.co/login?next=%2Fnew-dataset) from your account on the Hugging Face Hub, but this guide will show you how to upload a dataset from the terminal. 1. Make sure you are in the virtual environment where you installed Datasets, and run the following command: ``` huggingface-cli login ``` 2. Login using your Hugging Face Hub credentials, and create a new dataset repository: ``` huggingface-cli repo create your_dataset_name --type dataset ``` Add the `-organization` flag to create a repository under a specific organization: ``` huggingface-cli repo create your_dataset_name --type dataset --organization your-org-name ``` ### Clone the repository 3. Install [Git LFS](https://git-lfs.github.com/) and clone your repository (refer to the [Git over SSH docs](https://huggingface.co/docs/hub/security-git-ssh) if you prefer cloning through SSH): ``` # Make sure you have git-lfs installed # (https://git-lfs.github.com/) git lfs install git clone https://huggingface.co/datasets/namespace/your_dataset_name ``` Here the `namespace` is either your username or your organization name. ### Prepare your files 4. Now is a good time to check your directory to ensure the only files you're uploading are: - The data files of the dataset - The dataset card `README.md` - (optional) `your_dataset_name.py` is your dataset loading script (optional if your data files are already in the supported formats csv/jsonl/json/parquet/txt). To create a dataset script, see the [dataset script](dataset_script) page. ### Upload your files You can directly upload your files to your repository on the Hugging Face Hub, but this guide will show you how to upload the files from the terminal. 5. It is important to add the large data files first with `git lfs track` or else you will encounter an error later when you push your files: ``` cp /somewhere/data/*.json . git lfs track *.json git add .gitattributes git add *.json git commit -m "add json files" ``` 6. (Optional) Add the dataset loading script: ``` cp /somewhere/data/load_script.py . git add --all ``` 7. Verify the files have been correctly staged. Then you can commit and push your files: ``` git status git commit -m "First version of the your_dataset_name dataset." git push ``` Congratulations, your dataset has now been uploaded to the Hugging Face Hub where anyone can load it in a single line of code! 🥳 ``` dataset = load_dataset("namespace/your_dataset_name") ``` Finally, don't forget to enrich the dataset card to document your dataset and make it discoverable! Check out the [Create a dataset card](dataset_card) guide to learn more. ## Datasets on GitHub (legacy) Datasets used to be hosted on our GitHub repository, but all datasets have now been migrated to the Hugging Face Hub. The legacy GitHub datasets were added originally on our GitHub repository and therefore don't have a namespace on the Hub: "squad", "glue", etc. unlike the other datasets that are named "username/dataset_name" or "org/dataset_name". <Tip> The distinction between a Hub dataset within or without a namespace only comes from the legacy sharing workflow. It does not involve any ranking, decisioning, or opinion regarding the contents of the dataset itself. </Tip> Those datasets are now maintained on the Hub: if you think a fix is needed, please use their "Community" tab to open a discussion or create a Pull Request. The code of these datasets is reviewed by the Hugging Face team.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/nlp_process.mdx
# Process text data This guide shows specific methods for processing text datasets. Learn how to: - Tokenize a dataset with [`~Dataset.map`]. - Align dataset labels with label ids for NLI datasets. For a guide on how to process any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./process">general process guide</a>. ## Map The [`~Dataset.map`] function supports processing batches of examples at once which speeds up tokenization. Load a tokenizer from 🤗 [Transformers](https://huggingface.co/transformers/): ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") ``` Set the `batched` parameter to `True` in the [`~Dataset.map`] function to apply the tokenizer to batches of examples: ```py >>> dataset = dataset.map(lambda examples: tokenizer(examples["text"]), batched=True) >>> dataset[0] {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1, 'input_ids': [101, 1996, 2600, 2003, 16036, 2000, 2022, 1996, 7398, 2301, 1005, 1055, 2047, 1000, 16608, 1000, 1998, 2008, 2002, 1005, 1055, 2183, 2000, 2191, 1037, 17624, 2130, 3618, 2084, 7779, 29058, 8625, 13327, 1010, 3744, 1011, 18856, 19513, 3158, 5477, 4168, 2030, 7112, 16562, 2140, 1012, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} ``` The [`~Dataset.map`] function converts the returned values to a PyArrow-supported format. But explicitly returning the tensors as NumPy arrays is faster because it is a natively supported PyArrow format. Set `return_tensors="np"` when you tokenize your text: ```py >>> dataset = dataset.map(lambda examples: tokenizer(examples["text"], return_tensors="np"), batched=True) ``` ## Align The [`~Dataset.align_labels_with_mapping`] function aligns a dataset label id with the label name. Not all 🤗 Transformers models follow the prescribed label mapping of the original dataset, especially for NLI datasets. For example, the [MNLI](https://huggingface.co/datasets/glue) dataset uses the following label mapping: ```py >>> label2id = {"entailment": 0, "neutral": 1, "contradiction": 2} ``` To align the dataset label mapping with the mapping used by a model, create a dictionary of the label name and id to align on: ```py >>> label2id = {"contradiction": 0, "neutral": 1, "entailment": 2} ``` Pass the dictionary of the label mappings to the [`~Dataset.align_labels_with_mapping`] function, and the column to align on: ```py >>> from datasets import load_dataset >>> mnli = load_dataset("glue", "mnli", split="train") >>> mnli_aligned = mnli.align_labels_with_mapping(label2id, "label") ``` You can also use this function to assign a custom mapping of labels to ids.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_mapstyle_vs_iterable.mdx
# Differences between Dataset and IterableDataset There are two types of dataset objects, a [`Dataset`] and an [`IterableDataset`]. Whichever type of dataset you choose to use or create depends on the size of the dataset. In general, an [`IterableDataset`] is ideal for big datasets (think hundreds of GBs!) due to its lazy behavior and speed advantages, while a [`Dataset`] is great for everything else. This page will compare the differences between a [`Dataset`] and an [`IterableDataset`] to help you pick the right dataset object for you. ## Downloading and streaming When you have a regular [`Dataset`], you can access it using `my_dataset[0]`. This provides random access to the rows. Such datasets are also called "map-style" datasets. For example you can download ImageNet-1k like this and access any row: ```python from datasets import load_dataset imagenet = load_dataset("imagenet-1k", split="train") # downloads the full dataset print(imagenet[0]) ``` But one caveat is that you must have the entire dataset stored on your disk or in memory, which blocks you from accessing datasets bigger than the disk. Because it can become inconvenient for big datasets, there exists another type of dataset, the [`IterableDataset`]. When you have an `IterableDataset`, you can access it using a `for` loop to load the data progressively as you iterate over the dataset. This way, only a small fraction of examples is loaded in memory, and you don't write anything on disk. For example, you can stream the ImageNet-1k dataset without downloading it on disk: ```python from datasets import load_dataset imagenet = load_dataset("imagenet-1k", split="train", streaming=True) # will start loading the data when iterated over for example in imagenet: print(example) break ``` Streaming can read online data without writing any file to disk. For example, you can stream datasets made out of multiple shards, each of which is hundreds of gigabytes like [C4](https://huggingface.co/datasets/c4), [OSCAR](https://huggingface.co/datasets/oscar) or [LAION-2B](https://huggingface.co/datasets/laion/laion2B-en). Learn more about how to stream a dataset in the [Dataset Streaming Guide](./stream). This is not the only difference though, because the "lazy" behavior of an `IterableDataset` is also present when it comes to dataset creation and processing. ## Creating map-style datasets and iterable datasets You can create a [`Dataset`] using lists or dictionaries, and the data is entirely converted to Arrow so you can easily access any row: ```python my_dataset = Dataset.from_dict({"col_1": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}) print(my_dataset[0]) ``` To create an `IterableDataset` on the other hand, you must provide a "lazy" way to load the data. In Python, we generally use generator functions. These functions `yield` one example at a time, which means you can't access a row by slicing it like a regular `Dataset`: ```python def my_generator(n): for i in range(n): yield {"col_1": i} my_iterable_dataset = IterableDataset.from_generator(my_generator, gen_kwargs={"n": 10}) for example in my_iterable_dataset: print(example) break ``` ## Loading local files entirely and progressively It is possible to convert local or remote data files to an Arrow [`Dataset`] using [`load_dataset`]: ```python data_files = {"train": ["path/to/data.csv"]} my_dataset = load_dataset("csv", data_files=data_files, split="train") print(my_dataset[0]) ``` However, this requires a conversion step from CSV to Arrow format, which takes time and disk space if your dataset is big. To save disk space and skip the conversion step, you can define an `IterableDataset` by streaming from the local files directly. This way, the data is read progressively from the local files as you iterate over the dataset: ```python data_files = {"train": ["path/to/data.csv"]} my_iterable_dataset = load_dataset("csv", data_files=data_files, split="train", streaming=True) for example in my_iterable_dataset: # this reads the CSV file progressively as you iterate over the dataset print(example) break ``` Many file formats are supported, like CSV, JSONL, and Parquet, as well as image and audio files. You can find more information in the corresponding guides for loading [tabular](./tabular_load), [text](./nlp_load), [vision](./image_load), and [audio](./audio_load]) datasets. ## Eager data processing and lazy data processing When you process a [`Dataset`] object using [`Dataset.map`], the entire dataset is processed immediately and returned. This is similar to how `pandas` works for example. ```python my_dataset = my_dataset.map(process_fn) # process_fn is applied on all the examples of the dataset print(my_dataset[0]) ``` On the other hand, due to the "lazy" nature of an `IterableDataset`, calling [`IterableDataset.map`] does not apply your `map` function over the full dataset. Instead, your `map` function is applied on-the-fly. Because of that, you can chain multiple processing steps and they will all run at once when you start iterating over the dataset: ```python my_iterable_dataset = my_iterable_dataset.map(process_fn_1) my_iterable_dataset = my_iterable_dataset.filter(filter_fn) my_iterable_dataset = my_iterable_dataset.map(process_fn_2) # process_fn_1, filter_fn and process_fn_2 are applied on-the-fly when iterating over the dataset for example in my_iterable_dataset: print(example) break ``` ## Exact and fast approximate shuffling When you shuffle a [`Dataset`] using [`Dataset.shuffle`], you apply an exact shuffling of the dataset. It works by taking a list of indices `[0, 1, 2, ... len(my_dataset) - 1]` and shuffling this list. Then, accessing `my_dataset[0]` returns the row and index defined by the first element of the indices mapping that has been shuffled: ```python my_dataset = my_dataset.shuffle(seed=42) print(my_dataset[0]) ``` Since we don't have random access to the rows in the case of an `IterableDataset`, we can't use a shuffled list of indices and access a row at an arbitrary position. This prevents the use of exact shuffling. Instead, a fast approximate shuffling is used in [`IterableDataset.shuffle`]. It uses a shuffle buffer to sample random examples iteratively from the dataset. Since the dataset is still read iteratively, it provides excellent speed performance: ```python my_iterable_dataset = my_iterable_dataset.shuffle(seed=42, buffer_size=100) for example in my_iterable_dataset: print(example) break ``` But using a shuffle buffer is not enough to provide a satisfactory shuffling for machine learning model training. So [`IterableDataset.shuffle`] also shuffles the dataset shards if your dataset is made of multiple files or sources: ```python # Stream from the internet my_iterable_dataset = load_dataset("deepmind/code_contests", split="train", streaming=True) my_iterable_dataset.n_shards # 39 # Stream from local files data_files = {"train": [f"path/to/data_{i}.csv" for i in range(1024)]} my_iterable_dataset = load_dataset("csv", data_files=data_files, split="train", streaming=True) my_iterable_dataset.n_shards # 1024 # From a generator function def my_generator(n, sources): for source in sources: for example_id_for_current_source in range(n): yield {"example_id": f"{source}_{example_id_for_current_source}"} gen_kwargs = {"n": 10, "sources": [f"path/to/data_{i}" for i in range(1024)]} my_iterable_dataset = IterableDataset.from_generator(my_generator, gen_kwargs=gen_kwargs) my_iterable_dataset.n_shards # 1024 ``` ## Speed differences Regular [`Dataset`] objects are based on Arrow which provides fast random access to the rows. Thanks to memory mapping and the fact that Arrow is an in-memory format, reading data from disk doesn't do expensive system calls and deserialization. It provides even faster data loading when iterating using a `for` loop by iterating on contiguous Arrow record batches. However as soon as your [`Dataset`] has an indices mapping (via [`Dataset.shuffle`] for example), the speed can become 10x slower. This is because there is an extra step to get the row index to read using the indices mapping, and most importantly, you aren't reading contiguous chunks of data anymore. To restore the speed, you'd need to rewrite the entire dataset on your disk again using [`Dataset.flatten_indices`], which removes the indices mapping. This may take a lot of time depending of the size of your dataset though: ```python my_dataset[0] # fast my_dataset = my_dataset.shuffle(seed=42) my_dataset[0] # up to 10x slower my_dataset = my_dataset.flatten_indices() # rewrite the shuffled dataset on disk as contiguous chunks of data my_dataset[0] # fast again ``` In this case, we recommend switching to an [`IterableDataset`] and leveraging its fast approximate shuffling method [`IterableDataset.shuffle`]. It only shuffles the shards order and adds a shuffle buffer to your dataset, which keeps the speed of your dataset optimal. You can also reshuffle the dataset easily: ```python for example in enumerate(my_iterable_dataset): # fast pass shuffled_iterable_dataset = my_iterable_dataset.shuffle(seed=42, buffer_size=100) for example in enumerate(shuffled_iterable_dataset): # as fast as before pass shuffled_iterable_dataset = my_iterable_dataset.shuffle(seed=1337, buffer_size=100) # reshuffling using another seed is instantaneous for example in enumerate(shuffled_iterable_dataset): # still as fast as before pass ``` If you're using your dataset on multiple epochs, the effective seed to shuffle the shards order in the shuffle buffer is `seed + epoch`. It makes it easy to reshuffle a dataset between epochs: ```python for epoch in range(n_epochs): my_iterable_dataset.set_epoch(epoch) for example in my_iterable_dataset: # fast + reshuffled at each epoch using `effective_seed = seed + epoch` pass ``` ## Switch from map-style to iterable If you want to benefit from the "lazy" behavior of an [`IterableDataset`] or their speed advantages, you can switch your map-style [`Dataset`] to an [`IterableDataset`]: ```python my_iterable_dataset = my_dataset.to_iterable_dataset() ``` If you want to shuffle your dataset or [use it with a PyTorch DataLoader](./use_with_pytorch#stream-data), we recommend generating a sharded [`IterableDataset`]: ```python my_iterable_dataset = my_dataset.to_iterable_dataset(num_shards=1024) my_iterable_dataset.n_shards # 1024 ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/index.mdx
# Datasets <img class="float-left !m-0 !border-0 !dark:border-0 !shadow-none !max-w-lg w-[150px]" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/datasets_logo.png"/> 🤗 Datasets is a library for easily accessing and sharing datasets for Audio, Computer Vision, and Natural Language Processing (NLP) tasks. Load a dataset in a single line of code, and use our powerful data processing methods to quickly get your dataset ready for training in a deep learning model. Backed by the Apache Arrow format, process large datasets with zero-copy reads without any memory constraints for optimal speed and efficiency. We also feature a deep integration with the [Hugging Face Hub](https://huggingface.co/datasets), allowing you to easily load and share a dataset with the wider machine learning community. Find your dataset today on the [Hugging Face Hub](https://huggingface.co/datasets), and take an in-depth look inside of it with the live viewer. <div class="mt-10"> <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5"> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorial" ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div> <p class="text-gray-700">Learn the basics and become familiar with loading, accessing, and processing a dataset. Start here if you are using 🤗 Datasets for the first time!</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./how_to" ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div> <p class="text-gray-700">Practical guides to help you achieve a specific goal. Take a look at these guides to learn how to use 🤗 Datasets to solve real-world problems.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./about_arrow" ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div> <p class="text-gray-700">High-level explanations for building a better understanding about important topics such as the underlying data format, the cache, and how datasets are generated.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./package_reference/main_classes" ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div> <p class="text-gray-700">Technical descriptions of how 🤗 Datasets classes and methods work.</p> </a> </div> </div>
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/how_to.md
# Overview The how-to guides offer a more comprehensive overview of all the tools 🤗 Datasets offers and how to use them. This will help you tackle messier real-world datasets where you may need to manipulate the dataset structure or content to get it ready for training. The guides assume you are familiar and comfortable with the 🤗 Datasets basics. We recommend newer users check out our [tutorials](tutorial) first. <Tip> Interested in learning more? Take a look at [Chapter 5](https://huggingface.co/course/chapter5/1?fw=pt) of the Hugging Face course! </Tip> The guides are organized into six sections: - <span class="underline decoration-sky-400 decoration-2 font-semibold">General usage</span>: Functions for general dataset loading and processing. The functions shown in this section are applicable across all dataset modalities. - <span class="underline decoration-pink-400 decoration-2 font-semibold">Audio</span>: How to load, process, and share audio datasets. - <span class="underline decoration-yellow-400 decoration-2 font-semibold">Vision</span>: How to load, process, and share image datasets. - <span class="underline decoration-green-400 decoration-2 font-semibold">Text</span>: How to load, process, and share text datasets. - <span class="underline decoration-orange-400 decoration-2 font-semibold">Tabular</span>: How to load, process, and share tabular datasets. - <span class="underline decoration-indigo-400 decoration-2 font-semibold">Dataset repository</span>: How to share and upload a dataset to the <a href="https://huggingface.co/datasets">Hub</a>. If you have any questions about 🤗 Datasets, feel free to join and ask the community on our [forum](https://discuss.huggingface.co/c/datasets/10).
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/repository_structure.mdx
# Structure your repository To host and share your dataset, create a dataset repository on the Hugging Face Hub and upload your data files. This guide will show you how to structure your dataset repository when you upload it. A dataset with a supported structure and file format (`.txt`, `.csv`, `.parquet`, `.jsonl`, `.mp3`, `.jpg`, `.zip` etc.) are loaded automatically with [`~datasets.load_dataset`], and it'll have a dataset viewer on its dataset page on the Hub. ## Main use-case The simplest dataset structure has two files: `train.csv` and `test.csv` (this works with any supported file format). Your repository will also contain a `README.md` file, the [dataset card](dataset_card) displayed on your dataset page. ``` my_dataset_repository/ ├── README.md ├── train.csv └── test.csv ``` In this simple case, you'll get a dataset with two splits: `train` (containing examples from `train.csv`) and `test` (containing examples from `test.csv`). ## Define your splits and subsets in YAML ## Splits If you have multiple files and want to define which file goes into which split, you can use the YAML `configs` field at the top of your README.md. For example, given a repository like this one: ``` my_dataset_repository/ ├── README.md ├── data.csv └── holdout.csv ``` You can define your splits by adding the `configs` field in the YAML block at the top of your README.md: ```yaml --- configs: - config_name: default data_files: - split: train path: "data.csv" - split: test path: "holdout.csv" --- ``` You can select multiple files per split using a list of paths: ``` my_dataset_repository/ ├── README.md ├── data/ │ ├── abc.csv │ └── def.csv └── holdout/ └── ghi.csv ``` ```yaml --- configs: - config_name: default data_files: - split: train path: - "data/abc.csv" - "data/def.csv" - split: test path: "holdout/ghi.csv" --- ``` Or you can use glob patterns to automatically list all the files you need: ```yaml --- configs: - config_name: default data_files: - split: train path: "data/*.csv" - split: test path: "holdout/*.csv" --- ``` <Tip warning={true}> Note that `config_name` field is required even if you have a single configuration. </Tip> ## Configurations Your dataset might have several subsets of data that you want to be able to load separately. In that case you can define a list of configurations inside the `configs` field in YAML: ``` my_dataset_repository/ ├── README.md ├── main_data.csv └── additional_data.csv ``` ```yaml --- configs: - config_name: main_data data_files: "main_data.csv" - config_name: additional_data data_files: "additional_data.csv" --- ``` Each configuration is shown separately on the Hugging Face Hub, and can be loaded by passing its name as a second parameter: ```python from datasets import load_dataset main_data = load_dataset("my_dataset_repository", "main_data") additional_data = load_dataset("my_dataset_repository", "additional_data") ``` ## Builder parameters Not only `data_files`, but other builder-specific parameters can be passed via YAML, allowing for more flexibility on how to load the data while not requiring any custom code. For example, define which separator to use in which configuration to load your `csv` files: ```yaml --- configs: - config_name: tab data_files: "main_data.csv" sep: "\t" - config_name: comma data_files: "additional_data.csv" sep: "," --- ``` Refer to [specific builders' documentation](./package_reference/builder_classes) to see what configuration parameters they have. <Tip> You can set a default configuration using `default: true`, e.g. you can run `main_data = load_dataset("my_dataset_repository")` if you set ```yaml - config_name: main_data data_files: "main_data.csv" default: true ``` </Tip> ## Automatic splits detection If no YAML is provided, 🤗 Datasets searches for certain patterns in the dataset repository to automatically infer the dataset splits. There is an order to the patterns, beginning with the custom filename split format to treating all files as a single split if no pattern is found. ### Directory name Your data files may also be placed into different directories named `train`, `test`, and `validation` where each directory contains the data files for that split: ``` my_dataset_repository/ ├── README.md └── data/ ├── train/ │ └── bees.csv ├── test/ │ └── more_bees.csv └── validation/ └── even_more_bees.csv ``` ### Filename splits If you don't have any non-traditional splits, then you can place the split name anywhere in the data file and it is automatically inferred. The only rule is that the split name must be delimited by non-word characters, like `test-file.csv` for example instead of `testfile.csv`. Supported delimiters include underscores, dashes, spaces, dots, and numbers. For example, the following file names are all acceptable: - train split: `train.csv`, `my_train_file.csv`, `train1.csv` - validation split: `validation.csv`, `my_validation_file.csv`, `validation1.csv` - test split: `test.csv`, `my_test_file.csv`, `test1.csv` Here is an example where all the files are placed into a directory named `data`: ``` my_dataset_repository/ ├── README.md └── data/ ├── train.csv ├── test.csv └── validation.csv ``` ### Custom filename split If your dataset splits have custom names that aren't `train`, `test`, or `validation`, then you can name your data files like `data/<split_name>-xxxxx-of-xxxxx.csv`. Here is an example with three splits, `train`, `test`, and `random`: ``` my_dataset_repository/ ├── README.md └── data/ ├── train-00000-of-00003.csv ├── train-00001-of-00003.csv ├── train-00002-of-00003.csv ├── test-00000-of-00001.csv ├── random-00000-of-00003.csv ├── random-00001-of-00003.csv └── random-00002-of-00003.csv ``` ### Single split When 🤗 Datasets can't find any of the above patterns, then it'll treat all the files as a single train split. If your dataset splits aren't loading as expected, it may be due to an incorrect pattern. ### Split name keywords There are several ways to name splits. Validation splits are sometimes called "dev", and test splits may be referred to as "eval". These other split names are also supported, and the following keywords are equivalent: - train, training - validation, valid, val, dev - test, testing, eval, evaluation The structure below is a valid repository: ``` my_dataset_repository/ ├── README.md └── data/ ├── training.csv ├── eval.csv └── valid.csv ``` ### Multiple files per split If one of your splits comprises several files, 🤗 Datasets can still infer whether it is the train, validation, and test split from the file name. For example, if your train and test splits span several files: ``` my_dataset_repository/ ├── README.md ├── train_0.csv ├── train_1.csv ├── train_2.csv ├── train_3.csv ├── test_0.csv └── test_1.csv ``` Make sure all the files of your `train` set have *train* in their names (same for test and validation). Even if you add a prefix or suffix to `train` in the file name (like `my_train_file_00001.csv` for example), 🤗 Datasets can still infer the appropriate split. For convenience, you can also place your data files into different directories. In this case, the split name is inferred from the directory name. ``` my_dataset_repository/ ├── README.md └── data/ ├── train/ │ ├── shard_0.csv │ ├── shard_1.csv │ ├── shard_2.csv │ └── shard_3.csv └── test/ ├── shard_0.csv └── shard_1.csv ``` For more flexibility over how to load and generate a dataset, you can also write a [dataset loading script](./dataset_script).
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/tabular_load.mdx
# Load tabular data A tabular dataset is a generic dataset used to describe any data stored in rows and columns, where the rows represent an example and the columns represent a feature (can be continuous or categorical). These datasets are commonly stored in CSV files, Pandas DataFrames, and in database tables. This guide will show you how to load and create a tabular dataset from: - CSV files - Pandas DataFrames - Databases ## CSV files 🤗 Datasets can read CSV files by specifying the generic `csv` dataset builder name in the [`~datasets.load_dataset`] method. To load more than one CSV file, pass them as a list to the `data_files` parameter: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("csv", data_files="my_file.csv") # load multiple CSV files >>> dataset = load_dataset("csv", data_files=["my_file_1.csv", "my_file_2.csv", "my_file_3.csv"]) ``` You can also map specific CSV files to the train and test splits: ```py >>> dataset = load_dataset("csv", data_files={"train": ["my_train_file_1.csv", "my_train_file_2.csv"], "test": "my_test_file.csv"}) ``` To load remote CSV files, pass the URLs instead: ```py >>> base_url = "https://huggingface.co/datasets/lhoestq/demo1/resolve/main/data/" >>> dataset = load_dataset('csv', data_files={"train": base_url + "train.csv", "test": base_url + "test.csv"}) ``` To load zipped CSV files: ```py >>> url = "https://domain.org/train_data.zip" >>> data_files = {"train": url} >>> dataset = load_dataset("csv", data_files=data_files) ``` ## Pandas DataFrames 🤗 Datasets also supports loading datasets from [Pandas DataFrames](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) with the [`~datasets.Dataset.from_pandas`] method: ```py >>> from datasets import Dataset >>> import pandas as pd # create a Pandas DataFrame >>> df = pd.read_csv("https://huggingface.co/datasets/imodels/credit-card/raw/main/train.csv") >>> df = pd.DataFrame(df) # load Dataset from Pandas DataFrame >>> dataset = Dataset.from_pandas(df) ``` Use the `splits` parameter to specify the name of the dataset split: ```py >>> train_ds = Dataset.from_pandas(train_df, split="train") >>> test_ds = Dataset.from_pandas(test_df, split="test") ``` If the dataset doesn't look as expected, you should explicitly [specify your dataset features](loading#specify-features). A [pandas.Series](https://pandas.pydata.org/docs/reference/api/pandas.Series.html) may not always carry enough information for Arrow to automatically infer a data type. For example, if a DataFrame is of length `0` or if the Series only contains `None/NaN` objects, the type is set to `null`. ## Databases Datasets stored in databases are typically accessed with SQL queries. With 🤗 Datasets, you can connect to a database, query for the data you need, and create a dataset out of it. Then you can use all the processing features of 🤗 Datasets to prepare your dataset for training. ### SQLite SQLite is a small, lightweight database that is fast and easy to set up. You can use an existing database if you'd like, or follow along and start from scratch. Start by creating a quick SQLite database with this [Covid-19 data](https://github.com/nytimes/covid-19-data/blob/master/us-states.csv) from the New York Times: ```py >>> import sqlite3 >>> import pandas as pd >>> conn = sqlite3.connect("us_covid_data.db") >>> df = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv") >>> df.to_sql("states", conn, if_exists="replace") ``` This creates a `states` table in the `us_covid_data.db` database which you can now load into a dataset. To connect to the database, you'll need the [URI string](https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls) that identifies your database. Connecting to a database with a URI caches the returned dataset. The URI string differs for each database dialect, so be sure to check the [Database URLs](https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls) for whichever database you're using. For SQLite, it is: ```py >>> uri = "sqlite:///us_covid_data.db" ``` Load the table by passing the table name and URI to [`~datasets.Dataset.from_sql`]: ```py >>> from datasets import Dataset >>> ds = Dataset.from_sql("states", uri) >>> ds Dataset({ features: ['index', 'date', 'state', 'fips', 'cases', 'deaths'], num_rows: 54382 }) ``` Then you can use all of 🤗 Datasets process features like [`~datasets.Dataset.filter`] for example: ```py >>> ds.filter(lambda x: x["state"] == "California") ``` You can also load a dataset from a SQL query instead of an entire table, which is useful for querying and joining multiple tables. Load the dataset by passing your query and URI to [`~datasets.Dataset.from_sql`]: ```py >>> from datasets import Dataset >>> ds = Dataset.from_sql('SELECT * FROM states WHERE state="California";', uri) >>> ds Dataset({ features: ['index', 'date', 'state', 'fips', 'cases', 'deaths'], num_rows: 1019 }) ``` Then you can use all of 🤗 Datasets process features like [`~datasets.Dataset.filter`] for example: ```py >>> ds.filter(lambda x: x["cases"] > 10000) ``` ### PostgreSQL You can also connect and load a dataset from a PostgreSQL database, however we won't directly demonstrate how in the documentation because the example is only meant to be run in a notebook. Instead, take a look at how to install and setup a PostgreSQL server in this [notebook](https://colab.research.google.com/github/nateraw/huggingface-hub-examples/blob/main/sql_with_huggingface_datasets.ipynb#scrollTo=d83yGQMPHGFi)! After you've setup your PostgreSQL database, you can use the [`~datasets.Dataset.from_sql`] method to load a dataset from a table or query.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/depth_estimation.mdx
# Depth estimation Depth estimation datasets are used to train a model to approximate the relative distance of every pixel in an image from the camera, also known as depth. The applications enabled by these datasets primarily lie in areas like visual machine perception and perception in robotics. Example applications include mapping streets for self-driving cars. This guide will show you how to apply transformations to a depth estimation dataset. Before you start, make sure you have up-to-date versions of `albumentations` installed: ```bash pip install -U albumentations ``` [Albumentations](https://albumentations.ai/) is a Python library for performing data augmentation for computer vision. It supports various computer vision tasks such as image classification, object detection, segmentation, and keypoint estimation. This guide uses the [NYU Depth V2](https://huggingface.co/datasets/sayakpaul/nyu_depth_v2) dataset which is comprised of video sequences from various indoor scenes, recorded by RGB and depth cameras. The dataset consists of scenes from 3 cities and provides images along with their depth maps as labels. Load the `train` split of the dataset and take a look at an example: ```py >>> from datasets import load_dataset >>> train_dataset = load_dataset("sayakpaul/nyu_depth_v2", split="train") >>> index = 17 >>> example = train_dataset[index] >>> example {'image': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=640x480>, 'depth_map': <PIL.TiffImagePlugin.TiffImageFile image mode=F size=640x480>} ``` The dataset has two fields: * `image`: a PIL PNG image object with `uint8` data type. * `depth_map`: a PIL Tiff image object with `float32` data type which is the depth map of the image. It is mention-worthy that JPEG/PNG format can only store `uint8` or `uint16` data. As the depth map is `float32` data, it can't be stored using PNG/JPEG. However, we can save the depth map using TIFF format as it supports a wider range of data types, including `float32` data. Next, check out an image with: ```py >>> example["image"] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_sample.png"> </div> Before we look at the depth map, we need to first convert its data type to `uint8` using `.convert('RGB')` as PIL can't display `float32` images. Now take a look at its corresponding depth map: ```py >>> example["depth_map"].convert("RGB") ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_target.png"> </div> It's all black! You'll need to add some color to the depth map to visualize it properly. To do that, either we can apply color automatically during display using `plt.imshow()` or create a colored depth map using `plt.cm` and then display it. In this example, we have used the latter one, as we can save/write the colored depth map later. (the utility below is taken from the [FastDepth repository](https://github.com/dwofk/fast-depth/blob/master/utils.py)). ```py >>> import numpy as np >>> import matplotlib.pyplot as plt >>> cmap = plt.cm.viridis >>> def colored_depthmap(depth, d_min=None, d_max=None): ... if d_min is None: ... d_min = np.min(depth) ... if d_max is None: ... d_max = np.max(depth) ... depth_relative = (depth - d_min) / (d_max - d_min) ... return 255 * cmap(depth_relative)[:,:,:3] >>> def show_depthmap(depth_map): ... if not isinstance(depth_map, np.ndarray): ... depth_map = np.array(depth_map) ... if depth_map.ndim == 3: ... depth_map = depth_map.squeeze() ... d_min = np.min(depth_map) ... d_max = np.max(depth_map) ... depth_map = colored_depthmap(depth_map, d_min, d_max) ... plt.imshow(depth_map.astype("uint8")) ... plt.axis("off") ... plt.show() >>> show_depthmap(example["depth_map"]) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_target_viz.png"> </div> You can also visualize several different images and their corresponding depth maps. ```py >>> def merge_into_row(input_image, depth_target): ... if not isinstance(input_image, np.ndarray): ... input_image = np.array(input_image) ... ... d_min = np.min(depth_target) ... d_max = np.max(depth_target) ... depth_target_col = colored_depthmap(depth_target, d_min, d_max) ... img_merge = np.hstack([input_image, depth_target_col]) ... ... return img_merge >>> random_indices = np.random.choice(len(train_dataset), 9).tolist() >>> plt.figure(figsize=(15, 6)) >>> for i, idx in enumerate(random_indices): ... example = train_dataset[idx] ... ax = plt.subplot(3, 3, i + 1) ... image_viz = merge_into_row( ... example["image"], example["depth_map"] ... ) ... plt.imshow(image_viz.astype("uint8")) ... plt.axis("off") ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_collage.png"> </div> Now apply some augmentations with `albumentations`. The augmentation transformations include: * Random horizontal flipping * Random cropping * Random brightness and contrast * Random gamma correction * Random hue saturation ```py >>> import albumentations as A >>> crop_size = (448, 576) >>> transforms = [ ... A.HorizontalFlip(p=0.5), ... A.RandomCrop(crop_size[0], crop_size[1]), ... A.RandomBrightnessContrast(), ... A.RandomGamma(), ... A.HueSaturationValue() ... ] ``` Additionally, define a mapping to better reflect the target key name. ```py >>> additional_targets = {"depth": "mask"} >>> aug = A.Compose(transforms=transforms, additional_targets=additional_targets) ``` With `additional_targets` defined, you can pass the target depth maps to the `depth` argument of `aug` instead of `mask`. You'll notice this change in the `apply_transforms()` function defined below. Create a function to apply the transformation to the images as well as their depth maps: ```py >>> def apply_transforms(examples): ... transformed_images, transformed_maps = [], [] ... for image, depth_map in zip(examples["image"], examples["depth_map"]): ... image, depth_map = np.array(image), np.array(depth_map) ... transformed = aug(image=image, depth=depth_map) ... transformed_images.append(transformed["image"]) ... transformed_maps.append(transformed["depth"]) ... ... examples["pixel_values"] = transformed_images ... examples["labels"] = transformed_maps ... return examples ``` Use the [`~Dataset.set_transform`] function to apply the transformation on-the-fly to batches of the dataset to consume less disk space: ```py >>> train_dataset.set_transform(apply_transforms) ``` You can verify the transformation worked by indexing into the `pixel_values` and `labels` of an example image: ```py >>> example = train_dataset[index] >>> plt.imshow(example["pixel_values"]) >>> plt.axis("off") >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_sample_aug.png"> </div> Visualize the same transformation on the image's corresponding depth map: ```py >>> show_depthmap(example["labels"]) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_target_aug.png"> </div> You can also visualize multiple training samples reusing the previous `random_indices`: ```py >>> plt.figure(figsize=(15, 6)) >>> for i, idx in enumerate(random_indices): ... ax = plt.subplot(3, 3, i + 1) ... example = train_dataset[idx] ... image_viz = merge_into_row( ... example["pixel_values"], example["labels"] ... ) ... plt.imshow(image_viz.astype("uint8")) ... plt.axis("off") ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/depth_est_aug_collage.png"> </div>
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/audio_process.mdx
# Process audio data This guide shows specific methods for processing audio datasets. Learn how to: - Resample the sampling rate. - Use [`~Dataset.map`] with audio datasets. For a guide on how to process any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./process">general process guide</a>. ## Cast The [`~Dataset.cast_column`] function is used to cast a column to another feature to be decoded. When you use this function with the [`Audio`] feature, you can resample the sampling rate: ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train") >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) ``` Audio files are decoded and resampled on-the-fly, so the next time you access an example, the audio file is resampled to 16kHz: ```py >>> dataset[0]["audio"] {'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 16000} ``` <div class="flex justify-center"> <img class="block dark:hidden" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/resample.gif"/> <img class="hidden dark:block" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/resample-dark.gif"/> </div> ## Map The [`~Dataset.map`] function helps preprocess your entire dataset at once. Depending on the type of model you're working with, you'll need to either load a [feature extractor](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoFeatureExtractor) or a [processor](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoProcessor). - For pretrained speech recognition models, load a feature extractor and tokenizer and combine them in a `processor`: ```py >>> from transformers import AutoTokenizer, AutoFeatureExtractor, AutoProcessor >>> model_checkpoint = "facebook/wav2vec2-large-xlsr-53" # after defining a vocab.json file you can instantiate a tokenizer object: >>> tokenizer = AutoTokenizer("./vocab.json", unk_token="[UNK]", pad_token="[PAD]", word_delimiter_token="|") >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_checkpoint) >>> processor = AutoProcessor.from_pretrained(feature_extractor=feature_extractor, tokenizer=tokenizer) ``` - For fine-tuned speech recognition models, you only need to load a `processor`: ```py >>> from transformers import AutoProcessor >>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") ``` When you use [`~Dataset.map`] with your preprocessing function, include the `audio` column to ensure you're actually resampling the audio data: ```py >>> def prepare_dataset(batch): ... audio = batch["audio"] ... batch["input_values"] = processor(audio["array"], sampling_rate=audio["sampling_rate"]).input_values[0] ... batch["input_length"] = len(batch["input_values"]) ... with processor.as_target_processor(): ... batch["labels"] = processor(batch["sentence"]).input_ids ... return batch >>> dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names) ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/audio_load.mdx
# Load audio data You can load an audio dataset using the [`Audio`] feature that automatically decodes and resamples the audio files when you access the examples. Audio decoding is based on the [`soundfile`](https://github.com/bastibe/python-soundfile) python package, which uses the [`libsndfile`](https://github.com/libsndfile/libsndfile) C library under the hood. ## Installation To work with audio datasets, you need to have the `audio` dependencies installed. Check out the [installation](./installation#audio) guide to learn how to install it. ## Local files You can load your own dataset using the paths to your audio files. Use the [`~Dataset.cast_column`] function to take a column of audio file paths, and cast it to the [`Audio`] feature: ```py >>> audio_dataset = Dataset.from_dict({"audio": ["path/to/audio_1", "path/to/audio_2", ..., "path/to/audio_n"]}).cast_column("audio", Audio()) >>> audio_dataset[0]["audio"] {'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, 0. , 0. ], dtype=float32), 'path': 'path/to/audio_1', 'sampling_rate': 16000} ``` ## AudioFolder You can also load a dataset with an `AudioFolder` dataset builder. It does not require writing a custom dataloader, making it useful for quickly creating and loading audio datasets with several thousand audio files. ## AudioFolder with metadata To link your audio files with metadata information, make sure your dataset has a `metadata.csv` file. Your dataset structure might look like: ``` folder/train/metadata.csv folder/train/first_audio_file.mp3 folder/train/second_audio_file.mp3 folder/train/third_audio_file.mp3 ``` Your `metadata.csv` file must have a `file_name` column which links audio files with their metadata. An example `metadata.csv` file might look like: ```text file_name,transcription first_audio_file.mp3,znowu się duch z ciałem zrośnie w młodocianej wstaniesz wiosnie i możesz skutkiem tych leków umierać wstawać wiek wieków dalej tam były przestrogi jak siekać głowę jak nogi second_audio_file.mp3,już u źwierzyńca podwojów król zasiada przy nim książęta i panowie rada a gdzie wzniosły krążył ganek rycerze obok kochanek król skinął palcem zaczęto igrzysko third_audio_file.mp3,pewnie kędyś w obłędzie ubite minęły szlaki zaczekajmy dzień jaki poślemy szukać wszędzie dziś jutro pewnie będzie posłali wszędzie sługi czekali dzień i drugi gdy nic nie doczekali z płaczem chcą jechać dali ``` `AudioFolder` will load audio data and create a `transcription` column containing texts from `metadata.csv`: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("audiofolder", data_dir="/path/to/folder") >>> # OR by specifying the list of files >>> dataset = load_dataset("audiofolder", data_files=["path/to/audio_1", "path/to/audio_2", ..., "path/to/audio_n"]) ``` You can load remote datasets from their URLs with the data_files parameter: ```py >>> dataset = load_dataset("audiofolder", data_files=["https://foo.bar/audio_1", "https://foo.bar/audio_2", ..., "https://foo.bar/audio_n"] >>> # for example, pass SpeechCommands archive: >>> dataset = load_dataset("audiofolder", data_files="https://s3.amazonaws.com/datasets.huggingface.co/SpeechCommands/v0.01/v0.01_test.tar.gz") ``` Metadata can also be specified as JSON Lines, in which case use `metadata.jsonl` as the name of the metadata file. This format is helpful in scenarios when one of the columns is complex, e.g. a list of floats, to avoid parsing errors or reading the complex values as strings. To ignore the information in the metadata file, set `drop_metadata=True` in [`load_dataset`]: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("audiofolder", data_dir="/path/to/folder", drop_metadata=True) ``` If you don't have a metadata file, `AudioFolder` automatically infers the label name from the directory name. If you want to drop automatically created labels, set `drop_labels=True`. In this case, your dataset will only contain an audio column: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("audiofolder", data_dir="/path/to/folder_without_metadata", drop_labels=True) ``` <Tip> For more information about creating your own `AudioFolder` dataset, take a look at the [Create an audio dataset](./audio_dataset) guide. </Tip> For a guide on how to load any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./loading">general loading guide</a>.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/_redirects.yml
# This first_section was backported from nginx loading_datasets: loading share_dataset: share quicktour: quickstart dataset_streaming: stream torch_tensorflow: use_dataset splits: loading#slice-splits processing: process faiss_and_ea: faiss_es features: about_dataset_features using_metrics: how_to_metrics exploring: access package_reference/logging_methods: package_reference/utilities # end of first_section
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_cache.mdx
# The cache The cache is one of the reasons why 🤗 Datasets is so efficient. It stores previously downloaded and processed datasets so when you need to use them again, they are reloaded directly from the cache. This avoids having to download a dataset all over again, or reapplying processing functions. Even after you close and start another Python session, 🤗 Datasets will reload your dataset directly from the cache! ## Fingerprint How does the cache keeps track of what transforms are applied to a dataset? Well, 🤗 Datasets assigns a fingerprint to the cache file. A fingerprint keeps track of the current state of a dataset. The initial fingerprint is computed using a hash from the Arrow table, or a hash of the Arrow files if the dataset is on disk. Subsequent fingerprints are computed by combining the fingerprint of the previous state, and a hash of the latest transform applied. <Tip> Transforms are any of the processing methods from the [How-to Process](./process) guides such as [`Dataset.map`] or [`Dataset.shuffle`]. </Tip> Here are what the actual fingerprints look like: ```py >>> from datasets import Dataset >>> dataset1 = Dataset.from_dict({"a": [0, 1, 2]}) >>> dataset2 = dataset1.map(lambda x: {"a": x["a"] + 1}) >>> print(dataset1._fingerprint, dataset2._fingerprint) d19493523d95e2dc 5b86abacd4b42434 ``` In order for a transform to be hashable, it needs to be picklable by [dill](https://dill.readthedocs.io/en/latest/) or [pickle](https://docs.python.org/3/library/pickle). When you use a non-hashable transform, 🤗 Datasets uses a random fingerprint instead and raises a warning. The non-hashable transform is considered different from the previous transforms. As a result, 🤗 Datasets will recompute all the transforms. Make sure your transforms are serializable with pickle or dill to avoid this! An example of when 🤗 Datasets recomputes everything is when caching is disabled. When this happens, the cache files are generated every time and they get written to a temporary directory. Once your Python session ends, the cache files in the temporary directory are deleted. A random hash is assigned to these cache files, instead of a fingerprint. <Tip> When caching is disabled, use [`Dataset.save_to_disk`] to save your transformed dataset or it will be deleted once the session ends. </Tip> ## Hashing The fingerprint of a dataset is updated by hashing the function passed to `map` as well as the `map` parameters (`batch_size`, `remove_columns`, etc.). You can check the hash of any Python object using the [`fingerprint.Hasher`]: ```py >>> from datasets.fingerprint import Hasher >>> my_func = lambda example: {"length": len(example["text"])} >>> print(Hasher.hash(my_func)) '3d35e2b3e94c81d6' ``` The hash is computed by dumping the object using a `dill` pickler and hashing the dumped bytes. The pickler recursively dumps all the variables used in your function, so any change you do to an object that is used in your function, will cause the hash to change. If one of your functions doesn't seem to have the same hash across sessions, it means at least one of its variables contains a Python object that is not deterministic. When this happens, feel free to hash any object you find suspicious to try to find the object that caused the hash to change. For example, if you use a list for which the order of its elements is not deterministic across sessions, then the hash won't be the same across sessions either.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/process.mdx
# Process 🤗 Datasets provides many tools for modifying the structure and content of a dataset. These tools are important for tidying up a dataset, creating additional columns, converting between features and formats, and much more. This guide will show you how to: - Reorder rows and split the dataset. - Rename and remove columns, and other common column operations. - Apply processing functions to each example in a dataset. - Concatenate datasets. - Apply a custom formatting transform. - Save and export processed datasets. For more details specific to processing other dataset modalities, take a look at the <a class="underline decoration-pink-400 decoration-2 font-semibold" href="./audio_process">process audio dataset guide</a>, the <a class="underline decoration-yellow-400 decoration-2 font-semibold" href="./image_process">process image dataset guide</a>, or the <a class="underline decoration-green-400 decoration-2 font-semibold" href="./nlp_process">process text dataset guide</a>. The examples in this guide use the MRPC dataset, but feel free to load any dataset of your choice and follow along! ```py >>> from datasets import load_dataset >>> dataset = load_dataset("glue", "mrpc", split="train") ``` <Tip warning={true}> All processing methods in this guide return a new [`Dataset`] object. Modification is not done in-place. Be careful about overriding your previous dataset! </Tip> ## Sort, shuffle, select, split, and shard There are several functions for rearranging the structure of a dataset. These functions are useful for selecting only the rows you want, creating train and test splits, and sharding very large datasets into smaller chunks. ### Sort Use [`~Dataset.sort`] to sort column values according to their numerical values. The provided column must be NumPy compatible. ```py >>> dataset["label"][:10] [1, 0, 1, 0, 1, 1, 0, 1, 0, 0] >>> sorted_dataset = dataset.sort("label") >>> sorted_dataset["label"][:10] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> sorted_dataset["label"][-10:] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ``` Under the hood, this creates a list of indices that is sorted according to values of the column. This indices mapping is then used to access the right rows in the underlying Arrow table. ### Shuffle The [`~Dataset.shuffle`] function randomly rearranges the column values. You can specify the `generator` parameter in this function to use a different `numpy.random.Generator` if you want more control over the algorithm used to shuffle the dataset. ```py >>> shuffled_dataset = sorted_dataset.shuffle(seed=42) >>> shuffled_dataset["label"][:10] [1, 1, 1, 0, 1, 1, 1, 1, 1, 0] ``` Shuffling takes the list of indices `[0:len(my_dataset)]` and shuffles it to create an indices mapping. However as soon as your [`Dataset`] has an indices mapping, the speed can become 10x slower. This is because there is an extra step to get the row index to read using the indices mapping, and most importantly, you aren't reading contiguous chunks of data anymore. To restore the speed, you'd need to rewrite the entire dataset on your disk again using [`Dataset.flatten_indices`], which removes the indices mapping. Alternatively, you can switch to an [`IterableDataset`] and leverage its fast approximate shuffling [`IterableDataset.shuffle`]: ```py >>> iterable_dataset = dataset.to_iterable_dataset(num_shards=128) >>> shuffled_iterable_dataset = iterable_dataset.shuffle(seed=42, buffer_size=1000) ``` ### Select and Filter There are two options for filtering rows in a dataset: [`~Dataset.select`] and [`~Dataset.filter`]. - [`~Dataset.select`] returns rows according to a list of indices: ```py >>> small_dataset = dataset.select([0, 10, 20, 30, 40, 50]) >>> len(small_dataset) 6 ``` - [`~Dataset.filter`] returns rows that match a specified condition: ```py >>> start_with_ar = dataset.filter(lambda example: example["sentence1"].startswith("Ar")) >>> len(start_with_ar) 6 >>> start_with_ar["sentence1"] ['Around 0335 GMT , Tab shares were up 19 cents , or 4.4 % , at A $ 4.56 , having earlier set a record high of A $ 4.57 .', 'Arison said Mann may have been one of the pioneers of the world music movement and he had a deep love of Brazilian music .', 'Arts helped coach the youth on an eighth-grade football team at Lombardi Middle School in Green Bay .', 'Around 9 : 00 a.m. EDT ( 1300 GMT ) , the euro was at $ 1.1566 against the dollar , up 0.07 percent on the day .', "Arguing that the case was an isolated example , Canada has threatened a trade backlash if Tokyo 's ban is not justified on scientific grounds .", 'Artists are worried the plan would harm those who need help most - performers who have a difficult time lining up shows .' ] ``` [`~Dataset.filter`] can also filter by indices if you set `with_indices=True`: ```py >>> even_dataset = dataset.filter(lambda example, idx: idx % 2 == 0, with_indices=True) >>> len(even_dataset) 1834 >>> len(dataset) / 2 1834.0 ``` Unless the list of indices to keep is contiguous, those methods also create an indices mapping under the hood. ### Split The [`~Dataset.train_test_split`] function creates train and test splits if your dataset doesn't already have them. This allows you to adjust the relative proportions or an absolute number of samples in each split. In the example below, use the `test_size` parameter to create a test split that is 10% of the original dataset: ```py >>> dataset.train_test_split(test_size=0.1) {'train': Dataset(schema: {'sentence1': 'string', 'sentence2': 'string', 'label': 'int64', 'idx': 'int32'}, num_rows: 3301), 'test': Dataset(schema: {'sentence1': 'string', 'sentence2': 'string', 'label': 'int64', 'idx': 'int32'}, num_rows: 367)} >>> 0.1 * len(dataset) 366.8 ``` The splits are shuffled by default, but you can set `shuffle=False` to prevent shuffling. ### Shard 🤗 Datasets supports sharding to divide a very large dataset into a predefined number of chunks. Specify the `num_shards` parameter in [`~Dataset.shard`] to determine the number of shards to split the dataset into. You'll also need to provide the shard you want to return with the `index` parameter. For example, the [imdb](https://huggingface.co/datasets/imdb) dataset has 25000 examples: ```py >>> from datasets import load_dataset >>> datasets = load_dataset("imdb", split="train") >>> print(dataset) Dataset({ features: ['text', 'label'], num_rows: 25000 }) ``` After sharding the dataset into four chunks, the first shard will only have 6250 examples: ```py >>> dataset.shard(num_shards=4, index=0) Dataset({ features: ['text', 'label'], num_rows: 6250 }) >>> print(25000/4) 6250.0 ``` ## Rename, remove, cast, and flatten The following functions allow you to modify the columns of a dataset. These functions are useful for renaming or removing columns, changing columns to a new set of features, and flattening nested column structures. ### Rename Use [`~Dataset.rename_column`] when you need to rename a column in your dataset. Features associated with the original column are actually moved under the new column name, instead of just replacing the original column in-place. Provide [`~Dataset.rename_column`] with the name of the original column, and the new column name: ```py >>> dataset Dataset({ features: ['sentence1', 'sentence2', 'label', 'idx'], num_rows: 3668 }) >>> dataset = dataset.rename_column("sentence1", "sentenceA") >>> dataset = dataset.rename_column("sentence2", "sentenceB") >>> dataset Dataset({ features: ['sentenceA', 'sentenceB', 'label', 'idx'], num_rows: 3668 }) ``` ### Remove When you need to remove one or more columns, provide the column name to remove to the [`~Dataset.remove_columns`] function. Remove more than one column by providing a list of column names: ```py >>> dataset = dataset.remove_columns("label") >>> dataset Dataset({ features: ['sentence1', 'sentence2', 'idx'], num_rows: 3668 }) >>> dataset = dataset.remove_columns(["sentence1", "sentence2"]) >>> dataset Dataset({ features: ['idx'], num_rows: 3668 }) ``` Conversely, [`~Dataset.select_columns`] selects one or more columns to keep and removes the rest. This function takes either one or a list of column names: ```py >>> dataset Dataset({ features: ['sentence1', 'sentence2', 'label', 'idx'], num_rows: 3668 }) >>> dataset = dataset.select_columns(['sentence1', 'sentence2', 'idx']) >>> dataset Dataset({ features: ['sentence1', 'sentence2', 'idx'], num_rows: 3668 }) >>> dataset = dataset.select_columns('idx') >>> dataset Dataset({ features: ['idx'], num_rows: 3668 }) ``` ### Cast The [`~Dataset.cast`] function transforms the feature type of one or more columns. This function accepts your new [`Features`] as its argument. The example below demonstrates how to change the [`ClassLabel`] and [`Value`] features: ```py >>> dataset.features {'sentence1': Value(dtype='string', id=None), 'sentence2': Value(dtype='string', id=None), 'label': ClassLabel(num_classes=2, names=['not_equivalent', 'equivalent'], names_file=None, id=None), 'idx': Value(dtype='int32', id=None)} >>> from datasets import ClassLabel, Value >>> new_features = dataset.features.copy() >>> new_features["label"] = ClassLabel(names=["negative", "positive"]) >>> new_features["idx"] = Value("int64") >>> dataset = dataset.cast(new_features) >>> dataset.features {'sentence1': Value(dtype='string', id=None), 'sentence2': Value(dtype='string', id=None), 'label': ClassLabel(num_classes=2, names=['negative', 'positive'], names_file=None, id=None), 'idx': Value(dtype='int64', id=None)} ``` <Tip> Casting only works if the original feature type and new feature type are compatible. For example, you can cast a column with the feature type `Value("int32")` to `Value("bool")` if the original column only contains ones and zeros. </Tip> Use the [`~Dataset.cast_column`] function to change the feature type of a single column. Pass the column name and its new feature type as arguments: ```py >>> dataset.features {'audio': Audio(sampling_rate=44100, mono=True, id=None)} >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) >>> dataset.features {'audio': Audio(sampling_rate=16000, mono=True, id=None)} ``` ### Flatten Sometimes a column can be a nested structure of several types. Take a look at the nested structure below from the SQuAD dataset: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("squad", split="train") >>> dataset.features {'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None), 'context': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None), 'title': Value(dtype='string', id=None)} ``` The `answers` field contains two subfields: `text` and `answer_start`. Use the [`~Dataset.flatten`] function to extract the subfields into their own separate columns: ```py >>> flat_dataset = dataset.flatten() >>> flat_dataset Dataset({ features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'], num_rows: 87599 }) ``` Notice how the subfields are now their own independent columns: `answers.text` and `answers.answer_start`. ## Map Some of the more powerful applications of 🤗 Datasets come from using the [`~Dataset.map`] function. The primary purpose of [`~Dataset.map`] is to speed up processing functions. It allows you to apply a processing function to each example in a dataset, independently or in batches. This function can even create new rows and columns. In the following example, prefix each `sentence1` value in the dataset with `'My sentence: '`. Start by creating a function that adds `'My sentence: '` to the beginning of each sentence. The function needs to accept and output a `dict`: ```py >>> def add_prefix(example): ... example["sentence1"] = 'My sentence: ' + example["sentence1"] ... return example ``` Now use [`~Dataset.map`] to apply the `add_prefix` function to the entire dataset: ```py >>> updated_dataset = small_dataset.map(add_prefix) >>> updated_dataset["sentence1"][:5] ['My sentence: Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', "My sentence: Yucaipa owned Dominick 's before selling the chain to Safeway in 1998 for $ 2.5 billion .", 'My sentence: They had published an advertisement on the Internet on June 10 , offering the cargo for sale , he added .', 'My sentence: Around 0335 GMT , Tab shares were up 19 cents , or 4.4 % , at A $ 4.56 , having earlier set a record high of A $ 4.57 .', ] ``` Let's take a look at another example, except this time, you'll remove a column with [`~Dataset.map`]. When you remove a column, it is only removed after the example has been provided to the mapped function. This allows the mapped function to use the content of the columns before they are removed. Specify the column to remove with the `remove_columns` parameter in [`~Dataset.map`]: ```py >>> updated_dataset = dataset.map(lambda example: {"new_sentence": example["sentence1"]}, remove_columns=["sentence1"]) >>> updated_dataset.column_names ['sentence2', 'label', 'idx', 'new_sentence'] ``` <Tip> 🤗 Datasets also has a [`~Dataset.remove_columns`] function which is faster because it doesn't copy the data of the remaining columns. </Tip> You can also use [`~Dataset.map`] with indices if you set `with_indices=True`. The example below adds the index to the beginning of each sentence: ```py >>> updated_dataset = dataset.map(lambda example, idx: {"sentence2": f"{idx}: " + example["sentence2"]}, with_indices=True) >>> updated_dataset["sentence2"][:5] ['0: Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .', "1: Yucaipa bought Dominick 's in 1995 for $ 693 million and sold it to Safeway for $ 1.8 billion in 1998 .", "2: On June 10 , the ship 's owners had published an advertisement on the Internet , offering the explosives for sale .", '3: Tab shares jumped 20 cents , or 4.6 % , to set a record closing high at A $ 4.57 .', '4: PG & E Corp. shares jumped $ 1.63 or 8 percent to $ 21.03 on the New York Stock Exchange on Friday .' ] ``` ### Multiprocessing Multiprocessing significantly speeds up processing by parallelizing processes on the CPU. Set the `num_proc` parameter in [`~Dataset.map`] to set the number of processes to use: ```py >>> updated_dataset = dataset.map(lambda example, idx: {"sentence2": f"{idx}: " + example["sentence2"]}, num_proc=4) ``` The [`~Dataset.map`] also works with the rank of the process if you set `with_rank=True`. This is analogous to the `with_indices` parameter. The `with_rank` parameter in the mapped function goes after the `index` one if it is already present. ```py >>> from multiprocess import set_start_method >>> import torch >>> import os >>> >>> for i in range(torch.cuda.device_count()): # send model to every GPU ... model.to(f"cuda:{i}") >>> >>> def gpu_computation(example, rank): ... torch.cuda.set_device(f"cuda:{rank}") # use one GPU ... # Your big GPU call goes here, for example ... inputs = tokenizer(texts, truncation=True, return_tensors="pt").to(f"cuda:{rank}") ... outputs = model.generate(**inputs) ... example["generated_text"] = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True) ... return example >>> >>> if __name__ == "__main__": ... set_start_method("spawn") ... updated_dataset = dataset.map(gpu_computation, with_rank=True, num_proc=torch.cuda.device_count()) ``` The main use-case for rank is to parallelize computation across several GPUs. This requires setting `multiprocess.set_start_method("spawn")`. If you don't you'll receive the following CUDA error: ```bash RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method. ``` ### Batch processing The [`~Dataset.map`] function supports working with batches of examples. Operate on batches by setting `batched=True`. The default batch size is 1000, but you can adjust it with the `batch_size` parameter. Batch processing enables interesting applications such as splitting long sentences into shorter chunks and data augmentation. #### Split long examples When examples are too long, you may want to split them into several smaller chunks. Begin by creating a function that: 1. Splits the `sentence1` field into chunks of 50 characters. 2. Stacks all the chunks together to create the new dataset. ```py >>> def chunk_examples(examples): ... chunks = [] ... for sentence in examples["sentence1"]: ... chunks += [sentence[i:i + 50] for i in range(0, len(sentence), 50)] ... return {"chunks": chunks} ``` Apply the function with [`~Dataset.map`]: ```py >>> chunked_dataset = dataset.map(chunk_examples, batched=True, remove_columns=dataset.column_names) >>> chunked_dataset[:10] {'chunks': ['Amrozi accused his brother , whom he called " the ', 'witness " , of deliberately distorting his evidenc', 'e .', "Yucaipa owned Dominick 's before selling the chain", ' to Safeway in 1998 for $ 2.5 billion .', 'They had published an advertisement on the Interne', 't on June 10 , offering the cargo for sale , he ad', 'ded .', 'Around 0335 GMT , Tab shares were up 19 cents , or', ' 4.4 % , at A $ 4.56 , having earlier set a record']} ``` Notice how the sentences are split into shorter chunks now, and there are more rows in the dataset. ```py >>> dataset Dataset({ features: ['sentence1', 'sentence2', 'label', 'idx'], num_rows: 3668 }) >>> chunked_dataset Dataset(schema: {'chunks': 'string'}, num_rows: 10470) ``` #### Data augmentation The [`~Dataset.map`] function could also be used for data augmentation. The following example generates additional words for a masked token in a sentence. Load and use the [RoBERTA](https://huggingface.co/roberta-base) model in 🤗 Transformers' [FillMaskPipeline](https://huggingface.co/transformers/main_classes/pipelines#transformers.FillMaskPipeline): ```py >>> from random import randint >>> from transformers import pipeline >>> fillmask = pipeline("fill-mask", model="roberta-base") >>> mask_token = fillmask.tokenizer.mask_token >>> smaller_dataset = dataset.filter(lambda e, i: i<100, with_indices=True) ``` Create a function to randomly select a word to mask in the sentence. The function should also return the original sentence and the top two replacements generated by RoBERTA. ```py >>> def augment_data(examples): ... outputs = [] ... for sentence in examples["sentence1"]: ... words = sentence.split(' ') ... K = randint(1, len(words)-1) ... masked_sentence = " ".join(words[:K] + [mask_token] + words[K+1:]) ... predictions = fillmask(masked_sentence) ... augmented_sequences = [predictions[i]["sequence"] for i in range(3)] ... outputs += [sentence] + augmented_sequences ... ... return {"data": outputs} ``` Use [`~Dataset.map`] to apply the function over the whole dataset: ```py >>> augmented_dataset = smaller_dataset.map(augment_data, batched=True, remove_columns=dataset.column_names, batch_size=8) >>> augmented_dataset[:9]["data"] ['Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', 'Amrozi accused his brother, whom he called " the witness ", of deliberately withholding his evidence.', 'Amrozi accused his brother, whom he called " the witness ", of deliberately suppressing his evidence.', 'Amrozi accused his brother, whom he called " the witness ", of deliberately destroying his evidence.', "Yucaipa owned Dominick 's before selling the chain to Safeway in 1998 for $ 2.5 billion .", 'Yucaipa owned Dominick Stores before selling the chain to Safeway in 1998 for $ 2.5 billion.', "Yucaipa owned Dominick's before selling the chain to Safeway in 1998 for $ 2.5 billion.", 'Yucaipa owned Dominick Pizza before selling the chain to Safeway in 1998 for $ 2.5 billion.' ] ``` For each original sentence, RoBERTA augmented a random word with three alternatives. The original word `distorting` is supplemented by `withholding`, `suppressing`, and `destroying`. ### Process multiple splits Many datasets have splits that can be processed simultaneously with [`DatasetDict.map`]. For example, tokenize the `sentence1` field in the train and test split by: ```py >>> from datasets import load_dataset # load all the splits >>> dataset = load_dataset('glue', 'mrpc') >>> encoded_dataset = dataset.map(lambda examples: tokenizer(examples["sentence1"]), batched=True) >>> encoded_dataset["train"][0] {'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .', 'label': 1, 'idx': 0, 'input_ids': [ 101, 7277, 2180, 5303, 4806, 1117, 1711, 117, 2292, 1119, 1270, 107, 1103, 7737, 107, 117, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] } ``` ### Distributed usage When you use [`~Dataset.map`] in a distributed setting, you should also use [torch.distributed.barrier](https://pytorch.org/docs/stable/distributed?highlight=barrier#torch.distributed.barrier). This ensures the main process performs the mapping, while the other processes load the results, thereby avoiding duplicate work. The following example shows how you can use `torch.distributed.barrier` to synchronize the processes: ```py >>> from datasets import Dataset >>> import torch.distributed >>> dataset1 = Dataset.from_dict({"a": [0, 1, 2]}) >>> if training_args.local_rank > 0: ... print("Waiting for main process to perform the mapping") ... torch.distributed.barrier() >>> dataset2 = dataset1.map(lambda x: {"a": x["a"] + 1}) >>> if training_args.local_rank == 0: ... print("Loading results from main process") ... torch.distributed.barrier() ``` ## Concatenate Separate datasets can be concatenated if they share the same column types. Concatenate datasets with [`concatenate_datasets`]: ```py >>> from datasets import concatenate_datasets, load_dataset >>> bookcorpus = load_dataset("bookcorpus", split="train") >>> wiki = load_dataset("wikipedia", "20220301.en", split="train") >>> wiki = wiki.remove_columns([col for col in wiki.column_names if col != "text"]) # only keep the 'text' column >>> assert bookcorpus.features.type == wiki.features.type >>> bert_dataset = concatenate_datasets([bookcorpus, wiki]) ``` You can also concatenate two datasets horizontally by setting `axis=1` as long as the datasets have the same number of rows: ```py >>> from datasets import Dataset >>> bookcorpus_ids = Dataset.from_dict({"ids": list(range(len(bookcorpus)))}) >>> bookcorpus_with_ids = concatenate_datasets([bookcorpus, bookcorpus_ids], axis=1) ``` ### Interleave You can also mix several datasets together by taking alternating examples from each one to create a new dataset. This is known as *interleaving*, which is enabled by the [`interleave_datasets`] function. Both [`interleave_datasets`] and [`concatenate_datasets`] work with regular [`Dataset`] and [`IterableDataset`] objects. Refer to the [Stream](./stream#interleave) guide for an example of how to interleave [`IterableDataset`] objects. You can define sampling probabilities for each of the original datasets to specify how to interleave the datasets. In this case, the new dataset is constructed by getting examples one by one from a random dataset until one of the datasets runs out of samples. ```py >>> seed = 42 >>> probabilities = [0.3, 0.5, 0.2] >>> d1 = Dataset.from_dict({"a": [0, 1, 2]}) >>> d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) >>> d3 = Dataset.from_dict({"a": [20, 21, 22]}) >>> dataset = interleave_datasets([d1, d2, d3], probabilities=probabilities, seed=seed) >>> dataset["a"] [10, 11, 20, 12, 0, 21, 13] ``` You can also specify the `stopping_strategy`. The default strategy, `first_exhausted`, is a subsampling strategy, i.e the dataset construction is stopped as soon one of the dataset runs out of samples. You can specify `stopping_strategy=all_exhausted` to execute an oversampling strategy. In this case, the dataset construction is stopped as soon as every samples in every dataset has been added at least once. In practice, it means that if a dataset is exhausted, it will return to the beginning of this dataset until the stop criterion has been reached. Note that if no sampling probabilities are specified, the new dataset will have `max_length_datasets*nb_dataset samples`. ```py >>> d1 = Dataset.from_dict({"a": [0, 1, 2]}) >>> d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) >>> d3 = Dataset.from_dict({"a": [20, 21, 22]}) >>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted") >>> dataset["a"] [0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 20] ``` ## Format The [`~Dataset.set_format`] function changes the format of a column to be compatible with some common data formats. Specify the output you'd like in the `type` parameter and the columns you want to format. Formatting is applied on-the-fly. For example, create PyTorch tensors by setting `type="torch"`: ```py >>> import torch >>> dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"]) ``` The [`~Dataset.with_format`] function also changes the format of a column, except it returns a new [`Dataset`] object: ```py >>> dataset = dataset.with_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"]) ``` <Tip> 🤗 Datasets also provides support for other common data formats such as NumPy, Pandas, and JAX. Check out the [Using Datasets with TensorFlow](https://huggingface.co/docs/datasets/master/en/use_with_tensorflow#using-totfdataset) guide for more details on how to efficiently create a TensorFlow dataset. </Tip> If you need to reset the dataset to its original format, use the [`~Dataset.reset_format`] function: ```py >>> dataset.format {'type': 'torch', 'format_kwargs': {}, 'columns': ['label'], 'output_all_columns': False} >>> dataset.reset_format() >>> dataset.format {'type': 'python', 'format_kwargs': {}, 'columns': ['idx', 'label', 'sentence1', 'sentence2'], 'output_all_columns': False} ``` ### Format transform The [`~Dataset.set_transform`] function applies a custom formatting transform on-the-fly. This function replaces any previously specified format. For example, you can use this function to tokenize and pad tokens on-the-fly. Tokenization is only applied when examples are accessed: ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") >>> def encode(batch): ... return tokenizer(batch["sentence1"], padding="longest", truncation=True, max_length=512, return_tensors="pt") >>> dataset.set_transform(encode) >>> dataset.format {'type': 'custom', 'format_kwargs': {'transform': <function __main__.encode(batch)>}, 'columns': ['idx', 'label', 'sentence1', 'sentence2'], 'output_all_columns': False} ``` You can also use the [`~Dataset.set_transform`] function to decode formats not supported by [`Features`]. For example, the [`Audio`] feature uses [`soundfile`](https://python-soundfile.readthedocs.io/en/0.11.0/) - a fast and simple library to install - but it does not provide support for less common audio formats. Here is where you can use [`~Dataset.set_transform`] to apply a custom decoding transform on the fly. You're free to use any library you like to decode the audio files. The example below uses the [`pydub`](http://pydub.com/) package to open an audio format not supported by `soundfile`: ```py >>> import numpy as np >>> from pydub import AudioSegment >>> audio_dataset_amr = Dataset.from_dict({"audio": ["audio_samples/audio.amr"]}) >>> def decode_audio_with_pydub(batch, sampling_rate=16_000): ... def pydub_decode_file(audio_path): ... sound = AudioSegment.from_file(audio_path) ... if sound.frame_rate != sampling_rate: ... sound = sound.set_frame_rate(sampling_rate) ... channel_sounds = sound.split_to_mono() ... samples = [s.get_array_of_samples() for s in channel_sounds] ... fp_arr = np.array(samples).T.astype(np.float32) ... fp_arr /= np.iinfo(samples[0].typecode).max ... return fp_arr ... ... batch["audio"] = [pydub_decode_file(audio_path) for audio_path in batch["audio"]] ... return batch >>> audio_dataset_amr.set_transform(decode_audio_with_pydub) ``` ## Save Once you are done processing your dataset, you can save and reuse it later with [`~Dataset.save_to_disk`]. Save your dataset by providing the path to the directory you wish to save it to: ```py >>> encoded_dataset.save_to_disk("path/of/my/dataset/directory") ``` Use the [`load_from_disk`] function to reload the dataset: ```py >>> from datasets import load_from_disk >>> reloaded_dataset = load_from_disk("path/of/my/dataset/directory") ``` <Tip> Want to save your dataset to a cloud storage provider? Read our [Cloud Storage](./filesystems) guide to learn how to save your dataset to AWS or Google Cloud Storage. </Tip> ## Export 🤗 Datasets supports exporting as well so you can work with your dataset in other applications. The following table shows currently supported file formats you can export to: | File type | Export method | |-------------------------|----------------------------------------------------------------| | CSV | [`Dataset.to_csv`] | | JSON | [`Dataset.to_json`] | | Parquet | [`Dataset.to_parquet`] | | SQL | [`Dataset.to_sql`] | | In-memory Python object | [`Dataset.to_pandas`] or [`Dataset.to_dict`] | For example, export your dataset to a CSV file like this: ```py >>> encoded_dataset.to_csv("path/of/my/dataset.csv") ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/use_with_jax.mdx
# Use with JAX This document is a quick introduction to using `datasets` with JAX, with a particular focus on how to get `jax.Array` objects out of our datasets, and how to use them to train JAX models. <Tip> `jax` and `jaxlib` are required to reproduce to code above, so please make sure you install them as `pip install datasets[jax]`. </Tip> ## Dataset format By default, datasets return regular Python objects: integers, floats, strings, lists, etc., and string and binary objects are unchanged, since JAX only supports numbers. To get JAX arrays (numpy-like) instead, you can set the format of the dataset to `jax`: ```py >>> from datasets import Dataset >>> data = [[1, 2], [3, 4]] >>> ds = Dataset.from_dict({"data": data}) >>> ds = ds.with_format("jax") >>> ds[0] {'data': DeviceArray([1, 2], dtype=int32)} >>> ds[:2] {'data': DeviceArray([ [1, 2], [3, 4]], dtype=int32)} ``` <Tip> A [`Dataset`] object is a wrapper of an Arrow table, which allows fast reads from arrays in the dataset to JAX arrays. </Tip> Note that the exact same procedure applies to `DatasetDict` objects, so that when setting the format of a `DatasetDict` to `jax`, all the `Dataset`s there will be formatted as `jax`: ```py >>> from datasets import DatasetDict >>> data = {"train": {"data": [[1, 2], [3, 4]]}, "test": {"data": [[5, 6], [7, 8]]}} >>> dds = DatasetDict.from_dict(data) >>> dds = dds.with_format("jax") >>> dds["train"][:2] {'data': DeviceArray([ [1, 2], [3, 4]], dtype=int32)} ``` Another thing you'll need to take into consideration is that the formatting is not applied until you actually access the data. So if you want to get a JAX array out of a dataset, you'll need to access the data first, otherwise the format will remain the same. Finally, to load the data in the device of your choice, you can specify the `device` argument, but note that `jaxlib.xla_extension.Device` is not supported as it's not serializable with neither `pickle` not `dill`, so you'll need to use its string identifier instead: ```py >>> import jax >>> from datasets import Dataset >>> data = [[1, 2], [3, 4]] >>> ds = Dataset.from_dict({"data": data}) >>> device = str(jax.devices()[0]) # Not casting to `str` before passing it to `with_format` will raise a `ValueError` >>> ds = ds.with_format("jax", device=device) >>> ds[0] {'data': DeviceArray([1, 2], dtype=int32)} >>> ds[0]["data"].device() TFRT_CPU_0 >>> assert ds[0]["data"].device() == jax.devices()[0] True ``` Note that if the `device` argument is not provided to `with_format` then it will use the default device which is `jax.devices()[0]`. ## N-dimensional arrays If your dataset consists of N-dimensional arrays, you will see that by default they are considered as nested lists. In particular, a JAX formatted dataset outputs a `DeviceArray` object, which is a numpy-like array, so it does not need the [`Array`] feature type to be specified as opposed to PyTorch or TensorFlow formatters. ```py >>> from datasets import Dataset >>> data = [[[1, 2],[3, 4]], [[5, 6],[7, 8]]] >>> ds = Dataset.from_dict({"data": data}) >>> ds = ds.with_format("jax") >>> ds[0] {'data': DeviceArray([[1, 2], [3, 4]], dtype=int32)} ``` ## Other feature types [`ClassLabel`] data is properly converted to arrays: ```py >>> from datasets import Dataset, Features, ClassLabel >>> labels = [0, 0, 1] >>> features = Features({"label": ClassLabel(names=["negative", "positive"])}) >>> ds = Dataset.from_dict({"label": labels}, features=features) >>> ds = ds.with_format("jax") >>> ds[:3] {'label': DeviceArray([0, 0, 1], dtype=int32)} ``` String and binary objects are unchanged, since JAX only supports numbers. The [`Image`] and [`Audio`] feature types are also supported. <Tip> To use the [`Image`] feature type, you'll need to install the `vision` extra as `pip install datasets[vision]`. </Tip> ```py >>> from datasets import Dataset, Features, Image >>> images = ["path/to/image.png"] * 10 >>> features = Features({"image": Image()}) >>> ds = Dataset.from_dict({"image": images}, features=features) >>> ds = ds.with_format("jax") >>> ds[0]["image"].shape (512, 512, 3) >>> ds[0] {'image': DeviceArray([[[ 255, 255, 255], [ 255, 255, 255], ..., [ 255, 255, 255], [ 255, 255, 255]]], dtype=uint8)} >>> ds[:2]["image"].shape (2, 512, 512, 3) >>> ds[:2] {'image': DeviceArray([[[[ 255, 255, 255], [ 255, 255, 255], ..., [ 255, 255, 255], [ 255, 255, 255]]]], dtype=uint8)} ``` <Tip> To use the [`Audio`] feature type, you'll need to install the `audio` extra as `pip install datasets[audio]`. </Tip> ```py >>> from datasets import Dataset, Features, Audio >>> audio = ["path/to/audio.wav"] * 10 >>> features = Features({"audio": Audio()}) >>> ds = Dataset.from_dict({"audio": audio}, features=features) >>> ds = ds.with_format("jax") >>> ds[0]["audio"]["array"] DeviceArray([-0.059021 , -0.03894043, -0.00735474, ..., 0.0133667 , 0.01809692, 0.00268555], dtype=float32) >>> ds[0]["audio"]["sampling_rate"] DeviceArray(44100, dtype=int32, weak_type=True) ``` ## Data loading JAX doesn't have any built-in data loading capabilities, so you'll need to use a library such as [PyTorch](https://pytorch.org/) to load your data using a `DataLoader` or [TensorFlow](https://www.tensorflow.org/) using a `tf.data.Dataset`. Citing the [JAX documentation](https://jax.readthedocs.io/en/latest/notebooks/Neural_Network_and_Data_Loading.html#data-loading-with-pytorch) on this topic: "JAX is laser-focused on program transformations and accelerator-backed NumPy, so we don’t include data loading or munging in the JAX library. There are already a lot of great data loaders out there, so let’s just use them instead of reinventing anything. We’ll grab PyTorch’s data loader, and make a tiny shim to make it work with NumPy arrays.". So that's the reason why JAX-formatting in `datasets` is so useful, because it lets you use any model from the HuggingFace Hub with JAX, without having to worry about the data loading part. ### Using `with_format('jax')` The easiest way to get JAX arrays out of a dataset is to use the `with_format('jax')` method. Lets assume that we want to train a neural network on the [MNIST dataset](http://yann.lecun.com/exdb/mnist/) available at the HuggingFace Hub at https://huggingface.co/datasets/mnist. ```py >>> from datasets import load_dataset >>> ds = load_dataset("mnist") >>> ds = ds.with_format("jax") >>> ds["train"][0] {'image': DeviceArray([[ 0, 0, 0, ...], [ 0, 0, 0, ...], ..., [ 0, 0, 0, ...], [ 0, 0, 0, ...]], dtype=uint8), 'label': DeviceArray(5, dtype=int32)} ``` Once the format is set we can feed the dataset to the JAX model in batches using the `Dataset.iter()` method: ```py >>> for epoch in range(epochs): ... for batch in ds["train"].iter(batch_size=32): ... x, y = batch["image"], batch["label"] ... ... ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/metrics.mdx
# Evaluate predictions <Tip warning={true}> Metrics is deprecated in 🤗 Datasets. To learn more about how to use metrics, take a look at the library 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index)! In addition to metrics, you can find more tools for evaluating models and datasets. </Tip> 🤗 Datasets provides various common and NLP-specific [metrics](https://huggingface.co/metrics) for you to measure your models performance. In this section of the tutorials, you will load a metric and use it to evaluate your models predictions. You can see what metrics are available with [`list_metrics`]: ```py >>> from datasets import list_metrics >>> metrics_list = list_metrics() >>> len(metrics_list) 28 >>> print(metrics_list) ['accuracy', 'bertscore', 'bleu', 'bleurt', 'cer', 'comet', 'coval', 'cuad', 'f1', 'gleu', 'glue', 'indic_glue', 'matthews_correlation', 'meteor', 'pearsonr', 'precision', 'recall', 'rouge', 'sacrebleu', 'sari', 'seqeval', 'spearmanr', 'squad', 'squad_v2', 'super_glue', 'wer', 'wiki_split', 'xnli'] ``` ## Load metric It is very easy to load a metric with 🤗 Datasets. In fact, you will notice that it is very similar to loading a dataset! Load a metric from the Hub with [`load_metric`]: ```py >>> from datasets import load_metric >>> metric = load_metric('glue', 'mrpc') ``` This will load the metric associated with the MRPC dataset from the GLUE benchmark. ## Select a configuration If you are using a benchmark dataset, you need to select a metric that is associated with the configuration you are using. Select a metric configuration by providing the configuration name: ```py >>> metric = load_metric('glue', 'mrpc') ``` ## Metrics object Before you begin using a [`Metric`] object, you should get to know it a little better. As with a dataset, you can return some basic information about a metric. For example, access the `inputs_description` parameter in [`datasets.MetricInfo`] to get more information about a metrics expected input format and some usage examples: ```py >>> print(metric.inputs_description) Compute GLUE evaluation metric associated to each GLUE dataset. Args: predictions: list of predictions to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. Returns: depending on the GLUE subset, one or several of: "accuracy": Accuracy "f1": F1 score "pearson": Pearson Correlation "spearmanr": Spearman Correlation "matthews_correlation": Matthew Correlation Examples: >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} ... >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp' >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} ... ``` Notice for the MRPC configuration, the metric expects the input format to be zero or one. For a complete list of attributes you can return with your metric, take a look at [`MetricInfo`]. ## Compute metric Once you have loaded a metric, you are ready to use it to evaluate a models predictions. Provide the model predictions and references to [`~datasets.Metric.compute`]: ```py >>> model_predictions = model(model_inputs) >>> final_score = metric.compute(predictions=model_predictions, references=gold_references) ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/_config.py
# docstyle-ignore INSTALL_CONTENT = """ # Datasets installation ! pip install datasets transformers # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/datasets.git """ notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}] default_branch_name = "main" version_prefix = ""
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/image_classification.mdx
# Image classification Image classification datasets are used to train a model to classify an entire image. There are a wide variety of applications enabled by these datasets such as identifying endangered wildlife species or screening for disease in medical images. This guide will show you how to apply transformations to an image classification dataset. Before you start, make sure you have up-to-date versions of `albumentations` and `cv2` installed: ```bash pip install -U albumentations opencv-python ``` This guide uses the [Beans](https://huggingface.co/datasets/beans) dataset for identifying the type of bean plant disease based on an image of its leaf. Load the dataset and take a look at an example: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("beans") >>> dataset["train"][10] {'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x500 at 0x7F8D2F4D7A10>, 'image_file_path': '/root/.cache/huggingface/datasets/downloads/extracted/b0a21163f78769a2cf11f58dfc767fb458fc7cea5c05dccc0144a2c0f0bc1292/train/angular_leaf_spot/angular_leaf_spot_train.204.jpg', 'labels': 0} ``` The dataset has three fields: * `image`: a PIL image object. * `image_file_path`: the path to the image file. * `labels`: the label or category of the image. Next, check out an image: <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/img_clf.png"> </div> Now apply some augmentations with `albumentations`. You'll randomly crop the image, flip it horizontally, and adjust its brightness. ```py >>> import cv2 >>> import albumentations >>> import numpy as np >>> transform = albumentations.Compose([ ... albumentations.RandomCrop(width=256, height=256), ... albumentations.HorizontalFlip(p=0.5), ... albumentations.RandomBrightnessContrast(p=0.2), ... ]) ``` Create a function to apply the transformation to the images: ```py >>> def transforms(examples): ... examples["pixel_values"] = [ ... transform(image=np.array(image))["image"] for image in examples["image"] ... ] ... ... return examples ``` Use the [`~Dataset.set_transform`] function to apply the transformation on-the-fly to batches of the dataset to consume less disk space: ```py >>> dataset.set_transform(transforms) ``` You can verify the transformation worked by indexing into the `pixel_values` of the first example: ```py >>> import numpy as np >>> import matplotlib.pyplot as plt >>> img = dataset["train"][0]["pixel_values"] >>> plt.imshow(img) ``` <div class="flex justify-center"> <img class="block dark:hidden" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/img_clf_aug.png"> <img class="hidden dark:block" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/img_clf_aug.png"/> </div> <Tip> Now that you know how to process a dataset for image classification, learn [how to train an image classification model](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb) and use it for inference. </Tip>
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/semantic_segmentation.mdx
# Semantic segmentation Semantic segmentation datasets are used to train a model to classify every pixel in an image. There are a wide variety of applications enabled by these datasets such as background removal from images, stylizing images, or scene understanding for autonomous driving. This guide will show you how to apply transformations to an image segmentation dataset. Before you start, make sure you have up-to-date versions of `albumentations` and `cv2` installed: ```bash pip install -U albumentations opencv-python ``` [Albumentations](https://albumentations.ai/) is a Python library for performing data augmentation for computer vision. It supports various computer vision tasks such as image classification, object detection, segmentation, and keypoint estimation. This guide uses the [Scene Parsing](https://huggingface.co/datasets/scene_parse_150) dataset for segmenting and parsing an image into different image regions associated with semantic categories, such as sky, road, person, and bed. Load the `train` split of the dataset and take a look at an example: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("scene_parse_150", split="train") >>> index = 10 >>> dataset[index] {'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=683x512 at 0x7FB37B0EC810>, 'annotation': <PIL.PngImagePlugin.PngImageFile image mode=L size=683x512 at 0x7FB37B0EC9D0>, 'scene_category': 927} ``` The dataset has three fields: * `image`: a PIL image object. * `annotation`: segmentation mask of the image. * `scene_category`: the label or scene category of the image (like “kitchen” or “office”). Next, check out an image with: ```py >>> dataset[index]["image"] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/image_seg.png"> </div> Similarly, you can check out the respective segmentation mask: ```py >>> dataset[index]["annotation"] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/seg_mask.png"> </div> We can also add a [color palette](https://github.com/tensorflow/models/blob/3f1ca33afe3c1631b733ea7e40c294273b9e406d/research/deeplab/utils/get_dataset_colormap.py#L51) on the segmentation mask and overlay it on top of the original image to visualize the dataset: After defining the color palette, you should be ready to visualize some overlays. ```py >>> import matplotlib.pyplot as plt >>> def visualize_seg_mask(image: np.ndarray, mask: np.ndarray): ... color_seg = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8) ... palette = np.array(create_ade20k_label_colormap()) ... for label, color in enumerate(palette): ... color_seg[mask == label, :] = color ... color_seg = color_seg[..., ::-1] # convert to BGR ... img = np.array(image) * 0.5 + color_seg * 0.5 # plot the image with the segmentation map ... img = img.astype(np.uint8) ... plt.figure(figsize=(15, 10)) ... plt.imshow(img) ... plt.axis("off") ... plt.show() >>> visualize_seg_mask( ... np.array(dataset[index]["image"]), ... np.array(dataset[index]["annotation"]) ... ) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/seg_overlay.png"> </div> Now apply some augmentations with `albumentations`. You’ll first resize the image and adjust its brightness. ```py >>> import albumentations >>> transform = albumentations.Compose( ... [ ... albumentations.Resize(256, 256), ... albumentations.RandomBrightnessContrast(brightness_limit=0.3, contrast_limit=0.3, p=0.5), ... ] ... ) ``` Create a function to apply the transformation to the images: ```py >>> def transforms(examples): ... transformed_images, transformed_masks = [], [] ... ... for image, seg_mask in zip(examples["image"], examples["annotation"]): ... image, seg_mask = np.array(image), np.array(seg_mask) ... transformed = transform(image=image, mask=seg_mask) ... transformed_images.append(transformed["image"]) ... transformed_masks.append(transformed["mask"]) ... ... examples["pixel_values"] = transformed_images ... examples["label"] = transformed_masks ... return examples ``` Use the [`~Dataset.set_transform`] function to apply the transformation on-the-fly to batches of the dataset to consume less disk space: ```py >>> dataset.set_transform(transforms) ``` You can verify the transformation worked by indexing into the `pixel_values` and `label` of an example: ```py >>> image = np.array(dataset[index]["pixel_values"]) >>> mask = np.array(dataset[index]["label"]) >>> visualize_seg_mask(image, mask) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/albumentations_seg.png"> </div> In this guide, you have used `albumentations` for augmenting the dataset. It's also possible to use `torchvision` to apply some similar transforms. ```py >>> from torchvision.transforms import Resize, ColorJitter, Compose >>> transformation_chain = Compose([ ... Resize((256, 256)), ... ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1) ... ]) >>> resize = Resize((256, 256)) >>> def train_transforms(example_batch): ... example_batch["pixel_values"] = [transformation_chain(x) for x in example_batch["image"]] ... example_batch["label"] = [resize(x) for x in example_batch["annotation"]] ... return example_batch >>> dataset.set_transform(train_transforms) >>> image = np.array(dataset[index]["pixel_values"]) >>> mask = np.array(dataset[index]["label"]) >>> visualize_seg_mask(image, mask) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/torchvision_seg.png"> </div> <Tip> Now that you know how to process a dataset for semantic segmentation, learn [how to train a semantic segmentation model](https://huggingface.co/docs/transformers/tasks/semantic_segmentation) and use it for inference. </Tip>
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/filesystems.mdx
# Cloud storage 🤗 Datasets supports access to cloud storage providers through a `fsspec` FileSystem implementations. You can save and load datasets from any cloud storage in a Pythonic way. Take a look at the following table for some example of supported cloud storage providers: | Storage provider | Filesystem implementation | |----------------------|---------------------------------------------------------------| | Amazon S3 | [s3fs](https://s3fs.readthedocs.io/en/latest/) | | Google Cloud Storage | [gcsfs](https://gcsfs.readthedocs.io/en/latest/) | | Azure Blob/DataLake | [adlfs](https://github.com/fsspec/adlfs) | | Dropbox | [dropboxdrivefs](https://github.com/MarineChap/dropboxdrivefs)| | Google Drive | [gdrivefs](https://github.com/intake/gdrivefs) | | Oracle Cloud Storage | [ocifs](https://ocifs.readthedocs.io/en/latest/) | This guide will show you how to save and load datasets with any cloud storage. Here are examples for S3, Google Cloud Storage, Azure Blob Storage, and Oracle Cloud Object Storage. ## Set up your cloud storage FileSystem ### Amazon S3 1. Install the S3 FileSystem implementation: ``` >>> pip install s3fs ``` 2. Define your credentials To use an anonymous connection, use `anon=True`. Otherwise, include your `aws_access_key_id` and `aws_secret_access_key` whenever you are interacting with a private S3 bucket. ```py >>> storage_options = {"anon": True} # for anonymous connection # or use your credentials >>> storage_options = {"key": aws_access_key_id, "secret": aws_secret_access_key} # for private buckets # or use a botocore session >>> import aiobotocore.session >>> s3_session = aiobotocore.session.AioSession(profile="my_profile_name") >>> storage_options = {"session": s3_session} ``` 3. Create your FileSystem instance ```py >>> import s3fs >>> fs = s3fs.S3FileSystem(**storage_options) ``` ### Google Cloud Storage 1. Install the Google Cloud Storage implementation: ``` >>> conda install -c conda-forge gcsfs # or install with pip >>> pip install gcsfs ``` 2. Define your credentials ```py >>> storage_options={"token": "anon"} # for anonymous connection # or use your credentials of your default gcloud credentials or from the google metadata service >>> storage_options={"project": "my-google-project"} # or use your credentials from elsewhere, see the documentation at https://gcsfs.readthedocs.io/ >>> storage_options={"project": "my-google-project", "token": TOKEN} ``` 3. Create your FileSystem instance ```py >>> import gcsfs >>> fs = gcsfs.GCSFileSystem(**storage_options) ``` ### Azure Blob Storage 1. Install the Azure Blob Storage implementation: ``` >>> conda install -c conda-forge adlfs # or install with pip >>> pip install adlfs ``` 2. Define your credentials ```py >>> storage_options = {"anon": True} # for anonymous connection # or use your credentials >>> storage_options = {"account_name": ACCOUNT_NAME, "account_key": ACCOUNT_KEY} # gen 2 filesystem # or use your credentials with the gen 1 filesystem >>> storage_options={"tenant_id": TENANT_ID, "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET} ``` 3. Create your FileSystem instance ```py >>> import adlfs >>> fs = adlfs.AzureBlobFileSystem(**storage_options) ``` ### Oracle Cloud Object Storage 1. Install the OCI FileSystem implementation: ``` >>> pip install ocifs ``` 2. Define your credentials ```py >>> storage_options = {"config": "~/.oci/config", "region": "us-ashburn-1"} ``` 3. Create your FileSystem instance ```py >>> import ocifs >>> fs = ocifs.OCIFileSystem(**storage_options) ``` ## Load and Save your datasets using your cloud storage FileSystem ### Download and prepare a dataset into a cloud storage You can download and prepare a dataset into your cloud storage by specifying a remote `output_dir` in `download_and_prepare`. Don't forget to use the previously defined `storage_options` containing your credentials to write into a private cloud storage. The `download_and_prepare` method works in two steps: 1. it first downloads the raw data files (if any) in your local cache. You can set your cache directory by passing `cache_dir` to [`load_dataset_builder`] 2. then it generates the dataset in Arrow or Parquet format in your cloud storage by iterating over the raw data files. Load a dataset builder from the Hugging Face Hub (see [how to load from the Hugging Face Hub](./loading#hugging-face-hub)): ```py >>> output_dir = "s3://my-bucket/imdb" >>> builder = load_dataset_builder("imdb") >>> builder.download_and_prepare(output_dir, storage_options=storage_options, file_format="parquet") ``` Load a dataset builder using a loading script (see [how to load a local loading script](./loading#local-loading-script)): ```py >>> output_dir = "s3://my-bucket/imdb" >>> builder = load_dataset_builder("path/to/local/loading_script/loading_script.py") >>> builder.download_and_prepare(output_dir, storage_options=storage_options, file_format="parquet") ``` Use your own data files (see [how to load local and remote files](./loading#local-and-remote-files)): ```py >>> data_files = {"train": ["path/to/train.csv"]} >>> output_dir = "s3://my-bucket/imdb" >>> builder = load_dataset_builder("csv", data_files=data_files) >>> builder.download_and_prepare(output_dir, storage_options=storage_options, file_format="parquet") ``` It is highly recommended to save the files as compressed Parquet files to optimize I/O by specifying `file_format="parquet"`. Otherwise the dataset is saved as an uncompressed Arrow file. You can also specify the size of the shards using `max_shard_size` (default is 500MB): ```py >>> builder.download_and_prepare(output_dir, storage_options=storage_options, file_format="parquet", max_shard_size="1GB") ``` #### Dask Dask is a parallel computing library and it has a pandas-like API for working with larger than memory Parquet datasets in parallel. Dask can use multiple threads or processes on a single machine, or a cluster of machines to process data in parallel. Dask supports local data but also data from a cloud storage. Therefore you can load a dataset saved as sharded Parquet files in Dask with ```py import dask.dataframe as dd df = dd.read_parquet(output_dir, storage_options=storage_options) # or if your dataset is split into train/valid/test df_train = dd.read_parquet(output_dir + f"/{builder.name}-train-*.parquet", storage_options=storage_options) df_valid = dd.read_parquet(output_dir + f"/{builder.name}-validation-*.parquet", storage_options=storage_options) df_test = dd.read_parquet(output_dir + f"/{builder.name}-test-*.parquet", storage_options=storage_options) ``` You can find more about dask dataframes in their [documentation](https://docs.dask.org/en/stable/dataframe.html). ## Saving serialized datasets After you have processed your dataset, you can save it to your cloud storage with [`Dataset.save_to_disk`]: ```py # saves encoded_dataset to amazon s3 >>> encoded_dataset.save_to_disk("s3://my-private-datasets/imdb/train", storage_options=storage_options) # saves encoded_dataset to google cloud storage >>> encoded_dataset.save_to_disk("gcs://my-private-datasets/imdb/train", storage_options=storage_options) # saves encoded_dataset to microsoft azure blob/datalake >>> encoded_dataset.save_to_disk("adl://my-private-datasets/imdb/train", storage_options=storage_options) ``` <Tip> Remember to define your credentials in your [FileSystem instance](#set-up-your-cloud-storage-filesystem) `fs` whenever you are interacting with a private cloud storage. </Tip> ## Listing serialized datasets List files from a cloud storage with your FileSystem instance `fs`, using `fs.ls`: ```py >>> fs.ls("my-private-datasets/imdb/train", detail=False) ["dataset_info.json.json","dataset.arrow","state.json"] ``` ### Load serialized datasets When you are ready to use your dataset again, reload it with [`Dataset.load_from_disk`]: ```py >>> from datasets import load_from_disk # load encoded_dataset from cloud storage >>> dataset = load_from_disk("s3://a-public-datasets/imdb/train", storage_options=storage_options) >>> print(len(dataset)) 25000 ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/image_process.mdx
# Process image data This guide shows specific methods for processing image datasets. Learn how to: - Use [`~Dataset.map`] with image dataset. - Apply data augmentations to a dataset with [`~Dataset.set_transform`]. For a guide on how to process any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./process">general process guide</a>. ## Map The [`~Dataset.map`] function can apply transforms over an entire dataset. For example, create a basic [`Resize`](https://pytorch.org/vision/stable/generated/torchvision.transforms.Resize.html) function: ```py >>> def transforms(examples): ... examples["pixel_values"] = [image.convert("RGB").resize((100,100)) for image in examples["image"]] ... return examples ``` Now use the [`~Dataset.map`] function to resize the entire dataset, and set `batched=True` to speed up the process by accepting batches of examples. The transform returns `pixel_values` as a cacheable `PIL.Image` object: ```py >>> dataset = dataset.map(transforms, remove_columns=["image"], batched=True) >>> dataset[0] {'label': 6, 'pixel_values': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=100x100 at 0x7F058237BB10>} ``` The cache file saves time because you don't have to execute the same transform twice. The [`~Dataset.map`] function is best for operations you only run once per training - like resizing an image - instead of using it for operations executed for each epoch, like data augmentations. [`~Dataset.map`] takes up some memory, but you can reduce its memory requirements with the following parameters: - [`batch_size`](./package_reference/main_classes#datasets.DatasetDict.map.batch_size) determines the number of examples that are processed in one call to the transform function. - [`writer_batch_size`](./package_reference/main_classes#datasets.DatasetDict.map.writer_batch_size) determines the number of processed examples that are kept in memory before they are stored away. Both parameter values default to 1000, which can be expensive if you are storing images. Lower these values to use less memory when you use [`~Dataset.map`]. ## Apply transforms 🤗 Datasets applies data augmentations from any library or package to your dataset. Transforms can be applied on-the-fly on batches of data with [`~Dataset.set_transform`], which consumes less disk space. <Tip> The following example uses [torchvision](https://pytorch.org/vision/stable/index.html), but feel free to use other data augmentation libraries like [Albumentations](https://albumentations.ai/docs/), [Kornia](https://kornia.readthedocs.io/en/latest/), and [imgaug](https://imgaug.readthedocs.io/en/latest/). </Tip> For example, if you'd like to change the color properties of an image randomly: ```py >>> from torchvision.transforms import Compose, ColorJitter, ToTensor >>> jitter = Compose( ... [ ... ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.7), ... ToTensor(), ... ] ... ) ``` Create a function to apply the `ColorJitter` transform: ```py >>> def transforms(examples): ... examples["pixel_values"] = [jitter(image.convert("RGB")) for image in examples["image"]] ... return examples ``` Apply the transform with the [`~Dataset.set_transform`] function: ```py >>> dataset.set_transform(transforms) ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/use_dataset.mdx
# Preprocess In addition to loading datasets, 🤗 Datasets other main goal is to offer a diverse set of preprocessing functions to get a dataset into an appropriate format for training with your machine learning framework. There are many possible ways to preprocess a dataset, and it all depends on your specific dataset. Sometimes you may need to rename a column, and other times you might need to unflatten nested fields. 🤗 Datasets provides a way to do most of these things. But in nearly all preprocessing cases, depending on your dataset modality, you'll need to: - Tokenize a text dataset. - Resample an audio dataset. - Apply transforms to an image dataset. The last preprocessing step is usually setting your dataset format to be compatible with your machine learning framework's expected input format. In this tutorial, you'll also need to install the 🤗 Transformers library: ```bash pip install transformers ``` Grab a dataset of your choice and follow along! ## Tokenize text Models cannot process raw text, so you'll need to convert the text into numbers. Tokenization provides a way to do this by dividing text into individual words called *tokens*. Tokens are finally converted to numbers. <Tip> Check out the [Tokenizers](https://huggingface.co/course/chapter2/4?fw=pt) section in Chapter 2 of the Hugging Face course to learn more about tokenization and different tokenization algorithms. </Tip> **1**. Start by loading the [rotten_tomatoes](https://huggingface.co/datasets/rotten_tomatoes) dataset and the tokenizer corresponding to a pretrained [BERT](https://huggingface.co/bert-base-uncased) model. Using the same tokenizer as the pretrained model is important because you want to make sure the text is split in the same way. ```py >>> from transformers import AutoTokenizer >>> from datasets import load_dataset >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") >>> dataset = load_dataset("rotten_tomatoes", split="train") ``` **2**. Call your tokenizer on the first row of `text` in the dataset: ```py >>> tokenizer(dataset[0]["text"]) {'input_ids': [101, 1103, 2067, 1110, 17348, 1106, 1129, 1103, 6880, 1432, 112, 188, 1207, 107, 14255, 1389, 107, 1105, 1115, 1119, 112, 188, 1280, 1106, 1294, 170, 24194, 1256, 3407, 1190, 170, 11791, 5253, 188, 1732, 7200, 10947, 12606, 2895, 117, 179, 7766, 118, 172, 15554, 1181, 3498, 6961, 3263, 1137, 188, 1566, 7912, 14516, 6997, 119, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} ``` The tokenizer returns a dictionary with three items: - `input_ids`: the numbers representing the tokens in the text. - `token_type_ids`: indicates which sequence a token belongs to if there is more than one sequence. - `attention_mask`: indicates whether a token should be masked or not. These values are actually the model inputs. **3**. The fastest way to tokenize your entire dataset is to use the [`~Dataset.map`] function. This function speeds up tokenization by applying the tokenizer to batches of examples instead of individual examples. Set the `batched` parameter to `True`: ```py >>> def tokenization(example): ... return tokenizer(example["text"]) >>> dataset = dataset.map(tokenization, batched=True) ``` **4**. Set the format of your dataset to be compatible with your machine learning framework: <frameworkcontent> <pt> Use the [`~Dataset.set_format`] function to set the dataset format to be compatible with PyTorch: ```py >>> dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "label"]) >>> dataset.format['type'] 'torch' ``` </pt> <tf> Use the [`~Dataset.to_tf_dataset`] function to set the dataset format to be compatible with TensorFlow. You'll also need to import a [data collator](https://huggingface.co/docs/transformers/main_classes/data_collator#transformers.DataCollatorWithPadding) from 🤗 Transformers to combine the varying sequence lengths into a single batch of equal lengths: ```py >>> from transformers import DataCollatorWithPadding >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf") >>> tf_dataset = dataset.to_tf_dataset( ... columns=["input_ids", "token_type_ids", "attention_mask"], ... label_cols=["label"], ... batch_size=2, ... collate_fn=data_collator, ... shuffle=True ... ) ``` </tf> </frameworkcontent> **5**. The dataset is now ready for training with your machine learning framework! ## Resample audio signals Audio inputs like text datasets need to be divided into discrete data points. This is known as *sampling*; the sampling rate tells you how much of the speech signal is captured per second. It is important to make sure the sampling rate of your dataset matches the sampling rate of the data used to pretrain the model you're using. If the sampling rates are different, the pretrained model may perform poorly on your dataset because it doesn't recognize the differences in the sampling rate. **1**. Start by loading the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset, the [`Audio`] feature, and the feature extractor corresponding to a pretrained [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base-960h) model: ```py >>> from transformers import AutoFeatureExtractor >>> from datasets import load_dataset, Audio >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h") >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train") ``` **2**. Index into the first row of the dataset. When you call the `audio` column of the dataset, it is automatically decoded and resampled: ```py >>> dataset[0]["audio"] {'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, 0. , 0. ], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 8000} ``` **3**. Reading a dataset card is incredibly useful and can give you a lot of information about the dataset. A quick look at the MInDS-14 dataset card tells you the sampling rate is 8kHz. Likewise, you can get many details about a model from its model card. The Wav2Vec2 model card says it was sampled on 16kHz speech audio. This means you'll need to upsample the MInDS-14 dataset to match the sampling rate of the model. Use the [`~Dataset.cast_column`] function and set the `sampling_rate` parameter in the [`Audio`] feature to upsample the audio signal. When you call the `audio` column now, it is decoded and resampled to 16kHz: ```py >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000)) >>> dataset[0]["audio"] {'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 16000} ``` **4**. Use the [`~Dataset.map`] function to resample the entire dataset to 16kHz. This function speeds up resampling by applying the feature extractor to batches of examples instead of individual examples. Set the `batched` parameter to `True`: ```py >>> def preprocess_function(examples): ... audio_arrays = [x["array"] for x in examples["audio"]] ... inputs = feature_extractor( ... audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=16000, truncation=True ... ) ... return inputs >>> dataset = dataset.map(preprocess_function, batched=True) ``` **5**. The dataset is now ready for training with your machine learning framework! ## Apply data augmentations The most common preprocessing you'll do with image datasets is *data augmentation*, a process that introduces random variations to an image without changing the meaning of the data. This can mean changing the color properties of an image or randomly cropping an image. You are free to use any data augmentation library you like, and 🤗 Datasets will help you apply your data augmentations to your dataset. **1**. Start by loading the [Beans](https://huggingface.co/datasets/beans) dataset, the `Image` feature, and the feature extractor corresponding to a pretrained [ViT](https://huggingface.co/google/vit-base-patch16-224-in21k) model: ```py >>> from transformers import AutoFeatureExtractor >>> from datasets import load_dataset, Image >>> feature_extractor = AutoFeatureExtractor.from_pretrained("google/vit-base-patch16-224-in21k") >>> dataset = load_dataset("beans", split="train") ``` **2**. Index into the first row of the dataset. When you call the `image` column of the dataset, the underlying PIL object is automatically decoded into an image. ```py >>> dataset[0]["image"] ``` **3**. Now, you can apply some transforms to the image. Feel free to take a look at the [various transforms available](https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#sphx-glr-auto-examples-plot-transforms-py) in torchvision and choose one you'd like to experiment with. This example applies a transform that randomly rotates the image: ```py >>> from torchvision.transforms import RandomRotation >>> rotate = RandomRotation(degrees=(0, 90)) >>> def transforms(examples): ... examples["pixel_values"] = [rotate(image.convert("RGB")) for image in examples["image"]] ... return examples ``` **4**. Use the [`~Dataset.set_transform`] function to apply the transform on-the-fly. When you index into the image `pixel_values`, the transform is applied, and your image gets rotated. ```py >>> dataset.set_transform(transforms) >>> dataset[0]["pixel_values"] ``` **5**. The dataset is now ready for training with your machine learning framework!
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/use_with_spark.mdx
# Use with Spark This document is a quick introduction to using 🤗 Datasets with Spark, with a particular focus on how to load a Spark DataFrame into a [`Dataset`] object. From there, you have fast access to any element and you can use it as a data loader to train models. ## Load from Spark A [`Dataset`] object is a wrapper of an Arrow table, which allows fast reads from arrays in the dataset to PyTorch, TensorFlow and JAX tensors. The Arrow table is memory mapped from disk, which can load datasets bigger than your available RAM. You can get a [`Dataset`] from a Spark DataFrame using [`Dataset.from_spark`]: ```py >>> from datasets import Dataset >>> df = spark.createDataFrame( ... data=[[1, "Elia"], [2, "Teo"], [3, "Fang"]], ... columns=["id", "name"], ... ) >>> ds = Dataset.from_spark(df) ``` The Spark workers write the dataset on disk in a cache directory as Arrow files, and the [`Dataset`] is loaded from there. Alternatively, you can skip materialization by using [`IterableDataset.from_spark`], which returns an [`IterableDataset`]: ```py >>> from datasets import IterableDataset >>> df = spark.createDataFrame( ... data=[[1, "Elia"], [2, "Teo"], [3, "Fang"]], ... columns=["id", "name"], ... ) >>> ds = IterableDataset.from_spark(df) >>> print(next(iter(ds))) {"id": 1, "name": "Elia"} ``` ### Caching When using [`Dataset.from_spark`], the resulting [`Dataset`] is cached; if you call [`Dataset.from_spark`] multiple times on the same DataFrame it won't re-run the Spark job that writes the dataset as Arrow files on disk. You can set the cache location by passing `cache_dir=` to [`Dataset.from_spark`]. Make sure to use a disk that is available to both your workers and your current machine (the driver). <Tip warning={true}> In a different session, a Spark DataFrame doesn't have the same [semantic hash](https://spark.apache.org/docs/3.2.0/api/python/reference/api/pyspark.sql.DataFrame.semanticHash.html), and it will rerun a Spark job and store it in a new cache. </Tip> ### Feature types If your dataset is made of images, audio data or N-dimensional arrays, you can specify the `features=` argument in [`Dataset.from_spark`] (or [`IterableDataset.from_spark`]): ```py >>> from datasets import Dataset, Features, Image, Value >>> data = [(0, open("image.png", "rb").read())] >>> df = spark.createDataFrame(data, "idx: int, image: binary") >>> # Also works if you have arrays >>> # data = [(0, np.zeros(shape=(32, 32, 3), dtype=np.int32).tolist())] >>> # df = spark.createDataFrame(data, "idx: int, image: array<array<array<int>>>") >>> features = Features({"idx": Value("int64"), "image": Image()}) >>> dataset = Dataset.from_spark(df, features=features) >>> dataset[0] {'idx': 0, 'image': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=32x32>} ``` You can check the [`Features`] documentation to know about all the feature types available.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/image_dataset.mdx
# Create an image dataset There are two methods for creating and sharing an image dataset. This guide will show you how to: * Create an image dataset with `ImageFolder` and some metadata. This is a no-code solution for quickly creating an image dataset with several thousand images. * Create an image dataset by writing a loading script. This method is a bit more involved, but you have greater flexibility over how a dataset is defined, downloaded, and generated which can be useful for more complex or large scale image datasets. <Tip> You can control access to your dataset by requiring users to share their contact information first. Check out the [Gated datasets](https://huggingface.co/docs/hub/datasets-gated) guide for more information about how to enable this feature on the Hub. </Tip> ## ImageFolder The `ImageFolder` is a dataset builder designed to quickly load an image dataset with several thousand images without requiring you to write any code. <Tip> 💡 Take a look at the [Split pattern hierarchy](repository_structure#split-pattern-hierarchy) to learn more about how `ImageFolder` creates dataset splits based on your dataset repository structure. </Tip> `ImageFolder` automatically infers the class labels of your dataset based on the directory name. Store your dataset in a directory structure like: ``` folder/train/dog/golden_retriever.png folder/train/dog/german_shepherd.png folder/train/dog/chihuahua.png folder/train/cat/maine_coon.png folder/train/cat/bengal.png folder/train/cat/birman.png ``` Then users can load your dataset by specifying `imagefolder` in [`load_dataset`] and the directory in `data_dir`: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder") ``` You can also use `imagefolder` to load datasets involving multiple splits. To do so, your dataset directory should have the following structure: ``` folder/train/dog/golden_retriever.png folder/train/cat/maine_coon.png folder/test/dog/german_shepherd.png folder/test/cat/bengal.png ``` <Tip warning={true}> If all image files are contained in a single directory or if they are not on the same level of directory structure, `label` column won't be added automatically. If you need it, set `drop_labels=False` explicitly. </Tip> If there is additional information you'd like to include about your dataset, like text captions or bounding boxes, add it as a `metadata.csv` file in your folder. This lets you quickly create datasets for different computer vision tasks like text captioning or object detection. You can also use a JSONL file `metadata.jsonl`. ``` folder/train/metadata.csv folder/train/0001.png folder/train/0002.png folder/train/0003.png ``` You can also zip your images: ``` folder/metadata.csv folder/train.zip folder/test.zip folder/valid.zip ``` Your `metadata.csv` file must have a `file_name` column which links image files with their metadata: ```csv file_name,additional_feature 0001.png,This is a first value of a text feature you added to your images 0002.png,This is a second value of a text feature you added to your images 0003.png,This is a third value of a text feature you added to your images ``` or using `metadata.jsonl`: ```jsonl {"file_name": "0001.png", "additional_feature": "This is a first value of a text feature you added to your images"} {"file_name": "0002.png", "additional_feature": "This is a second value of a text feature you added to your images"} {"file_name": "0003.png", "additional_feature": "This is a third value of a text feature you added to your images"} ``` <Tip> If metadata files are present, the inferred labels based on the directory name are dropped by default. To include those labels, set `drop_labels=False` in `load_dataset`. </Tip> ### Image captioning Image captioning datasets have text describing an image. An example `metadata.csv` may look like: ```csv file_name,text 0001.png,This is a golden retriever playing with a ball 0002.png,A german shepherd 0003.png,One chihuahua ``` Load the dataset with `ImageFolder`, and it will create a `text` column for the image captions: ```py >>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder", split="train") >>> dataset[0]["text"] "This is a golden retriever playing with a ball" ``` ### Object detection Object detection datasets have bounding boxes and categories identifying objects in an image. An example `metadata.jsonl` may look like: ```jsonl {"file_name": "0001.png", "objects": {"bbox": [[302.0, 109.0, 73.0, 52.0]], "categories": [0]}} {"file_name": "0002.png", "objects": {"bbox": [[810.0, 100.0, 57.0, 28.0]], "categories": [1]}} {"file_name": "0003.png", "objects": {"bbox": [[160.0, 31.0, 248.0, 616.0], [741.0, 68.0, 202.0, 401.0]], "categories": [2, 2]}} ``` Load the dataset with `ImageFolder`, and it will create a `objects` column with the bounding boxes and the categories: ```py >>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder", split="train") >>> dataset[0]["objects"] {"bbox": [[302.0, 109.0, 73.0, 52.0]], "categories": [0]} ``` ### Upload dataset to the Hub Once you've created a dataset, you can share it to the Hub with the [`~datasets.DatasetDict.push_to_hub`] method. Make sure you have the [huggingface_hub](https://huggingface.co/docs/huggingface_hub/index) library installed and you're logged in to your Hugging Face account (see the [Upload with Python tutorial](upload_dataset#upload-with-python) for more details). Upload your dataset with [`~datasets.DatasetDict.push_to_hub`]: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder", split="train") >>> dataset.push_to_hub("stevhliu/my-image-captioning-dataset") ``` ## WebDataset The [WebDataset](https://github.com/webdataset/webdataset) format is based on TAR archives and is suitable for big image datasets. Indeed you can group your images in TAR archives (e.g. 1GB of images per TAR archive) and have thousands of TAR archives: ``` folder/train/00000.tar folder/train/00001.tar folder/train/00002.tar ... ``` In the archives, each example is made of files sharing the same prefix: ``` e39871fd9fd74f55.jpg e39871fd9fd74f55.json f18b91585c4d3f3e.jpg f18b91585c4d3f3e.json ede6e66b2fb59aab.jpg ede6e66b2fb59aab.json ed600d57fcee4f94.jpg ed600d57fcee4f94.json ... ``` You can put your images labels/captions/bounding boxes using JSON or text files for example. For more details on the WebDataset format and the python library, please check the [WebDataset documentation](https://webdataset.github.io/webdataset). Load your WebDataset and it will create on column per file suffix (here "jpg" and "json"): ```python >>> from datasets import load_dataset >>> dataset = load_dataset("webdataset", data_dir="/path/to/folder", split="train") >>> dataset[0]["json"] {"bbox": [[302.0, 109.0, 73.0, 52.0]], "categories": [0]} ``` ## Loading script Write a dataset loading script to share a dataset. It defines a dataset's splits and configurations, and handles downloading and generating a dataset. The script is located in the same folder or repository as the dataset and should have the same name. ``` my_dataset/ ├── README.md ├── my_dataset.py └── data/ # optional, may contain your images or TAR archives ``` This structure allows your dataset to be loaded in one line: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("path/to/my_dataset") ``` This guide will show you how to create a dataset loading script for image datasets, which is a bit different from <a class="underline decoration-green-400 decoration-2 font-semibold" href="./dataset_script">creating a loading script for text datasets</a>. You'll learn how to: * Create a dataset builder class. * Create dataset configurations. * Add dataset metadata. * Download and define the dataset splits. * Generate the dataset. * Generate the dataset metadata (optional). * Upload the dataset to the Hub. The best way to learn is to open up an existing image dataset loading script, like [Food-101](https://huggingface.co/datasets/food101/blob/main/food101.py), and follow along! <Tip> To help you get started, we created a loading script [template](https://github.com/huggingface/datasets/blob/main/templates/new_dataset_script.py) you can copy and use as a starting point! </Tip> ### Create a dataset builder class [`GeneratorBasedBuilder`] is the base class for datasets generated from a dictionary generator. Within this class, there are three methods to help create your dataset: * `info` stores information about your dataset like its description, license, and features. * `split_generators` downloads the dataset and defines its splits. * `generate_examples` generates the images and labels for each split. Start by creating your dataset class as a subclass of [`GeneratorBasedBuilder`] and add the three methods. Don't worry about filling in each of these methods yet, you'll develop those over the next few sections: ```py class Food101(datasets.GeneratorBasedBuilder): """Food-101 Images dataset""" def _info(self): def _split_generators(self, dl_manager): def _generate_examples(self, images, metadata_path): ``` #### Multiple configurations In some cases, a dataset may have more than one configuration. For example, if you check out the [Imagenette dataset](https://huggingface.co/datasets/frgfm/imagenette), you'll notice there are three subsets. To create different configurations, use the [`BuilderConfig`] class to create a subclass for your dataset. Provide the links to download the images and labels in `data_url` and `metadata_urls`: ```py class Food101Config(datasets.BuilderConfig): """Builder Config for Food-101""" def __init__(self, data_url, metadata_urls, **kwargs): """BuilderConfig for Food-101. Args: data_url: `string`, url to download the zip file from. metadata_urls: dictionary with keys 'train' and 'validation' containing the archive metadata URLs **kwargs: keyword arguments forwarded to super. """ super(Food101Config, self).__init__(version=datasets.Version("1.0.0"), **kwargs) self.data_url = data_url self.metadata_urls = metadata_urls ``` Now you can define your subsets at the top of [`GeneratorBasedBuilder`]. Imagine you want to create two subsets in the Food-101 dataset based on whether it is a breakfast or dinner food. 1. Define your subsets with `Food101Config` in a list in `BUILDER_CONFIGS`. 2. For each configuration, provide a name, description, and where to download the images and labels from. ```py class Food101(datasets.GeneratorBasedBuilder): """Food-101 Images dataset""" BUILDER_CONFIGS = [ Food101Config( name="breakfast", description="Food types commonly eaten during breakfast.", data_url="https://link-to-breakfast-foods.zip", metadata_urls={ "train": "https://link-to-breakfast-foods-train.txt", "validation": "https://link-to-breakfast-foods-validation.txt" }, , Food101Config( name="dinner", description="Food types commonly eaten during dinner.", data_url="https://link-to-dinner-foods.zip", metadata_urls={ "train": "https://link-to-dinner-foods-train.txt", "validation": "https://link-to-dinner-foods-validation.txt" }, )... ] ``` Now if users want to load the `breakfast` configuration, they can use the configuration name: ```py >>> from datasets import load_dataset >>> ds = load_dataset("food101", "breakfast", split="train") ``` ### Add dataset metadata Adding information about your dataset is useful for users to learn more about it. This information is stored in the [`DatasetInfo`] class which is returned by the `info` method. Users can access this information by: ```py >>> from datasets import load_dataset_builder >>> ds_builder = load_dataset_builder("food101") >>> ds_builder.info ``` There is a lot of information you can specify about your dataset, but some important ones to include are: 1. `description` provides a concise description of the dataset. 2. `features` specify the dataset column types. Since you're creating an image loading script, you'll need to include the [`Image`] feature. 3. `supervised_keys` specify the input feature and label. 4. `homepage` provides a link to the dataset homepage. 5. `citation` is a BibTeX citation of the dataset. 6. `license` states the dataset's license. <Tip> You'll notice a lot of the dataset information is defined earlier in the loading script which makes it easier to read. There are also other [`~Datasets.Features`] you can input, so be sure to check out the full list for more details. </Tip> ```py def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "image": datasets.Image(), "label": datasets.ClassLabel(names=_NAMES), } ), supervised_keys=("image", "label"), homepage=_HOMEPAGE, citation=_CITATION, license=_LICENSE, task_templates=[ImageClassification(image_column="image", label_column="label")], ) ``` ### Download and define the dataset splits Now that you've added some information about your dataset, the next step is to download the dataset and generate the splits. 1. Use the [`DownloadManager.download`] method to download the dataset and any other metadata you'd like to associate with it. This method accepts: * a name to a file inside a Hub dataset repository (in other words, the `data/` folder) * a URL to a file hosted somewhere else * a list or dictionary of file names or URLs In the Food-101 loading script, you'll notice again the URLs are defined earlier in the script. 2. After you've downloaded the dataset, use the [`SplitGenerator`] to organize the images and labels in each split. Name each split with a standard name like: `Split.TRAIN`, `Split.TEST`, and `SPLIT.Validation`. In the `gen_kwargs` parameter, specify the file paths to the `images` to iterate over and load. If necessary, you can use [`DownloadManager.iter_archive`] to iterate over images in TAR archives. You can also specify the associated labels in the `metadata_path`. The `images` and `metadata_path` are actually passed onto the next step where you'll actually generate the dataset. <Tip warning={true}> To stream a TAR archive file, you need to use [`DownloadManager.iter_archive`]! The [`DownloadManager.download_and_extract`] function does not support TAR archives in streaming mode. </Tip> ```py def _split_generators(self, dl_manager): archive_path = dl_manager.download(_BASE_URL) split_metadata_paths = dl_manager.download(_METADATA_URLS) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "images": dl_manager.iter_archive(archive_path), "metadata_path": split_metadata_paths["train"], }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "images": dl_manager.iter_archive(archive_path), "metadata_path": split_metadata_paths["test"], }, ), ] ``` ### Generate the dataset The last method in the [`GeneratorBasedBuilder`] class actually generates the images and labels in the dataset. It yields a dataset according to the stucture specified in `features` from the `info` method. As you can see, `generate_examples` accepts the `images` and `metadata_path` from the previous method as arguments. <Tip warning={true}> To stream a TAR archive file, the `metadata_path` needs to be opened and read first. TAR files are accessed and yielded sequentially. This means you need to have the metadata information in hand first so you can yield it with its corresponding image. </Tip> Now you can write a function for opening and loading examples from the dataset: ```py def _generate_examples(self, images, metadata_path): """Generate images and labels for splits.""" with open(metadata_path, encoding="utf-8") as f: files_to_keep = set(f.read().split("\n")) for file_path, file_obj in images: if file_path.startswith(_IMAGES_DIR): if file_path[len(_IMAGES_DIR) : -len(".jpg")] in files_to_keep: label = file_path.split("/")[2] yield file_path, { "image": {"path": file_path, "bytes": file_obj.read()}, "label": label, } ``` ### Generate the dataset metadata (optional) The dataset metadata can be generated and stored in the dataset card (`README.md` file). Run the following command to generate your dataset metadata in `README.md` and make sure your new loading script works correctly: ```bash datasets-cli test path/to/<your-dataset-loading-script> --save_info --all_configs ``` If your loading script passed the test, you should now have the `dataset_info` YAML fields in the header of the `README.md` file in your dataset folder. ### Upload the dataset to the Hub Once your script is ready, [create a dataset card](./dataset_card) and [upload it to the Hub](./share). Congratulations, you can now load your dataset from the Hub! 🥳 ```py >>> from datasets import load_dataset >>> load_dataset("<username>/my_dataset") ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/beam.mdx
# Beam Datasets Some datasets are too large to be processed on a single machine. Instead, you can process them with [Apache Beam](https://beam.apache.org/), a library for parallel data processing. The processing pipeline is executed on a distributed processing backend such as [Apache Flink](https://flink.apache.org/), [Apache Spark](https://spark.apache.org/), or [Google Cloud Dataflow](https://cloud.google.com/dataflow). We have already created Beam pipelines for some of the larger datasets like [wikipedia](https://huggingface.co/datasets/wikipedia), and [wiki40b](https://huggingface.co/datasets/wiki40b). You can load these normally with [`load_dataset`]. But if you want to run your own Beam pipeline with Dataflow, here is how: 1. Specify the dataset and configuration you want to process: ``` DATASET_NAME=your_dataset_name # ex: wikipedia CONFIG_NAME=your_config_name # ex: 20220301.en ``` 2. Input your Google Cloud Platform information: ``` PROJECT=your_project BUCKET=your_bucket REGION=your_region ``` 3. Specify your Python requirements: ``` echo "datasets" > /tmp/beam_requirements.txt echo "apache_beam" >> /tmp/beam_requirements.txt ``` 4. Run the pipeline: ``` datasets-cli run_beam datasets/$DATASET_NAME \ --name $CONFIG_NAME \ --save_info \ --cache_dir gs://$BUCKET/cache/datasets \ --beam_pipeline_options=\ "runner=DataflowRunner,project=$PROJECT,job_name=$DATASET_NAME-gen,"\ "staging_location=gs://$BUCKET/binaries,temp_location=gs://$BUCKET/temp,"\ "region=$REGION,requirements_file=/tmp/beam_requirements.txt" ``` <Tip> When you run your pipeline, you can adjust the parameters to change the runner (Flink or Spark), output location (S3 bucket or HDFS), and the number of workers. </Tip>
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/use_with_tensorflow.mdx
# Using Datasets with TensorFlow This document is a quick introduction to using `datasets` with TensorFlow, with a particular focus on how to get `tf.Tensor` objects out of our datasets, and how to stream data from Hugging Face `Dataset` objects to Keras methods like `model.fit()`. ## Dataset format By default, datasets return regular Python objects: integers, floats, strings, lists, etc. To get TensorFlow tensors instead, you can set the format of the dataset to `tf`: ```py >>> from datasets import Dataset >>> data = [[1, 2],[3, 4]] >>> ds = Dataset.from_dict({"data": data}) >>> ds = ds.with_format("tf") >>> ds[0] {'data': <tf.Tensor: shape=(2,), dtype=int64, numpy=array([1, 2])>} >>> ds[:2] {'data': <tf.Tensor: shape=(2, 2), dtype=int64, numpy= array([[1, 2], [3, 4]])>} ``` <Tip> A [`Dataset`] object is a wrapper of an Arrow table, which allows fast reads from arrays in the dataset to TensorFlow tensors. </Tip> This can be useful for converting your dataset to a dict of `Tensor` objects, or for writing a generator to load TF samples from it. If you wish to convert the entire dataset to `Tensor`, simply query the full dataset: ```py >>> ds[:] {'data': <tf.Tensor: shape=(2, 2), dtype=int64, numpy= array([[1, 2], [3, 4]])>} ``` ## N-dimensional arrays If your dataset consists of N-dimensional arrays, you will see that by default they are considered as nested lists. In particular, a TensorFlow formatted dataset outputs a `RaggedTensor` instead of a single tensor: ```py >>> from datasets import Dataset >>> data = [[[1, 2],[3, 4]],[[5, 6],[7, 8]]] >>> ds = Dataset.from_dict({"data": data}) >>> ds = ds.with_format("tf") >>> ds[0] {'data': <tf.RaggedTensor [[1, 2], [3, 4]]>} ``` To get a single tensor, you must explicitly use the [`Array`] feature type and specify the shape of your tensors: ```py >>> from datasets import Dataset, Features, Array2D >>> data = [[[1, 2],[3, 4]],[[5, 6],[7, 8]]] >>> features = Features({"data": Array2D(shape=(2, 2), dtype='int32')}) >>> ds = Dataset.from_dict({"data": data}, features=features) >>> ds = ds.with_format("tf") >>> ds[0] {'data': <tf.Tensor: shape=(2, 2), dtype=int64, numpy= array([[1, 2], [3, 4]])>} >>> ds[:2] {'data': <tf.Tensor: shape=(2, 2, 2), dtype=int64, numpy= array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])>} ``` ## Other feature types [`ClassLabel`] data are properly converted to tensors: ```py >>> from datasets import Dataset, Features, ClassLabel >>> labels = [0, 0, 1] >>> features = Features({"label": ClassLabel(names=["negative", "positive"])}) >>> ds = Dataset.from_dict({"label": labels}, features=features) >>> ds = ds.with_format("tf") >>> ds[:3] {'label': <tf.Tensor: shape=(3,), dtype=int64, numpy=array([0, 0, 1])>} ``` Strings and binary objects are also supported: ```py >>> from datasets import Dataset, Features >>> text = ["foo", "bar"] >>> data = [0, 1] >>> ds = Dataset.from_dict({"text": text, "data": data}) >>> ds = ds.with_format("tf") >>> ds[:2] {'text': <tf.Tensor: shape=(2,), dtype=string, numpy=array([b'foo', b'bar'], dtype=object)>, 'data': <tf.Tensor: shape=(2,), dtype=int64, numpy=array([0, 1])>} ``` You can also explicitly format certain columns and leave the other columns unformatted: ```py >>> ds = ds.with_format("tf", columns=["data"], output_all_columns=True) >>> ds[:2] {'data': <tf.Tensor: shape=(2,), dtype=int64, numpy=array([0, 1])>, 'text': ['foo', 'bar']} ``` String and binary objects are unchanged, since PyTorch only supports numbers. The [`Image`] and [`Audio`] feature types are also supported. <Tip> To use the [`Image`] feature type, you'll need to install the `vision` extra as `pip install datasets[vision]`. </Tip> ```py >>> from datasets import Dataset, Features, Audio, Image >>> images = ["path/to/image.png"] * 10 >>> features = Features({"image": Image()}) >>> ds = Dataset.from_dict({"image": images}, features=features) >>> ds = ds.with_format("tf") >>> ds[0] {'image': <tf.Tensor: shape=(512, 512, 4), dtype=uint8, numpy= array([[[255, 215, 106, 255], [255, 215, 106, 255], ..., [255, 255, 255, 255], [255, 255, 255, 255]]], dtype=uint8)>} >>> ds[:2] {'image': <tf.Tensor: shape=(2, 512, 512, 4), dtype=uint8, numpy= array([[[[255, 215, 106, 255], [255, 215, 106, 255], ..., [255, 255, 255, 255], [255, 255, 255, 255]]]], dtype=uint8)>} ``` <Tip> To use the [`Audio`] feature type, you'll need to install the `audio` extra as `pip install datasets[audio]`. </Tip> ```py >>> from datasets import Dataset, Features, Audio, Image >>> audio = ["path/to/audio.wav"] * 10 >>> features = Features({"audio": Audio()}) >>> ds = Dataset.from_dict({"audio": audio}, features=features) >>> ds = ds.with_format("tf") >>> ds[0]["audio"]["array"] <tf.Tensor: shape=(202311,), dtype=float32, numpy= array([ 6.1035156e-05, 1.5258789e-05, 1.6784668e-04, ..., -1.5258789e-05, -1.5258789e-05, 1.5258789e-05], dtype=float32)> >>> ds[0]["audio"]["sampling_rate"] <tf.Tensor: shape=(), dtype=int32, numpy=44100> ``` ## Data loading Although you can load individual samples and batches just by indexing into your dataset, this won't work if you want to use Keras methods like `fit()` and `predict()`. You could write a generator function that shuffles and loads batches from your dataset and `fit()` on that, but that sounds like a lot of unnecessary work. Instead, if you want to stream data from your dataset on-the-fly, we recommend converting your dataset to a `tf.data.Dataset` using the `to_tf_dataset()` method. The `tf.data.Dataset` class covers a wide range of use-cases - it is often created from Tensors in memory, or using a load function to read files on disc or external storage. The dataset can be transformed arbitrarily with the `map()` method, or methods like `batch()` and `shuffle()` can be used to create a dataset that's ready for training. These methods do not modify the stored data in any way - instead, the methods build a data pipeline graph that will be executed when the dataset is iterated over, usually during model training or inference. This is different from the `map()` method of Hugging Face `Dataset` objects, which runs the map function immediately and saves the new or changed columns. Since the entire data preprocessing pipeline can be compiled in a `tf.data.Dataset`, this approach allows for massively parallel, asynchronous data loading and training. However, the requirement for graph compilation can be a limitation, particularly for Hugging Face tokenizers, which are usually not (yet!) compilable as part of a TF graph. As a result, we usually advise pre-processing the dataset as a Hugging Face dataset, where arbitrary Python functions can be used, and then converting to `tf.data.Dataset` afterwards using `to_tf_dataset()` to get a batched dataset ready for training. To see examples of this approach, please see the [examples](https://github.com/huggingface/transformers/tree/main/examples) or [notebooks](https://huggingface.co/docs/transformers/notebooks) for `transformers`. ### Using `to_tf_dataset()` Using `to_tf_dataset()` is straightforward. Once your dataset is preprocessed and ready, simply call it like so: ```py >>> from datasets import Dataset >>> data = {"inputs": [[1, 2],[3, 4]], "labels": [0, 1]} >>> ds = Dataset.from_dict(data) >>> tf_ds = ds.to_tf_dataset( columns=["inputs"], label_cols=["labels"], batch_size=2, shuffle=True ) ``` The returned `tf_ds` object here is now fully ready to train on, and can be passed directly to `model.fit()`. Note that you set the batch size when creating the dataset, and so you don't need to specify it when calling `fit()`: ```py >>> model.fit(tf_ds, epochs=2) ``` For a full description of the arguments, please see the [`~Dataset.to_tf_dataset`] documentation. In many cases, you will also need to add a `collate_fn` to your call. This is a function that takes multiple elements of the dataset and combines them into a single batch. When all elements have the same length, the built-in default collator will suffice, but for more complex tasks a custom collator may be necessary. In particular, many tasks have samples with varying sequence lengths which will require a [data collator](https://huggingface.co/docs/transformers/main/en/main_classes/data_collator) that can pad batches correctly. You can see examples of this in the `transformers` NLP [examples](https://github.com/huggingface/transformers/tree/main/examples) and [notebooks](https://huggingface.co/docs/transformers/notebooks), where variable sequence lengths are very common. If you find that loading with `to_tf_dataset` is slow, you can also use the `num_workers` argument. This spins up multiple subprocesses to load data in parallel. This feature is recent and still somewhat experimental - please file an issue if you encounter any bugs while using it! ### When to use to_tf_dataset The astute reader may have noticed at this point that we have offered two approaches to achieve the same goal - if you want to pass your dataset to a TensorFlow model, you can either convert the dataset to a `Tensor` or `dict` of `Tensors` using `.with_format('tf')`, or you can convert the dataset to a `tf.data.Dataset` with `to_tf_dataset()`. Either of these can be passed to `model.fit()`, so which should you choose? The key thing to recognize is that when you convert the whole dataset to `Tensor`s, it is static and fully loaded into RAM. This is simple and convenient, but if any of the following apply, you should probably use `to_tf_dataset()` instead: - Your dataset is too large to fit in RAM. `to_tf_dataset()` streams only one batch at a time, so even very large datasets can be handled with this method. - You want to apply random transformations using `dataset.with_transform()` or the `collate_fn`. This is common in several modalities, such as image augmentations when training vision models, or random masking when training masked language models. Using `to_tf_dataset()` will apply those transformations at the moment when a batch is loaded, which means the same samples will get different augmentations each time they are loaded. This is usually what you want. - Your data has a variable dimension, such as input texts in NLP that consist of varying numbers of tokens. When you create a batch with samples with a variable dimension, the standard solution is to pad the shorter samples to the length of the longest one. When you stream samples from a dataset with `to_tf_dataset`, you can apply this padding to each batch via your `collate_fn`. However, if you want to convert such a dataset to dense `Tensor`s, then you will have to pad samples to the length of the longest sample in *the entire dataset!* This can result in huge amounts of padding, which wastes memory and reduces your model's speed. ### Caveats and limitations Right now, `to_tf_dataset()` always returns a batched dataset - we will add support for unbatched datasets soon!
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_dataset_features.mdx
# Dataset features [`Features`] defines the internal structure of a dataset. It is used to specify the underlying serialization format. What's more interesting to you though is that [`Features`] contains high-level information about everything from the column names and types, to the [`ClassLabel`]. You can think of [`Features`] as the backbone of a dataset. The [`Features`] format is simple: `dict[column_name, column_type]`. It is a dictionary of column name and column type pairs. The column type provides a wide range of options for describing the type of data you have. Let's have a look at the features of the MRPC dataset from the GLUE benchmark: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('glue', 'mrpc', split='train') >>> dataset.features {'idx': Value(dtype='int32', id=None), 'label': ClassLabel(num_classes=2, names=['not_equivalent', 'equivalent'], names_file=None, id=None), 'sentence1': Value(dtype='string', id=None), 'sentence2': Value(dtype='string', id=None), } ``` The [`Value`] feature tells 🤗 Datasets: - The `idx` data type is `int32`. - The `sentence1` and `sentence2` data types are `string`. 🤗 Datasets supports many other data types such as `bool`, `float32` and `binary` to name just a few. <Tip> Refer to [`Value`] for a full list of supported data types. </Tip> The [`ClassLabel`] feature informs 🤗 Datasets the `label` column contains two classes. The classes are labeled `not_equivalent` and `equivalent`. Labels are stored as integers in the dataset. When you retrieve the labels, [`ClassLabel.int2str`] and [`ClassLabel.str2int`] carries out the conversion from integer value to label name, and vice versa. If your data type contains a list of objects, then you want to use the [`Sequence`] feature. Remember the SQuAD dataset? ```py >>> from datasets import load_dataset >>> dataset = load_dataset('squad', split='train') >>> dataset.features {'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None), 'context': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None), 'title': Value(dtype='string', id=None)} ``` The `answers` field is constructed using the [`Sequence`] feature because it contains two subfields, `text` and `answer_start`, which are lists of `string` and `int32`, respectively. <Tip> See the [flatten](./process#flatten) section to learn how you can extract the nested subfields as their own independent columns. </Tip> The array feature type is useful for creating arrays of various sizes. You can create arrays with two dimensions using [`Array2D`], and even arrays with five dimensions using [`Array5D`]. ```py >>> features = Features({'a': Array2D(shape=(1, 3), dtype='int32')}) ``` The array type also allows the first dimension of the array to be dynamic. This is useful for handling sequences with variable lengths such as sentences, without having to pad or truncate the input to a uniform shape. ```py >>> features = Features({'a': Array3D(shape=(None, 5, 2), dtype='int32')}) ``` ## Audio feature Audio datasets have a column with type [`Audio`], which contains three important fields: * `array`: the decoded audio data represented as a 1-dimensional array. * `path`: the path to the downloaded audio file. * `sampling_rate`: the sampling rate of the audio data. When you load an audio dataset and call the audio column, the [`Audio`] feature automatically decodes and resamples the audio file: ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train") >>> dataset[0]["audio"] {'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, 0. , 0. ], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 8000} ``` <Tip warning={true}> Index into an audio dataset using the row index first and then the `audio` column - `dataset[0]["audio"]` - to avoid decoding and resampling all the audio files in the dataset. Otherwise, this can be a slow and time-consuming process if you have a large dataset. </Tip> With `decode=False`, the [`Audio`] type simply gives you the path or the bytes of the audio file, without decoding it into an `array`, ```py >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train").cast_column("audio", Audio(decode=False)) >>> dataset[0] {'audio': {'bytes': None, 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav'}, 'english_transcription': 'I would like to set up a joint account with my partner', 'intent_class': 11, 'lang_id': 4, 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'transcription': 'I would like to set up a joint account with my partner'} ``` ## Image feature Image datasets have a column with type [`Image`], which loads `PIL.Image` objects from images stored as bytes: When you load an image dataset and call the image column, the [`Image`] feature automatically decodes the image file: ```py >>> from datasets import load_dataset, Image >>> dataset = load_dataset("beans", split="train") >>> dataset[0]["image"] <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x500 at 0x125506CF8> ``` <Tip warning={true}> Index into an image dataset using the row index first and then the `image` column - `dataset[0]["image"]` - to avoid decoding all the image files in the dataset. Otherwise, this can be a slow and time-consuming process if you have a large dataset. </Tip> With `decode=False`, the [`Image`] type simply gives you the path or the bytes of the image file, without decoding it into an `PIL.Image`, ```py >>> dataset = load_dataset("beans", split="train").cast_column("image", Image(decode=False)) >>> dataset[0]["image"] {'bytes': None, 'path': '/Users/username/.cache/huggingface/datasets/downloads/extracted/772e7c1fba622cff102b85dd74bcce46e8168634df4eaade7bedd3b8d91d3cd7/train/healthy/healthy_train.265.jpg'} ``` Depending on the dataset, you may get the path to the local downloaded image, or the content of the image as bytes if the dataset is not made of individual files. You can also define a dataset of images from numpy arrays: ```python >>> ds = Dataset.from_dict({"i": [np.zeros(shape=(16, 16, 3), dtype=np.uint8)]}, features=Features({"i": Image()})) ``` And in this case the numpy arrays are encoded into PNG (or TIFF if the pixels values precision is important). For multi-channels arrays like RGB or RGBA, only uint8 is supported. If you use a larger precision, you get a warning and the array is downcasted to uint8. For gray-scale images you can use the integer or float precision you want as long as it is compatible with `Pillow`. A warning is shown if your image integer or float precision is too high, and in this case the array is downcated: an int64 array is downcasted to int32, and a float64 array is downcasted to float32.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/cache.mdx
# Cache management When you download a dataset, the processing scripts and data are stored locally on your computer. The cache allows 🤗 Datasets to avoid re-downloading or processing the entire dataset every time you use it. This guide will show you how to: - Change the cache directory. - Control how a dataset is loaded from the cache. - Clean up cache files in the directory. - Enable or disable caching. ## Cache directory The default cache directory is `~/.cache/huggingface/datasets`. Change the cache location by setting the shell environment variable, `HF_DATASETS_CACHE` to another directory: ``` $ export HF_DATASETS_CACHE="/path/to/another/directory" ``` When you load a dataset, you also have the option to change where the data is cached. Change the `cache_dir` parameter to the path you want: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('LOADING_SCRIPT', cache_dir="PATH/TO/MY/CACHE/DIR") ``` Similarly, you can change where a metric is cached with the `cache_dir` parameter: ```py >>> from datasets import load_metric >>> metric = load_metric('glue', 'mrpc', cache_dir="MY/CACHE/DIRECTORY") ``` ## Download mode After you download a dataset, control how it is loaded by [`load_dataset`] with the `download_mode` parameter. By default, 🤗 Datasets will reuse a dataset if it exists. But if you need the original dataset without any processing functions applied, re-download the files as shown below: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('squad', download_mode='force_redownload') ``` Refer to [`DownloadMode`] for a full list of download modes. ## Cache files Clean up the cache files in the directory with [`Dataset.cleanup_cache_files`]: ```py # Returns the number of removed cache files >>> dataset.cleanup_cache_files() 2 ``` ## Enable or disable caching If you're using a cached file locally, it will automatically reload the dataset with any previous transforms you applied to the dataset. Disable this behavior by setting the argument `load_from_cache_file=False` in [`Dataset.map`]: ```py >>> updated_dataset = small_dataset.map(add_prefix, load_from_cache_file=False) ``` In the example above, 🤗 Datasets will execute the function `add_prefix` over the entire dataset again instead of loading the dataset from its previous state. Disable caching on a global scale with [`disable_caching`]: ```py >>> from datasets import disable_caching >>> disable_caching() ``` When you disable caching, 🤗 Datasets will no longer reload cached files when applying transforms to datasets. Any transform you apply on your dataset will be need to be reapplied. <Tip> If you want to reuse a dataset from scratch, try setting the `download_mode` parameter in [`load_dataset`] instead. </Tip> You can also avoid caching your metric entirely, and keep it in CPU memory instead: ```py >>> from datasets import load_metric >>> metric = load_metric('glue', 'mrpc', keep_in_memory=True) ``` <Tip warning={true}> Keeping the predictions in-memory is not possible in a distributed setting since the CPU memory spaces of the various processes are not shared. </Tip> <a id='load_dataset_enhancing_performance'></a> ## Improve performance Disabling the cache and copying the dataset in-memory will speed up dataset operations. There are two options for copying the dataset in-memory: 1. Set `datasets.config.IN_MEMORY_MAX_SIZE` to a nonzero value (in bytes) that fits in your RAM memory. 2. Set the environment variable `HF_DATASETS_IN_MEMORY_MAX_SIZE` to a nonzero value. Note that the first method takes higher precedence.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/audio_dataset.mdx
# Create an audio dataset You can share a dataset with your team or with anyone in the community by creating a dataset repository on the Hugging Face Hub: ```py from datasets import load_dataset dataset = load_dataset("<username>/my_dataset") ``` There are several methods for creating and sharing an audio dataset: * Create an audio dataset from local files in python with [`Dataset.push_to_hub`]. This is an easy way that requires only a few steps in python. * Create an audio dataset repository with the `AudioFolder` builder. This is a no-code solution for quickly creating an audio dataset with several thousand audio files. * Create an audio dataset by writing a loading script. This method is for advanced users and requires more effort and coding, but you have greater flexibility over how a dataset is defined, downloaded, and generated which can be useful for more complex or large scale audio datasets. <Tip> You can control access to your dataset by requiring users to share their contact information first. Check out the [Gated datasets](https://huggingface.co/docs/hub/datasets-gated) guide for more information about how to enable this feature on the Hub. </Tip> ## Local files You can load your own dataset using the paths to your audio files. Use the [`~Dataset.cast_column`] function to take a column of audio file paths, and cast it to the [`Audio`] feature: ```py >>> audio_dataset = Dataset.from_dict({"audio": ["path/to/audio_1", "path/to/audio_2", ..., "path/to/audio_n"]}).cast_column("audio", Audio()) >>> audio_dataset[0]["audio"] {'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, 0. , 0. ], dtype=float32), 'path': 'path/to/audio_1', 'sampling_rate': 16000} ``` Then upload the dataset to the Hugging Face Hub using [`Dataset.push_to_hub`]: ```py audio_dataset.push_to_hub("<username>/my_dataset") ``` This will create a dataset repository containing your audio dataset: ``` my_dataset/ ├── README.md └── data/ └── train-00000-of-00001.parquet ``` ## AudioFolder The `AudioFolder` is a dataset builder designed to quickly load an audio dataset with several thousand audio files without requiring you to write any code. Any additional information about your dataset - such as transcription, speaker accent, or speaker intent - is automatically loaded by `AudioFolder` as long as you include this information in a metadata file (`metadata.csv`/`metadata.jsonl`). <Tip> 💡 Take a look at the [Split pattern hierarchy](repository_structure#split-pattern-hierarchy) to learn more about how `AudioFolder` creates dataset splits based on your dataset repository structure. </Tip> Create a dataset repository on the Hugging Face Hub and upload your dataset directory following the `AudioFolder` structure: ``` my_dataset/ ├── README.md ├── metadata.csv └── data/ ``` The `data` folder can be any name you want. <Tip> It can be helpful to store your metadata as a `jsonl` file if the data columns contain a more complex format (like a list of floats) to avoid parsing errors or reading complex values as strings. </Tip> The metadata file should include a `file_name` column to link an audio file to it's metadata: ```csv file_name,transcription data/first_audio_file.mp3,znowu się duch z ciałem zrośnie w młodocianej wstaniesz wiosnie i możesz skutkiem tych leków umierać wstawać wiek wieków dalej tam były przestrogi jak siekać głowę jak nogi data/second_audio_file.mp3,już u źwierzyńca podwojów król zasiada przy nim książęta i panowie rada a gdzie wzniosły krążył ganek rycerze obok kochanek król skinął palcem zaczęto igrzysko data/third_audio_file.mp3,pewnie kędyś w obłędzie ubite minęły szlaki zaczekajmy dzień jaki poślemy szukać wszędzie dziś jutro pewnie będzie posłali wszędzie sługi czekali dzień i drugi gdy nic nie doczekali z płaczem chcą jechać dali ``` Then you can store your dataset in a directory structure like this: ``` metadata.csv data/first_audio_file.mp3 data/second_audio_file.mp3 data/third_audio_file.mp3 ``` Users can now load your dataset and the associated metadata by specifying `audiofolder` in [`load_dataset`] and the dataset directory in `data_dir`: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("audiofolder", data_dir="/path/to/data") >>> dataset["train"][0] {'audio': {'path': '/path/to/extracted/audio/first_audio_file.mp3', 'array': array([ 0.00088501, 0.0012207 , 0.00131226, ..., -0.00045776, -0.00054932, -0.00054932], dtype=float32), 'sampling_rate': 16000}, 'transcription': 'znowu się duch z ciałem zrośnie w młodocianej wstaniesz wiosnie i możesz skutkiem tych leków umierać wstawać wiek wieków dalej tam były przestrogi jak siekać głowę jak nogi' } ``` You can also use `audiofolder` to load datasets involving multiple splits. To do so, your dataset directory might have the following structure: ``` data/train/first_train_audio_file.mp3 data/train/second_train_audio_file.mp3 data/test/first_test_audio_file.mp3 data/test/second_test_audio_file.mp3 ``` <Tip warning={true}> Note that if audio files are located not right next to a metadata file, `file_name` column should be a full relative path to an audio file, not just its filename. </Tip> For audio datasets that don't have any associated metadata, `AudioFolder` automatically infers the class labels of the dataset based on the directory name. It might be useful for audio classification tasks. Your dataset directory might look like: ``` data/train/electronic/01.mp3 data/train/punk/01.mp3 data/test/electronic/09.mp3 data/test/punk/09.mp3 ``` Load the dataset with `AudioFolder`, and it will create a `label` column from the directory name (language id): ```py >>> from datasets import load_dataset >>> dataset = load_dataset("audiofolder", data_dir="/path/to/data") >>> dataset["train"][0] {'audio': {'path': '/path/to/electronic/01.mp3', 'array': array([ 3.9714024e-07, 7.3031038e-07, 7.5640685e-07, ..., -1.1963668e-01, -1.1681189e-01, -1.1244172e-01], dtype=float32), 'sampling_rate': 44100}, 'label': 0 # "electronic" } >>> dataset["train"][-1] {'audio': {'path': '/path/to/punk/01.mp3', 'array': array([0.15237972, 0.13222949, 0.10627693, ..., 0.41940814, 0.37578005, 0.33717662], dtype=float32), 'sampling_rate': 44100}, 'label': 1 # "punk" } ``` <Tip warning={true}> If all audio files are contained in a single directory or if they are not on the same level of directory structure, `label` column won't be added automatically. If you need it, set `drop_labels=False` explicitly. </Tip> <Tip> Some audio datasets, like those found in [Kaggle competitions](https://www.kaggle.com/competitions/kaggle-pog-series-s01e02/overview), have separate metadata files for each split. Provided the metadata features are the same for each split, `audiofolder` can be used to load all splits at once. If the metadata features differ across each split, you should load them with separate `load_dataset()` calls. </Tip> ## Loading script Write a dataset loading script to manually create a dataset. It defines a dataset's splits and configurations, and handles downloading and generating the dataset examples. The script should have the same name as your dataset folder or repository: ``` my_dataset/ ├── README.md ├── my_dataset.py └── data/ ``` The `data` folder can be any name you want, it doesn't have to be `data`. This folder is optional, unless you're hosting your dataset on the Hub. This directory structure allows your dataset to be loaded in one line: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("path/to/my_dataset") ``` This guide will show you how to create a dataset loading script for audio datasets, which is a bit different from <a class="underline decoration-green-400 decoration-2 font-semibold" href="./dataset_script">creating a loading script for text datasets</a>. Audio datasets are commonly stored in `tar.gz` archives which requires a particular approach to support streaming mode. While streaming is not required, we highly encourage implementing streaming support in your audio dataset because: 1. Users without a lot of disk space can use your dataset without downloading it. Learn more about streaming in the [Stream](./stream) guide! 2. Users can preview a dataset in the dataset viewer. Here is an example using TAR archives: ``` my_dataset/ ├── README.md ├── my_dataset.py └── data/ ├── train.tar.gz ├── test.tar.gz └── metadata.csv ``` In addition to learning how to create a streamable dataset, you'll also learn how to: * Create a dataset builder class. * Create dataset configurations. * Add dataset metadata. * Download and define the dataset splits. * Generate the dataset. * Upload the dataset to the Hub. The best way to learn is to open up an existing audio dataset loading script, like [Vivos](https://huggingface.co/datasets/vivos/blob/main/vivos.py), and follow along! <Tip warning=True> This guide shows how to process audio data stored in TAR archives - the most frequent case for audio datasets. Check out [minds14](https://huggingface.co/datasets/PolyAI/minds14/blob/main/minds14.py) dataset for an example of an audio script which uses ZIP archives. </Tip> <Tip> To help you get started, we created a loading script [template](https://github.com/huggingface/datasets/blob/main/templates/new_dataset_script.py) you can copy and use as a starting point! </Tip> ### Create a dataset builder class [`GeneratorBasedBuilder`] is the base class for datasets generated from a dictionary generator. Within this class, there are three methods to help create your dataset: * `_info` stores information about your dataset like its description, license, and features. * `_split_generators` downloads the dataset and defines its splits. * `_generate_examples` generates the dataset's samples containing the audio data and other features specified in `info` for each split. Start by creating your dataset class as a subclass of [`GeneratorBasedBuilder`] and add the three methods. Don't worry about filling in each of these methods yet, you'll develop those over the next few sections: ```py class VivosDataset(datasets.GeneratorBasedBuilder): """VIVOS is a free Vietnamese speech corpus consisting of 15 hours of recording speech prepared for Vietnamese Automatic Speech Recognition task.""" def _info(self): def _split_generators(self, dl_manager): def _generate_examples(self, prompts_path, path_to_clips, audio_files): ``` #### Multiple configurations In some cases, a dataset may have more than one configuration. For example, [LibriVox Indonesia](https://huggingface.co/datasets/indonesian-nlp/librivox-indonesia) dataset has several configurations corresponding to different languages. To create different configurations, use the [`BuilderConfig`] class to create a subclass of your dataset. The only required parameter is the `name` of the configuration, which must be passed to the configuration's superclass `__init__()`. Otherwise, you can specify any custom parameters you want in your configuration class. ```py class LibriVoxIndonesiaConfig(datasets.BuilderConfig): """BuilderConfig for LibriVoxIndonesia.""" def __init__(self, name, version, **kwargs): self.language = kwargs.pop("language", None) self.release_date = kwargs.pop("release_date", None) self.num_clips = kwargs.pop("num_clips", None) self.num_speakers = kwargs.pop("num_speakers", None) self.validated_hr = kwargs.pop("validated_hr", None) self.total_hr = kwargs.pop("total_hr", None) self.size_bytes = kwargs.pop("size_bytes", None) self.size_human = size_str(self.size_bytes) description = ( f"LibriVox-Indonesia speech to text dataset in {self.language} released on {self.release_date}. " f"The dataset comprises {self.validated_hr} hours of transcribed speech data" ) super(LibriVoxIndonesiaConfig, self).__init__( name=name, version=datasets.Version(version), description=description, **kwargs, ) ``` Define your configurations in the `BUILDER_CONFIGS` class variable inside [`GeneratorBasedBuilder`]. In this example, the author imports the languages from a separate `release_stats.py` [file](https://huggingface.co/datasets/indonesian-nlp/librivox-indonesia/blob/main/release_stats.py) from their repository, and then loops through each language to create a configuration: ```py class LibriVoxIndonesia(datasets.GeneratorBasedBuilder): DEFAULT_CONFIG_NAME = "all" BUILDER_CONFIGS = [ LibriVoxIndonesiaConfig( name=lang, version=STATS["version"], language=LANGUAGES[lang], release_date=STATS["date"], num_clips=lang_stats["clips"], num_speakers=lang_stats["users"], total_hr=float(lang_stats["totalHrs"]) if lang_stats["totalHrs"] else None, size_bytes=int(lang_stats["size"]) if lang_stats["size"] else None, ) for lang, lang_stats in STATS["locales"].items() ] ``` <Tip> Typically, users need to specify a configuration to load in [`load_dataset`], otherwise a `ValueError` is raised. You can avoid this by setting a default dataset configuration to load in `DEFAULT_CONFIG_NAME`. </Tip> Now if users want to load the Balinese (`bal`) configuration, they can use the configuration name: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("indonesian-nlp/librivox-indonesia", "bal", split="train") ``` ### Add dataset metadata Adding information about your dataset helps users to learn more about it. This information is stored in the [`DatasetInfo`] class which is returned by the `info` method. Users can access this information by: ```py >>> from datasets import load_dataset_builder >>> ds_builder = load_dataset_builder("vivos") >>> ds_builder.info ``` There is a lot of information you can include about your dataset, but some important ones are: 1. `description` provides a concise description of the dataset. 2. `features` specify the dataset column types. Since you're creating an audio loading script, you'll need to include the [`Audio`] feature and the `sampling_rate` of the dataset. 3. `homepage` provides a link to the dataset homepage. 4. `license` specify the permissions for using a dataset as defined by the license type. 5. `citation` is a BibTeX citation of the dataset. <Tip> You'll notice a lot of the dataset information is defined earlier in the loading script which can make it easier to read. There are also other [`~Dataset.Features`] you can input, so be sure to check out the full list and [features guide](./about_dataset_features) for more details. </Tip> ```py def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "speaker_id": datasets.Value("string"), "path": datasets.Value("string"), "audio": datasets.Audio(sampling_rate=16_000), "sentence": datasets.Value("string"), } ), supervised_keys=None, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) ``` ### Download and define the dataset splits Now that you've added some information about your dataset, the next step is to download the dataset and define the splits. 1. Use the [`~DownloadManager.download`] method to download metadata file at `_PROMPTS_URLS` and audio TAR archive at `_DATA_URL`. This method returns the path to the local file/archive. In streaming mode, it doesn't download the file(s) and just returns a URL to stream the data from. This method accepts: * a relative path to a file inside a Hub dataset repository (for example, in the `data/` folder) * a URL to a file hosted somewhere else * a (nested) list or dictionary of file names or URLs 2. After you've downloaded the dataset, use the [`SplitGenerator`] to organize the audio files and sentence prompts in each split. Name each split with a standard name like: `Split.TRAIN`, `Split.TEST`, and `SPLIT.Validation`. In the `gen_kwargs` parameter, specify the file path to the `prompts_path` and `path_to_clips`. For `audio_files`, you'll need to use [`~DownloadManager.iter_archive`] to iterate over the audio files in the TAR archive. This enables streaming for your dataset. All of these file paths are passed onto the next step where you'll actually generate the dataset. ```py def _split_generators(self, dl_manager): """Returns SplitGenerators.""" prompts_paths = dl_manager.download(_PROMPTS_URLS) archive = dl_manager.download(_DATA_URL) train_dir = "vivos/train" test_dir = "vivos/test" return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "prompts_path": prompts_paths["train"], "path_to_clips": train_dir + "/waves", "audio_files": dl_manager.iter_archive(archive), }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "prompts_path": prompts_paths["test"], "path_to_clips": test_dir + "/waves", "audio_files": dl_manager.iter_archive(archive), }, ), ] ``` <Tip warning={true}> This implementation does not extract downloaded archives. If you want to extract files after download, you need to additionally use [`~DownloadManager.extract`], see the [(Advanced) Extract TAR archives](#advanced-extract-tar-archives-locally) section. </Tip> ### Generate the dataset The last method in the [`GeneratorBasedBuilder`] class actually generates the samples in the dataset. It yields a dataset according to the structure specified in `features` from the `info` method. As you can see, `generate_examples` accepts the `prompts_path`, `path_to_clips`, and `audio_files` from the previous method as arguments. Files inside TAR archives are accessed and yielded sequentially. This means you need to have the metadata associated with the audio files in the TAR file in hand first so you can yield it with its corresponding audio file. ```py examples = {} with open(prompts_path, encoding="utf-8") as f: for row in f: data = row.strip().split(" ", 1) speaker_id = data[0].split("_")[0] audio_path = "/".join([path_to_clips, speaker_id, data[0] + ".wav"]) examples[audio_path] = { "speaker_id": speaker_id, "path": audio_path, "sentence": data[1], } ``` Finally, iterate over files in `audio_files` and yield them along with their corresponding metadata. [`~DownloadManager.iter_archive`] yields a tuple of (`path`, `f`) where `path` is a **relative** path to a file inside TAR archive and `f` is a file object itself. ```py inside_clips_dir = False id_ = 0 for path, f in audio_files: if path.startswith(path_to_clips): inside_clips_dir = True if path in examples: audio = {"path": path, "bytes": f.read()} yield id_, {**examples[path], "audio": audio} id_ += 1 elif inside_clips_dir: break ``` Put these two steps together, and the whole `_generate_examples` method looks like: ```py def _generate_examples(self, prompts_path, path_to_clips, audio_files): """Yields examples as (key, example) tuples.""" examples = {} with open(prompts_path, encoding="utf-8") as f: for row in f: data = row.strip().split(" ", 1) speaker_id = data[0].split("_")[0] audio_path = "/".join([path_to_clips, speaker_id, data[0] + ".wav"]) examples[audio_path] = { "speaker_id": speaker_id, "path": audio_path, "sentence": data[1], } inside_clips_dir = False id_ = 0 for path, f in audio_files: if path.startswith(path_to_clips): inside_clips_dir = True if path in examples: audio = {"path": path, "bytes": f.read()} yield id_, {**examples[path], "audio": audio} id_ += 1 elif inside_clips_dir: break ``` ### Upload the dataset to the Hub Once your script is ready, [create a dataset card](./dataset_card) and [upload it to the Hub](./share). Congratulations, you can now load your dataset from the Hub! 🥳 ```py >>> from datasets import load_dataset >>> load_dataset("<username>/my_dataset") ``` ### (Advanced) Extract TAR archives locally In the example above downloaded archives are not extracted and therefore examples do not contain information about where they are stored locally. To explain how to do the extraction in a way that it also supports streaming, we will briefly go through the [LibriVox Indonesia](https://huggingface.co/datasets/indonesian-nlp/librivox-indonesia/blob/main/librivox-indonesia.py) loading script. #### Download and define the dataset splits 1. Use the [`~DownloadManager.download`] method to download the audio data at `_AUDIO_URL`. 2. To extract audio TAR archive locally, use the [`~DownloadManager.extract`]. You can use this method only in non-streaming mode (when `dl_manager.is_streaming=False`). This returns a local path to the extracted archive directory: ```py local_extracted_archive = dl_manager.extract(audio_path) if not dl_manager.is_streaming else None ``` 3. Use the [`~DownloadManager.iter_archive`] method to iterate over the archive at `audio_path`, just like in the Vivos example above. [`~DownloadManager.iter_archive`] doesn't provide any information about the full paths of files from the archive, even if it has been extracted. As a result, you need to pass the `local_extracted_archive` path to the next step in `gen_kwargs`, in order to preserve information about where the archive was extracted to. This is required to construct the correct paths to the local files when you generate the examples. <Tip warning={true}> The reason you need to use a combination of [`~DownloadManager.download`] and [`~DownloadManager.iter_archive`] is because files in TAR archives can't be accessed directly by their paths. Instead, you'll need to iterate over the files within the archive! You can use [`~DownloadManager.download_and_extract`] and [`~DownloadManager.extract`] with TAR archives only in non-streaming mode, otherwise it would throw an error. </Tip> 4. Use the [`~DownloadManager.download_and_extract`] method to download the metadata file specified in `_METADATA_URL`. This method returns a path to a local file in non-streaming mode. In streaming mode, it doesn't download file locally and returns the same URL. 5. Now use the [`SplitGenerator`] to organize the audio files and metadata in each split. Name each split with a standard name like: `Split.TRAIN`, `Split.TEST`, and `SPLIT.Validation`. In the `gen_kwargs` parameter, specify the file paths to `local_extracted_archive`, `audio_files`, `metadata_path`, and `path_to_clips`. Remember, for `audio_files`, you need to use [`~DownloadManager.iter_archive`] to iterate over the audio files in the TAR archives. This enables streaming for your dataset! All of these file paths are passed onto the next step where the dataset samples are generated. ```py def _split_generators(self, dl_manager): """Returns SplitGenerators.""" dl_manager.download_config.ignore_url_params = True audio_path = dl_manager.download(_AUDIO_URL) local_extracted_archive = dl_manager.extract(audio_path) if not dl_manager.is_streaming else None path_to_clips = "librivox-indonesia" return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "local_extracted_archive": local_extracted_archive, "audio_files": dl_manager.iter_archive(audio_path), "metadata_path": dl_manager.download_and_extract(_METADATA_URL + "/metadata_train.csv.gz"), "path_to_clips": path_to_clips, }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "local_extracted_archive": local_extracted_archive, "audio_files": dl_manager.iter_archive(audio_path), "metadata_path": dl_manager.download_and_extract(_METADATA_URL + "/metadata_test.csv.gz"), "path_to_clips": path_to_clips, }, ), ] ``` #### Generate the dataset Here `_generate_examples` accepts `local_extracted_archive`, `audio_files`, `metadata_path`, and `path_to_clips` from the previous method as arguments. 1. TAR files are accessed and yielded sequentially. This means you need to have the metadata in `metadata_path` associated with the audio files in the TAR file in hand first so that you can yield it with its corresponding audio file further: ```py with open(metadata_path, "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: if self.config.name == "all" or self.config.name == row["language"]: row["path"] = os.path.join(path_to_clips, row["path"]) # if data is incomplete, fill with empty values for field in data_fields: if field not in row: row[field] = "" metadata[row["path"]] = row ``` 2. Now you can yield the files in `audio_files` archive. When you use [`~DownloadManager.iter_archive`], it yielded a tuple of (`path`, `f`) where `path` is a **relative path** to a file inside the archive, and `f` is the file object itself. To get the **full path** to the locally extracted file, join the path of the directory (`local_extracted_path`) where the archive is extracted to and the relative audio file path (`path`): ```py for path, f in audio_files: if path in metadata: result = dict(metadata[path]) # set the audio feature and the path to the extracted file path = os.path.join(local_extracted_archive, path) if local_extracted_archive else path result["audio"] = {"path": path, "bytes": f.read()} result["path"] = path yield id_, result id_ += 1 ```` Put both of these steps together, and the whole `_generate_examples` method should look like: ```py def _generate_examples( self, local_extracted_archive, audio_files, metadata_path, path_to_clips, ): """Yields examples.""" data_fields = list(self._info().features.keys()) metadata = {} with open(metadata_path, "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: if self.config.name == "all" or self.config.name == row["language"]: row["path"] = os.path.join(path_to_clips, row["path"]) # if data is incomplete, fill with empty values for field in data_fields: if field not in row: row[field] = "" metadata[row["path"]] = row id_ = 0 for path, f in audio_files: if path in metadata: result = dict(metadata[path]) # set the audio feature and the path to the extracted file path = os.path.join(local_extracted_archive, path) if local_extracted_archive else path result["audio"] = {"path": path, "bytes": f.read()} result["path"] = path yield id_, result id_ += 1 ```
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/_toctree.yml
- sections: - local: index title: 🤗 Datasets - local: quickstart title: Quickstart - local: installation title: Installation title: Get started - sections: - local: tutorial title: Overview - local: load_hub title: Load a dataset from the Hub - local: access title: Know your dataset - local: use_dataset title: Preprocess - local: metrics title: Evaluate predictions - local: create_dataset title: Create a dataset - local: upload_dataset title: Share a dataset to the Hub title: "Tutorials" - sections: - local: how_to title: Overview - sections: - local: loading title: Load - local: process title: Process - local: stream title: Stream - local: use_with_tensorflow title: Use with TensorFlow - local: use_with_pytorch title: Use with PyTorch - local: use_with_jax title: Use with JAX - local: use_with_spark title: Use with Spark - local: cache title: Cache management - local: filesystems title: Cloud storage - local: faiss_es title: Search index - local: how_to_metrics title: Metrics - local: beam title: Beam Datasets - local: troubleshoot title: Troubleshooting title: "General usage" - sections: - local: audio_load title: Load audio data - local: audio_process title: Process audio data - local: audio_dataset title: Create an audio dataset title: "Audio" - sections: - local: image_load title: Load image data - local: image_process title: Process image data - local: image_dataset title: Create an image dataset - local: depth_estimation title: Depth estimation - local: image_classification title: Image classification - local: semantic_segmentation title: Semantic segmentation - local: object_detection title: Object detection title: "Vision" - sections: - local: nlp_load title: Load text data - local: nlp_process title: Process text data title: "Text" - sections: - local: tabular_load title: Load tabular data title: "Tabular" - sections: - local: share title: Share - local: dataset_card title: Create a dataset card - local: repository_structure title: Structure your repository - local: dataset_script title: Create a dataset loading script title: "Dataset repository" title: "How-to guides" - sections: - local: about_arrow title: Datasets 🤝 Arrow - local: about_cache title: The cache - local: about_mapstyle_vs_iterable title: Dataset or IterableDataset - local: about_dataset_features title: Dataset features - local: about_dataset_load title: Build and load - local: about_map_batch title: Batch mapping - local: about_metrics title: All about metrics title: "Conceptual guides" - sections: - local: package_reference/main_classes title: Main classes - local: package_reference/builder_classes title: Builder classes - local: package_reference/loading_methods title: Loading methods - local: package_reference/table_classes title: Table Classes - local: package_reference/utilities title: Utilities - local: package_reference/task_templates title: Task templates title: "Reference"
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/upload_dataset.mdx
# Share a dataset to the Hub The [Hub](https://huggingface.co/datasets) is home to an extensive collection of community-curated and popular research datasets. We encourage you to share your dataset to the Hub to help grow the ML community and accelerate progress for everyone. All contributions are welcome; adding a dataset is just a drag and drop away! Start by [creating a Hugging Face Hub account](https://huggingface.co/join) if you don't have one yet. ## Upload with the Hub UI The Hub's web-based interface allows users without any developer experience to upload a dataset. ### Create a repository A repository hosts all your dataset files, including the revision history, making storing more than one dataset version possible. 1. Click on your profile and select **New Dataset** to create a new dataset repository. 2. Pick a name for your dataset, and choose whether it is a public or private dataset. A public dataset is visible to anyone, whereas a private dataset can only be viewed by you or members of your organization. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/create_repo.png"/> </div> ### Upload dataset 1. Once you've created a repository, navigate to the **Files and versions** tab to add a file. Select **Add file** to upload your dataset files. We support many text, audio, and image data extensions such as `.csv`, `.mp3`, and `.jpg` among many others. For text data extensions like `.csv`, `.json`, `.jsonl`, and `.txt`, we recommend compressing them before uploading to the Hub (to `.zip` or `.gz` file extension for example). Text file extensions are not tracked by Git LFS by default, and if they're greater than 10MB, they will not be committed and uploaded. Take a look at the `.gitattributes` file in your repository for a complete list of tracked file extensions. For this tutorial, you can use the following sample `.csv` files since they're small: <a href="https://huggingface.co/datasets/stevhliu/demo/raw/main/train.csv" download>train.csv</a>, <a href="https://huggingface.co/datasets/stevhliu/demo/raw/main/test.csv" download>test.csv</a>. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/upload_files.png"/> </div> 2. Drag and drop your dataset files and add a brief descriptive commit message. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/commit_files.png"/> </div> 3. After uploading your dataset files, they are stored in your dataset repository. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/files_stored.png"/> </div> ### Create a Dataset card Adding a Dataset card is super valuable for helping users find your dataset and understand how to use it responsibly. 1. Click on **Create Dataset Card** to create a Dataset card. This button creates a `README.md` file in your repository. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/dataset_card.png"/> </div> 2. At the top, you'll see the **Metadata UI** with several fields to select from like license, language, and task categories. These are the most important tags for helping users discover your dataset on the Hub. When you select an option from each field, they'll be automatically added to the top of the dataset card. You can also look at the [Dataset Card specifications](https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1), which has a complete set of (but not required) tag options like `annotations_creators`, to help you choose the appropriate tags. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/metadata_ui.png"/> </div> 3. Click on the **Import dataset card template** link at the top of the editor to automatically create a dataset card template. Filling out the template is a great way to introduce your dataset to the community and help users understand how to use it. For a detailed example of what a good Dataset card should look like, take a look at the [CNN DailyMail Dataset card](https://huggingface.co/datasets/cnn_dailymail). ### Load dataset Once your dataset is stored on the Hub, anyone can load it with the [`load_dataset`] function: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("stevhliu/demo") ``` ## Upload with Python Users who prefer to upload a dataset programmatically can use the [huggingface_hub](https://huggingface.co/docs/huggingface_hub/index) library. This library allows users to interact with the Hub from Python. 1. Begin by installing the library: ```bash pip install huggingface_hub ``` 2. To upload a dataset on the Hub in Python, you need to log in to your Hugging Face account: ```bash huggingface-cli login ``` 3. Use the [`push_to_hub()`](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.DatasetDict.push_to_hub) function to help you add, commit, and push a file to your repository: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("stevhliu/demo") # dataset = dataset.map(...) # do all your processing here >>> dataset.push_to_hub("stevhliu/processed_demo") ``` To set your dataset as private, set the `private` parameter to `True`. This parameter will only work if you are creating a repository for the first time. ```py >>> dataset.push_to_hub("stevhliu/private_processed_demo", private=True) ``` To add a new configuration (or subset) to a dataset or to add a new split (train/validation/test), please refer to the [`Dataset.push_to_hub`] documentation. ### Privacy A private dataset is only accessible by you. Similarly, if you share a dataset within your organization, then members of the organization can also access the dataset. Load a private dataset by providing your authentication token to the `token` parameter: ```py >>> from datasets import load_dataset # Load a private individual dataset >>> dataset = load_dataset("stevhliu/demo", token=True) # Load a private organization dataset >>> dataset = load_dataset("organization/dataset_name", token=True) ``` ## What's next? Congratulations, you've completed the tutorials! 🥳 From here, you can go on to: - Learn more about how to use 🤗 Datasets other functions to [process your dataset](process). - [Stream large datasets](stream) without downloading it locally. - [Define your dataset splits and configurations](repository_structure) or [loading script](dataset_script) and share your dataset with the community. If you have any questions about 🤗 Datasets, feel free to join and ask the community on our [forum](https://discuss.huggingface.co/c/datasets/10).
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/quickstart.mdx
<!--Copyright 2023 The HuggingFace Team. All rights reserved. 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. --> # Quickstart [[open-in-colab]] This quickstart is intended for developers who are ready to dive into the code and see an example of how to integrate 🤗 Datasets into their model training workflow. If you're a beginner, we recommend starting with our [tutorials](./tutorial), where you'll get a more thorough introduction. Each dataset is unique, and depending on the task, some datasets may require additional steps to prepare it for training. But you can always use 🤗 Datasets tools to load and process a dataset. The fastest and easiest way to get started is by loading an existing dataset from the [Hugging Face Hub](https://huggingface.co/datasets). There are thousands of datasets to choose from, spanning many tasks. Choose the type of dataset you want to work with, and let's get started! <div class="mt-4"> <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-3 md:gap-y-4 md:gap-x-5"> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#audio" ><div class="w-full text-center bg-gradient-to-r from-violet-300 via-sky-400 to-green-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Audio</div> <p class="text-gray-700">Resample an audio dataset and get it ready for a model to classify what type of banking issue a speaker is calling about.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#vision" ><div class="w-full text-center bg-gradient-to-r from-pink-400 via-purple-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Vision</div> <p class="text-gray-700">Apply data augmentation to an image dataset and get it ready for a model to diagnose disease in bean plants.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#nlp" ><div class="w-full text-center bg-gradient-to-r from-orange-300 via-red-400 to-violet-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">NLP</div> <p class="text-gray-700">Tokenize a dataset and get it ready for a model to determine whether a pair of sentences have the same meaning.</p> </a> </div> </div> <Tip> Check out [Chapter 5](https://huggingface.co/course/chapter5/1?fw=pt) of the Hugging Face course to learn more about other important topics such as loading remote or local datasets, tools for cleaning up a dataset, and creating your own dataset. </Tip> Start by installing 🤗 Datasets: ```bash pip install datasets ``` 🤗 Datasets also support audio and image data formats: * To work with audio datasets, install the [`Audio`] feature: ```bash pip install datasets[audio] ``` * To work with image datasets, install the [`Image`] feature: ```bash pip install datasets[vision] ``` Besides 🤗 Datasets, make sure your preferred machine learning framework is installed: <frameworkcontent> <pt> ```bash pip install torch ``` </pt> <tf> ```bash pip install tensorflow ``` </tf> </frameworkcontent> ## Audio Audio datasets are loaded just like text datasets. However, an audio dataset is preprocessed a bit differently. Instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor). An audio input may also require resampling its sampling rate to match the sampling rate of the pretrained model you're using. In this quickstart, you'll prepare the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset for a model train on and classify the banking issue a customer is having. **1**. Load the MInDS-14 dataset by providing the [`load_dataset`] function with the dataset name, dataset configuration (not all datasets will have a configuration), and a dataset split: ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train") ``` **2**. Next, load a pretrained [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) model and its corresponding feature extractor from the [🤗 Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task. ```py >>> from transformers import AutoModelForAudioClassification, AutoFeatureExtractor >>> model = AutoModelForAudioClassification.from_pretrained("facebook/wav2vec2-base") >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") ``` **3**. The [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset card indicates the sampling rate is 8kHz, but the Wav2Vec2 model was pretrained on a sampling rate of 16kHZ. You'll need to upsample the `audio` column with the [`~Dataset.cast_column`] function and [`Audio`] feature to match the model's sampling rate. ```py >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) >>> dataset[0]["audio"] {'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 16000} ``` **4**. Create a function to preprocess the audio `array` with the feature extractor, and truncate and pad the sequences into tidy rectangular tensors. The most important thing to remember is to call the audio `array` in the feature extractor since the `array` - the actual speech signal - is the model input. Once you have a preprocessing function, use the [`~Dataset.map`] function to speed up processing by applying the function to batches of examples in the dataset. ```py >>> def preprocess_function(examples): ... audio_arrays = [x["array"] for x in examples["audio"]] ... inputs = feature_extractor( ... audio_arrays, ... sampling_rate=16000, ... padding=True, ... max_length=100000, ... truncation=True, ... ) ... return inputs >>> dataset = dataset.map(preprocess_function, batched=True) ``` **5**. Use the [`~Dataset.rename_column`] function to rename the `intent_class` column to `labels`, which is the expected input name in [Wav2Vec2ForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2ForSequenceClassification): ```py >>> dataset = dataset.rename_column("intent_class", "labels") ``` **6**. Set the dataset format according to the machine learning framework you're using. <frameworkcontent> <pt> Use the [`~Dataset.set_format`] function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader): ```py >>> from torch.utils.data import DataLoader >>> dataset.set_format(type="torch", columns=["input_values", "labels"]) >>> dataloader = DataLoader(dataset, batch_size=4) ``` </pt> <tf> Use the [`~transformers.TFPreTrainedModel.prepare_tf_dataset`] method from 🤗 Transformers to prepare the dataset to be compatible with TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification. ```py >>> import tensorflow as tf >>> tf_dataset = model.prepare_tf_dataset( ... dataset, ... batch_size=4, ... shuffle=True, ... ) ``` </tf> </frameworkcontent> **7**. Start training with your machine learning framework! Check out the 🤗 Transformers [audio classification guide](https://huggingface.co/docs/transformers/tasks/audio_classification) for an end-to-end example of how to train a model on an audio dataset. ## Vision Image datasets are loaded just like text datasets. However, instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor) to preprocess the dataset. Applying data augmentation to an image is common in computer vision to make the model more robust against overfitting. You're free to use any data augmentation library you want, and then you can apply the augmentations with 🤗 Datasets. In this quickstart, you'll load the [Beans](https://huggingface.co/datasets/beans) dataset and get it ready for the model to train on and identify disease from the leaf images. **1**. Load the Beans dataset by providing the [`load_dataset`] function with the dataset name and a dataset split: ```py >>> from datasets import load_dataset, Image >>> dataset = load_dataset("beans", split="train") ``` **2**. Now you can add some data augmentations with any library ([Albumentations](https://albumentations.ai/), [imgaug](https://imgaug.readthedocs.io/en/latest/), [Kornia](https://kornia.readthedocs.io/en/latest/)) you like. Here, you'll use [torchvision](https://pytorch.org/vision/stable/transforms.html) to randomly change the color properties of an image: ```py >>> from torchvision.transforms import Compose, ColorJitter, ToTensor >>> jitter = Compose( ... [ColorJitter(brightness=0.5, hue=0.5), ToTensor()] ... ) ``` **3**. Create a function to apply your transform to the dataset and generate the model input: `pixel_values`. ```python >>> def transforms(examples): ... examples["pixel_values"] = [jitter(image.convert("RGB")) for image in examples["image"]] ... return examples ``` **4**. Use the [`~Dataset.with_transform`] function to apply the data augmentations on-the-fly: ```py >>> dataset = dataset.with_transform(transforms) ``` **5**. Set the dataset format according to the machine learning framework you're using. <frameworkcontent> <pt> Wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader). You'll also need to create a collate function to collate the samples into batches: ```py >>> from torch.utils.data import DataLoader >>> def collate_fn(examples): ... images = [] ... labels = [] ... for example in examples: ... images.append((example["pixel_values"])) ... labels.append(example["labels"]) ... ... pixel_values = torch.stack(images) ... labels = torch.tensor(labels) ... return {"pixel_values": pixel_values, "labels": labels} >>> dataloader = DataLoader(dataset, collate_fn=collate_fn, batch_size=4) ``` </pt> <tf> Use the [`~transformers.TFPreTrainedModel.prepare_tf_dataset`] method from 🤗 Transformers to prepare the dataset to be compatible with TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification. Before you start, make sure you have up-to-date versions of `albumentations` and `cv2` installed: ```bash pip install -U albumentations opencv-python ``` ```py >>> import albumentations >>> import numpy as np >>> transform = albumentations.Compose([ ... albumentations.RandomCrop(width=256, height=256), ... albumentations.HorizontalFlip(p=0.5), ... albumentations.RandomBrightnessContrast(p=0.2), ... ]) >>> def transforms(examples): ... examples["pixel_values"] = [ ... transform(image=np.array(image))["image"] for image in examples["image"] ... ] ... return examples >>> dataset.set_transform(transforms) >>> tf_dataset = model.prepare_tf_dataset( ... dataset, ... batch_size=4, ... shuffle=True, ... ) ``` </tf> </frameworkcontent> **6**. Start training with your machine learning framework! Check out the 🤗 Transformers [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification) for an end-to-end example of how to train a model on an image dataset. ## NLP Text needs to be tokenized into individual tokens by a [tokenizer](https://huggingface.co/docs/transformers/main_classes/tokenizer). For the quickstart, you'll load the [Microsoft Research Paraphrase Corpus (MRPC)](https://huggingface.co/datasets/glue/viewer/mrpc) training dataset to train a model to determine whether a pair of sentences mean the same thing. **1**. Load the MRPC dataset by providing the [`load_dataset`] function with the dataset name, dataset configuration (not all datasets will have a configuration), and dataset split: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("glue", "mrpc", split="train") ``` **2**. Next, load a pretrained [BERT](https://huggingface.co/bert-base-uncased) model and its corresponding tokenizer from the [🤗 Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task. ```py >>> from transformers import AutoModelForSequenceClassification, AutoTokenizer >>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") ===PT-TF-SPLIT=== >>> from transformers import TFAutoModelForSequenceClassification, AutoTokenizer >>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-uncased") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") ``` **3**. Create a function to tokenize the dataset, and you should also truncate and pad the text into tidy rectangular tensors. The tokenizer generates three new columns in the dataset: `input_ids`, `token_type_ids`, and an `attention_mask`. These are the model inputs. Use the [`~Dataset.map`] function to speed up processing by applying your tokenization function to batches of examples in the dataset: ```py >>> def encode(examples): ... return tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, padding="max_length") >>> dataset = dataset.map(encode, batched=True) >>> dataset[0] {'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .', 'label': 1, 'idx': 0, 'input_ids': array([ 101, 7277, 2180, 5303, 4806, 1117, 1711, 117, 2292, 1119, 1270, 107, 1103, 7737, 107, 117, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102, 11336, 6732, 3384, 1106, 1140, 1112, 1178, 107, 1103, 7737, 107, 117, 7277, 2180, 5303, 4806, 1117, 1711, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102]), 'token_type_ids': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), 'attention_mask': array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])} ``` **4**. Rename the `label` column to `labels`, which is the expected input name in [BertForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/bert#transformers.BertForSequenceClassification): ```py >>> dataset = dataset.map(lambda examples: {"labels": examples["label"]}, batched=True) ``` **5**. Set the dataset format according to the machine learning framework you're using. <frameworkcontent> <pt> Use the [`~Dataset.set_format`] function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader): ```py >>> import torch >>> dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "labels"]) >>> dataloader = torch.utils.data.DataLoader(dataset, batch_size=32) ``` </pt> <tf> Use the [`~transformers.TFPreTrainedModel.prepare_tf_dataset`] method from 🤗 Transformers to prepare the dataset to be compatible with TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification. ```py >>> import tensorflow as tf >>> tf_dataset = model.prepare_tf_dataset( ... dataset, ... batch_size=4, ... shuffle=True, ... ) ``` </tf> </frameworkcontent> **6**. Start training with your machine learning framework! Check out the 🤗 Transformers [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification) for an end-to-end example of how to train a model on a text dataset. ## What's next? This completes the 🤗 Datasets quickstart! You can load any text, audio, or image dataset with a single function and get it ready for your model to train on. For your next steps, take a look at our [How-to guides](./how_to) and learn how to do more specific things like loading different dataset formats, aligning labels, and streaming large datasets. If you're interested in learning more about 🤗 Datasets core concepts, grab a cup of coffee and read our [Conceptual Guides](./about_arrow)!
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/about_metrics.mdx
# All about metrics <Tip warning={true}> Metrics is deprecated in 🤗 Datasets. To learn more about how to use metrics, take a look at the library 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index)! In addition to metrics, you can find more tools for evaluating models and datasets. </Tip> 🤗 Datasets provides access to a wide range of NLP metrics. You can load metrics associated with benchmark datasets like GLUE or SQuAD, and complex metrics like BLEURT or BERTScore, with a single command: [`load_metric`]. Once you've loaded a metric, easily compute and evaluate a model's performance. ## ELI5: `load_metric` Loading a dataset and loading a metric share many similarities. This was an intentional design choice because we wanted to create a simple and unified experience. When you call [`load_metric`], the metric loading script is downloaded and imported from GitHub (if it hasn't already been downloaded before). It contains information about the metric such as it's citation, homepage, and description. The metric loading script will instantiate and return a [`Metric`] object. This stores the predictions and references, which you need to compute the metric values. The [`Metric`] object is stored as an Apache Arrow table. As a result, the predictions and references are stored directly on disk with memory-mapping. This enables 🤗 Datasets to do a lazy computation of the metric, and makes it easier to gather all the predictions in a distributed setting. ## Distributed evaluation Computing metrics in a distributed environment can be tricky. Metric evaluation is executed in separate Python processes, or nodes, on different subsets of a dataset. Typically, when a metric score is additive (`f(AuB) = f(A) + f(B)`), you can use distributed reduce operations to gather the scores for each subset of the dataset. But when a metric is non-additive (`f(AuB) ≠ f(A) + f(B)`), it's not that simple. For example, you can't take the sum of the [F1](https://huggingface.co/metrics/f1) scores of each data subset as your **final metric**. A common way to overcome this issue is to fallback on single process evaluation. The metrics are evaluated on a single GPU, which becomes inefficient. 🤗 Datasets solves this issue by only computing the final metric on the first node. The predictions and references are computed and provided to the metric separately for each node. These are temporarily stored in an Apache Arrow table, avoiding cluttering the GPU or CPU memory. When you are ready to [`Metric.compute`] the final metric, the first node is able to access the predictions and references stored on all the other nodes. Once it has gathered all the predictions and references, [`Metric.compute`] will perform the final metric evaluation. This solution allows 🤗 Datasets to perform distributed predictions, which is important for evaluation speed in distributed settings. At the same time, you can also use complex non-additive metrics without wasting valuable GPU or CPU memory.
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/object_detection.mdx
# Object detection Object detection models identify something in an image, and object detection datasets are used for applications such as autonomous driving and detecting natural hazards like wildfire. This guide will show you how to apply transformations to an object detection dataset following the [tutorial](https://albumentations.ai/docs/examples/example_bboxes/) from [Albumentations](https://albumentations.ai/docs/). To run these examples, make sure you have up-to-date versions of `albumentations` and `cv2` installed: ``` pip install -U albumentations opencv-python ``` In this example, you'll use the [`cppe-5`](https://huggingface.co/datasets/cppe-5) dataset for identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic. Load the dataset and take a look at an example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("cppe-5") >>> example = ds['train'][0] >>> example {'height': 663, 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=943x663 at 0x7FC3DC756250>, 'image_id': 15, 'objects': {'area': [3796, 1596, 152768, 81002], 'bbox': [[302.0, 109.0, 73.0, 52.0], [810.0, 100.0, 57.0, 28.0], [160.0, 31.0, 248.0, 616.0], [741.0, 68.0, 202.0, 401.0]], 'category': [4, 4, 0, 0], 'id': [114, 115, 116, 117]}, 'width': 943} ``` The dataset has the following fields: - `image`: PIL.Image.Image object containing the image. - `image_id`: The image ID. - `height`: The image height. - `width`: The image width. - `objects`: A dictionary containing bounding box metadata for the objects in the image: - `id`: The annotation id. - `area`: The area of the bounding box. - `bbox`: The object's bounding box (in the [coco](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) format). - `category`: The object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`. You can visualize the `bboxes` on the image using some internal torch utilities. To do that, you will need to reference the [`~datasets.ClassLabel`] feature associated with the category IDs so you can look up the string labels: ```py >>> import torch >>> from torchvision.ops import box_convert >>> from torchvision.utils import draw_bounding_boxes >>> from torchvision.transforms.functional import pil_to_tensor, to_pil_image >>> categories = ds['train'].features['objects'].feature['category'] >>> boxes_xywh = torch.tensor(example['objects']['bbox']) >>> boxes_xyxy = box_convert(boxes_xywh, 'xywh', 'xyxy') >>> labels = [categories.int2str(x) for x in example['objects']['category']] >>> to_pil_image( ... draw_bounding_boxes( ... pil_to_tensor(example['image']), ... boxes_xyxy, ... colors="red", ... labels=labels, ... ) ... ) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/visualize_detection_example.png"> </div> With `albumentations`, you can apply transforms that will affect the image while also updating the `bboxes` accordingly. In this case, the image is resized to (480, 480), flipped horizontally, and brightened. ```py >>> import albumentations >>> import numpy as np >>> transform = albumentations.Compose([ ... albumentations.Resize(480, 480), ... albumentations.HorizontalFlip(p=1.0), ... albumentations.RandomBrightnessContrast(p=1.0), ... ], bbox_params=albumentations.BboxParams(format='coco', label_fields=['category'])) >>> image = np.array(example['image']) >>> out = transform( ... image=image, ... bboxes=example['objects']['bbox'], ... category=example['objects']['category'], ... ) ``` Now when you visualize the result, the image should be flipped, but the `bboxes` should still be in the right places. ```py >>> image = torch.tensor(out['image']).permute(2, 0, 1) >>> boxes_xywh = torch.stack([torch.tensor(x) for x in out['bboxes']]) >>> boxes_xyxy = box_convert(boxes_xywh, 'xywh', 'xyxy') >>> labels = [categories.int2str(x) for x in out['category']] >>> to_pil_image( ... draw_bounding_boxes( ... image, ... boxes_xyxy, ... colors='red', ... labels=labels ... ) ... ) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/visualize_detection_example_transformed.png"> </div> Create a function to apply the transform to a batch of examples: ```py >>> def transforms(examples): ... images, bboxes, categories = [], [], [] ... for image, objects in zip(examples['image'], examples['objects']): ... image = np.array(image.convert("RGB")) ... out = transform( ... image=image, ... bboxes=objects['bbox'], ... category=objects['category'] ... ) ... images.append(torch.tensor(out['image']).permute(2, 0, 1)) ... bboxes.append(torch.tensor(out['bboxes'])) ... categories.append(out['category']) ... return {'image': images, 'bbox': bboxes, 'category': categories} ``` Use the [`~Dataset.set_transform`] function to apply the transform on-the-fly which consumes less disk space. The randomness of data augmentation may return a different image if you access the same example twice. It is especially useful when training a model for several epochs. ```py >>> ds['train'].set_transform(transforms) ``` You can verify the transform works by visualizing the 10th example: ```py >>> example = ds['train'][10] >>> to_pil_image( ... draw_bounding_boxes( ... example['image'], ... box_convert(example['bbox'], 'xywh', 'xyxy'), ... colors='red', ... labels=[categories.int2str(x) for x in example['category']] ... ) ... ) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/visualize_detection_example_transformed_2.png"> </div> <Tip> Now that you know how to process a dataset for object detection, learn [how to train an object detection model](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/YOLOS/Fine_tuning_YOLOS_for_object_detection_on_custom_dataset_(balloon).ipynb) and use it for inference. </Tip>
0
hf_public_repos/datasets/docs
hf_public_repos/datasets/docs/source/how_to_metrics.mdx
# Metrics <Tip warning={true}> Metrics is deprecated in 🤗 Datasets. To learn more about how to use metrics, take a look at the library 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index)! In addition to metrics, you can find more tools for evaluating models and datasets. </Tip> Metrics are important for evaluating a model's predictions. In the tutorial, you learned how to compute a metric over an entire evaluation set. You have also seen how to load a metric. This guide will show you how to: - Add predictions and references. - Compute metrics using different methods. - Write your own metric loading script. ## Add predictions and references When you want to add model predictions and references to a [`Metric`] instance, you have two options: - [`Metric.add`] adds a single `prediction` and `reference`. - [`Metric.add_batch`] adds a batch of `predictions` and `references`. Use [`Metric.add_batch`] by passing it your model predictions, and the references the model predictions should be evaluated against: ```py >>> import datasets >>> metric = datasets.load_metric('my_metric') >>> for model_input, gold_references in evaluation_dataset: ... model_predictions = model(model_inputs) ... metric.add_batch(predictions=model_predictions, references=gold_references) >>> final_score = metric.compute() ``` <Tip> Metrics accepts various input formats (Python lists, NumPy arrays, PyTorch tensors, etc.) and converts them to an appropriate format for storage and computation. </Tip> ## Compute scores The most straightforward way to calculate a metric is to call [`Metric.compute`]. But some metrics have additional arguments that allow you to modify the metrics behavior. Let's load the [SacreBLEU](https://huggingface.co/metrics/sacrebleu) metric, and compute it with a different smoothing method. 1. Load the SacreBLEU metric: ```py >>> import datasets >>> metric = datasets.load_metric('sacrebleu') ``` 2. Inspect the different argument methods for computing the metric: ```py >>> print(metric.inputs_description) Produces BLEU scores along with its sufficient statistics from a source against one or more references. Args: predictions: The system stream (a sequence of segments). references: A list of one or more reference streams (each a sequence of segments). smooth_method: The smoothing method to use. (Default: 'exp'). smooth_value: The smoothing value. Only valid for 'floor' and 'add-k'. (Defaults: floor: 0.1, add-k: 1). tokenize: Tokenization method to use for BLEU. If not provided, defaults to 'zh' for Chinese, 'ja-mecab' for Japanese and '13a' (mteval) otherwise. lowercase: Lowercase the data. If True, enables case-insensitivity. (Default: False). force: Insist that your tokenized input is actually detokenized. ... ``` 3. Compute the metric with the `floor` method, and a different `smooth_value`: ```py >>> score = metric.compute(smooth_method="floor", smooth_value=0.2) ``` <a id='metric_script'></a> ## Custom metric loading script Write a metric loading script to use your own custom metric (or one that is not on the Hub). Then you can load it as usual with [`load_metric`]. To help you get started, open the [SQuAD metric loading script](https://github.com/huggingface/datasets/blob/main/metrics/squad/squad.py) and follow along. <Tip> Get jump started with our metric loading script [template](https://github.com/huggingface/datasets/blob/f9713d2e23813142a02f1b0e965095f528785cff/templates/new_metric_script.py)! </Tip> ### Add metric attributes Start by adding some information about your metric in [`Metric._info`]. The most important attributes you should specify are: 1. [`MetricInfo.description`] provides a brief description about your metric. 2. [`MetricInfo.citation`] contains a BibTex citation for the metric. 3. [`MetricInfo.inputs_description`] describes the expected inputs and outputs. It may also provide an example usage of the metric. 4. [`MetricInfo.features`] defines the name and type of the predictions and references. After you've filled out all these fields in the template, it should look like the following example from the SQuAD metric script: ```py class Squad(datasets.Metric): def _info(self): return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": {"id": datasets.Value("string"), "prediction_text": datasets.Value("string")}, "references": { "id": datasets.Value("string"), "answers": datasets.features.Sequence( { "text": datasets.Value("string"), "answer_start": datasets.Value("int32"), } ), }, } ), codebase_urls=["https://rajpurkar.github.io/SQuAD-explorer/"], reference_urls=["https://rajpurkar.github.io/SQuAD-explorer/"], ) ``` ### Download metric files If your metric needs to download, or retrieve local files, you will need to use the [`Metric._download_and_prepare`] method. For this example, let's examine the [BLEURT metric loading script](https://github.com/huggingface/datasets/blob/main/metrics/bleurt/bleurt.py). 1. Provide a dictionary of URLs that point to the metric files: ```py CHECKPOINT_URLS = { "bleurt-tiny-128": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip", "bleurt-tiny-512": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip", "bleurt-base-128": "https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip", "bleurt-base-512": "https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip", "bleurt-large-128": "https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip", "bleurt-large-512": "https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip", } ``` <Tip> If the files are stored locally, provide a dictionary of path(s) instead of URLs. </Tip> 2. [`Metric._download_and_prepare`] will take the URLs and download the metric files specified: ```py def _download_and_prepare(self, dl_manager): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( "Using default BLEURT-Base checkpoint for sequence maximum length 128. " "You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512')." ) self.config_name = "bleurt-base-128" if self.config_name not in CHECKPOINT_URLS.keys(): raise KeyError( f"{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}" ) # download the model checkpoint specified by self.config_name and set up the scorer model_path = dl_manager.download_and_extract(CHECKPOINT_URLS[self.config_name]) self.scorer = score.BleurtScorer(os.path.join(model_path, self.config_name)) ``` ### Compute score [`DatasetBuilder._compute`] provides the actual instructions for how to compute a metric given the predictions and references. Now let's take a look at the [GLUE metric loading script](https://github.com/huggingface/datasets/blob/main/metrics/glue/glue.py). 1. Provide the functions for [`DatasetBuilder._compute`] to calculate your metric: ```py def simple_accuracy(preds, labels): return (preds == labels).mean().item() def acc_and_f1(preds, labels): acc = simple_accuracy(preds, labels) f1 = f1_score(y_true=labels, y_pred=preds).item() return { "accuracy": acc, "f1": f1, } def pearson_and_spearman(preds, labels): pearson_corr = pearsonr(preds, labels)[0].item() spearman_corr = spearmanr(preds, labels)[0].item() return { "pearson": pearson_corr, "spearmanr": spearman_corr, } ``` 2. Create [`DatasetBuilder._compute`] with instructions for what metric to calculate for each configuration: ```py def _compute(self, predictions, references): if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(references, predictions)} elif self.config_name == "stsb": return pearson_and_spearman(predictions, references) elif self.config_name in ["mrpc", "qqp"]: return acc_and_f1(predictions, references) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(predictions, references)} else: raise KeyError( "You should supply a configuration name selected in " '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' ) ``` ### Test Once you're finished writing your metric loading script, try to load it locally: ```py >>> from datasets import load_metric >>> metric = load_metric('PATH/TO/MY/SCRIPT.py') ```
0
hf_public_repos/datasets/docs/source
hf_public_repos/datasets/docs/source/package_reference/builder_classes.mdx
# Builder classes ## Builders 🤗 Datasets relies on two main classes during the dataset building process: [`DatasetBuilder`] and [`BuilderConfig`]. [[autodoc]] datasets.DatasetBuilder [[autodoc]] datasets.GeneratorBasedBuilder [[autodoc]] datasets.BeamBasedBuilder [[autodoc]] datasets.ArrowBasedBuilder [[autodoc]] datasets.BuilderConfig ## Download [[autodoc]] datasets.DownloadManager [[autodoc]] datasets.StreamingDownloadManager [[autodoc]] datasets.DownloadConfig [[autodoc]] datasets.DownloadMode ## Verification [[autodoc]] datasets.VerificationMode ## Splits [[autodoc]] datasets.SplitGenerator [[autodoc]] datasets.Split [[autodoc]] datasets.NamedSplit [[autodoc]] datasets.NamedSplitAll [[autodoc]] datasets.ReadInstruction ## Version [[autodoc]] datasets.utils.Version
0
hf_public_repos/datasets/docs/source
hf_public_repos/datasets/docs/source/package_reference/table_classes.mdx
# Table Classes Each `Dataset` object is backed by a PyArrow Table. A Table can be loaded from either the disk (memory mapped) or in memory. Several Table types are available, and they all inherit from [`table.Table`]. ## Table [[autodoc]] datasets.table.Table - validate - equals - to_batches - to_pydict - to_pandas - to_string - field - column - itercolumns - schema - columns - num_columns - num_rows - shape - nbytes ## InMemoryTable [[autodoc]] datasets.table.InMemoryTable - validate - equals - to_batches - to_pydict - to_pandas - to_string - field - column - itercolumns - schema - columns - num_columns - num_rows - shape - nbytes - column_names - slice - filter - flatten - combine_chunks - cast - replace_schema_metadata - add_column - append_column - remove_column - set_column - rename_columns - select - drop - from_file - from_buffer - from_pandas - from_arrays - from_pydict - from_batches ## MemoryMappedTable [[autodoc]] datasets.table.MemoryMappedTable - validate - equals - to_batches - to_pydict - to_pandas - to_string - field - column - itercolumns - schema - columns - num_columns - num_rows - shape - nbytes - column_names - slice - filter - flatten - combine_chunks - cast - replace_schema_metadata - add_column - append_column - remove_column - set_column - rename_columns - select - drop - from_file ## ConcatenationTable [[autodoc]] datasets.table.ConcatenationTable - validate - equals - to_batches - to_pydict - to_pandas - to_string - field - column - itercolumns - schema - columns - num_columns - num_rows - shape - nbytes - column_names - slice - filter - flatten - combine_chunks - cast - replace_schema_metadata - add_column - append_column - remove_column - set_column - rename_columns - select - drop - from_blocks - from_tables ## Utils [[autodoc]] datasets.table.concat_tables [[autodoc]] datasets.table.list_table_cache_files
0
hf_public_repos/datasets/docs/source
hf_public_repos/datasets/docs/source/package_reference/main_classes.mdx
# Main classes ## DatasetInfo [[autodoc]] datasets.DatasetInfo ## Dataset The base class [`Dataset`] implements a Dataset backed by an Apache Arrow table. [[autodoc]] datasets.Dataset - add_column - add_item - from_file - from_buffer - from_pandas - from_dict - from_generator - data - cache_files - num_columns - num_rows - column_names - shape - unique - flatten - cast - cast_column - remove_columns - rename_column - rename_columns - select_columns - class_encode_column - __len__ - __iter__ - iter - formatted_as - set_format - set_transform - reset_format - with_format - with_transform - __getitem__ - cleanup_cache_files - map - filter - select - sort - shuffle - train_test_split - shard - to_tf_dataset - push_to_hub - save_to_disk - load_from_disk - flatten_indices - to_csv - to_pandas - to_dict - to_json - to_parquet - to_sql - to_iterable_dataset - add_faiss_index - add_faiss_index_from_external_arrays - save_faiss_index - load_faiss_index - add_elasticsearch_index - load_elasticsearch_index - list_indexes - get_index - drop_index - search - search_batch - get_nearest_examples - get_nearest_examples_batch - info - split - builder_name - citation - config_name - dataset_size - description - download_checksums - download_size - features - homepage - license - size_in_bytes - supervised_keys - version - from_csv - from_json - from_parquet - from_text - from_sql - prepare_for_task - align_labels_with_mapping [[autodoc]] datasets.concatenate_datasets [[autodoc]] datasets.interleave_datasets [[autodoc]] datasets.distributed.split_dataset_by_node [[autodoc]] datasets.enable_caching [[autodoc]] datasets.disable_caching [[autodoc]] datasets.is_caching_enabled ## DatasetDict Dictionary with split names as keys ('train', 'test' for example), and `Dataset` objects as values. It also has dataset transform methods like map or filter, to process all the splits at once. [[autodoc]] datasets.DatasetDict - data - cache_files - num_columns - num_rows - column_names - shape - unique - cleanup_cache_files - map - filter - sort - shuffle - set_format - reset_format - formatted_as - with_format - with_transform - flatten - cast - cast_column - remove_columns - rename_column - rename_columns - select_columns - class_encode_column - push_to_hub - save_to_disk - load_from_disk - from_csv - from_json - from_parquet - from_text - prepare_for_task <a id='package_reference_features'></a> ## IterableDataset The base class [`IterableDataset`] implements an iterable Dataset backed by python generators. [[autodoc]] datasets.IterableDataset - from_generator - remove_columns - select_columns - cast_column - cast - __iter__ - iter - map - rename_column - filter - shuffle - skip - take - info - split - builder_name - citation - config_name - dataset_size - description - download_checksums - download_size - features - homepage - license - size_in_bytes - supervised_keys - version ## IterableDatasetDict Dictionary with split names as keys ('train', 'test' for example), and `IterableDataset` objects as values. [[autodoc]] datasets.IterableDatasetDict - map - filter - shuffle - with_format - cast - cast_column - remove_columns - rename_column - rename_columns - select_columns ## Features [[autodoc]] datasets.Features [[autodoc]] datasets.Sequence [[autodoc]] datasets.ClassLabel [[autodoc]] datasets.Value [[autodoc]] datasets.Translation [[autodoc]] datasets.TranslationVariableLanguages [[autodoc]] datasets.Array2D [[autodoc]] datasets.Array3D [[autodoc]] datasets.Array4D [[autodoc]] datasets.Array5D [[autodoc]] datasets.Audio [[autodoc]] datasets.Image ## MetricInfo [[autodoc]] datasets.MetricInfo ## Metric The base class `Metric` implements a Metric backed by one or several [`Dataset`]. [[autodoc]] datasets.Metric ## Filesystems [[autodoc]] datasets.filesystems.S3FileSystem [[autodoc]] datasets.filesystems.extract_path_from_uri [[autodoc]] datasets.filesystems.is_remote_filesystem ## Fingerprint [[autodoc]] datasets.fingerprint.Hasher
0
hf_public_repos/datasets/docs/source
hf_public_repos/datasets/docs/source/package_reference/loading_methods.mdx
# Loading methods Methods for listing and loading datasets and metrics: ## Datasets [[autodoc]] datasets.list_datasets [[autodoc]] datasets.load_dataset [[autodoc]] datasets.load_from_disk [[autodoc]] datasets.load_dataset_builder [[autodoc]] datasets.get_dataset_config_names [[autodoc]] datasets.get_dataset_infos [[autodoc]] datasets.get_dataset_split_names [[autodoc]] datasets.inspect_dataset ## Metrics <Tip warning={true}> Metrics is deprecated in 🤗 Datasets. To learn more about how to use metrics, take a look at the library 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index)! In addition to metrics, you can find more tools for evaluating models and datasets. </Tip> [[autodoc]] datasets.list_metrics [[autodoc]] datasets.load_metric [[autodoc]] datasets.inspect_metric ## From files Configurations used to load data files. They are used when loading local files or a dataset repository: - local files: `load_dataset("parquet", data_dir="path/to/data/dir")` - dataset repository: `load_dataset("allenai/c4")` You can pass arguments to `load_dataset` to configure data loading. For example you can specify the `sep` parameter to define the [`~datasets.packaged_modules.csv.CsvConfig`] that is used to load the data: ```python load_dataset("csv", data_dir="path/to/data/dir", sep="\t") ``` ### Text [[autodoc]] datasets.packaged_modules.text.TextConfig [[autodoc]] datasets.packaged_modules.text.Text ### CSV [[autodoc]] datasets.packaged_modules.csv.CsvConfig [[autodoc]] datasets.packaged_modules.csv.Csv ### JSON [[autodoc]] datasets.packaged_modules.json.JsonConfig [[autodoc]] datasets.packaged_modules.json.Json ### Parquet [[autodoc]] datasets.packaged_modules.parquet.ParquetConfig [[autodoc]] datasets.packaged_modules.parquet.Parquet ### Arrow [[autodoc]] datasets.packaged_modules.arrow.ArrowConfig [[autodoc]] datasets.packaged_modules.arrow.Arrow ### SQL [[autodoc]] datasets.packaged_modules.sql.SqlConfig [[autodoc]] datasets.packaged_modules.sql.Sql ### Images [[autodoc]] datasets.packaged_modules.imagefolder.ImageFolderConfig [[autodoc]] datasets.packaged_modules.imagefolder.ImageFolder ### Audio [[autodoc]] datasets.packaged_modules.audiofolder.AudioFolderConfig [[autodoc]] datasets.packaged_modules.audiofolder.AudioFolder ### WebDataset [[autodoc]] datasets.packaged_modules.webdataset.WebDataset
0
hf_public_repos/datasets/docs/source
hf_public_repos/datasets/docs/source/package_reference/utilities.mdx
# Utilities ## Configure logging 🤗 Datasets strives to be transparent and explicit about how it works, but this can be quite verbose at times. We have included a series of logging methods which allow you to easily adjust the level of verbosity of the entire library. Currently the default verbosity of the library is set to `WARNING`. To change the level of verbosity, use one of the direct setters. For instance, here is how to change the verbosity to the `INFO` level: ```py import datasets datasets.logging.set_verbosity_info() ``` You can also use the environment variable `DATASETS_VERBOSITY` to override the default verbosity, and set it to one of the following: `debug`, `info`, `warning`, `error`, `critical`: ```bash DATASETS_VERBOSITY=error ./myprogram.py ``` All the methods of this logging module are documented below. The main ones are: - [`logging.get_verbosity`] to get the current level of verbosity in the logger - [`logging.set_verbosity`] to set the verbosity to the level of your choice In order from the least to the most verbose (with their corresponding `int` values): 1. `logging.CRITICAL` or `logging.FATAL` (int value, 50): only report the most critical errors. 2. `logging.ERROR` (int value, 40): only report errors. 3. `logging.WARNING` or `logging.WARN` (int value, 30): only reports error and warnings. This the default level used by the library. 4. `logging.INFO` (int value, 20): reports error, warnings and basic information. 5. `logging.DEBUG` (int value, 10): report all information. [[autodoc]] datasets.logging.get_verbosity [[autodoc]] datasets.logging.set_verbosity [[autodoc]] datasets.logging.set_verbosity_info [[autodoc]] datasets.logging.set_verbosity_warning [[autodoc]] datasets.logging.set_verbosity_debug [[autodoc]] datasets.logging.set_verbosity_error [[autodoc]] datasets.logging.disable_propagation [[autodoc]] datasets.logging.enable_propagation ## Configure progress bars By default, `tqdm` progress bars will be displayed during dataset download and preprocessing. You can disable them globally by setting `HF_DATASETS_DISABLE_PROGRESS_BARS` environment variable. You can also enable/disable them using [`~utils.enable_progress_bars`] and [`~utils.disable_progress_bars`]. If set, the environment variable has priority on the helpers. [[autodoc]] datasets.utils.enable_progress_bars [[autodoc]] datasets.utils.disable_progress_bars [[autodoc]] datasets.utils.are_progress_bars_disabled
0
hf_public_repos/datasets/docs/source
hf_public_repos/datasets/docs/source/package_reference/task_templates.mdx
# Task templates <Tip warning={true}> The Task API is deprecated in favor of [`train-eval-index`](https://github.com/huggingface/hub-docs/blob/9ab2555e1c146122056aba6f89af404a8bc9a6f1/datasetcard.md?plain=1#L90-L106) and will be removed in the next major release. </Tip> The tasks supported by [`Dataset.prepare_for_task`] and [`DatasetDict.prepare_for_task`]. [[autodoc]] datasets.tasks.AutomaticSpeechRecognition [[autodoc]] datasets.tasks.AudioClassification [[autodoc]] datasets.tasks.ImageClassification - align_with_features [[autodoc]] datasets.tasks.LanguageModeling [[autodoc]] datasets.tasks.QuestionAnsweringExtractive [[autodoc]] datasets.tasks.Summarization [[autodoc]] datasets.tasks.TextClassification - align_with_features
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/metric_card_template.md
# Metric Card for *Current Metric* ***Metric Card Instructions:*** *Copy this file into the relevant metric folder, then fill it out and save it as README.md. Feel free to take a look at existing metric cards if you'd like examples.* ## Metric Description *Give a brief overview of this metric.* ## How to Use *Give general statement of how to use the metric* *Provide simplest possible example for using the metric* ### Inputs *List all input arguments in the format below* - **input_field** *(type): Definition of input, with explanation if necessary. State any default value(s).* ### Output Values *Explain what this metric outputs (e.g. a single score, a list of scores)* *Give an example of what the metric output looks like.* *State the range of possible values that the metric's output can take, as well as what in that range is considered good. For example: "This metric can take on any value between 0 and 100, inclusive. Higher scores are better."* #### Values from Popular Papers *Give examples, preferrably with links, to papers that have reported this metric, along with the values they have reported.* ### Examples *Give code examples of the metric being used. Try to include examples that clear up any potential ambiguity left from the metric description above. If possible, provide a range of examples that show both typical and atypical results, as well as examples where a variety of input parameters are passed.* ## Limitations and Bias *Note any known limitations or biases that the metric has, with links and references if possible.* ## Citation *Cite the source where this metric was introduced.* ## Further References *Add any useful further references.*
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/new_dataset_script.py
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. # TODO: Address all TODOs and remove all explanatory comments """TODO: Add a description here.""" import csv import json import os import datasets # TODO: Add BibTeX citation # Find for instance the citation on arxiv or on the dataset repo/website _CITATION = """\ @InProceedings{huggingface:dataset, title = {A great new dataset}, author={huggingface, Inc. }, year={2020} } """ # TODO: Add description of the dataset here # You can copy an official description _DESCRIPTION = """\ This new dataset is designed to solve this great NLP task and is crafted with a lot of care. """ # TODO: Add a link to an official homepage for the dataset here _HOMEPAGE = "" # TODO: Add the licence for the dataset here if you can find it _LICENSE = "" # TODO: Add link to the official dataset URLs here # The HuggingFace Datasets library doesn't host the datasets but only points to the original files. # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method) _URLS = { "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip", "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip", } # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case class NewDataset(datasets.GeneratorBasedBuilder): """TODO: Short description of my dataset.""" VERSION = datasets.Version("1.1.0") # This is an example of a dataset with multiple configurations. # If you don't want/need to define several sub-sets in your dataset, # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes. # If you need to make complex sub-parts in the datasets with configurable options # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig # BUILDER_CONFIG_CLASS = MyBuilderConfig # You will be able to load one or the other configurations in the following list with # data = datasets.load_dataset('my_dataset', 'first_domain') # data = datasets.load_dataset('my_dataset', 'second_domain') BUILDER_CONFIGS = [ datasets.BuilderConfig(name="first_domain", version=VERSION, description="This part of my dataset covers a first domain"), datasets.BuilderConfig(name="second_domain", version=VERSION, description="This part of my dataset covers a second domain"), ] DEFAULT_CONFIG_NAME = "first_domain" # It's not mandatory to have a default configuration. Just use one if it make sense. def _info(self): # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset if self.config.name == "first_domain": # This is the name of the configuration selected in BUILDER_CONFIGS above features = datasets.Features( { "sentence": datasets.Value("string"), "option1": datasets.Value("string"), "answer": datasets.Value("string") # These are the features of your dataset like images, labels ... } ) else: # This is an example to show how to have different features for "first_domain" and "second_domain" features = datasets.Features( { "sentence": datasets.Value("string"), "option2": datasets.Value("string"), "second_domain_answer": datasets.Value("string") # These are the features of your dataset like images, labels ... } ) return datasets.DatasetInfo( # This is the description that will appear on the datasets page. description=_DESCRIPTION, # This defines the different columns of the dataset and their types features=features, # Here we define them above because they are different between the two configurations # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and # specify them. They'll be used if as_supervised=True in builder.as_dataset. # supervised_keys=("sentence", "label"), # Homepage of the dataset for documentation homepage=_HOMEPAGE, # License for the dataset if available license=_LICENSE, # Citation for the dataset citation=_CITATION, ) def _split_generators(self, dl_manager): # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive urls = _URLS[self.config.name] data_dir = dl_manager.download_and_extract(urls) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, "train.jsonl"), "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, "dev.jsonl"), "split": "dev", }, ), datasets.SplitGenerator( name=datasets.Split.TEST, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, "test.jsonl"), "split": "test" }, ), ] # method parameters are unpacked from `gen_kwargs` as given in `_split_generators` def _generate_examples(self, filepath, split): # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset. # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example. with open(filepath, encoding="utf-8") as f: for key, row in enumerate(f): data = json.loads(row) if self.config.name == "first_domain": # Yields examples as (key, example) tuples yield key, { "sentence": data["sentence"], "option1": data["option1"], "answer": "" if split == "test" else data["answer"], } else: yield key, { "sentence": data["sentence"], "option2": data["option2"], "second_domain_answer": "" if split == "test" else data["second_domain_answer"], }
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/README.md
--- TODO: Add YAML tags here. Copy-paste the tags obtained with the online tagging app: https://huggingface.co/spaces/huggingface/datasets-tagging --- # Dataset Card for [Dataset Name] ## Table of Contents - [Table of Contents](#table-of-contents) - [Dataset Description](#dataset-description) - [Dataset Summary](#dataset-summary) - [Supported Tasks and Leaderboards](#supported-tasks-and-leaderboards) - [Languages](#languages) - [Dataset Structure](#dataset-structure) - [Data Instances](#data-instances) - [Data Fields](#data-fields) - [Data Splits](#data-splits) - [Dataset Creation](#dataset-creation) - [Curation Rationale](#curation-rationale) - [Source Data](#source-data) - [Annotations](#annotations) - [Personal and Sensitive Information](#personal-and-sensitive-information) - [Considerations for Using the Data](#considerations-for-using-the-data) - [Social Impact of Dataset](#social-impact-of-dataset) - [Discussion of Biases](#discussion-of-biases) - [Other Known Limitations](#other-known-limitations) - [Additional Information](#additional-information) - [Dataset Curators](#dataset-curators) - [Licensing Information](#licensing-information) - [Citation Information](#citation-information) - [Contributions](#contributions) ## Dataset Description - **Homepage:** - **Repository:** - **Paper:** - **Leaderboard:** - **Point of Contact:** ### Dataset Summary [More Information Needed] ### Supported Tasks and Leaderboards [More Information Needed] ### Languages [More Information Needed] ## Dataset Structure ### Data Instances [More Information Needed] ### Data Fields [More Information Needed] ### Data Splits [More Information Needed] ## Dataset Creation ### Curation Rationale [More Information Needed] ### Source Data #### Initial Data Collection and Normalization [More Information Needed] #### Who are the source language producers? [More Information Needed] ### Annotations #### Annotation process [More Information Needed] #### Who are the annotators? [More Information Needed] ### Personal and Sensitive Information [More Information Needed] ## Considerations for Using the Data ### Social Impact of Dataset [More Information Needed] ### Discussion of Biases [More Information Needed] ### Other Known Limitations [More Information Needed] ## Additional Information ### Dataset Curators [More Information Needed] ### Licensing Information [More Information Needed] ### Citation Information [More Information Needed] ### Contributions Thanks to [@github-username](https://github.com/<github-username>) for adding this dataset.
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/README_guide.md
--- YAML tags (full spec here: https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1): - copy-paste the tags obtained with the online tagging app: https://huggingface.co/spaces/huggingface/datasets-tagging --- # Dataset Card Creation Guide ## Table of Contents - [Dataset Card Creation Guide](#dataset-card-creation-guide) - [Table of Contents](#table-of-contents) - [Dataset Description](#dataset-description) - [Dataset Summary](#dataset-summary) - [Supported Tasks and Leaderboards](#supported-tasks-and-leaderboards) - [Languages](#languages) - [Dataset Structure](#dataset-structure) - [Data Instances](#data-instances) - [Data Fields](#data-fields) - [Data Splits](#data-splits) - [Dataset Creation](#dataset-creation) - [Curation Rationale](#curation-rationale) - [Source Data](#source-data) - [Initial Data Collection and Normalization](#initial-data-collection-and-normalization) - [Who are the source language producers?](#who-are-the-source-language-producers) - [Annotations](#annotations) - [Annotation process](#annotation-process) - [Who are the annotators?](#who-are-the-annotators) - [Personal and Sensitive Information](#personal-and-sensitive-information) - [Considerations for Using the Data](#considerations-for-using-the-data) - [Social Impact of Dataset](#social-impact-of-dataset) - [Discussion of Biases](#discussion-of-biases) - [Other Known Limitations](#other-known-limitations) - [Additional Information](#additional-information) - [Dataset Curators](#dataset-curators) - [Licensing Information](#licensing-information) - [Citation Information](#citation-information) - [Contributions](#contributions) ## Dataset Description - **Homepage:** [Add homepage URL here if available (unless it's a GitHub repository)]() - **Repository:** [If the dataset is hosted on github or has a github homepage, add URL here]() - **Paper:** [If the dataset was introduced by a paper or there was a paper written describing the dataset, add URL here (landing page for Arxiv paper preferred)]() - **Leaderboard:** [If the dataset supports an active leaderboard, add link here]() - **Point of Contact:** [If known, name and email of at least one person the reader can contact for questions about the dataset.]() ### Dataset Summary Briefly summarize the dataset, its intended use and the supported tasks. Give an overview of how and why the dataset was created. The summary should explicitly mention the languages present in the dataset (possibly in broad terms, e.g. *translations between several pairs of European languages*), and describe the domain, topic, or genre covered. ### Supported Tasks and Leaderboards For each of the tasks tagged for this dataset, give a brief description of the tag, metrics, and suggested models (with a link to their HuggingFace implementation if available). Give a similar description of tasks that were not covered by the structured tag set (repace the `task-category-tag` with an appropriate `other:other-task-name`). - `task-category-tag`: The dataset can be used to train a model for [TASK NAME], which consists in [TASK DESCRIPTION]. Success on this task is typically measured by achieving a *high/low* [metric name](https://huggingface.co/metrics/metric_name). The ([model name](https://huggingface.co/model_name) or [model class](https://huggingface.co/transformers/model_doc/model_class.html)) model currently achieves the following score. *[IF A LEADERBOARD IS AVAILABLE]:* This task has an active leaderboard which can be found at [leaderboard url]() and ranks models based on [metric name](https://huggingface.co/metrics/metric_name) while also reporting [other metric name](https://huggingface.co/metrics/other_metric_name). ### Languages Provide a brief overview of the languages represented in the dataset. Describe relevant details about specifics of the language such as whether it is social media text, African American English,... When relevant, please provide [BCP-47 codes](https://tools.ietf.org/html/bcp47), which consist of a [primary language subtag](https://tools.ietf.org/html/bcp47#section-2.2.1), with a [script subtag](https://tools.ietf.org/html/bcp47#section-2.2.3) and/or [region subtag](https://tools.ietf.org/html/bcp47#section-2.2.4) if available. ## Dataset Structure ### Data Instances Provide an JSON-formatted example and brief description of a typical instance in the dataset. If available, provide a link to further examples. ``` { 'example_field': ..., ... } ``` Provide any additional information that is not covered in the other sections about the data here. In particular describe any relationships between data points and if these relationships are made explicit. ### Data Fields List and describe the fields present in the dataset. Mention their data type, and whether they are used as input or output in any of the tasks the dataset currently supports. If the data has span indices, describe their attributes, such as whether they are at the character level or word level, whether they are contiguous or not, etc. If the datasets contains example IDs, state whether they have an inherent meaning, such as a mapping to other datasets or pointing to relationships between data points. - `example_field`: description of `example_field` Note that the descriptions can be initialized with the **Show Markdown Data Fields** output of the [Datasets Tagging app](https://huggingface.co/spaces/huggingface/datasets-tagging), you will then only need to refine the generated descriptions. ### Data Splits Describe and name the splits in the dataset if there are more than one. Describe any criteria for splitting the data, if used. If there are differences between the splits (e.g. if the training annotations are machine-generated and the dev and test ones are created by humans, or if different numbers of annotators contributed to each example), describe them here. Provide the sizes of each split. As appropriate, provide any descriptive statistics for the features, such as average length. For example: | | train | validation | test | |-------------------------|------:|-----------:|-----:| | Input Sentences | | | | | Average Sentence Length | | | | ## Dataset Creation ### Curation Rationale What need motivated the creation of this dataset? What are some of the reasons underlying the major choices involved in putting it together? ### Source Data This section describes the source data (e.g. news text and headlines, social media posts, translated sentences,...) #### Initial Data Collection and Normalization Describe the data collection process. Describe any criteria for data selection or filtering. List any key words or search terms used. If possible, include runtime information for the collection process. If data was collected from other pre-existing datasets, link to source here and to their [Hugging Face version](https://huggingface.co/datasets/dataset_name). If the data was modified or normalized after being collected (e.g. if the data is word-tokenized), describe the process and the tools used. #### Who are the source language producers? State whether the data was produced by humans or machine generated. Describe the people or systems who originally created the data. If available, include self-reported demographic or identity information for the source data creators, but avoid inferring this information. Instead state that this information is unknown. See [Larson 2017](https://www.aclweb.org/anthology/W17-1601.pdf) for using identity categories as a variables, particularly gender. Describe the conditions under which the data was created (for example, if the producers were crowdworkers, state what platform was used, or if the data was found, what website the data was found on). If compensation was provided, include that information here. Describe other people represented or mentioned in the data. Where possible, link to references for the information. ### Annotations If the dataset contains annotations which are not part of the initial data collection, describe them in the following paragraphs. #### Annotation process If applicable, describe the annotation process and any tools used, or state otherwise. Describe the amount of data annotated, if not all. Describe or reference annotation guidelines provided to the annotators. If available, provide interannotator statistics. Describe any annotation validation processes. #### Who are the annotators? If annotations were collected for the source data (such as class labels or syntactic parses), state whether the annotations were produced by humans or machine generated. Describe the people or systems who originally created the annotations and their selection criteria if applicable. If available, include self-reported demographic or identity information for the annotators, but avoid inferring this information. Instead state that this information is unknown. See [Larson 2017](https://www.aclweb.org/anthology/W17-1601.pdf) for using identity categories as a variables, particularly gender. Describe the conditions under which the data was annotated (for example, if the annotators were crowdworkers, state what platform was used, or if the data was found, what website the data was found on). If compensation was provided, include that information here. ### Personal and Sensitive Information State whether the dataset uses identity categories and, if so, how the information is used. Describe where this information comes from (i.e. self-reporting, collecting from profiles, inferring, etc.). See [Larson 2017](https://www.aclweb.org/anthology/W17-1601.pdf) for using identity categories as a variables, particularly gender. State whether the data is linked to individuals and whether those individuals can be identified in the dataset, either directly or indirectly (i.e., in combination with other data). State whether the dataset contains other data that might be considered sensitive (e.g., data that reveals racial or ethnic origins, sexual orientations, religious beliefs, political opinions or union memberships, or locations; financial or health data; biometric or genetic data; forms of government identification, such as social security numbers; criminal history). If efforts were made to anonymize the data, describe the anonymization process. ## Considerations for Using the Data ### Social Impact of Dataset Please discuss some of the ways you believe the use of this dataset will impact society. The statement should include both positive outlooks, such as outlining how technologies developed through its use may improve people's lives, and discuss the accompanying risks. These risks may range from making important decisions more opaque to people who are affected by the technology, to reinforcing existing harmful biases (whose specifics should be discussed in the next section), among other considerations. Also describe in this section if the proposed dataset contains a low-resource or under-represented language. If this is the case or if this task has any impact on underserved communities, please elaborate here. ### Discussion of Biases Provide descriptions of specific biases that are likely to be reflected in the data, and state whether any steps were taken to reduce their impact. For Wikipedia text, see for example [Dinan et al 2020 on biases in Wikipedia (esp. Table 1)](https://arxiv.org/abs/2005.00614), or [Blodgett et al 2020](https://www.aclweb.org/anthology/2020.acl-main.485/) for a more general discussion of the topic. If analyses have been run quantifying these biases, please add brief summaries and links to the studies here. ### Other Known Limitations If studies of the datasets have outlined other limitations of the dataset, such as annotation artifacts, please outline and cite them here. ## Additional Information ### Dataset Curators List the people involved in collecting the dataset and their affiliation(s). If funding information is known, include it here. ### Licensing Information Provide the license and link to the license webpage if available. ### Citation Information Provide the [BibTex](http://www.bibtex.org/)-formatted reference for the dataset. For example: ``` @article{article_id, author = {Author List}, title = {Dataset Paper Title}, journal = {Publication Venue}, year = {2525} } ``` If the dataset has a [DOI](https://www.doi.org/), please provide it here. ### Contributions Thanks to [@github-username](https://github.com/<github-username>) for adding this dataset.
0
hf_public_repos/datasets
hf_public_repos/datasets/notebooks/README.md
<!--- Copyright 2023 The HuggingFace Team. All rights reserved. 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. --> # 🤗 Datasets Notebooks You can find here a list of the official notebooks provided by Hugging Face. Also, we would like to list here interesting content created by the community. If you wrote some notebook(s) leveraging 🤗 Datasets and would like it to be listed here, please open a Pull Request so it can be included under the Community notebooks. ## Hugging Face's notebooks 🤗 ### Documentation notebooks You can open any page of the documentation as a notebook in Colab (there is a button directly on said pages) but they are also listed here if you need them: | Notebook | Description | | | |:----------|:-------------|:-------------|------:| | [Quickstart](https://github.com/huggingface/notebooks/blob/main/datasets_doc/en/quickstart.ipynb) | A quick presentation on integrating Datasets into a model training workflow |[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/datasets_doc/en/quickstart.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/datasets_doc/en/quickstart.ipynb)|
0
hf_public_repos/datasets
hf_public_repos/datasets/notebooks/Overview.ipynb
# install datasets !pip install datasets# Let's import the library. We typically only need at most two methods: from datasets import list_datasets, load_dataset from pprint import pprint# Currently available datasets datasets = list_datasets() print(f"🤩 Currently {len(datasets)} datasets are available on the hub:") pprint(datasets[:100] + [f"{len(datasets) - 100} more..."], compact=True)# You can access various attributes of the datasets before downloading them squad_dataset = list_datasets(with_details=True)[datasets.index('squad')] pprint(squad_dataset.__dict__) # It's a simple python dataclass# Downloading and loading a dataset dataset = load_dataset('squad', split='validation[:10%]')# Informations on the dataset (description, citation, size, splits, format...) # are provided in `dataset.info` (a simple python dataclass) and also as direct attributes in the dataset object pprint(dataset.info.__dict__)print(dataset)print(f"👉 Dataset len(dataset): {len(dataset)}") print("\n👉 First item 'dataset[0]':") pprint(dataset[0])# Or get slices with several examples: print("\n👉Slice of the two items 'dataset[10:12]':") pprint(dataset[10:12])# You can get a full column of the dataset by indexing with its name as a string: print(dataset['question'][:10])print(dataset[0]['question'] == dataset['question'][0]) print(dataset[10:20]['context'] == dataset['context'][10:20])# You can inspect the dataset column names and types print("Column names:") pprint(dataset.column_names) print("Features:") pprint(dataset.features)# Datasets also have shapes informations print("The number of rows", dataset.num_rows, "also available as len(dataset)", len(dataset)) print("The number of columns", dataset.num_columns) print("The shape (rows, columns)", dataset.shape)# Let's print the length of each `context` string in our subset of the dataset # (10% of the validation i.e. 1057 examples) dataset.map(lambda example: print(len(example['context']), end=','))from datasets import logging logging.set_verbosity_warning() dataset.map(lambda example: print(len(example['context']), end=','))# Let's keep it verbose for our tutorial though from datasets import logging logging.set_verbosity_info()# Let's add a prefix 'My cute title: ' to each of our titles def add_prefix_to_title(example): example['title'] = 'My cute title: ' + example['title'] return example prefixed_dataset = dataset.map(add_prefix_to_title) print(prefixed_dataset.unique('title')) # `.unique()` is a super fast way to print the unique elemnts in a column (see the doc for all the methods)# Since the input example dict is updated with our function output dict, # we can actually just return the updated 'title' field titled_dataset = dataset.map(lambda example: {'title': 'My cutest title: ' + example['title']}) print(titled_dataset.unique('title'))# This will remove the 'title' column while doing the update (after having send it the the mapped function so you can use it in your function!) less_columns_dataset = dataset.map(lambda example: {'new_title': 'Wouhahh: ' + example['title']}, remove_columns=['title']) print(less_columns_dataset.column_names) print(less_columns_dataset.unique('new_title'))# This will add the index in the dataset to the 'question' field with_indices_dataset = dataset.map(lambda example, idx: {'question': f'{idx}: ' + example['question']}, with_indices=True) pprint(with_indices_dataset['question'][:5])# Let's import a fast tokenizer that can work on batched inputs # (the 'Fast' tokenizers in HuggingFace) from transformers import BertTokenizerFast, logging as transformers_logging transformers_logging.set_verbosity_warning() tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased')# Now let's batch tokenize our dataset 'context' encoded_dataset = dataset.map(lambda example: tokenizer(example['context']), batched=True) print("encoded_dataset[0]") pprint(encoded_dataset[0], compact=True)# we have added additional columns pprint(encoded_dataset.column_names)# Let show a more complex processing with the full preparation of the SQuAD dataset # for training a model from Transformers def convert_to_features(batch): # Tokenize contexts and questions (as pairs of inputs) encodings = tokenizer(batch['context'], batch['question'], truncation=True) # Compute start and end tokens for labels start_positions, end_positions = [], [] for i, answer in enumerate(batch['answers']): first_char = answer['answer_start'][0] last_char = first_char + len(answer['text'][0]) - 1 start_positions.append(encodings.char_to_token(i, first_char)) end_positions.append(encodings.char_to_token(i, last_char)) encodings.update({'start_positions': start_positions, 'end_positions': end_positions}) return encodings encoded_dataset = dataset.map(convert_to_features, batched=True)# Now our dataset comprise the labels for the start and end position # as well as the offsets for converting back tokens # in span of the original string for evaluation print("column_names", encoded_dataset.column_names) print("start_positions", encoded_dataset[:5]['start_positions'])image_dataset = load_dataset("cats_vs_dogs", split="train") image_dataset[0]image_dataset[0]["image"]from datasets import load_dataset audio_dataset = load_dataset("common_voice", "fi", split="train") audio_dataset[0]audio_dataset[0]["audio"]["array"], audio_dataset[0]["audio"]["sampling_rate"]from datasets import Audio audio_dataset = audio_dataset.cast_column("audio", Audio(sampling_rate=16_000)) audio_dataset[0]["audio"]["array"], audio_dataset[0]["audio"]["sampling_rate"]columns_to_return = ['input_ids', 'token_type_ids', 'attention_mask', 'start_positions', 'end_positions'] # Uncomment whichever one is appropriate for you # encoded_dataset.set_format(type='torch', columns=columns_to_return) encoded_dataset.set_format(type='tensorflow', columns=columns_to_return) # Our dataset indexing output is now ready for being used in a pytorch dataloader pprint(encoded_dataset[1], compact=True)# Note that the columns are not removed from the dataset, just not returned when calling __getitem__ # Similarly the inner type of the dataset is not changed to torch.Tensor, the conversion and filtering is done on-the-fly when querying the dataset print(encoded_dataset.column_names)# We can remove the formatting with `.reset_format()` # or, identically, a call to `.set_format()` with no arguments encoded_dataset.reset_format() pprint(encoded_dataset[1], compact=True)# The current format can be checked with `.format`, # which is a dict of the type and formatting pprint(encoded_dataset.format)import torch from datasets import load_dataset from transformers import BertTokenizerFast # Load our training dataset and tokenizer dataset = load_dataset('squad') tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased') def get_correct_alignement(context, answer): """ Some original examples in SQuAD have indices wrong by 1 or 2 character. We test and fix this here. """ gold_text = answer['text'][0] start_idx = answer['answer_start'][0] end_idx = start_idx + len(gold_text) if context[start_idx:end_idx] == gold_text: return start_idx, end_idx # When the gold label position is good elif context[start_idx-1:end_idx-1] == gold_text: return start_idx-1, end_idx-1 # When the gold label is off by one character elif context[start_idx-2:end_idx-2] == gold_text: return start_idx-2, end_idx-2 # When the gold label is off by two character else: raise ValueError() # Tokenize our training dataset def convert_to_features(example_batch): # Tokenize contexts and questions (as pairs of inputs) encodings = tokenizer(example_batch['context'], example_batch['question'], truncation=True) # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methods. start_positions, end_positions = [], [] for i, (context, answer) in enumerate(zip(example_batch['context'], example_batch['answers'])): start_idx, end_idx = get_correct_alignement(context, answer) start_positions.append(encodings.char_to_token(i, start_idx)) end_positions.append(encodings.char_to_token(i, end_idx-1)) encodings.update({'start_positions': start_positions, 'end_positions': end_positions}) return encodings encoded_dataset = dataset.map(convert_to_features, batched=True) # Format our dataset to outputs torch.Tensor to train a pytorch model columns = ['input_ids', 'token_type_ids', 'attention_mask', 'start_positions', 'end_positions'] encoded_dataset.set_format(type='torch', columns=columns) # Instantiate a PyTorch Dataloader around our dataset # Let's do dynamic batching (pad on the fly with our own collate_fn) def collate_fn(examples): return tokenizer.pad(examples, return_tensors='pt') dataloader = torch.utils.data.DataLoader(encoded_dataset['train'], collate_fn=collate_fn, batch_size=8)columns = ['input_ids', 'token_type_ids', 'attention_mask', 'start_positions', 'end_positions'] # Let's do dynamic batching (pad on the fly with our own collate_fn) def collate_fn(examples): return tokenizer.pad(examples, return_tensors='np') # to_tf_dataset() returns a tf.data.Dataset that we can pass straight to model.fit(). encoded_tf_dataset = encoded_dataset['train'].to_tf_dataset( columns=columns, collate_fn=collate_fn, batch_size=8, shuffle=True, )# Let's load a pretrained Bert model and a simple optimizer from transformers import AutoModelForQuestionAnswering model = AutoModelForQuestionAnswering.from_pretrained('bert-base-cased', return_dict=True) optimizer = torch.optim.Adam(model.parameters(), lr=1e-5)# Now let's train our model device = 'cuda' if torch.cuda.is_available() else 'cpu' model.train().to(device) for i, batch in enumerate(dataloader): batch.to(device) outputs = model(**batch) loss = outputs.loss loss.backward() optimizer.step() model.zero_grad() print(f'Step {i} - loss: {loss:.3}') if i > 5: break# Let's load a pretrained Bert model and a simple optimizer from transformers import TFAutoModelForQuestionAnswering import tensorflow as tf model = TFAutoModelForQuestionAnswering.from_pretrained('bert-base-cased') # No loss argument! model.compile(optimizer=tf.keras.optimizers.Adam(1e-5))model.fit(encoded_tf_dataset, epochs=1, steps_per_epoch=3)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/inspect.py
# Copyright 2020 The HuggingFace 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. # Lint as: python3 """ List and inspect datasets.""" import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download.streaming_download_manager import StreamingDownloadManager from .info import DatasetInfo from .load import ( dataset_module_factory, get_dataset_builder_class, import_main_class, load_dataset_builder, metric_module_factory, ) from .utils.deprecation_utils import deprecated from .utils.file_utils import relative_to_absolute_path from .utils.logging import get_logger from .utils.version import Version logger = get_logger(__name__) class SplitsNotFoundError(ValueError): pass @deprecated("Use 'huggingface_hub.list_datasets' instead.") def list_datasets(with_community_datasets=True, with_details=False): """List all the datasets scripts available on the Hugging Face Hub. Args: with_community_datasets (`bool`, *optional*, defaults to `True`): Include the community provided datasets. with_details (`bool`, *optional*, defaults to `False`): Return the full details on the datasets instead of only the short name. Example: ```py >>> from datasets import list_datasets >>> list_datasets() ['acronym_identification', 'ade_corpus_v2', 'adversarial_qa', 'aeslc', 'afrikaans_ner_corpus', 'ag_news', ... ] ``` """ datasets = huggingface_hub.list_datasets(full=with_details) if not with_community_datasets: datasets = [dataset for dataset in datasets if "/" not in dataset.id] if not with_details: datasets = [dataset.id for dataset in datasets] return list(datasets) @deprecated( "Use 'evaluate.list_evaluation_modules' instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate" ) def list_metrics(with_community_metrics=True, with_details=False): """List all the metrics script available on the Hugging Face Hub. <Deprecated version="2.5.0"> Use `evaluate.list_evaluation_modules` instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate </Deprecated> Args: with_community_metrics (:obj:`bool`, optional, default ``True``): Include the community provided metrics. with_details (:obj:`bool`, optional, default ``False``): Return the full details on the metrics instead of only the short name. Example: ```py >>> from datasets import list_metrics >>> list_metrics() ['accuracy', 'bertscore', 'bleu', 'bleurt', 'cer', 'chrf', ... ] ``` """ metrics = huggingface_hub.list_metrics() if not with_community_metrics: metrics = [metric for metric in metrics if "/" not in metric.id] if not with_details: metrics = [metric.id for metric in metrics] return metrics @deprecated("Clone the dataset repository from the Hugging Face Hub instead.") def inspect_dataset(path: str, local_path: str, download_config: Optional[DownloadConfig] = None, **download_kwargs): """ Allow inspection/modification of a dataset script by copying on local drive at local_path. Args: path (`str`): Path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'`. - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with [`list_datasets`]) e.g. `'squad'`, `'glue'` or `'openai/webtext'`. local_path (`str`): Path to the local folder to copy the dataset script to. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. **download_kwargs (additional keyword arguments): Optional arguments for [`DownloadConfig`] which will override the attributes of `download_config` if supplied. """ if download_config is None: download_config = DownloadConfig(**download_kwargs) if os.path.isfile(path): path = str(Path(path).parent) if os.path.isdir(path): shutil.copytree(path, local_path, dirs_exist_ok=True) else: huggingface_hub.HfApi(endpoint=config.HF_ENDPOINT, token=download_config.token).snapshot_download( repo_id=path, repo_type="dataset", local_dir=local_path, force_download=download_config.force_download ) print( f"The dataset {path} can be inspected at {local_path}. " f'You can modify this loading script if it has one and use it with `datasets.load_dataset("{PurePath(local_path).as_posix()}")`.' ) @deprecated( "Use 'evaluate.inspect_evaluation_module' instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate" ) def inspect_metric(path: str, local_path: str, download_config: Optional[DownloadConfig] = None, **download_kwargs): r""" Allow inspection/modification of a metric script by copying it on local drive at local_path. <Deprecated version="2.5.0"> Use `evaluate.inspect_evaluation_module` instead, from the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> Args: path (``str``): path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. ``'./dataset/squad'`` or ``'./dataset/squad/squad.py'`` - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with ``datasets.list_datasets()``) e.g. ``'squad'``, ``'glue'`` or ``'openai/webtext'`` local_path (``str``): path to the local folder to copy the datset script to. download_config (Optional ``datasets.DownloadConfig``): specific download configuration parameters. **download_kwargs (additional keyword arguments): optional attributes for DownloadConfig() which will override the attributes in download_config if supplied. """ metric_module = metric_module_factory(path, download_config=download_config, **download_kwargs) metric_cls = import_main_class(metric_module.module_path, dataset=False) module_source_path = inspect.getsourcefile(metric_cls) module_source_dirpath = os.path.dirname(module_source_path) for dirpath, dirnames, filenames in os.walk(module_source_dirpath): dst_dirpath = os.path.join(local_path, os.path.relpath(dirpath, module_source_dirpath)) os.makedirs(dst_dirpath, exist_ok=True) # skipping hidden directories; prune the search dirnames[:] = [dirname for dirname in dirnames if not dirname.startswith((".", "__"))] for filename in filenames: shutil.copy2(os.path.join(dirpath, filename), os.path.join(dst_dirpath, filename)) shutil.copystat(dirpath, dst_dirpath) local_path = relative_to_absolute_path(local_path) print( f"The processing scripts for metric {path} can be inspected at {local_path}. " f"The main class is in {module_source_dirpath}. " f'You can modify this processing scripts and use it with `datasets.load_metric("{PurePath(local_path).as_posix()}")`.' ) def get_dataset_infos( path: str, data_files: Optional[Union[Dict, List, str]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", **config_kwargs, ): """Get the meta information about a dataset, returned as a dict mapping config name to DatasetInfoDict. Args: path (`str`): path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'` - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with [`datasets.list_datasets`]) e.g. `'squad'`, `'glue'` or``'openai/webtext'` revision (`Union[str, datasets.Version]`, *optional*): If specified, the dataset module will be loaded from the datasets repository at this version. By default: - it is set to the local version of the lib. - it will also try to load it from the main branch if it's not available at the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. data_files (`Union[Dict, List, str]`, *optional*): Defining the data_files of the dataset configuration. 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 version="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. </Deprecated> **config_kwargs (additional keyword arguments): Optional attributes for builder class which will override the attributes if supplied. Example: ```py >>> from datasets import get_dataset_infos >>> get_dataset_infos('rotten_tomatoes') {'default': DatasetInfo(description="Movie Review Dataset.\nThis is a dataset of containing 5,331 positive and 5,331 negative processed\nsentences from Rotten Tomatoes movie reviews...), ...} ``` """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token config_names = get_dataset_config_names( path=path, revision=revision, download_config=download_config, download_mode=download_mode, data_files=data_files, token=token, ) return { config_name: get_dataset_config_info( path=path, config_name=config_name, data_files=data_files, download_config=download_config, download_mode=download_mode, revision=revision, token=token, **config_kwargs, ) for config_name in config_names } def get_dataset_config_names( path: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, data_files: Optional[Union[Dict, List, str]] = None, **download_kwargs, ): """Get the list of available config names for a particular dataset. Args: path (`str`): path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'` - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with [`datasets.list_datasets`]) e.g. `'squad'`, `'glue'` or `'openai/webtext'` revision (`Union[str, datasets.Version]`, *optional*): If specified, the dataset module will be loaded from the datasets repository at this version. By default: - it is set to the local version of the lib. - it will also try to load it from the main branch if it's not available at the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. dynamic_modules_path (`str`, defaults to `~/.cache/huggingface/modules/datasets_modules`): Optional path to the directory in which the dynamic modules are saved. It must have been initialized with `init_dynamic_modules`. By default the datasets and metrics are stored inside the `datasets_modules` module. data_files (`Union[Dict, List, str]`, *optional*): Defining the data_files of the dataset configuration. **download_kwargs (additional keyword arguments): Optional attributes for [`DownloadConfig`] which will override the attributes in `download_config` if supplied, for example `token`. Example: ```py >>> from datasets import get_dataset_config_names >>> get_dataset_config_names("glue") ['cola', 'sst2', 'mrpc', 'qqp', 'stsb', 'mnli', 'mnli_mismatched', 'mnli_matched', 'qnli', 'rte', 'wnli', 'ax'] ``` """ dataset_module = dataset_module_factory( path, revision=revision, download_config=download_config, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, data_files=data_files, **download_kwargs, ) builder_cls = get_dataset_builder_class(dataset_module, dataset_name=os.path.basename(path)) return list(builder_cls.builder_configs.keys()) or [ dataset_module.builder_kwargs.get("config_name", builder_cls.DEFAULT_CONFIG_NAME or "default") ] def get_dataset_default_config_name( path: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, data_files: Optional[Union[Dict, List, str]] = None, **download_kwargs, ) -> Optional[str]: """Get the default config name for a particular dataset. Args: path (`str`): path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'` - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with [`datasets.list_datasets`]) e.g. `'squad'`, `'glue'` or `'openai/webtext'` revision (`Union[str, datasets.Version]`, *optional*): If specified, the dataset module will be loaded from the datasets repository at this version. By default: - it is set to the local version of the lib. - it will also try to load it from the main branch if it's not available at the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. dynamic_modules_path (`str`, defaults to `~/.cache/huggingface/modules/datasets_modules`): Optional path to the directory in which the dynamic modules are saved. It must have been initialized with `init_dynamic_modules`. By default the datasets and metrics are stored inside the `datasets_modules` module. data_files (`Union[Dict, List, str]`, *optional*): Defining the data_files of the dataset configuration. **download_kwargs (additional keyword arguments): Optional attributes for [`DownloadConfig`] which will override the attributes in `download_config` if supplied, for example `token`. Returns: Optional[str] Example: ```py >>> from datasets import get_dataset_default_config_name >>> get_dataset_default_config_name("openbookqa") 'main' ``` """ dataset_module = dataset_module_factory( path, revision=revision, download_config=download_config, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, data_files=data_files, **download_kwargs, ) builder_cls = get_dataset_builder_class(dataset_module, dataset_name=os.path.basename(path)) builder_configs = list(builder_cls.builder_configs.keys()) if builder_configs: default_config_name = builder_configs[0] if len(builder_configs) == 1 else None else: default_config_name = "default" return builder_cls.DEFAULT_CONFIG_NAME or default_config_name def get_dataset_config_info( path: str, config_name: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", **config_kwargs, ) -> DatasetInfo: """Get the meta information (DatasetInfo) about a dataset for a particular config Args: path (``str``): path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. ``'./dataset/squad'`` or ``'./dataset/squad/squad.py'`` - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with ``datasets.list_datasets()``) e.g. ``'squad'``, ``'glue'`` or ``'openai/webtext'`` config_name (:obj:`str`, optional): Defining the name of the dataset configuration. data_files (:obj:`str` or :obj:`Sequence` or :obj:`Mapping`, optional): Path(s) to source data file(s). download_config (:class:`~download.DownloadConfig`, optional): Specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. revision (:class:`~utils.Version` or :obj:`str`, optional): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. token (``str`` or :obj:`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 :obj:`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 version="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. </Deprecated> **config_kwargs (additional keyword arguments): optional attributes for builder class which will override the attributes if supplied. """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token builder = load_dataset_builder( path, name=config_name, data_files=data_files, download_config=download_config, download_mode=download_mode, revision=revision, token=token, **config_kwargs, ) info = builder.info if info.splits is None: download_config = download_config.copy() if download_config else DownloadConfig() if token is not None: download_config.token = token builder._check_manual_download( StreamingDownloadManager(base_path=builder.base_path, download_config=download_config) ) try: info.splits = { split_generator.name: {"name": split_generator.name, "dataset_name": path} for split_generator in builder._split_generators( StreamingDownloadManager(base_path=builder.base_path, download_config=download_config) ) } except Exception as err: raise SplitsNotFoundError("The split names could not be parsed from the dataset config.") from err return info def get_dataset_split_names( path: str, config_name: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", **config_kwargs, ): """Get the list of available splits for a particular config and dataset. Args: path (`str`): path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'` - a dataset identifier on the Hugging Face Hub (list all available datasets and ids with [`datasets.list_datasets`]) e.g. `'squad'`, `'glue'` or `'openai/webtext'` config_name (`str`, *optional*): Defining the name of the dataset configuration. data_files (`str` or `Sequence` or `Mapping`, *optional*): Path(s) to source data file(s). download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. revision ([`Version`] or `str`, *optional*): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. 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 version="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. </Deprecated> **config_kwargs (additional keyword arguments): Optional attributes for builder class which will override the attributes if supplied. Example: ```py >>> from datasets import get_dataset_split_names >>> get_dataset_split_names('rotten_tomatoes') ['train', 'validation', 'test'] ``` """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token info = get_dataset_config_info( path, config_name=config_name, data_files=data_files, download_config=download_config, download_mode=download_mode, revision=revision, token=token, **config_kwargs, ) return list(info.splits.keys())
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/streaming.py
import importlib import inspect from functools import wraps from typing import TYPE_CHECKING, Optional from .download.download_config import DownloadConfig from .download.streaming_download_manager import ( xbasename, xdirname, xet_parse, xexists, xgetsize, xglob, xgzip_open, xisdir, xisfile, xjoin, xlistdir, xnumpy_load, xopen, xpandas_read_csv, xpandas_read_excel, xPath, xpyarrow_parquet_read_table, xrelpath, xsio_loadmat, xsplit, xsplitext, xwalk, xxml_dom_minidom_parse, ) from .utils.logging import get_logger from .utils.patching import patch_submodule from .utils.py_utils import get_imports logger = get_logger(__name__) if TYPE_CHECKING: from .builder import DatasetBuilder def extend_module_for_streaming(module_path, download_config: Optional[DownloadConfig] = None): """Extend the module to support streaming. We patch some functions in the module to use `fsspec` to support data streaming: - We use `fsspec.open` to open and read remote files. We patch the module function: - `open` - We use the "::" hop separator to join paths and navigate remote compressed/archive files. We patch the module functions: - `os.path.join` - `pathlib.Path.joinpath` and `pathlib.Path.__truediv__` (called when using the "/" operator) The patched functions are replaced with custom functions defined to work with the :class:`~download.streaming_download_manager.StreamingDownloadManager`. Args: module_path: Path to the module to be extended. download_config : mainly use use_auth_token or storage_options to support different platforms and auth types. """ module = importlib.import_module(module_path) # TODO(QL): always update the module to add subsequent new authentication without removing old ones if hasattr(module, "_patched_for_streaming") and module._patched_for_streaming: if isinstance(module._patched_for_streaming, DownloadConfig): module._patched_for_streaming.token = download_config.token module._patched_for_streaming.storage_options = download_config.storage_options return def wrap_auth(function): @wraps(function) def wrapper(*args, **kwargs): return function(*args, download_config=download_config, **kwargs) wrapper._decorator_name_ = "wrap_auth" return wrapper # open files in a streaming fashion patch_submodule(module, "open", wrap_auth(xopen)).start() patch_submodule(module, "os.listdir", wrap_auth(xlistdir)).start() patch_submodule(module, "os.walk", wrap_auth(xwalk)).start() patch_submodule(module, "glob.glob", wrap_auth(xglob)).start() # allow to navigate in remote zip files patch_submodule(module, "os.path.join", xjoin).start() patch_submodule(module, "os.path.dirname", xdirname).start() patch_submodule(module, "os.path.basename", xbasename).start() patch_submodule(module, "os.path.relpath", xrelpath).start() patch_submodule(module, "os.path.split", xsplit).start() patch_submodule(module, "os.path.splitext", xsplitext).start() # allow checks on paths patch_submodule(module, "os.path.exists", wrap_auth(xexists)).start() patch_submodule(module, "os.path.isdir", wrap_auth(xisdir)).start() patch_submodule(module, "os.path.isfile", wrap_auth(xisfile)).start() patch_submodule(module, "os.path.getsize", wrap_auth(xgetsize)).start() patch_submodule(module, "pathlib.Path", xPath).start() # file readers patch_submodule(module, "gzip.open", wrap_auth(xgzip_open)).start() patch_submodule(module, "numpy.load", wrap_auth(xnumpy_load)).start() patch_submodule(module, "pandas.read_csv", wrap_auth(xpandas_read_csv), attrs=["__version__"]).start() patch_submodule(module, "pandas.read_excel", wrap_auth(xpandas_read_excel), attrs=["__version__"]).start() patch_submodule(module, "scipy.io.loadmat", wrap_auth(xsio_loadmat), attrs=["__version__"]).start() patch_submodule(module, "xml.etree.ElementTree.parse", wrap_auth(xet_parse)).start() patch_submodule(module, "xml.dom.minidom.parse", wrap_auth(xxml_dom_minidom_parse)).start() # pyarrow: do not patch pyarrow attribute in packaged modules if not module.__name__.startswith("datasets.packaged_modules."): patch_submodule(module, "pyarrow.parquet.read_table", wrap_auth(xpyarrow_parquet_read_table)).start() module._patched_for_streaming = download_config def extend_dataset_builder_for_streaming(builder: "DatasetBuilder"): """Extend the dataset builder module and the modules imported by it to support streaming. Args: builder (:class:`DatasetBuilder`): Dataset builder instance. """ # this extends the open and os.path.join functions for data streaming download_config = DownloadConfig(storage_options=builder.storage_options, token=builder.token) extend_module_for_streaming(builder.__module__, download_config=download_config) # if needed, we also have to extend additional internal imports (like wmt14 -> wmt_utils) if not builder.__module__.startswith("datasets."): # check that it's not a packaged builder like csv for imports in get_imports(inspect.getfile(builder.__class__)): if imports[0] == "internal": internal_import_name = imports[1] internal_module_name = ".".join(builder.__module__.split(".")[:-1] + [internal_import_name]) extend_module_for_streaming(internal_module_name, download_config=download_config) # builders can inherit from other builders that might use streaming functionality # (for example, ImageFolder and AudioFolder inherit from FolderBuilder which implements examples generation) # but these parents builders are not patched automatically as they are not instantiated, so we patch them here from .builder import DatasetBuilder parent_builder_modules = [ cls.__module__ for cls in type(builder).__mro__[1:] # make sure it's not the same module we've already patched if issubclass(cls, DatasetBuilder) and cls.__module__ != DatasetBuilder.__module__ ] # check it's not a standard builder from datasets.builder for module in parent_builder_modules: extend_module_for_streaming(module, download_config=download_config)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/table.py
import copy import os import warnings from functools import partial from itertools import groupby from typing import TYPE_CHECKING, Callable, Iterator, List, Optional, Tuple, TypeVar, Union import numpy as np import pyarrow as pa import pyarrow.compute as pc from . import config from .utils.logging import get_logger if TYPE_CHECKING: from .features.features import Features, FeatureType logger = get_logger(__name__) def inject_arrow_table_documentation(arrow_table_method): def wrapper(fn): fn.__doc__ = arrow_table_method.__doc__ + (fn.__doc__ if fn.__doc__ is not None else "") fn.__doc__ = fn.__doc__.replace("pyarrow.Table", "Table") if hasattr(arrow_table_method, "__annotations__"): fn.__annotations__ = arrow_table_method.__annotations__ return fn return wrapper def _in_memory_arrow_table_from_file(filename: str) -> pa.Table: in_memory_stream = pa.input_stream(filename) opened_stream = pa.ipc.open_stream(in_memory_stream) pa_table = opened_stream.read_all() return pa_table def _in_memory_arrow_table_from_buffer(buffer: pa.Buffer) -> pa.Table: stream = pa.BufferReader(buffer) opened_stream = pa.ipc.open_stream(stream) table = opened_stream.read_all() return table def _memory_mapped_record_batch_reader_from_file(filename: str) -> pa.RecordBatchStreamReader: memory_mapped_stream = pa.memory_map(filename) return pa.ipc.open_stream(memory_mapped_stream) def read_schema_from_file(filename: str) -> pa.Schema: """ Infer arrow table schema from file without loading whole file into memory. Usefull especially while having very big files. """ with pa.memory_map(filename) as memory_mapped_stream: schema = pa.ipc.open_stream(memory_mapped_stream).schema return schema def _memory_mapped_arrow_table_from_file(filename: str) -> pa.Table: opened_stream = _memory_mapped_record_batch_reader_from_file(filename) pa_table = opened_stream.read_all() return pa_table def _deepcopy(x, memo: dict): """deepcopy a regular class instance""" cls = x.__class__ result = cls.__new__(cls) memo[id(x)] = result for k, v in x.__dict__.items(): setattr(result, k, copy.deepcopy(v, memo)) return result def _interpolation_search(arr: List[int], x: int) -> int: """ Return the position i of a sorted array so that arr[i] <= x < arr[i+1] Args: arr (`List[int]`): non-empty sorted list of integers x (`int`): query Returns: `int`: the position i so that arr[i] <= x < arr[i+1] Raises: `IndexError`: if the array is empty or if the query is outside the array values """ i, j = 0, len(arr) - 1 while i < j and arr[i] <= x < arr[j]: k = i + ((j - i) * (x - arr[i]) // (arr[j] - arr[i])) if arr[k] <= x < arr[k + 1]: return k elif arr[k] < x: i, j = k + 1, j else: i, j = i, k raise IndexError(f"Invalid query '{x}' for size {arr[-1] if len(arr) else 'none'}.") class IndexedTableMixin: def __init__(self, table: pa.Table): self._schema: pa.Schema = table.schema self._batches: List[pa.RecordBatch] = [ recordbatch for recordbatch in table.to_batches() if len(recordbatch) > 0 ] self._offsets: np.ndarray = np.cumsum([0] + [len(b) for b in self._batches], dtype=np.int64) def fast_gather(self, indices: Union[List[int], np.ndarray]) -> pa.Table: """ Create a pa.Table by gathering the records at the records at the specified indices. Should be faster than pa.concat_tables(table.fast_slice(int(i) % table.num_rows, 1) for i in indices) since NumPy can compute the binary searches in parallel, highly optimized C """ if not len(indices): raise ValueError("Indices must be non-empty") batch_indices = np.searchsorted(self._offsets, indices, side="right") - 1 return pa.Table.from_batches( [ self._batches[batch_idx].slice(i - self._offsets[batch_idx], 1) for batch_idx, i in zip(batch_indices, indices) ], schema=self._schema, ) def fast_slice(self, offset=0, length=None) -> pa.Table: """ Slice the Table using interpolation search. The behavior is the same as `pyarrow.Table.slice` but it's significantly faster. Interpolation search is used to find the start and end indexes of the batches we want to keep. The batches to keep are then concatenated to form the sliced Table. """ if offset < 0: raise IndexError("Offset must be non-negative") elif offset >= self._offsets[-1] or (length is not None and length <= 0): return pa.Table.from_batches([], schema=self._schema) i = _interpolation_search(self._offsets, offset) if length is None or length + offset >= self._offsets[-1]: batches = self._batches[i:] batches[0] = batches[0].slice(offset - self._offsets[i]) else: j = _interpolation_search(self._offsets, offset + length - 1) batches = self._batches[i : j + 1] batches[-1] = batches[-1].slice(0, offset + length - self._offsets[j]) batches[0] = batches[0].slice(offset - self._offsets[i]) return pa.Table.from_batches(batches, schema=self._schema) class Table(IndexedTableMixin): """ Wraps a pyarrow Table by using composition. This is the base class for `InMemoryTable`, `MemoryMappedTable` and `ConcatenationTable`. It implements all the basic attributes/methods of the pyarrow Table class except the Table transforms: `slice, filter, flatten, combine_chunks, cast, add_column, append_column, remove_column, set_column, rename_columns` and `drop`. The implementation of these methods differs for the subclasses. """ def __init__(self, table: pa.Table): super().__init__(table) self.table = table def __deepcopy__(self, memo: dict): # arrow tables are immutable, so there's no need to copy self.table # moreover calling deepcopy on a pyarrow table seems to make pa.total_allocated_bytes() decrease for some reason # by adding it to the memo, self.table won't be copied memo[id(self.table)] = self.table # same for the recordbatches used by the index memo[id(self._batches)] = list(self._batches) return _deepcopy(self, memo) def validate(self, *args, **kwargs): """ Perform validation checks. An exception is raised if validation fails. By default only cheap validation checks are run. Pass `full=True` for thorough validation checks (potentially `O(n)`). Args: full (`bool`, defaults to `False`): If `True`, run expensive checks, otherwise cheap checks only. Raises: `pa.lib.ArrowInvalid`: if validation fails """ return self.table.validate(*args, **kwargs) def equals(self, *args, **kwargs): """ Check if contents of two tables are equal. Args: other ([`~datasets.table.Table`]): Table to compare against. check_metadata `bool`, defaults to `False`): Whether schema metadata equality should be checked as well. Returns: `bool` """ args = tuple(arg.table if isinstance(arg, Table) else arg for arg in args) kwargs = {k: v.table if isinstance(v, Table) else v for k, v in kwargs} return self.table.equals(*args, **kwargs) def to_batches(self, *args, **kwargs): """ Convert Table to list of (contiguous) `RecordBatch` objects. Args: max_chunksize (`int`, defaults to `None`): Maximum size for `RecordBatch` chunks. Individual chunks may be smaller depending on the chunk layout of individual columns. Returns: `List[pyarrow.RecordBatch]` """ return self.table.to_batches(*args, **kwargs) def to_pydict(self, *args, **kwargs): """ Convert the Table to a `dict` or `OrderedDict`. Returns: `dict` """ return self.table.to_pydict(*args, **kwargs) def to_pylist(self, *args, **kwargs): """ Convert the Table to a list Returns: `list` """ try: return self.table.to_pylist(*args, **kwargs) except AttributeError: # pyarrow <7 does not have to_pylist, so we use to_pydict pydict = self.table.to_pydict(*args, **kwargs) return [{k: pydict[k][i] for k in pydict} for i in range(len(self.table))] def to_pandas(self, *args, **kwargs): """ Convert to a pandas-compatible NumPy array or DataFrame, as appropriate. Args: memory_pool (`MemoryPool`, defaults to `None`): Arrow MemoryPool to use for allocations. Uses the default memory pool is not passed. strings_to_categorical (`bool`, defaults to `False`): Encode string (UTF8) and binary types to `pandas.Categorical`. categories (`list`, defaults to `empty`): List of fields that should be returned as `pandas.Categorical`. Only applies to table-like data structures. zero_copy_only (`bool`, defaults to `False`): Raise an `ArrowException` if this function call would require copying the underlying data. integer_object_nulls (`bool`, defaults to `False`): Cast integers with nulls to objects. date_as_object (`bool`, defaults to `True`): Cast dates to objects. If `False`, convert to `datetime64[ns]` dtype. timestamp_as_object (`bool`, defaults to `False`): Cast non-nanosecond timestamps (`np.datetime64`) to objects. This is useful if you have timestamps that don't fit in the normal date range of nanosecond timestamps (1678 CE-2262 CE). If `False`, all timestamps are converted to `datetime64[ns]` dtype. use_threads (`bool`, defaults to `True`): Whether to parallelize the conversion using multiple threads. deduplicate_objects (`bool`, defaults to `False`): Do not create multiple copies Python objects when created, to save on memory use. Conversion will be slower. ignore_metadata (`bool`, defaults to `False`): If `True`, do not use the 'pandas' metadata to reconstruct the DataFrame index, if present. safe (`bool`, defaults to `True`): For certain data types, a cast is needed in order to store the data in a pandas DataFrame or Series (e.g. timestamps are always stored as nanoseconds in pandas). This option controls whether it is a safe cast or not. split_blocks (`bool`, defaults to `False`): If `True`, generate one internal "block" for each column when creating a pandas.DataFrame from a `RecordBatch` or `Table`. While this can temporarily reduce memory note that various pandas operations can trigger "consolidation" which may balloon memory use. self_destruct (`bool`, defaults to `False`): EXPERIMENTAL: If `True`, attempt to deallocate the originating Arrow memory while converting the Arrow object to pandas. If you use the object after calling `to_pandas` with this option it will crash your program. types_mapper (`function`, defaults to `None`): A function mapping a pyarrow DataType to a pandas `ExtensionDtype`. This can be used to override the default pandas type for conversion of built-in pyarrow types or in absence of `pandas_metadata` in the Table schema. The function receives a pyarrow DataType and is expected to return a pandas `ExtensionDtype` or `None` if the default conversion should be used for that type. If you have a dictionary mapping, you can pass `dict.get` as function. Returns: `pandas.Series` or `pandas.DataFrame`: `pandas.Series` or `pandas.DataFrame` depending on type of object """ return self.table.to_pandas(*args, **kwargs) def to_string(self, *args, **kwargs): return self.table.to_string(*args, **kwargs) def to_reader(self, max_chunksize: Optional[int] = None): """ Convert the Table to a RecordBatchReader. Note that this method is zero-copy, it merely exposes the same data under a different API. Args: max_chunksize (`int`, defaults to `None`) Maximum size for RecordBatch chunks. Individual chunks may be smaller depending on the chunk layout of individual columns. Returns: `pyarrow.RecordBatchReader` """ return self.table.to_reader(max_chunksize=max_chunksize) def field(self, *args, **kwargs): """ Select a schema field by its column name or numeric index. Args: i (`Union[int, str]`): The index or name of the field to retrieve. Returns: `pyarrow.Field` """ return self.table.field(*args, **kwargs) def column(self, *args, **kwargs): """ Select a column by its column name, or numeric index. Args: i (`Union[int, str]`): The index or name of the column to retrieve. Returns: `pyarrow.ChunkedArray` """ return self.table.column(*args, **kwargs) def itercolumns(self, *args, **kwargs): """ Iterator over all columns in their numerical order. Yields: `pyarrow.ChunkedArray` """ return self.table.itercolumns(*args, **kwargs) @property def schema(self): """ Schema of the table and its columns. Returns: `pyarrow.Schema` """ return self.table.schema @property def columns(self): """ List of all columns in numerical order. Returns: `List[pa.ChunkedArray]` """ return self.table.columns @property def num_columns(self): """ Number of columns in this table. Returns: int """ return self.table.num_columns @property def num_rows(self): """ Number of rows in this table. Due to the definition of a table, all columns have the same number of rows. Returns: int """ return self.table.num_rows @property def shape(self): """ Dimensions of the table: (#rows, #columns). Returns: `(int, int)`: Number of rows and number of columns. """ return self.table.shape @property def nbytes(self): """ Total number of bytes consumed by the elements of the table. """ return self.table.nbytes @property def column_names(self): """ Names of the table's columns. """ return self.table.column_names def __eq__(self, other): return self.equals(other) def __getitem__(self, i): return self.table[i] def __len__(self): return len(self.table) def __repr__(self): return self.table.__repr__().replace("pyarrow.Table", self.__class__.__name__) def __str__(self): return self.table.__str__().replace("pyarrow.Table", self.__class__.__name__) def slice(self, *args, **kwargs): """ Compute zero-copy slice of this Table. Args: offset (`int`, defaults to `0`): Offset from start of table to slice. length (`int`, defaults to `None`): Length of slice (default is until end of table starting from offset). Returns: `datasets.table.Table` """ raise NotImplementedError() def filter(self, *args, **kwargs): """ Select records from a Table. See `pyarrow.compute.filter` for full usage. """ raise NotImplementedError() def flatten(self, *args, **kwargs): """ Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ raise NotImplementedError() def combine_chunks(self, *args, **kwargs): """ Make a new table by combining the chunks this table has. All the underlying chunks in the `ChunkedArray` of each column are concatenated into zero or one chunk. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ raise NotImplementedError() def cast(self, *args, **kwargs): """ Cast table values to another schema. Args: target_schema (`Schema`): Schema to cast to, the names and order of fields must match. safe (`bool`, defaults to `True`): Check for overflows or other unsafe conversions. Returns: `datasets.table.Table` """ raise NotImplementedError() def replace_schema_metadata(self, *args, **kwargs): """ EXPERIMENTAL: Create shallow copy of table by replacing schema key-value metadata with the indicated new metadata (which may be None, which deletes any existing metadata Args: metadata (`dict`, defaults to `None`): Returns: `datasets.table.Table`: shallow_copy """ raise NotImplementedError() def add_column(self, *args, **kwargs): """ Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ raise NotImplementedError() def append_column(self, *args, **kwargs): """ Append column at end of columns. Args: field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ raise NotImplementedError() def remove_column(self, *args, **kwargs): """ Create new Table with the indicated column removed. Args: i (`int`): Index of column to remove. Returns: `datasets.table.Table`: New table without the column. """ raise NotImplementedError() def set_column(self, *args, **kwargs): """ Replace column in Table at position. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column set. """ raise NotImplementedError() def rename_columns(self, *args, **kwargs): """ Create new table with columns renamed to provided names. """ raise NotImplementedError() def drop(self, *args, **kwargs): """ Drop one or more columns and return a new table. Args: columns (`List[str]`): List of field names referencing existing columns. Raises: `KeyError` : if any of the passed columns name are not existing. Returns: `datasets.table.Table`: New table without the columns. """ raise NotImplementedError() def select(self, *args, **kwargs): """ Select columns of the table. Returns a new table with the specified columns, and metadata preserved. Args: columns (:obj:`Union[List[str], List[int]]`): The column names or integer indices to select. Returns: `datasets.table.Table`: table with only a subset of the columns """ raise NotImplementedError() class TableBlock(Table): """ `TableBlock` is the allowed class inside a `ConcanetationTable`. Only `MemoryMappedTable` and `InMemoryTable` are `TableBlock`. This is because we don't want a `ConcanetationTable` made out of other `ConcanetationTables`. """ pass class InMemoryTable(TableBlock): """ The table is said in-memory when it is loaded into the user's RAM. Pickling it does copy all the data using memory. Its implementation is simple and uses the underlying pyarrow Table methods directly. This is different from the `MemoryMapped` table, for which pickling doesn't copy all the data in memory. For a `MemoryMapped`, unpickling instead reloads the table from the disk. `InMemoryTable` must be used when data fit in memory, while `MemoryMapped` are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. """ @classmethod def from_file(cls, filename: str): table = _in_memory_arrow_table_from_file(filename) return cls(table) @classmethod def from_buffer(cls, buffer: pa.Buffer): table = _in_memory_arrow_table_from_buffer(buffer) return cls(table) @classmethod def from_pandas(cls, *args, **kwargs): """ Convert pandas.DataFrame to an Arrow Table. The column types in the resulting Arrow Table are inferred from the dtypes of the pandas.Series in the DataFrame. In the case of non-object Series, the NumPy dtype is translated to its Arrow equivalent. In the case of `object`, we need to guess the datatype by looking at the Python objects in this Series. Be aware that Series of the `object` dtype don't carry enough information to always lead to a meaningful Arrow type. In the case that we cannot infer a type, e.g. because the DataFrame is of length 0 or the Series only contains `None/nan` objects, the type is set to null. This behavior can be avoided by constructing an explicit schema and passing it to this function. Args: df (`pandas.DataFrame`): schema (`pyarrow.Schema`, *optional*): The expected schema of the Arrow Table. This can be used to indicate the type of columns if we cannot infer it automatically. If passed, the output will have exactly this schema. Columns specified in the schema that are not found in the DataFrame columns or its index will raise an error. Additional columns or index levels in the DataFrame which are not specified in the schema will be ignored. preserve_index (`bool`, *optional*): Whether to store the index as an additional column in the resulting `Table`. The default of None will store the index as a column, except for RangeIndex which is stored as metadata only. Use `preserve_index=True` to force it to be stored as a column. nthreads (`int`, defaults to `None` (may use up to system CPU count threads)) If greater than 1, convert columns to Arrow in parallel using indicated number of threads. columns (`List[str]`, *optional*): List of column to be converted. If `None`, use all columns. safe (`bool`, defaults to `True`): Check for overflows or other unsafe conversions, Returns: `datasets.table.Table`: Examples: ```python >>> import pandas as pd >>> import pyarrow as pa >>> df = pd.DataFrame({ ... 'int': [1, 2], ... 'str': ['a', 'b'] ... }) >>> pa.Table.from_pandas(df) <pyarrow.lib.Table object at 0x7f05d1fb1b40> ``` """ return cls(pa.Table.from_pandas(*args, **kwargs)) @classmethod def from_arrays(cls, *args, **kwargs): """ Construct a Table from Arrow arrays. Args: arrays (`List[Union[pyarrow.Array, pyarrow.ChunkedArray]]`): Equal-length arrays that should form the table. names (`List[str]`, *optional*): Names for the table columns. If not passed, schema must be passed. schema (`Schema`, defaults to `None`): Schema for the created table. If not passed, names must be passed. metadata (`Union[dict, Mapping]`, defaults to `None`): Optional metadata for the schema (if inferred). Returns: `datasets.table.Table` """ return cls(pa.Table.from_arrays(*args, **kwargs)) @classmethod def from_pydict(cls, *args, **kwargs): """ Construct a Table from Arrow arrays or columns. Args: mapping (`Union[dict, Mapping]`): A mapping of strings to Arrays or Python lists. schema (`Schema`, defaults to `None`): If not passed, will be inferred from the Mapping values metadata (`Union[dict, Mapping]`, defaults to `None`): Optional metadata for the schema (if inferred). Returns: `datasets.table.Table` """ return cls(pa.Table.from_pydict(*args, **kwargs)) @classmethod def from_pylist(cls, mapping, *args, **kwargs): """ Construct a Table from list of rows / dictionaries. Args: mapping (`List[dict]`): A mapping of strings to row values. schema (`Schema`, defaults to `None`): If not passed, will be inferred from the Mapping values metadata (`Union[dict, Mapping]`, defaults to `None`): Optional metadata for the schema (if inferred). Returns: `datasets.table.Table` """ return cls(pa.Table.from_pylist(mapping, *args, **kwargs)) @classmethod def from_batches(cls, *args, **kwargs): """ Construct a Table from a sequence or iterator of Arrow `RecordBatches`. Args: batches (`Union[Sequence[pyarrow.RecordBatch], Iterator[pyarrow.RecordBatch]]`): Sequence of `RecordBatch` to be converted, all schemas must be equal. schema (`Schema`, defaults to `None`): If not passed, will be inferred from the first `RecordBatch`. Returns: `datasets.table.Table`: """ return cls(pa.Table.from_batches(*args, **kwargs)) def slice(self, offset=0, length=None): """ Compute zero-copy slice of this Table. Args: offset (`int`, defaults to `0`): Offset from start of table to slice. length (`int`, defaults to `None`): Length of slice (default is until end of table starting from offset). Returns: `datasets.table.Table` """ # Use fast slicing here return InMemoryTable(self.fast_slice(offset=offset, length=length)) def filter(self, *args, **kwargs): """ Select records from a Table. See `pyarrow.compute.filter` for full usage. """ return InMemoryTable(self.table.filter(*args, **kwargs)) def flatten(self, *args, **kwargs): """ Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ return InMemoryTable(table_flatten(self.table, *args, **kwargs)) def combine_chunks(self, *args, **kwargs): """ Make a new table by combining the chunks this table has. All the underlying chunks in the `ChunkedArray` of each column are concatenated into zero or one chunk. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ return InMemoryTable(self.table.combine_chunks(*args, **kwargs)) def cast(self, *args, **kwargs): """ Cast table values to another schema. Args: target_schema (`Schema`): Schema to cast to, the names and order of fields must match. safe (`bool`, defaults to `True`): Check for overflows or other unsafe conversions. Returns: `datasets.table.Table` """ return InMemoryTable(table_cast(self.table, *args, **kwargs)) def replace_schema_metadata(self, *args, **kwargs): """ EXPERIMENTAL: Create shallow copy of table by replacing schema key-value metadata with the indicated new metadata (which may be `None`, which deletes any existing metadata). Args: metadata (`dict`, defaults to `None`): Returns: `datasets.table.Table`: shallow_copy """ return InMemoryTable(self.table.replace_schema_metadata(*args, **kwargs)) def add_column(self, *args, **kwargs): """ Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ return InMemoryTable(self.table.add_column(*args, **kwargs)) def append_column(self, *args, **kwargs): """ Append column at end of columns. Args: field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ return InMemoryTable(self.table.append_column(*args, **kwargs)) def remove_column(self, *args, **kwargs): """ Create new Table with the indicated column removed. Args: i (`int`): Index of column to remove. Returns: `datasets.table.Table`: New table without the column. """ return InMemoryTable(self.table.remove_column(*args, **kwargs)) def set_column(self, *args, **kwargs): """ Replace column in Table at position. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column set. """ return InMemoryTable(self.table.set_column(*args, **kwargs)) def rename_columns(self, *args, **kwargs): """ Create new table with columns renamed to provided names. """ return InMemoryTable(self.table.rename_columns(*args, **kwargs)) def drop(self, *args, **kwargs): """ Drop one or more columns and return a new table. Args: columns (`List[str]`): List of field names referencing existing columns. Raises: `KeyError` : if any of the passed columns name are not existing. Returns: `datasets.table.Table`: New table without the columns. """ return InMemoryTable(self.table.drop(*args, **kwargs)) def select(self, *args, **kwargs): """ Select columns of the table. Returns a new table with the specified columns, and metadata preserved. Args: columns (:obj:`Union[List[str], List[int]]`): The column names or integer indices to select. Returns: :class:`datasets.table.Table`: New table with the specified columns, and metadata preserved. """ return InMemoryTable(self.table.select(*args, **kwargs)) # The MemoryMappedTable needs replays to properly reload tables from the disk Replay = Tuple[str, tuple, dict] class MemoryMappedTable(TableBlock): """ The table is said memory mapped when it doesn't use the user's RAM but loads the data from the disk instead. Pickling it doesn't copy the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replay" when reloading the table from the disk. Its implementation requires to store an history of all the transforms that were applied to the underlying pyarrow Table, so that they can be "replayed" when reloading the Table from the disk. This is different from the `InMemoryTable` table, for which pickling does copy all the data in memory. `InMemoryTable` must be used when data fit in memory, while `MemoryMapped` are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. """ def __init__(self, table: pa.Table, path: str, replays: Optional[List[Replay]] = None): super().__init__(table) self.path = os.path.abspath(path) self.replays: List[Replay] = replays if replays is not None else [] @classmethod def from_file(cls, filename: str, replays=None): table = _memory_mapped_arrow_table_from_file(filename) table = cls._apply_replays(table, replays) return cls(table, filename, replays) def __getstate__(self): return {"path": self.path, "replays": self.replays} def __setstate__(self, state): path = state["path"] replays = state["replays"] table = _memory_mapped_arrow_table_from_file(path) table = self._apply_replays(table, replays) MemoryMappedTable.__init__(self, table, path=path, replays=replays) @staticmethod def _apply_replays(table: pa.Table, replays: Optional[List[Replay]] = None) -> pa.Table: if replays is not None: for name, args, kwargs in replays: if name == "cast": table = table_cast(table, *args, **kwargs) elif name == "flatten": table = table_flatten(table, *args, **kwargs) else: table = getattr(table, name)(*args, **kwargs) return table def _append_replay(self, replay: Replay) -> List[Replay]: replays = copy.deepcopy(self.replays) replays.append(replay) return replays def slice(self, offset=0, length=None): """ Compute zero-copy slice of this Table. Args: offset (`int`, defaults to `0`): Offset from start of table to slice. length (`int`, defaults to `None`): Length of slice (default is until end of table starting from offset). Returns: `datasets.table.Table` """ replay = ("slice", (offset, length), {}) replays = self._append_replay(replay) # Use fast slicing here return MemoryMappedTable(self.fast_slice(offset=offset, length=length), self.path, replays) def filter(self, *args, **kwargs): """ Select records from a Table. See `pyarrow.compute.filter` for full usage. """ replay = ("filter", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.filter(*args, **kwargs), self.path, replays) def flatten(self, *args, **kwargs): """ Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ replay = ("flatten", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(table_flatten(self.table, *args, **kwargs), self.path, replays) def combine_chunks(self, *args, **kwargs): """ Make a new table by combining the chunks this table has. All the underlying chunks in the ChunkedArray of each column are concatenated into zero or one chunk. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ replay = ("combine_chunks", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.combine_chunks(*args, **kwargs), self.path, replays) def cast(self, *args, **kwargs): """ Cast table values to another schema Args: target_schema (`Schema`): Schema to cast to, the names and order of fields must match. safe (`bool`, defaults to `True`): Check for overflows or other unsafe conversions. Returns: `datasets.table.Table` """ replay = ("cast", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(table_cast(self.table, *args, **kwargs), self.path, replays) def replace_schema_metadata(self, *args, **kwargs): """ EXPERIMENTAL: Create shallow copy of table by replacing schema key-value metadata with the indicated new metadata (which may be None, which deletes any existing metadata. Args: metadata (`dict`, defaults to `None`): Returns: `datasets.table.Table`: shallow_copy """ replay = ("replace_schema_metadata", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.replace_schema_metadata(*args, **kwargs), self.path, replays) def add_column(self, *args, **kwargs): """ Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ replay = ("add_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.add_column(*args, **kwargs), self.path, replays) def append_column(self, *args, **kwargs): """ Append column at end of columns. Args: field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ replay = ("append_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.append_column(*args, **kwargs), self.path, replays) def remove_column(self, *args, **kwargs): """ Create new Table with the indicated column removed. Args: i (`int`): Index of column to remove. Returns: `datasets.table.Table`: New table without the column. """ replay = ("remove_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.remove_column(*args, **kwargs), self.path, replays) def set_column(self, *args, **kwargs): """ Replace column in Table at position. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column set. """ replay = ("set_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.set_column(*args, **kwargs), self.path, replays) def rename_columns(self, *args, **kwargs): """ Create new table with columns renamed to provided names. """ replay = ("rename_columns", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.rename_columns(*args, **kwargs), self.path, replays) def drop(self, *args, **kwargs): """ Drop one or more columns and return a new table. Args: columns (`List[str]`): List of field names referencing existing columns. Raises: `KeyError` : if any of the passed columns name are not existing. Returns: `datasets.table.Table`: New table without the columns. """ replay = ("drop", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.drop(*args, **kwargs), self.path, replays) def select(self, *args, **kwargs): """ Select columns of the table. Returns a new table with the specified columns, and metadata preserved. Args: columns (:obj:`Union[List[str], List[int]]`): The column names or integer indices to select. Returns: :class:`datasets.table.Table`: New table with the specified columns, and metadata preserved. """ replay = ("select", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.select(*args, **kwargs), self.path, replays) # A ConcatenationTable is the concatenation of several tables. # The ``blocks`` attributes stores a list of list of blocks. # The first axis concatenates the tables along the axis 0 (it appends rows), # while the second axis concatenates tables along the axis 1 (it appends columns). TableBlockContainer = TypeVar("TableBlockContainer", TableBlock, List[TableBlock], List[List[TableBlock]]) class ConcatenationTable(Table): """ The table comes from the concatenation of several tables called blocks. It enables concatenation on both axis 0 (append rows) and axis 1 (append columns). The underlying tables are called "blocks" and can be either `InMemoryTable` or `MemoryMappedTable` objects. This allows to combine tables that come from memory or that are memory mapped. When a `ConcatenationTable` is pickled, then each block is pickled: - the `InMemoryTable` objects are pickled by copying all the data in memory. - the MemoryMappedTable objects are pickled without copying the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replays" when reloading the table from the disk. Its implementation requires to store each block separately. The `blocks` attributes stores a list of list of blocks. The first axis concatenates the tables along the axis 0 (it appends rows), while the second axis concatenates tables along the axis 1 (it appends columns). If some columns are missing when concatenating on axis 0, they are filled with null values. This is done using `pyarrow.concat_tables(tables, promote=True)`. You can access the fully combined table by accessing the `ConcatenationTable.table` attribute, and the blocks by accessing the `ConcatenationTable.blocks` attribute. """ def __init__(self, table: pa.Table, blocks: List[List[TableBlock]]): super().__init__(table) self.blocks = blocks # Check that all the blocks have the right type. # Only InMemoryTable and MemoryMappedTable are allowed. for subtables in blocks: for subtable in subtables: if not isinstance(subtable, TableBlock): raise TypeError( "The blocks of a ConcatenationTable must be InMemoryTable or MemoryMappedTable objects" f", but got {subtable}." ) def __getstate__(self): return {"blocks": self.blocks} def __setstate__(self, state): blocks = state["blocks"] table = self._concat_blocks_horizontally_and_vertically(blocks) ConcatenationTable.__init__(self, table, blocks=blocks) @staticmethod def _concat_blocks(blocks: List[Union[TableBlock, pa.Table]], axis: int = 0) -> pa.Table: pa_tables = [table.table if hasattr(table, "table") else table for table in blocks] if axis == 0: # we set promote=True to fill missing columns with null values if config.PYARROW_VERSION.major < 14: return pa.concat_tables(pa_tables, promote=True) else: return pa.concat_tables(pa_tables, promote_options="default") elif axis == 1: for i, table in enumerate(pa_tables): if i == 0: pa_table = table else: for name, col in zip(table.column_names, table.columns): pa_table = pa_table.append_column(name, col) return pa_table else: raise ValueError("'axis' must be either 0 or 1") @classmethod def _concat_blocks_horizontally_and_vertically(cls, blocks: List[List[TableBlock]]) -> pa.Table: pa_tables_to_concat_vertically = [] for i, tables in enumerate(blocks): if not tables: continue pa_table_horizontally_concatenated = cls._concat_blocks(tables, axis=1) pa_tables_to_concat_vertically.append(pa_table_horizontally_concatenated) return cls._concat_blocks(pa_tables_to_concat_vertically, axis=0) @classmethod def _merge_blocks(cls, blocks: TableBlockContainer, axis: Optional[int] = None) -> TableBlockContainer: if axis is not None: merged_blocks = [] for is_in_memory, block_group in groupby(blocks, key=lambda x: isinstance(x, InMemoryTable)): if is_in_memory: block_group = [InMemoryTable(cls._concat_blocks(list(block_group), axis=axis))] merged_blocks += list(block_group) else: # both merged_blocks = [cls._merge_blocks(row_block, axis=1) for row_block in blocks] if all(len(row_block) == 1 for row_block in merged_blocks): merged_blocks = cls._merge_blocks( [block for row_block in merged_blocks for block in row_block], axis=0 ) return merged_blocks @classmethod def _consolidate_blocks(cls, blocks: TableBlockContainer) -> TableBlockContainer: if isinstance(blocks, TableBlock): return blocks elif isinstance(blocks[0], TableBlock): return cls._merge_blocks(blocks, axis=0) else: return cls._merge_blocks(blocks) @classmethod def from_blocks(cls, blocks: TableBlockContainer) -> "ConcatenationTable": blocks = cls._consolidate_blocks(blocks) if isinstance(blocks, TableBlock): table = blocks return cls(table.table, [[table]]) elif isinstance(blocks[0], TableBlock): table = cls._concat_blocks(blocks, axis=0) blocks = [[t] for t in blocks] return cls(table, blocks) else: table = cls._concat_blocks_horizontally_and_vertically(blocks) return cls(table, blocks) @classmethod def from_tables(cls, tables: List[Union[pa.Table, Table]], axis: int = 0) -> "ConcatenationTable": """Create `ConcatenationTable` from list of tables. Args: tables (list of `Table` or list of `pyarrow.Table`): List of tables. axis (`{0, 1}`, defaults to `0`, meaning over rows): Axis to concatenate over, where `0` means over rows (vertically) and `1` means over columns (horizontally). <Added version="1.6.0"/> """ def to_blocks(table: Union[pa.Table, Table]) -> List[List[TableBlock]]: if isinstance(table, pa.Table): return [[InMemoryTable(table)]] elif isinstance(table, ConcatenationTable): return copy.deepcopy(table.blocks) else: return [[table]] def _slice_row_block(row_block: List[TableBlock], length: int) -> Tuple[List[TableBlock], List[TableBlock]]: sliced = [table.slice(0, length) for table in row_block] remainder = [table.slice(length, len(row_block[0]) - length) for table in row_block] return sliced, remainder def _split_both_like( result: List[List[TableBlock]], blocks: List[List[TableBlock]] ) -> Tuple[List[List[TableBlock]], List[List[TableBlock]]]: """ Make sure each row_block contain the same num_rows to be able to concatenate them on axis=1. To do so, we modify both blocks sets to have the same row_blocks boundaries. For example, if `result` has 2 row_blocks of 3 rows and `blocks` has 3 row_blocks of 2 rows, we modify both to have 4 row_blocks of size 2, 1, 1 and 2: [ x x x | x x x ] + [ y y | y y | y y ] ----------------------------- = [ x x | x | x | x x ] [ y y | y | y | y y ] """ result, blocks = list(result), list(blocks) new_result, new_blocks = [], [] while result and blocks: # we slice the longest row block to save two row blocks of same length # and we replace the long row block by its remainder if necessary if len(result[0][0]) > len(blocks[0][0]): new_blocks.append(blocks[0]) sliced, result[0] = _slice_row_block(result[0], len(blocks.pop(0)[0])) new_result.append(sliced) elif len(result[0][0]) < len(blocks[0][0]): new_result.append(result[0]) sliced, blocks[0] = _slice_row_block(blocks[0], len(result.pop(0)[0])) new_blocks.append(sliced) else: new_result.append(result.pop(0)) new_blocks.append(blocks.pop(0)) if result or blocks: raise ValueError("Failed to concatenate on axis=1 because tables don't have the same number of rows") return new_result, new_blocks def _extend_blocks( result: List[List[TableBlock]], blocks: List[List[TableBlock]], axis: int = 0 ) -> List[List[TableBlock]]: if axis == 0: result.extend(blocks) elif axis == 1: # We make sure each row_block have the same num_rows result, blocks = _split_both_like(result, blocks) for i, row_block in enumerate(blocks): result[i].extend(row_block) return result blocks = to_blocks(tables[0]) for table in tables[1:]: table_blocks = to_blocks(table) blocks = _extend_blocks(blocks, table_blocks, axis=axis) return cls.from_blocks(blocks) @property def _slices(self): offset = 0 for tables in self.blocks: length = len(tables[0]) yield (offset, length) offset += length def slice(self, offset=0, length=None): """ Compute zero-copy slice of this Table. Args: offset (`int`, defaults to `0`): Offset from start of table to slice. length (`int`, defaults to `None`): Length of slice (default is until end of table starting from offset). Returns: `datasets.table.Table` """ table = self.table.slice(offset, length=length) length = length if length is not None else self.num_rows - offset blocks = [] for tables in self.blocks: n_rows = len(tables[0]) if length == 0: break elif n_rows <= offset: offset = offset - n_rows elif n_rows <= offset + length: blocks.append([t.slice(offset) for t in tables]) length, offset = length + offset - n_rows, 0 else: blocks.append([t.slice(offset, length) for t in tables]) length, offset = 0, 0 return ConcatenationTable(table, blocks) def filter(self, mask, *args, **kwargs): """ Select records from a Table. See `pyarrow.compute.filter` for full usage. """ table = self.table.filter(mask, *args, **kwargs) blocks = [] for (offset, length), tables in zip(self._slices, self.blocks): submask = mask.slice(offset, length) blocks.append([t.filter(submask, *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def flatten(self, *args, **kwargs): """ Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ table = table_flatten(self.table, *args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.flatten(*args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def combine_chunks(self, *args, **kwargs): """ Make a new table by combining the chunks this table has. All the underlying chunks in the `ChunkedArray` of each column are concatenated into zero or one chunk. Args: memory_pool (`MemoryPool`, defaults to `None`): For memory allocations, if required, otherwise use default pool. Returns: `datasets.table.Table` """ table = self.table.combine_chunks(*args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.combine_chunks(*args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def cast(self, target_schema, *args, **kwargs): """ Cast table values to another schema. Args: target_schema (`Schema`): Schema to cast to, the names and order of fields must match. safe (`bool`, defaults to `True`): Check for overflows or other unsafe conversions. Returns: `datasets.table.Table` """ from .features import Features table = table_cast(self.table, target_schema, *args, **kwargs) target_features = Features.from_arrow_schema(target_schema) blocks = [] for subtables in self.blocks: new_tables = [] fields = list(target_schema) for subtable in subtables: subfields = [] for name in subtable.column_names: subfields.append(fields.pop(next(i for i, field in enumerate(fields) if field.name == name))) subfeatures = Features({subfield.name: target_features[subfield.name] for subfield in subfields}) subschema = subfeatures.arrow_schema new_tables.append(subtable.cast(subschema, *args, **kwargs)) blocks.append(new_tables) return ConcatenationTable(table, blocks) def replace_schema_metadata(self, *args, **kwargs): """ EXPERIMENTAL: Create shallow copy of table by replacing schema key-value metadata with the indicated new metadata (which may be `None`, which deletes any existing metadata). Args: metadata (`dict`, defaults to `None`): Returns: `datasets.table.Table`: shallow_copy """ table = self.table.replace_schema_metadata(*args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.replace_schema_metadata(*args, **kwargs) for t in tables]) return ConcatenationTable(table, self.blocks) def add_column(self, *args, **kwargs): """ Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ raise NotImplementedError() def append_column(self, *args, **kwargs): """ Append column at end of columns. Args: field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column added. """ raise NotImplementedError() def remove_column(self, i, *args, **kwargs): """ Create new Table with the indicated column removed. Args: i (`int`): Index of column to remove. Returns: `datasets.table.Table`: New table without the column. """ table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for tables in self.blocks: blocks.append( [ t.remove_column(t.column_names.index(name), *args, **kwargs) if name in t.column_names else t for t in tables ] ) return ConcatenationTable(table, blocks) def set_column(self, *args, **kwargs): """ Replace column in Table at position. Args: i (`int`): Index to place the column at. field_ (`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: `datasets.table.Table`: New table with the passed column set. """ raise NotImplementedError() def rename_columns(self, names, *args, **kwargs): """ Create new table with columns renamed to provided names. """ table = self.table.rename_columns(names, *args, **kwargs) names = dict(zip(self.table.column_names, names)) blocks = [] for tables in self.blocks: blocks.append( [t.rename_columns([names[name] for name in t.column_names], *args, **kwargs) for t in tables] ) return ConcatenationTable(table, blocks) def drop(self, columns, *args, **kwargs): """ Drop one or more columns and return a new table. Args: columns (`List[str]`): List of field names referencing existing columns. Raises: `KeyError` : if any of the passed columns name are not existing. Returns: `datasets.table.Table`: New table without the columns. """ table = self.table.drop(columns, *args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.drop([c for c in columns if c in t.column_names], *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def select(self, columns, *args, **kwargs): """ Select columns of the table. Returns a new table with the specified columns, and metadata preserved. Args: columns (:obj:`Union[List[str], List[int]]`): The column names or integer indices to select. Returns: :class:`datasets.table.Table`: New table with the specified columns, and metadata preserved. """ table = self.table.select(columns, *args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.select([c for c in columns if c in t.column_names], *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def concat_tables(tables: List[Table], axis: int = 0) -> Table: """ Concatenate tables. Args: tables (list of `Table`): List of tables to be concatenated. axis (`{0, 1}`, defaults to `0`, meaning over rows): Axis to concatenate over, where `0` means over rows (vertically) and `1` means over columns (horizontally). <Added version="1.6.0"/> Returns: `datasets.table.Table`: If the number of input tables is > 1, then the returned table is a `datasets.table.ConcatenationTable`. Otherwise if there's only one table, it is returned as is. """ tables = list(tables) if len(tables) == 1: return tables[0] return ConcatenationTable.from_tables(tables, axis=axis) def list_table_cache_files(table: Table) -> List[str]: """ Get the cache files that are loaded by the table. Cache file are used when parts of the table come from the disk via memory mapping. Returns: `List[str]`: A list of paths to the cache files loaded by the table. """ if isinstance(table, ConcatenationTable): cache_files = [] for subtables in table.blocks: for subtable in subtables: cache_files += list_table_cache_files(subtable) return cache_files elif isinstance(table, MemoryMappedTable): return [table.path] else: return [] def _wrap_for_chunked_arrays(func): """Apply the function on each chunk of a `pyarrow.ChunkedArray`, or on the array directly""" def wrapper(array, *args, **kwargs): if isinstance(array, pa.ChunkedArray): return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks]) else: return func(array, *args, **kwargs) return wrapper def _is_extension_type(pa_type: pa.DataType) -> bool: """ Check (recursively) if a pyarrow type is an extension type. """ if isinstance(pa_type, pa.StructType): return any(_is_extension_type(field.type) for field in pa_type) elif isinstance(pa_type, (pa.ListType, pa.FixedSizeListType, pa.LargeListType)): return _is_extension_type(pa_type.value_type) elif isinstance(pa_type, pa.ExtensionType): return True else: return False def array_concat(arrays: List[pa.Array]): """Improved version of pa.concat_arrays It supports concatenating pa.ExtensionArray objects by concatenating the underlying storages. Args: arrays (List[pa.Array]): List of arrays to contatenate Raises: pa.ArrowInvalid: if the arrow array concatenation fails ValueError: if the list of arrays is empty TypeError: if the arrays to be concatenated have different types Returns: array (:obj:`pyarrow.Array`): the concatenated array """ arrays = list(arrays) array_types = {array.type for array in arrays} if not array_types: raise ValueError("Couldn't concatenate empty list of arrays") if len(array_types) > 1: array_types = list(array_types) raise TypeError(f"Couldn't concatenate arrays with different types {array_types[0]} and {array_types[1]}") array_type = arrays[0].type arrays = [chunk for arr in arrays for chunk in (arr.chunks if isinstance(arr, pa.ChunkedArray) else (arr,))] if not _is_extension_type(array_type): return pa.concat_arrays(arrays) def _offsets_concat(offsets): offset = offsets[0] concatenated_offsets = offset for offset in offsets[1:]: offset = pc.subtract(offset, offset[0]) offset = pc.add(offset[1:], concatenated_offsets[-1]) concatenated_offsets = pa.concat_arrays([concatenated_offsets, offset]) return concatenated_offsets def _concat_arrays(arrays): array_type = arrays[0].type if isinstance(array_type, pa.ExtensionType): return array_type.wrap_array(_concat_arrays([array.storage for array in arrays])) elif pa.types.is_struct(array_type): return pa.StructArray.from_arrays( [_concat_arrays([array.field(field.name) for array in arrays]) for field in array_type], fields=list(array_type), mask=pa.concat_arrays([array.is_null() for array in arrays]), ) elif pa.types.is_list(array_type): if any(array.null_count > 0 for array in arrays): if config.PYARROW_VERSION.major < 10: warnings.warn( "None values are converted to empty lists in `pyarrow<10.0.0` when concatenating list arrays with None values. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676." ) else: return pa.ListArray.from_arrays( _offsets_concat([array.offsets for array in arrays]), _concat_arrays([array.values for array in arrays]), mask=pa.concat_arrays([array.is_null() for array in arrays]), ) return pa.ListArray.from_arrays( _offsets_concat([array.offsets for array in arrays]), _concat_arrays([array.values for array in arrays]), ) elif pa.types.is_fixed_size_list(array_type): if config.PYARROW_VERSION.major < 15: # PyArrow bug: https://github.com/apache/arrow/issues/35360 return pa.FixedSizeListArray.from_arrays( _concat_arrays([array.values[array.offset * array.type.list_size :] for array in arrays]), array_type.list_size, ) else: return pa.FixedSizeListArray.from_arrays( _concat_arrays([array.values for array in arrays]), array_type.value_type, array_type.list_size, ) return pa.concat_arrays(arrays) return _concat_arrays(arrays) @_wrap_for_chunked_arrays def array_cast(array: pa.Array, pa_type: pa.DataType, allow_number_to_str=True): """Improved version of `pa.Array.cast` It supports casting `pa.StructArray` objects to re-order the fields. It also let you control certain aspects of the casting, e.g. whether to disable numbers (`floats` or `ints`) to strings. Args: array (`pa.Array`): PyArrow array to cast pa_type (`pa.DataType`): Target PyArrow type allow_number_to_str (`bool`, defaults to `True`): Whether to allow casting numbers to strings. Defaults to `True`. Raises: `pa.ArrowInvalidError`: if the arrow data casting fails `TypeError`: if the target type is not supported according, e.g. - if a field is missing - if casting from numbers to strings and `allow_number_to_str` is `False` Returns: `List[pyarrow.Array]`: the casted array """ _c = partial(array_cast, allow_number_to_str=allow_number_to_str) if isinstance(array, pa.ExtensionArray): array = array.storage if isinstance(pa_type, pa.ExtensionType): return pa_type.wrap_array(_c(array, pa_type.storage_type)) elif array.type == pa_type: return array elif pa.types.is_struct(array.type): if pa.types.is_struct(pa_type) and ({field.name for field in pa_type} == {field.name for field in array.type}): if array.type.num_fields == 0: return array arrays = [_c(array.field(field.name), field.type) for field in pa_type] return pa.StructArray.from_arrays(arrays, fields=list(pa_type), mask=array.is_null()) elif pa.types.is_list(array.type): if pa.types.is_fixed_size_list(pa_type): if pa_type.list_size * len(array) == len(array.values): return pa.FixedSizeListArray.from_arrays( _c(array.values, pa_type.value_type), pa_type.list_size, ) elif pa.types.is_list(pa_type): if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists in `pyarrow<10.0.0` when converting array to {pa_type}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676." ) else: return pa.ListArray.from_arrays( array.offsets, _c(array.values, pa_type.value_type), mask=array.is_null() ) return pa.ListArray.from_arrays(array.offsets, _c(array.values, pa_type.value_type)) elif pa.types.is_fixed_size_list(array.type): array_values = array.values if config.PYARROW_VERSION.major < 15: # PyArrow bug: https://github.com/apache/arrow/issues/35360 array_values = array.values[array.offset * array.type.list_size :] if pa.types.is_fixed_size_list(pa_type): return pa.FixedSizeListArray.from_arrays( _c(array_values, pa_type.value_type), pa_type.list_size, ) elif pa.types.is_list(pa_type): offsets_arr = pa.array(np.arange(len(array) + 1) * array.type.list_size, pa.int32()) if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists in `pyarrow<10.0.0` when converting array to {pa_type}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676." ) else: return pa.ListArray.from_arrays( offsets_arr, _c(array_values, pa_type.value_type), mask=array.is_null() ) return pa.ListArray.from_arrays(offsets_arr, _c(array_values, pa_type.value_type)) else: if ( not allow_number_to_str and pa.types.is_string(pa_type) and (pa.types.is_floating(array.type) or pa.types.is_integer(array.type)) ): raise TypeError( f"Couldn't cast array of type {array.type} to {pa_type} since allow_number_to_str is set to {allow_number_to_str}" ) if pa.types.is_null(pa_type) and not pa.types.is_null(array.type): raise TypeError(f"Couldn't cast array of type {array.type} to {pa_type}") return array.cast(pa_type) raise TypeError(f"Couldn't cast array of type\n{array.type}\nto\n{pa_type}") @_wrap_for_chunked_arrays def cast_array_to_feature(array: pa.Array, feature: "FeatureType", allow_number_to_str=True): """Cast an array to the arrow type that corresponds to the requested feature type. For custom features like [`Audio`] or [`Image`], it takes into account the "cast_storage" methods they defined to enable casting from other arrow types. Args: array (`pa.Array`): The PyArrow array to cast. feature (`datasets.features.FeatureType`): The target feature type. allow_number_to_str (`bool`, defaults to `True`): Whether to allow casting numbers to strings. Defaults to `True`. Raises: `pa.ArrowInvalidError`: if the arrow data casting fails `TypeError`: if the target type is not supported according, e.g. - if a field is missing - if casting from numbers to strings and `allow_number_to_str` is `False` Returns: array (`pyarrow.Array`): the casted array """ from .features.features import Sequence, get_nested_type _c = partial(cast_array_to_feature, allow_number_to_str=allow_number_to_str) if isinstance(array, pa.ExtensionArray): array = array.storage if hasattr(feature, "cast_storage"): return feature.cast_storage(array) elif pa.types.is_struct(array.type): # feature must be a dict or Sequence(subfeatures_dict) if isinstance(feature, Sequence) and isinstance(feature.feature, dict): feature = { name: Sequence(subfeature, length=feature.length) for name, subfeature in feature.feature.items() } if isinstance(feature, dict) and {field.name for field in array.type} == set(feature): if array.type.num_fields == 0: return array arrays = [_c(array.field(name), subfeature) for name, subfeature in feature.items()] return pa.StructArray.from_arrays(arrays, names=list(feature), mask=array.is_null()) elif pa.types.is_list(array.type): # feature must be either [subfeature] or Sequence(subfeature) if isinstance(feature, list): casted_values = _c(array.values, feature[0]) if casted_values.type == array.values.type: return array else: if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists in `pyarrow<10.0.0` when converting array to {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676." ) else: return pa.ListArray.from_arrays(array.offsets, casted_values, mask=array.is_null()) return pa.ListArray.from_arrays(array.offsets, casted_values) elif isinstance(feature, Sequence): if feature.length > -1: if feature.length * len(array) == len(array.values): return pa.FixedSizeListArray.from_arrays(_c(array.values, feature.feature), feature.length) else: casted_values = _c(array.values, feature.feature) if casted_values.type == array.values.type: return array else: if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists in `pyarrow<10.0.0` when converting array to {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676." ) else: return pa.ListArray.from_arrays( array.offsets, _c(array.values, feature.feature), mask=array.is_null() ) return pa.ListArray.from_arrays(array.offsets, _c(array.values, feature.feature)) elif pa.types.is_fixed_size_list(array.type): # feature must be either [subfeature] or Sequence(subfeature) array_values = array.values if config.PYARROW_VERSION.major < 15: # PyArrow bug: https://github.com/apache/arrow/issues/35360 array_values = array.values[array.offset * array.type.list_size :] if isinstance(feature, list): if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists when converting array to {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`" ) else: return pa.ListArray.from_arrays(array.offsets, _c(array_values, feature[0]), mask=array.is_null()) return pa.ListArray.from_arrays(array.offsets, _c(array_values, feature[0])) elif isinstance(feature, Sequence): if feature.length > -1: if feature.length * len(array) == len(array_values): return pa.FixedSizeListArray.from_arrays(_c(array_values, feature.feature), feature.length) else: offsets_arr = pa.array(np.arange(len(array) + 1) * array.type.list_size, pa.int32()) if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists when converting array to {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`" ) else: return pa.ListArray.from_arrays( offsets_arr, _c(array_values, feature.feature), mask=array.is_null() ) return pa.ListArray.from_arrays(offsets_arr, _c(array_values, feature.feature)) if pa.types.is_null(array.type): return array_cast(array, get_nested_type(feature), allow_number_to_str=allow_number_to_str) elif not isinstance(feature, (Sequence, dict, list, tuple)): return array_cast(array, feature(), allow_number_to_str=allow_number_to_str) raise TypeError(f"Couldn't cast array of type\n{array.type}\nto\n{feature}") @_wrap_for_chunked_arrays def embed_array_storage(array: pa.Array, feature: "FeatureType"): """Embed data into an arrays's storage. For custom features like Audio or Image, it takes into account the "embed_storage" methods they defined to enable embedding external data (e.g. an image file) into an other arrow types. <Added version="2.4.0"/> Args: array (`pa.Array`): The PyArrow array in which to embed data. feature (`datasets.features.FeatureType`): Array features. Raises: `TypeError`: if the target type is not supported according, e.g. - if a field is missing Returns: array (`pyarrow.Array`): the casted array """ from .features import Sequence _e = embed_array_storage if isinstance(array, pa.ExtensionArray): array = array.storage if hasattr(feature, "embed_storage"): return feature.embed_storage(array) elif pa.types.is_struct(array.type): # feature must be a dict or Sequence(subfeatures_dict) if isinstance(feature, Sequence) and isinstance(feature.feature, dict): feature = { name: Sequence(subfeature, length=feature.length) for name, subfeature in feature.feature.items() } if isinstance(feature, dict): arrays = [_e(array.field(name), subfeature) for name, subfeature in feature.items()] return pa.StructArray.from_arrays(arrays, names=list(feature), mask=array.is_null()) elif pa.types.is_list(array.type): # feature must be either [subfeature] or Sequence(subfeature) if isinstance(feature, list): if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists when embedding array storage with {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`" ) else: return pa.ListArray.from_arrays(array.offsets, _e(array.values, feature[0]), mask=array.is_null()) return pa.ListArray.from_arrays(array.offsets, _e(array.values, feature[0])) elif isinstance(feature, Sequence): if feature.length > -1: if feature.length * len(array) == len(array.values): return pa.FixedSizeListArray.from_arrays(_e(array.values, feature.feature), feature.length) else: casted_values = _e(array.values, feature.feature) if casted_values.type == array.values.type: return array else: if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists when embedding array storage with {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`" ) else: return pa.ListArray.from_arrays( array.offsets, _e(array.values, feature.feature), mask=array.is_null() ) return pa.ListArray.from_arrays(array.offsets, _e(array.values, feature.feature)) elif pa.types.is_fixed_size_list(array.type): # feature must be either [subfeature] or Sequence(subfeature) array_values = array.values if config.PYARROW_VERSION.major < 15: # PyArrow bug: https://github.com/apache/arrow/issues/35360 array_values = array.values[array.offset * array.type.list_size :] if isinstance(feature, list): if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists when embedding array storage with {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`" ) else: return pa.ListArray.from_arrays(array.offsets, _e(array_values, feature[0]), mask=array.is_null()) return pa.ListArray.from_arrays(array.offsets, _e(array_values, feature[0])) elif isinstance(feature, Sequence): if feature.length > -1: if feature.length * len(array) == len(array_values): return pa.FixedSizeListArray.from_arrays(_e(array_values, feature.feature), feature.length) else: offsets_arr = pa.array(np.arange(len(array) + 1) * array.type.list_size, pa.int32()) if array.null_count > 0: if config.PYARROW_VERSION.major < 10: warnings.warn( f"None values are converted to empty lists when embedding array storage with {feature}. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`" ) else: return pa.ListArray.from_arrays( offsets_arr, _e(array_values, feature.feature), mask=array.is_null() ) return pa.ListArray.from_arrays(offsets_arr, _e(array_values, feature.feature)) if not isinstance(feature, (Sequence, dict, list, tuple)): return array raise TypeError(f"Couldn't embed array of type\n{array.type}\nwith\n{feature}") class CastError(ValueError): """When it's not possible to cast an Arrow table to a specific schema or set of features""" def __init__(self, *args, table_column_names: List[str], requested_column_names: List[str]) -> None: super().__init__(*args) self.table_column_names = table_column_names self.requested_column_names = requested_column_names def details(self): new_columns = set(self.table_column_names) - set(self.requested_column_names) missing_columns = set(self.requested_column_names) - set(self.table_column_names) if new_columns and missing_columns: return f"there are {len(new_columns)} new columns ({', '.join(new_columns)}) and {len(missing_columns)} missing columns ({', '.join(missing_columns)})." elif new_columns: return f"there are {len(new_columns)} new columns ({new_columns})" else: return f"there are {len(missing_columns)} missing columns ({missing_columns})" def cast_table_to_features(table: pa.Table, features: "Features"): """Cast a table to the arrow schema that corresponds to the requested features. Args: table (`pyarrow.Table`): PyArrow table to cast. features ([`Features`]): Target features. Returns: table (`pyarrow.Table`): the casted table """ if sorted(table.column_names) != sorted(features): raise CastError( f"Couldn't cast\n{table.schema}\nto\n{features}\nbecause column names don't match", table_column_names=table.column_names, requested_column_names=list(features), ) arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()] return pa.Table.from_arrays(arrays, schema=features.arrow_schema) def cast_table_to_schema(table: pa.Table, schema: pa.Schema): """Cast a table to the arrow schema. Different from `cast_table_to_features`, this method can preserve nullability. Args: table (`pa.Table`): PyArrow table to cast. features ([`Features`]): Target features. Returns: `pa.Table`: the casted table """ from .features import Features features = Features.from_arrow_schema(schema) if sorted(table.column_names) != sorted(features): raise CastError( f"Couldn't cast\n{table.schema}\nto\n{features}\nbecause column names don't match", table_column_names=table.column_names, requested_column_names=list(features), ) arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()] return pa.Table.from_arrays(arrays, schema=schema) def embed_table_storage(table: pa.Table): """Embed external data into a table's storage. <Added version="2.4.0"/> Args: table (`pyarrow.Table`): PyArrow table in which to embed data. Returns: table (`pyarrow.Table`): the table with embedded data """ from .features.features import Features, require_storage_embed features = Features.from_arrow_schema(table.schema) arrays = [ embed_array_storage(table[name], feature) if require_storage_embed(feature) else table[name] for name, feature in features.items() ] return pa.Table.from_arrays(arrays, schema=features.arrow_schema) def table_cast(table: pa.Table, schema: pa.Schema): """Improved version of `pa.Table.cast`. It supports casting to feature types stored in the schema metadata. Args: table (`pyarrow.Table`): PyArrow table to cast. schema (`pyarrow.Schema`): Target PyArrow schema. Returns: table (`pyarrow.Table`): the casted table """ if table.schema != schema: return cast_table_to_schema(table, schema) elif table.schema.metadata != schema.metadata: return table.replace_schema_metadata(schema.metadata) else: return table def table_flatten(table: pa.Table): """Improved version of `pa.Table.flatten`. It behaves as `pa.Table.flatten` in a sense it does 1-step flatten of the columns with a struct type into one column per struct field, but updates the metadata and skips decodable features unless the `decode` attribute of these features is set to False. Args: table (`pa.Table`): PyArrow table to flatten. Returns: `Table`: the flattened table """ from .features import Features features = Features.from_arrow_schema(table.schema) if any(hasattr(subfeature, "flatten") and subfeature.flatten() == subfeature for subfeature in features.values()): flat_arrays = [] flat_column_names = [] for field in table.schema: array = table.column(field.name) subfeature = features[field.name] if pa.types.is_struct(field.type) and ( not hasattr(subfeature, "flatten") or subfeature.flatten() != subfeature ): flat_arrays.extend(array.flatten()) flat_column_names.extend([f"{field.name}.{subfield.name}" for subfield in field.type]) else: flat_arrays.append(array) flat_column_names.append(field.name) flat_table = pa.Table.from_arrays( flat_arrays, names=flat_column_names, ) else: flat_table = table.flatten() # Preserve complex types in the metadata flat_features = features.flatten(max_depth=2) flat_features = Features({column_name: flat_features[column_name] for column_name in flat_table.column_names}) return flat_table.replace_schema_metadata(flat_features.arrow_schema.metadata) def table_visitor(table: pa.Table, function: Callable[[pa.Array], None]): """Visit all arrays in a table and apply a function to them. Args: table (`pyarrow.Table`): PyArrow table to visit. function (`Callable[[pa.Array], None]`): Function to apply to each array. """ from .features import Features, Sequence features = Features.from_arrow_schema(table.schema) def _visit(array, feature): if isinstance(array, pa.ChunkedArray): for chunk in array.chunks: _visit(chunk, feature) else: if isinstance(array, pa.ExtensionArray): array = array.storage function(array, feature) if pa.types.is_struct(array.type) and not hasattr(feature, "cast_storage"): if isinstance(feature, Sequence) and isinstance(feature.feature, dict): feature = { name: Sequence(subfeature, length=feature.length) for name, subfeature in feature.feature.items() } for name, subfeature in feature.items(): _visit(array.field(name), subfeature) elif pa.types.is_list(array.type): if isinstance(feature, list): _visit(array.values, feature[0]) elif isinstance(feature, Sequence): _visit(array.values, feature.feature) for name, feature in features.items(): _visit(table[name], feature) def table_iter(table: Table, batch_size: int, drop_last_batch=False) -> Iterator[pa.Table]: """Iterate over sub-tables of size `batch_size`. Args: table (`pyarrow.Table`): PyArrow table to iterate over. batch_size (`int`): Size of each sub-table to yield. drop_last_batch (`bool`, defaults to `False`): Drop the last batch if it is smaller than `batch_size`. """ chunks_buffer = [] chunks_buffer_size = 0 for chunk in table.to_reader(max_chunksize=batch_size): if len(chunk) == 0: continue elif chunks_buffer_size + len(chunk) < batch_size: chunks_buffer.append(chunk) chunks_buffer_size += len(chunk) continue elif chunks_buffer_size + len(chunk) == batch_size: chunks_buffer.append(chunk) yield pa.Table.from_batches(chunks_buffer) chunks_buffer = [] chunks_buffer_size = 0 else: cropped_chunk_length = batch_size - chunks_buffer_size chunks_buffer.append(chunk.slice(0, cropped_chunk_length)) yield pa.Table.from_batches(chunks_buffer) chunks_buffer = [chunk.slice(cropped_chunk_length, len(chunk) - cropped_chunk_length)] chunks_buffer_size = len(chunk) - cropped_chunk_length if not drop_last_batch and chunks_buffer: yield pa.Table.from_batches(chunks_buffer)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/arrow_reader.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """ Arrow ArrowReader.""" import copy import math import os import re import shutil from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, List, Optional, Union import pyarrow as pa import pyarrow.parquet as pq from .download.download_config import DownloadConfig from .naming import _split_re, filenames_for_dataset_split from .table import InMemoryTable, MemoryMappedTable, Table, concat_tables from .utils import logging from .utils.file_utils import cached_path if TYPE_CHECKING: from .info import DatasetInfo # noqa: F401 from .splits import Split, SplitInfo # noqa: F401 logger = logging.get_logger(__name__) HF_GCP_BASE_URL = "https://storage.googleapis.com/huggingface-nlp/cache/datasets" _SUB_SPEC_RE = re.compile( rf""" ^ (?P<split>{_split_re[1:-1]}) (\[ ((?P<from>-?\d+) (?P<from_pct>%)?)? : ((?P<to>-?\d+) (?P<to_pct>%)?)? \])?(\((?P<rounding>[^\)]*)\))? $ """, # remove ^ and $ re.X, ) _ADDITION_SEP_RE = re.compile(r"\s*\+\s*") class DatasetNotOnHfGcsError(ConnectionError): """When you can't get the dataset from the Hf google cloud storage""" pass class MissingFilesOnHfGcsError(ConnectionError): """When some files are missing on the Hf oogle cloud storage""" pass @dataclass(frozen=True) class FileInstructions: """The file instructions associated with a split ReadInstruction. Attributes: num_examples: `int`, The total number of examples file_instructions: List[dict(filename, skip, take)], the files information. The filenames contains the relative path, not absolute. skip/take indicates which example read in the file: `ds.slice(skip, take)` """ num_examples: int file_instructions: List[dict] def make_file_instructions( name: str, split_infos: List["SplitInfo"], instruction: Union[str, "ReadInstruction"], filetype_suffix: Optional[str] = None, prefix_path: Optional[str] = None, ) -> FileInstructions: """Returns instructions of the split dict. Args: name (`str`): Name of the dataset. split_infos (`list` of `[SplitInfo]`): Dataset splits information. instruction ([`ReadInstruction`] or `str`): Reading instruction for a dataset. filetype_suffix (`str`, *optional*): Suffix of dataset files, e.g. 'arrow' or 'parquet'. prefix_path (`str`, *optional*): Prefix of dataset files, e.g. directory name. Returns: [`FileInstructions`] """ if not isinstance(name, str): raise TypeError(f"Expected str 'name', but got: {type(name).__name__}") elif not name: raise ValueError("Expected non-empty str 'name'") name2len = {info.name: info.num_examples for info in split_infos} name2shard_lengths = {info.name: info.shard_lengths for info in split_infos} name2filenames = { info.name: filenames_for_dataset_split( path=prefix_path, dataset_name=name, split=info.name, filetype_suffix=filetype_suffix, shard_lengths=name2shard_lengths[info.name], ) for info in split_infos } if not isinstance(instruction, ReadInstruction): instruction = ReadInstruction.from_spec(instruction) # Create the absolute instruction (per split) absolute_instructions = instruction.to_absolute(name2len) # For each split, return the files instruction (skip/take) file_instructions = [] num_examples = 0 for abs_instr in absolute_instructions: split_length = name2len[abs_instr.splitname] filenames = name2filenames[abs_instr.splitname] shard_lengths = name2shard_lengths[abs_instr.splitname] from_ = 0 if abs_instr.from_ is None else abs_instr.from_ to = split_length if abs_instr.to is None else abs_instr.to if shard_lengths is None: # not sharded for filename in filenames: num_examples += to - from_ file_instructions.append({"filename": filename, "skip": from_, "take": to - from_}) else: # sharded index_start = 0 # Beginning (included) of moving window. index_end = 0 # End (excluded) of moving window. for filename, shard_length in zip(filenames, shard_lengths): index_end += shard_length if from_ < index_end and to > index_start: # There is something to take. skip = from_ - index_start if from_ > index_start else 0 take = to - index_start - skip if to < index_end else -1 if take == 0: continue file_instructions.append({"filename": filename, "skip": skip, "take": take}) num_examples += shard_length - skip if take == -1 else take index_start += shard_length return FileInstructions( num_examples=num_examples, file_instructions=file_instructions, ) class BaseReader: """ Build a Dataset object out of Instruction instance(s). """ def __init__(self, path: str, info: Optional["DatasetInfo"]): """Initializes ArrowReader. Args: path (str): path where tfrecords are stored. info (DatasetInfo): info about the dataset. """ self._path: str = path self._info: Optional["DatasetInfo"] = info self._filetype_suffix: Optional[str] = None def _get_table_from_filename(self, filename_skip_take, in_memory=False) -> Table: """Returns a Dataset instance from given (filename, skip, take).""" raise NotImplementedError def _read_files(self, files, in_memory=False) -> Table: """Returns Dataset for given file instructions. Args: files: List[dict(filename, skip, take)], the files information. The filenames contain the absolute path, not relative. skip/take indicates which example read in the file: `ds.slice(skip, take)` in_memory (bool, default False): Whether to copy the data in-memory. """ if len(files) == 0 or not all(isinstance(f, dict) for f in files): raise ValueError("please provide valid file informations") pa_tables = [] files = copy.deepcopy(files) for f in files: f["filename"] = os.path.join(self._path, f["filename"]) for f_dict in files: pa_table: Table = self._get_table_from_filename(f_dict, in_memory=in_memory) pa_tables.append(pa_table) pa_tables = [t for t in pa_tables if len(t) > 0] if not pa_tables and (self._info is None or self._info.features is None): raise ValueError( "Tried to read an empty table. Please specify at least info.features to create an empty table with the right type." ) pa_tables = pa_tables or [InMemoryTable.from_batches([], schema=pa.schema(self._info.features.type))] pa_table = concat_tables(pa_tables) if len(pa_tables) != 1 else pa_tables[0] return pa_table def get_file_instructions(self, name, instruction, split_infos): """Return list of dict {'filename': str, 'skip': int, 'take': int}""" file_instructions = make_file_instructions( name, split_infos, instruction, filetype_suffix=self._filetype_suffix, prefix_path=self._path ) files = file_instructions.file_instructions return files def read( self, name, instructions, split_infos, in_memory=False, ): """Returns Dataset instance(s). Args: name (str): name of the dataset. instructions (ReadInstruction): instructions to read. Instruction can be string and will then be passed to the Instruction constructor as it. split_infos (list of SplitInfo proto): the available splits for dataset. in_memory (bool, default False): Whether to copy the data in-memory. Returns: kwargs to build a single Dataset instance. """ files = self.get_file_instructions(name, instructions, split_infos) if not files: msg = f'Instruction "{instructions}" corresponds to no data!' raise ValueError(msg) return self.read_files(files=files, original_instructions=instructions, in_memory=in_memory) def read_files( self, files: List[dict], original_instructions: Union[None, "ReadInstruction", "Split"] = None, in_memory=False, ): """Returns single Dataset instance for the set of file instructions. Args: files: List[dict(filename, skip, take)], the files information. The filenames contains the relative path, not absolute. skip/take indicates which example read in the file: `ds.skip().take()` original_instructions: store the original instructions used to build the dataset split in the dataset. in_memory (bool, default False): Whether to copy the data in-memory. Returns: kwargs to build a Dataset instance. """ # Prepend path to filename pa_table = self._read_files(files, in_memory=in_memory) # If original_instructions is not None, convert it to a human-readable NamedSplit if original_instructions is not None: from .splits import Split # noqa split = Split(str(original_instructions)) else: split = None dataset_kwargs = {"arrow_table": pa_table, "info": self._info, "split": split} return dataset_kwargs def download_from_hf_gcs(self, download_config: DownloadConfig, relative_data_dir): """ Download the dataset files from the Hf GCS Args: dl_cache_dir: `str`, the local cache directory used to download files relative_data_dir: `str`, the relative directory of the remote files from the `datasets` directory on GCS. """ remote_cache_dir = HF_GCP_BASE_URL + "/" + relative_data_dir.replace(os.sep, "/") try: remote_dataset_info = os.path.join(remote_cache_dir, "dataset_info.json") downloaded_dataset_info = cached_path(remote_dataset_info.replace(os.sep, "/")) shutil.move(downloaded_dataset_info, os.path.join(self._path, "dataset_info.json")) if self._info is not None: self._info.update(self._info.from_directory(self._path)) except FileNotFoundError as err: raise DatasetNotOnHfGcsError(err) from None try: for split in self._info.splits: file_instructions = self.get_file_instructions( name=self._info.builder_name, instruction=split, split_infos=self._info.splits.values(), ) for file_instruction in file_instructions: file_to_download = str(Path(file_instruction["filename"]).relative_to(self._path)) remote_prepared_filename = os.path.join(remote_cache_dir, file_to_download) downloaded_prepared_filename = cached_path( remote_prepared_filename.replace(os.sep, "/"), download_config=download_config ) shutil.move(downloaded_prepared_filename, file_instruction["filename"]) except FileNotFoundError as err: raise MissingFilesOnHfGcsError(err) from None class ArrowReader(BaseReader): """ Build a Dataset object out of Instruction instance(s). This Reader uses either memory mapping or file descriptors (in-memory) on arrow files. """ def __init__(self, path: str, info: Optional["DatasetInfo"]): """Initializes ArrowReader. Args: path (str): path where Arrow files are stored. info (DatasetInfo): info about the dataset. """ super().__init__(path, info) self._filetype_suffix = "arrow" def _get_table_from_filename(self, filename_skip_take, in_memory=False) -> Table: """Returns a Dataset instance from given (filename, skip, take).""" filename, skip, take = ( filename_skip_take["filename"], filename_skip_take["skip"] if "skip" in filename_skip_take else None, filename_skip_take["take"] if "take" in filename_skip_take else None, ) table = ArrowReader.read_table(filename, in_memory=in_memory) if take == -1: take = len(table) - skip # here we don't want to slice an empty table, or it may segfault if skip is not None and take is not None and not (skip == 0 and take == len(table)): table = table.slice(skip, take) return table @staticmethod def read_table(filename, in_memory=False) -> Table: """ Read table from file. Args: filename (str): File name of the table. in_memory (bool, default=False): Whether to copy the data in-memory. Returns: pyarrow.Table """ table_cls = InMemoryTable if in_memory else MemoryMappedTable return table_cls.from_file(filename) class ParquetReader(BaseReader): """ Build a Dataset object out of Instruction instance(s). This Reader uses memory mapping on parquet files. """ def __init__(self, path: str, info: Optional["DatasetInfo"]): """Initializes ParquetReader. Args: path (str): path where tfrecords are stored. info (DatasetInfo): info about the dataset. """ super().__init__(path, info) self._filetype_suffix = "parquet" def _get_table_from_filename(self, filename_skip_take, **kwargs): """Returns a Dataset instance from given (filename, skip, take).""" filename, skip, take = ( filename_skip_take["filename"], filename_skip_take["skip"] if "skip" in filename_skip_take else None, filename_skip_take["take"] if "take" in filename_skip_take else None, ) # Parquet read_table always loads data in memory, independently of memory_map pa_table = pq.read_table(filename, memory_map=True) # here we don't want to slice an empty table, or it may segfault if skip is not None and take is not None and not (skip == 0 and take == len(pa_table)): pa_table = pa_table.slice(skip, take) return pa_table @dataclass(frozen=True) class _AbsoluteInstruction: """A machine friendly slice: defined absolute positive boundaries.""" splitname: str from_: int # uint (starting index). to: int # uint (ending index). @dataclass(frozen=True) class _RelativeInstruction: """Represents a single parsed slicing instruction, can use % and negatives.""" splitname: str from_: Optional[int] = None # int (starting index) or None if no lower boundary. to: Optional[int] = None # int (ending index) or None if no upper boundary. unit: Optional[str] = None rounding: Optional[str] = None def __post_init__(self): if self.unit is not None and self.unit not in ["%", "abs"]: raise ValueError("unit must be either % or abs") if self.rounding is not None and self.rounding not in ["closest", "pct1_dropremainder"]: raise ValueError("rounding must be either closest or pct1_dropremainder") if self.unit != "%" and self.rounding is not None: raise ValueError("It is forbidden to specify rounding if not using percent slicing.") if self.unit == "%" and self.from_ is not None and abs(self.from_) > 100: raise ValueError("Percent slice boundaries must be > -100 and < 100.") if self.unit == "%" and self.to is not None and abs(self.to) > 100: raise ValueError("Percent slice boundaries must be > -100 and < 100.") # Update via __dict__ due to instance being "frozen" self.__dict__["rounding"] = "closest" if self.rounding is None and self.unit == "%" else self.rounding def _str_to_read_instruction(spec): """Returns ReadInstruction for given string.""" res = _SUB_SPEC_RE.match(spec) if not res: raise ValueError(f"Unrecognized instruction format: {spec}") unit = "%" if res.group("from_pct") or res.group("to_pct") else "abs" return ReadInstruction( split_name=res.group("split"), rounding=res.group("rounding"), from_=int(res.group("from")) if res.group("from") else None, to=int(res.group("to")) if res.group("to") else None, unit=unit, ) def _pct_to_abs_pct1(boundary, num_examples): # Using math.trunc here, since -99.5% should give -99%, not -100%. if num_examples < 100: msg = ( 'Using "pct1_dropremainder" rounding on a split with less than 100 ' "elements is forbidden: it always results in an empty dataset." ) raise ValueError(msg) return boundary * math.trunc(num_examples / 100.0) def _pct_to_abs_closest(boundary, num_examples): return int(round(boundary * num_examples / 100.0)) def _rel_to_abs_instr(rel_instr, name2len): """Returns _AbsoluteInstruction instance for given RelativeInstruction. Args: rel_instr: RelativeInstruction instance. name2len: dict {split_name: num_examples}. """ pct_to_abs = _pct_to_abs_closest if rel_instr.rounding == "closest" else _pct_to_abs_pct1 split = rel_instr.splitname if split not in name2len: raise ValueError(f'Unknown split "{split}". Should be one of {list(name2len)}.') num_examples = name2len[split] from_ = rel_instr.from_ to = rel_instr.to if rel_instr.unit == "%": from_ = 0 if from_ is None else pct_to_abs(from_, num_examples) to = num_examples if to is None else pct_to_abs(to, num_examples) else: from_ = 0 if from_ is None else from_ to = num_examples if to is None else to if abs(from_) > num_examples or abs(to) > num_examples: msg = f'Requested slice [{from_ or ""}:{to or ""}] incompatible with {num_examples} examples.' raise ValueError(msg) if from_ < 0: from_ = num_examples + from_ elif from_ == 0: from_ = None if to < 0: to = num_examples + to elif to == num_examples: to = None return _AbsoluteInstruction(split, from_, to) class ReadInstruction: """Reading instruction for a dataset. Examples:: # 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)]) """ def _init(self, relative_instructions): # Private initializer. self._relative_instructions = relative_instructions @classmethod def _read_instruction_from_relative_instructions(cls, relative_instructions): """Returns ReadInstruction obj initialized with relative_instructions.""" # Use __new__ to bypass __init__ used by public API and not conveniant here. result = cls.__new__(cls) result._init(relative_instructions) # pylint: disable=protected-access return result def __init__(self, split_name, rounding=None, from_=None, to=None, unit=None): """Initialize ReadInstruction. Args: split_name (str): name of the split to read. Eg: 'train'. rounding (str, optional): The rounding behaviour to use when percent slicing is used. Ignored when slicing with absolute indices. Possible values: - 'closest' (default): The specified percentages are rounded to the closest value. Use this if you want specified percents to be as much exact as possible. - 'pct1_dropremainder': the specified percentages are treated as multiple of 1%. Use this option if you want consistency. Eg: len(5%) == 5 * len(1%). Using this option, one might not be able to use the full set of examples, if the number of those is not a multiple of 100. from_ (int): to (int): alternative way of specifying slicing boundaries. If any of {from_, to, unit} argument is used, slicing cannot be specified as string. unit (str): optional, one of: '%': to set the slicing unit as percents of the split size. 'abs': to set the slicing unit as absolute numbers. """ # This constructor is not always called. See factory method # `_read_instruction_from_relative_instructions`. Common init instructions # MUST be placed in the _init method. self._init([_RelativeInstruction(split_name, from_, to, unit, rounding)]) @classmethod def from_spec(cls, spec): """Creates a `ReadInstruction` instance out of a string spec. Args: 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`). Examples: ``` 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. ``` Returns: ReadInstruction instance. """ spec = str(spec) # Need to convert to str in case of NamedSplit instance. subs = _ADDITION_SEP_RE.split(spec) if not subs: raise ValueError(f"No instructions could be built out of {spec}") instruction = _str_to_read_instruction(subs[0]) return sum((_str_to_read_instruction(sub) for sub in subs[1:]), instruction) def to_spec(self): rel_instr_specs = [] for rel_instr in self._relative_instructions: rel_instr_spec = rel_instr.splitname if rel_instr.from_ is not None or rel_instr.to is not None: from_ = rel_instr.from_ to = rel_instr.to unit = rel_instr.unit rounding = rel_instr.rounding unit = unit if unit == "%" else "" from_ = str(from_) + unit if from_ is not None else "" to = str(to) + unit if to is not None else "" slice_str = f"[{from_}:{to}]" rounding_str = ( f"({rounding})" if unit == "%" and rounding is not None and rounding != "closest" else "" ) rel_instr_spec += slice_str + rounding_str rel_instr_specs.append(rel_instr_spec) return "+".join(rel_instr_specs) def __add__(self, other): """Returns a new ReadInstruction obj, result of appending other to self.""" if not isinstance(other, ReadInstruction): msg = "ReadInstruction can only be added to another ReadInstruction obj." raise TypeError(msg) self_ris = self._relative_instructions other_ris = other._relative_instructions # pylint: disable=protected-access if ( self_ris[0].unit != "abs" and other_ris[0].unit != "abs" and self._relative_instructions[0].rounding != other_ris[0].rounding ): raise ValueError("It is forbidden to sum ReadInstruction instances with different rounding values.") return self._read_instruction_from_relative_instructions(self_ris + other_ris) def __str__(self): return self.to_spec() def __repr__(self): return f"ReadInstruction({self._relative_instructions})" def to_absolute(self, name2len): """Translate instruction into a list of absolute instructions. Those absolute instructions are then to be added together. Args: name2len (`dict`): Associating split names to number of examples. Returns: list of _AbsoluteInstruction instances (corresponds to the + in spec). """ return [_rel_to_abs_instr(rel_instr, name2len) for rel_instr in self._relative_instructions]
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/load.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """Access datasets.""" import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union import fsspec import requests import yaml from huggingface_hub import DatasetCard, DatasetCardData, HfApi, HfFileSystem from . import config from .arrow_dataset import Dataset from .builder import BuilderConfig, DatasetBuilder from .data_files import ( DEFAULT_PATTERNS_ALL, DataFilesDict, DataFilesList, DataFilesPatternsDict, DataFilesPatternsList, EmptyDatasetError, get_data_patterns, get_metadata_patterns, sanitize_patterns, ) from .dataset_dict import DatasetDict, IterableDatasetDict from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download.streaming_download_manager import StreamingDownloadManager, xbasename, xglob, xjoin from .exceptions import DataFilesNotFoundError, DatasetNotFoundError from .features import Features from .fingerprint import Hasher from .info import DatasetInfo, DatasetInfosDict from .iterable_dataset import IterableDataset from .metric import Metric from .naming import camelcase_to_snakecase, snakecase_to_camelcase from .packaged_modules import ( _EXTENSION_TO_MODULE, _MODULE_SUPPORTS_METADATA, _MODULE_TO_EXTENSIONS, _PACKAGED_DATASETS_MODULES, _hash_python_lines, ) from .splits import Split from .utils import _datasets_server from .utils._filelock import FileLock from .utils.deprecation_utils import deprecated from .utils.file_utils import ( OfflineModeIsEnabled, _raise_if_offline_mode_is_enabled, cached_path, head_hf_s3, hf_github_url, init_hf_modules, is_relative_path, relative_to_absolute_path, url_or_path_join, ) from .utils.hub import hf_hub_url from .utils.info_utils import VerificationMode, is_small_dataset from .utils.logging import get_logger from .utils.metadata import MetadataConfigs from .utils.py_utils import get_imports from .utils.version import Version logger = get_logger(__name__) ALL_ALLOWED_EXTENSIONS = list(_EXTENSION_TO_MODULE.keys()) + [".zip"] def _raise_timeout_error(signum, frame): raise ValueError( "Loading this dataset requires you to execute custom code contained in the dataset repository on your local " "machine. Please set the option `trust_remote_code=True` to permit loading of this dataset." ) def resolve_trust_remote_code(trust_remote_code: Optional[bool], repo_id: str) -> bool: """ Copied and adapted from Transformers https://github.com/huggingface/transformers/blob/2098d343cc4b4b9d2aea84b3cf1eb5a1e610deff/src/transformers/dynamic_module_utils.py#L589 """ trust_remote_code = trust_remote_code if trust_remote_code is not None else config.HF_DATASETS_TRUST_REMOTE_CODE if trust_remote_code is None: if config.TIME_OUT_REMOTE_CODE > 0: try: signal.signal(signal.SIGALRM, _raise_timeout_error) signal.alarm(config.TIME_OUT_REMOTE_CODE) while trust_remote_code is None: answer = input( f"The repository for {repo_id} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at https://hf.co/datasets/{repo_id}.\n" f"You can avoid this prompt in future by passing the argument `trust_remote_code=True`.\n\n" f"Do you wish to run the custom code? [y/N] " ) if answer.lower() in ["yes", "y", "1"]: trust_remote_code = True elif answer.lower() in ["no", "n", "0", ""]: trust_remote_code = False signal.alarm(0) except Exception: # OS which does not support signal.SIGALRM raise ValueError( f"The repository for {repo_id} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at https://hf.co/datasets/{repo_id}.\n" f"Please pass the argument `trust_remote_code=True` to allow custom code to be run." ) else: # For the CI which might put the timeout at 0 _raise_timeout_error(None, None) return trust_remote_code def init_dynamic_modules( name: str = config.MODULE_NAME_FOR_DYNAMIC_MODULES, hf_modules_cache: Optional[Union[Path, str]] = None ): """ Create a module with name `name` in which you can add dynamic modules such as metrics or datasets. The module can be imported using its name. The module is created in the HF_MODULE_CACHE directory by default (~/.cache/huggingface/modules) but it can be overridden by specifying a path to another directory in `hf_modules_cache`. """ hf_modules_cache = init_hf_modules(hf_modules_cache) dynamic_modules_path = os.path.join(hf_modules_cache, name) os.makedirs(dynamic_modules_path, exist_ok=True) if not os.path.exists(os.path.join(dynamic_modules_path, "__init__.py")): with open(os.path.join(dynamic_modules_path, "__init__.py"), "w"): pass return dynamic_modules_path def import_main_class(module_path, dataset=True) -> Optional[Union[Type[DatasetBuilder], Type[Metric]]]: """Import a module at module_path and return its main class: - a DatasetBuilder if dataset is True - a Metric if dataset is False """ module = importlib.import_module(module_path) if dataset: main_cls_type = DatasetBuilder else: main_cls_type = Metric # Find the main class in our imported module module_main_cls = None for name, obj in module.__dict__.items(): if inspect.isclass(obj) and issubclass(obj, main_cls_type): if inspect.isabstract(obj): continue module_main_cls = obj obj_module = inspect.getmodule(obj) if obj_module is not None and module == obj_module: break return module_main_cls class _InitializeConfiguredDatasetBuilder: """ From https://stackoverflow.com/questions/4647566/pickle-a-dynamically-parameterized-sub-class See also ConfiguredDatasetBuilder.__reduce__ When called with the param value as the only argument, returns an un-initialized instance of the parameterized class. Subsequent __setstate__ will be called by pickle. """ def __call__(self, builder_cls, metadata_configs, default_config_name, name): # make a simple object which has no complex __init__ (this one will do) obj = _InitializeConfiguredDatasetBuilder() obj.__class__ = configure_builder_class( builder_cls, metadata_configs, default_config_name=default_config_name, dataset_name=name ) return obj def configure_builder_class( builder_cls: Type[DatasetBuilder], builder_configs: List[BuilderConfig], default_config_name: Optional[str], dataset_name: str, ) -> Type[DatasetBuilder]: """ Dynamically create a builder class with custom builder configs parsed from README.md file, i.e. set BUILDER_CONFIGS class variable of a builder class to custom configs list. """ class ConfiguredDatasetBuilder(builder_cls): BUILDER_CONFIGS = builder_configs DEFAULT_CONFIG_NAME = default_config_name __module__ = builder_cls.__module__ # so that the actual packaged builder can be imported def __reduce__(self): # to make dynamically created class pickable, see _InitializeParameterizedDatasetBuilder parent_builder_cls = self.__class__.__mro__[1] return ( _InitializeConfiguredDatasetBuilder(), ( parent_builder_cls, self.BUILDER_CONFIGS, self.DEFAULT_CONFIG_NAME, self.dataset_name, ), self.__dict__.copy(), ) ConfiguredDatasetBuilder.__name__ = ( f"{builder_cls.__name__.lower().capitalize()}{snakecase_to_camelcase(dataset_name)}" ) ConfiguredDatasetBuilder.__qualname__ = ( f"{builder_cls.__name__.lower().capitalize()}{snakecase_to_camelcase(dataset_name)}" ) return ConfiguredDatasetBuilder def get_dataset_builder_class( dataset_module: "DatasetModule", dataset_name: Optional[str] = None ) -> Type[DatasetBuilder]: builder_cls = import_main_class(dataset_module.module_path) if dataset_module.builder_configs_parameters.builder_configs: dataset_name = dataset_name or dataset_module.builder_kwargs.get("dataset_name") if dataset_name is None: raise ValueError("dataset_name should be specified but got None") builder_cls = configure_builder_class( builder_cls, builder_configs=dataset_module.builder_configs_parameters.builder_configs, default_config_name=dataset_module.builder_configs_parameters.default_config_name, dataset_name=dataset_name, ) return builder_cls def files_to_hash(file_paths: List[str]) -> str: """ Convert a list of scripts or text files provided in file_paths into a hashed filename in a repeatable way. """ # List all python files in directories if directories are supplied as part of external imports to_use_files: List[Union[Path, str]] = [] for file_path in file_paths: if os.path.isdir(file_path): to_use_files.extend(list(Path(file_path).rglob("*.[pP][yY]"))) else: to_use_files.append(file_path) # Get the code from all these files lines = [] for file_path in to_use_files: with open(file_path, encoding="utf-8") as f: lines.extend(f.readlines()) return _hash_python_lines(lines) def increase_load_count(name: str, resource_type: str): """Update the download count of a dataset or metric.""" if not config.HF_DATASETS_OFFLINE and config.HF_UPDATE_DOWNLOAD_COUNTS: try: head_hf_s3(name, filename=name + ".py", dataset=(resource_type == "dataset")) except Exception: pass def _download_additional_modules( name: str, base_path: str, imports: Tuple[str, str, str, str], download_config: Optional[DownloadConfig] ) -> List[Tuple[str, str]]: """ Download additional module for a module <name>.py at URL (or local path) <base_path>/<name>.py The imports must have been parsed first using ``get_imports``. If some modules need to be installed with pip, an error is raised showing how to install them. This function return the list of downloaded modules as tuples (import_name, module_file_path). The downloaded modules can then be moved into an importable directory with ``_copy_script_and_other_resources_in_importable_dir``. """ local_imports = [] library_imports = [] download_config = download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading extra modules" for import_type, import_name, import_path, sub_directory in imports: if import_type == "library": library_imports.append((import_name, import_path)) # Import from a library continue if import_name == name: raise ValueError( f"Error in the {name} script, importing relative {import_name} module " f"but {import_name} is the name of the script. " f"Please change relative import {import_name} to another name and add a '# From: URL_OR_PATH' " f"comment pointing to the original relative import file path." ) if import_type == "internal": url_or_filename = url_or_path_join(base_path, import_path + ".py") elif import_type == "external": url_or_filename = import_path else: raise ValueError("Wrong import_type") local_import_path = cached_path( url_or_filename, download_config=download_config, ) if sub_directory is not None: local_import_path = os.path.join(local_import_path, sub_directory) local_imports.append((import_name, local_import_path)) # Check library imports needs_to_be_installed = {} for library_import_name, library_import_path in library_imports: try: lib = importlib.import_module(library_import_name) # noqa F841 except ImportError: if library_import_name not in needs_to_be_installed or library_import_path != library_import_name: needs_to_be_installed[library_import_name] = library_import_path if needs_to_be_installed: _dependencies_str = "dependencies" if len(needs_to_be_installed) > 1 else "dependency" _them_str = "them" if len(needs_to_be_installed) > 1 else "it" if "sklearn" in needs_to_be_installed.keys(): needs_to_be_installed["sklearn"] = "scikit-learn" raise ImportError( f"To be able to use {name}, you need to install the following {_dependencies_str}: " f"{', '.join(needs_to_be_installed)}.\nPlease install {_them_str} using 'pip install " f"{' '.join(needs_to_be_installed.values())}' for instance." ) return local_imports def _copy_script_and_other_resources_in_importable_dir( name: str, importable_directory_path: str, subdirectory_name: str, original_local_path: str, local_imports: List[Tuple[str, str]], additional_files: List[Tuple[str, str]], download_mode: Optional[Union[DownloadMode, str]], ) -> str: """Copy a script and its required imports to an importable directory Args: name (str): name of the resource to load importable_directory_path (str): path to the loadable folder in the dynamic modules directory subdirectory_name (str): name of the subdirectory in importable_directory_path in which to place the script original_local_path (str): local path to the resource script local_imports (List[Tuple[str, str]]): list of (destination_filename, import_file_to_copy) additional_files (List[Tuple[str, str]]): list of (destination_filename, additional_file_to_copy) download_mode (Optional[Union[DownloadMode, str]]): download mode Return: importable_local_file: path to an importable module with importlib.import_module """ # Define a directory with a unique name in our dataset or metric folder # path is: ./datasets|metrics/dataset|metric_name/hash_from_code/script.py # we use a hash as subdirectory_name to be able to have multiple versions of a dataset/metric processing file together importable_subdirectory = os.path.join(importable_directory_path, subdirectory_name) importable_local_file = os.path.join(importable_subdirectory, name + ".py") # Prevent parallel disk operations lock_path = importable_directory_path + ".lock" with FileLock(lock_path): # Create main dataset/metrics folder if needed if download_mode == DownloadMode.FORCE_REDOWNLOAD and os.path.exists(importable_directory_path): shutil.rmtree(importable_directory_path) os.makedirs(importable_directory_path, exist_ok=True) # add an __init__ file to the main dataset folder if needed init_file_path = os.path.join(importable_directory_path, "__init__.py") if not os.path.exists(init_file_path): with open(init_file_path, "w"): pass # Create hash dataset folder if needed os.makedirs(importable_subdirectory, exist_ok=True) # add an __init__ file to the hash dataset folder if needed init_file_path = os.path.join(importable_subdirectory, "__init__.py") if not os.path.exists(init_file_path): with open(init_file_path, "w"): pass # Copy dataset.py file in hash folder if needed if not os.path.exists(importable_local_file): shutil.copyfile(original_local_path, importable_local_file) # Record metadata associating original dataset path with local unique folder # Use os.path.splitext to split extension from importable_local_file meta_path = os.path.splitext(importable_local_file)[0] + ".json" if not os.path.exists(meta_path): meta = {"original file path": original_local_path, "local file path": importable_local_file} # the filename is *.py in our case, so better rename to filename.json instead of filename.py.json with open(meta_path, "w", encoding="utf-8") as meta_file: json.dump(meta, meta_file) # Copy all the additional imports for import_name, import_path in local_imports: if os.path.isfile(import_path): full_path_local_import = os.path.join(importable_subdirectory, import_name + ".py") if not os.path.exists(full_path_local_import): shutil.copyfile(import_path, full_path_local_import) elif os.path.isdir(import_path): full_path_local_import = os.path.join(importable_subdirectory, import_name) if not os.path.exists(full_path_local_import): shutil.copytree(import_path, full_path_local_import) else: raise ImportError(f"Error with local import at {import_path}") # Copy additional files like dataset_infos.json file if needed for file_name, original_path in additional_files: destination_additional_path = os.path.join(importable_subdirectory, file_name) if not os.path.exists(destination_additional_path) or not filecmp.cmp( original_path, destination_additional_path ): shutil.copyfile(original_path, destination_additional_path) return importable_local_file def _get_importable_file_path( dynamic_modules_path: str, module_namespace: str, subdirectory_name: str, name: str, ) -> str: importable_directory_path = os.path.join(dynamic_modules_path, module_namespace, name.replace("/", "--")) return os.path.join(importable_directory_path, subdirectory_name, name + ".py") def _create_importable_file( local_path: str, local_imports: List[Tuple[str, str]], additional_files: List[Tuple[str, str]], dynamic_modules_path: str, module_namespace: str, subdirectory_name: str, name: str, download_mode: DownloadMode, ) -> None: importable_directory_path = os.path.join(dynamic_modules_path, module_namespace, name.replace("/", "--")) Path(importable_directory_path).mkdir(parents=True, exist_ok=True) (Path(importable_directory_path).parent / "__init__.py").touch(exist_ok=True) importable_local_file = _copy_script_and_other_resources_in_importable_dir( name=name.split("/")[-1], importable_directory_path=importable_directory_path, subdirectory_name=subdirectory_name, original_local_path=local_path, local_imports=local_imports, additional_files=additional_files, download_mode=download_mode, ) logger.debug(f"Created importable dataset file at {importable_local_file}") def _load_importable_file( dynamic_modules_path: str, module_namespace: str, subdirectory_name: str, name: str, ) -> Tuple[str, str]: module_path = ".".join( [ os.path.basename(dynamic_modules_path), module_namespace, name.replace("/", "--"), subdirectory_name, name.split("/")[-1], ] ) return module_path, subdirectory_name def infer_module_for_data_files_list( data_files_list: DataFilesList, download_config: Optional[DownloadConfig] = None ) -> Tuple[Optional[str], dict]: """Infer module (and builder kwargs) from list of data files. It picks the module based on the most common file extension. In case of a draw ".parquet" is the favorite, and then alphabetical order. Args: data_files_list (DataFilesList): List of data files. download_config (bool or str, optional): mainly use use_auth_token or storage_options to support different platforms and auth types. Returns: tuple[str, dict[str, Any]]: Tuple with - inferred module name - dict of builder kwargs """ extensions_counter = Counter( ("." + suffix.lower(), xbasename(filepath) in ("metadata.jsonl", "metadata.csv")) for filepath in data_files_list[: config.DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE] for suffix in xbasename(filepath).split(".")[1:] ) if extensions_counter: def sort_key(ext_count: Tuple[Tuple[str, bool], int]) -> Tuple[int, bool]: """Sort by count and set ".parquet" as the favorite in case of a draw, and ignore metadata files""" (ext, is_metadata), count = ext_count return (not is_metadata, count, ext == ".parquet", ext) for (ext, _), _ in sorted(extensions_counter.items(), key=sort_key, reverse=True): if ext in _EXTENSION_TO_MODULE: return _EXTENSION_TO_MODULE[ext] elif ext == ".zip": return infer_module_for_data_files_list_in_archives(data_files_list, download_config=download_config) return None, {} def infer_module_for_data_files_list_in_archives( data_files_list: DataFilesList, download_config: Optional[DownloadConfig] = None ) -> Tuple[Optional[str], dict]: """Infer module (and builder kwargs) from list of archive data files. Args: data_files_list (DataFilesList): List of data files. download_config (bool or str, optional): mainly use use_auth_token or storage_options to support different platforms and auth types. Returns: tuple[str, dict[str, Any]]: Tuple with - inferred module name - dict of builder kwargs """ archived_files = [] archive_files_counter = 0 for filepath in data_files_list: if str(filepath).endswith(".zip"): archive_files_counter += 1 if archive_files_counter > config.GLOBBED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE: break extracted = xjoin(StreamingDownloadManager().extract(filepath), "**") archived_files += [ f.split("::")[0] for f in xglob(extracted, recursive=True, download_config=download_config)[ : config.ARCHIVED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE ] ] extensions_counter = Counter( "." + suffix.lower() for filepath in archived_files for suffix in xbasename(filepath).split(".")[1:] ) if extensions_counter: most_common = extensions_counter.most_common(1)[0][0] if most_common in _EXTENSION_TO_MODULE: return _EXTENSION_TO_MODULE[most_common] return None, {} def infer_module_for_data_files( data_files: DataFilesDict, path: Optional[str] = None, download_config: Optional[DownloadConfig] = None ) -> Tuple[Optional[str], Dict[str, Any]]: """Infer module (and builder kwargs) from data files. Raise if module names for different splits don't match. Args: data_files ([`DataFilesDict`]): Dict of list of data files. path (str, *optional*): Dataset name or path. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters to authenticate on the Hugging Face Hub for private remote files. Returns: tuple[str, dict[str, Any]]: Tuple with - inferred module name - builder kwargs """ split_modules = { split: infer_module_for_data_files_list(data_files_list, download_config=download_config) for split, data_files_list in data_files.items() } module_name, default_builder_kwargs = next(iter(split_modules.values())) if any((module_name, default_builder_kwargs) != split_module for split_module in split_modules.values()): raise ValueError(f"Couldn't infer the same data file format for all splits. Got {split_modules}") if not module_name: raise DataFilesNotFoundError("No (supported) data files found" + (f" in {path}" if path else "")) return module_name, default_builder_kwargs def create_builder_configs_from_metadata_configs( module_path: str, metadata_configs: MetadataConfigs, supports_metadata: bool, base_path: Optional[str] = None, default_builder_kwargs: Dict[str, Any] = None, download_config: Optional[DownloadConfig] = None, ) -> Tuple[List[BuilderConfig], str]: builder_cls = import_main_class(module_path) builder_config_cls = builder_cls.BUILDER_CONFIG_CLASS default_config_name = metadata_configs.get_default_config_name() builder_configs = [] default_builder_kwargs = {} if default_builder_kwargs is None else default_builder_kwargs base_path = base_path if base_path is not None else "" for config_name, config_params in metadata_configs.items(): config_data_files = config_params.get("data_files") config_data_dir = config_params.get("data_dir") config_base_path = xjoin(base_path, config_data_dir) if config_data_dir else base_path try: config_patterns = ( sanitize_patterns(config_data_files) if config_data_files is not None else get_data_patterns(config_base_path) ) config_data_files_dict = DataFilesPatternsDict.from_patterns( config_patterns, allowed_extensions=ALL_ALLOWED_EXTENSIONS, ) except EmptyDatasetError as e: raise EmptyDatasetError( f"Dataset at '{base_path}' doesn't contain data files matching the patterns for config '{config_name}'," f" check `data_files` and `data_fir` parameters in the `configs` YAML field in README.md. " ) from e if config_data_files is None and supports_metadata and config_patterns != DEFAULT_PATTERNS_ALL: try: config_metadata_patterns = get_metadata_patterns(base_path, download_config=download_config) except FileNotFoundError: config_metadata_patterns = None if config_metadata_patterns is not None: config_metadata_data_files_list = DataFilesPatternsList.from_patterns(config_metadata_patterns) config_data_files_dict = DataFilesPatternsDict( { split: data_files_list + config_metadata_data_files_list for split, data_files_list in config_data_files_dict.items() } ) ignored_params = [ param for param in config_params if not hasattr(builder_config_cls, param) and param != "default" ] if ignored_params: logger.warning( f"Some datasets params were ignored: {ignored_params}. " "Make sure to use only valid params for the dataset builder and to have " "a up-to-date version of the `datasets` library." ) builder_configs.append( builder_config_cls( name=config_name, data_files=config_data_files_dict, data_dir=config_data_dir, **{ param: value for param, value in {**default_builder_kwargs, **config_params}.items() if hasattr(builder_config_cls, param) and param not in ("default", "data_files", "data_dir") }, ) ) return builder_configs, default_config_name @dataclass class BuilderConfigsParameters: """Dataclass containing objects related to creation of builder configurations from yaml's metadata content. Attributes: metadata_configs (`MetadataConfigs`, *optional*): Configs parsed from yaml's metadata. builder_configs (`list[BuilderConfig]`, *optional*): List of BuilderConfig objects created from metadata_configs above. default_config_name (`str`): Name of default config taken from yaml's metadata. """ metadata_configs: Optional[MetadataConfigs] = None builder_configs: Optional[List[BuilderConfig]] = None default_config_name: Optional[str] = None @dataclass class DatasetModule: module_path: str hash: str builder_kwargs: dict builder_configs_parameters: BuilderConfigsParameters = field(default_factory=BuilderConfigsParameters) dataset_infos: Optional[DatasetInfosDict] = None @dataclass class MetricModule: module_path: str hash: str class _DatasetModuleFactory: def get_module(self) -> DatasetModule: raise NotImplementedError class _MetricModuleFactory: def get_module(self) -> MetricModule: raise NotImplementedError class GithubMetricModuleFactory(_MetricModuleFactory): """Get the module of a metric. The metric script is downloaded from GitHub. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, name: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[str] = None, ): self.name = name self.revision = revision self.download_config = download_config.copy() if download_config else DownloadConfig() if self.download_config.max_retries < 3: self.download_config.max_retries = 3 self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code assert self.name.count("/") == 0 increase_load_count(name, resource_type="metric") def download_loading_script(self, revision: Optional[str]) -> str: file_path = hf_github_url(path=self.name, name=self.name + ".py", revision=revision, dataset=False) download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading builder script" return cached_path(file_path, download_config=download_config) def get_module(self) -> MetricModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: _loading_script_url = hf_github_url( path=self.name, name=self.name + ".py", revision=self.revision, dataset=False ) warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the metric. You can inspect the repository content at {_loading_script_url}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this metric from the next major release of `datasets`.", FutureWarning, ) # get script and other files revision = self.revision try: local_path = self.download_loading_script(revision) revision = self.revision except FileNotFoundError: if revision is not None: raise else: revision = "main" local_path = self.download_loading_script(revision) logger.warning( f"Couldn't find a directory or a metric named '{self.name}' in this version. " f"It was picked from the main branch on github instead." ) imports = get_imports(local_path) local_imports = _download_additional_modules( name=self.name, base_path=hf_github_url(path=self.name, name="", revision=revision, dataset=False), imports=imports, download_config=self.download_config, ) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([local_path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=local_path, local_imports=local_imports, additional_files=[], dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() return MetricModule(module_path, hash) class LocalMetricModuleFactory(_MetricModuleFactory): """Get the module of a local metric. The metric script is loaded from a local script. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, path: str, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[str] = None, ): self.path = path self.name = Path(path).stem self.download_config = download_config or DownloadConfig() self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code def get_module(self) -> MetricModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the metric. You can inspect the repository content at {self.path}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this metric from the next major release of `datasets`.", FutureWarning, ) # get script and other files imports = get_imports(self.path) local_imports = _download_additional_modules( name=self.name, base_path=str(Path(self.path).parent), imports=imports, download_config=self.download_config, ) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([self.path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=self.path, local_imports=local_imports, additional_files=[], dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() return MetricModule(module_path, hash) class LocalDatasetModuleFactoryWithScript(_DatasetModuleFactory): """Get the module of a local dataset. The dataset script is loaded from a local script.""" def __init__( self, path: str, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[bool] = None, ): self.path = path self.name = Path(path).stem self.download_config = download_config or DownloadConfig() self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code def get_module(self) -> DatasetModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at {self.path}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.", FutureWarning, ) # get script and other files dataset_infos_path = Path(self.path).parent / config.DATASETDICT_INFOS_FILENAME dataset_readme_path = Path(self.path).parent / config.REPOCARD_FILENAME imports = get_imports(self.path) local_imports = _download_additional_modules( name=self.name, base_path=str(Path(self.path).parent), imports=imports, download_config=self.download_config, ) additional_files = [] if dataset_infos_path.is_file(): additional_files.append((config.DATASETDICT_INFOS_FILENAME, str(dataset_infos_path))) if dataset_readme_path.is_file(): additional_files.append((config.REPOCARD_FILENAME, dataset_readme_path)) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([self.path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=self.path, local_imports=local_imports, additional_files=additional_files, dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() builder_kwargs = {"base_path": str(Path(self.path).parent)} return DatasetModule(module_path, hash, builder_kwargs) class LocalDatasetModuleFactoryWithoutScript(_DatasetModuleFactory): """Get the module of a dataset loaded from the user's data files. The dataset builder module to use is inferred from the data files extensions.""" def __init__( self, path: str, data_dir: Optional[str] = None, data_files: Optional[Union[str, List, Dict]] = None, download_mode: Optional[Union[DownloadMode, str]] = None, ): if data_dir and os.path.isabs(data_dir): raise ValueError(f"`data_dir` must be relative to a dataset directory's root: {path}") self.path = Path(path).as_posix() self.name = Path(path).stem self.data_files = data_files self.data_dir = data_dir self.download_mode = download_mode def get_module(self) -> DatasetModule: readme_path = os.path.join(self.path, config.REPOCARD_FILENAME) standalone_yaml_path = os.path.join(self.path, config.REPOYAML_FILENAME) dataset_card_data = DatasetCard.load(readme_path).data if os.path.isfile(readme_path) else DatasetCardData() if os.path.exists(standalone_yaml_path): with open(standalone_yaml_path, "r", encoding="utf-8") as f: standalone_yaml_data = yaml.safe_load(f.read()) if standalone_yaml_data: _dataset_card_data_dict = dataset_card_data.to_dict() _dataset_card_data_dict.update(standalone_yaml_data) dataset_card_data = DatasetCardData(**_dataset_card_data_dict) metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card_data) dataset_infos = DatasetInfosDict.from_dataset_card_data(dataset_card_data) # we need a set of data files to find which dataset builder to use # because we need to infer module name by files extensions base_path = Path(self.path, self.data_dir or "").expanduser().resolve().as_posix() if self.data_files is not None: patterns = sanitize_patterns(self.data_files) elif metadata_configs and "data_files" in next(iter(metadata_configs.values())): patterns = sanitize_patterns(next(iter(metadata_configs.values()))["data_files"]) else: patterns = get_data_patterns(base_path) data_files = DataFilesDict.from_patterns( patterns, base_path=base_path, allowed_extensions=ALL_ALLOWED_EXTENSIONS, ) module_name, default_builder_kwargs = infer_module_for_data_files( data_files=data_files, path=self.path, ) data_files = data_files.filter_extensions(_MODULE_TO_EXTENSIONS[module_name]) # Collect metadata files if the module supports them supports_metadata = module_name in _MODULE_SUPPORTS_METADATA if self.data_files is None and supports_metadata: try: metadata_patterns = get_metadata_patterns(base_path) except FileNotFoundError: metadata_patterns = None if metadata_patterns is not None: metadata_data_files_list = DataFilesList.from_patterns(metadata_patterns, base_path=base_path) if metadata_data_files_list: data_files = DataFilesDict( { split: data_files_list + metadata_data_files_list for split, data_files_list in data_files.items() } ) module_path, _ = _PACKAGED_DATASETS_MODULES[module_name] if metadata_configs: builder_configs, default_config_name = create_builder_configs_from_metadata_configs( module_path, metadata_configs, base_path=base_path, supports_metadata=supports_metadata, default_builder_kwargs=default_builder_kwargs, ) else: builder_configs: List[BuilderConfig] = [ import_main_class(module_path).BUILDER_CONFIG_CLASS( data_files=data_files, **default_builder_kwargs, ) ] default_config_name = None builder_kwargs = { "base_path": self.path, "dataset_name": camelcase_to_snakecase(Path(self.path).name), } # this file is deprecated and was created automatically in old versions of push_to_hub if os.path.isfile(os.path.join(self.path, config.DATASETDICT_INFOS_FILENAME)): with open(os.path.join(self.path, config.DATASETDICT_INFOS_FILENAME), encoding="utf-8") as f: legacy_dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(dataset_info_dict) for config_name, dataset_info_dict in json.load(f).items() } ) if len(legacy_dataset_infos) == 1: # old config e.g. named "username--dataset_name" legacy_config_name = next(iter(legacy_dataset_infos)) legacy_dataset_infos["default"] = legacy_dataset_infos.pop(legacy_config_name) legacy_dataset_infos.update(dataset_infos) dataset_infos = legacy_dataset_infos if default_config_name is None and len(dataset_infos) == 1: default_config_name = next(iter(dataset_infos)) hash = Hasher.hash({"dataset_infos": dataset_infos, "builder_configs": builder_configs}) return DatasetModule( module_path, hash, builder_kwargs, dataset_infos=dataset_infos, builder_configs_parameters=BuilderConfigsParameters( metadata_configs=metadata_configs, builder_configs=builder_configs, default_config_name=default_config_name, ), ) class PackagedDatasetModuleFactory(_DatasetModuleFactory): """Get the dataset builder module from the ones that are packaged with the library: csv, json, etc.""" def __init__( self, name: str, data_dir: Optional[str] = None, data_files: Optional[Union[str, List, Dict]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, ): self.name = name self.data_files = data_files self.data_dir = data_dir self.download_config = download_config self.download_mode = download_mode increase_load_count(name, resource_type="dataset") def get_module(self) -> DatasetModule: base_path = Path(self.data_dir or "").expanduser().resolve().as_posix() patterns = sanitize_patterns(self.data_files) if self.data_files is not None else get_data_patterns(base_path) data_files = DataFilesDict.from_patterns( patterns, download_config=self.download_config, base_path=base_path, ) supports_metadata = self.name in _MODULE_SUPPORTS_METADATA if self.data_files is None and supports_metadata and patterns != DEFAULT_PATTERNS_ALL: try: metadata_patterns = get_metadata_patterns(base_path, download_config=self.download_config) except FileNotFoundError: metadata_patterns = None if metadata_patterns is not None: metadata_data_files_list = DataFilesList.from_patterns( metadata_patterns, download_config=self.download_config, base_path=base_path ) if metadata_data_files_list: data_files = DataFilesDict( { split: data_files_list + metadata_data_files_list for split, data_files_list in data_files.items() } ) module_path, hash = _PACKAGED_DATASETS_MODULES[self.name] builder_kwargs = { "data_files": data_files, "dataset_name": self.name, } return DatasetModule(module_path, hash, builder_kwargs) class HubDatasetModuleFactoryWithoutScript(_DatasetModuleFactory): """ Get the module of a dataset loaded from data files of a dataset repository. The dataset builder module to use is inferred from the data files extensions. """ def __init__( self, name: str, revision: Optional[Union[str, Version]] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, List, Dict]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, ): self.name = name self.revision = revision self.data_files = data_files self.data_dir = data_dir self.download_config = download_config or DownloadConfig() self.download_mode = download_mode increase_load_count(name, resource_type="dataset") def get_module(self) -> DatasetModule: hfh_dataset_info = HfApi(config.HF_ENDPOINT).dataset_info( self.name, revision=self.revision, token=self.download_config.token, timeout=100.0, ) # even if metadata_configs is not None (which means that we will resolve files for each config later) # we cannot skip resolving all files because we need to infer module name by files extensions revision = hfh_dataset_info.sha # fix the revision in case there are new commits in the meantime base_path = f"hf://datasets/{self.name}@{revision}/{self.data_dir or ''}".rstrip("/") download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading readme" try: dataset_readme_path = cached_path( hf_hub_url(self.name, config.REPOCARD_FILENAME, revision=revision), download_config=download_config, ) dataset_card_data = DatasetCard.load(Path(dataset_readme_path)).data except FileNotFoundError: dataset_card_data = DatasetCardData() download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading standalone yaml" try: standalone_yaml_path = cached_path( hf_hub_url(self.name, config.REPOYAML_FILENAME, revision=revision), download_config=download_config, ) with open(standalone_yaml_path, "r", encoding="utf-8") as f: standalone_yaml_data = yaml.safe_load(f.read()) if standalone_yaml_data: _dataset_card_data_dict = dataset_card_data.to_dict() _dataset_card_data_dict.update(standalone_yaml_data) dataset_card_data = DatasetCardData(**_dataset_card_data_dict) except FileNotFoundError: pass metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card_data) dataset_infos = DatasetInfosDict.from_dataset_card_data(dataset_card_data) # we need a set of data files to find which dataset builder to use # because we need to infer module name by files extensions if self.data_files is not None: patterns = sanitize_patterns(self.data_files) elif metadata_configs and "data_files" in next(iter(metadata_configs.values())): patterns = sanitize_patterns(next(iter(metadata_configs.values()))["data_files"]) else: patterns = get_data_patterns(base_path, download_config=self.download_config) data_files = DataFilesDict.from_patterns( patterns, base_path=base_path, allowed_extensions=ALL_ALLOWED_EXTENSIONS, download_config=self.download_config, ) module_name, default_builder_kwargs = infer_module_for_data_files( data_files=data_files, path=self.name, download_config=self.download_config, ) data_files = data_files.filter_extensions(_MODULE_TO_EXTENSIONS[module_name]) # Collect metadata files if the module supports them supports_metadata = module_name in _MODULE_SUPPORTS_METADATA if self.data_files is None and supports_metadata: try: metadata_patterns = get_metadata_patterns(base_path, download_config=self.download_config) except FileNotFoundError: metadata_patterns = None if metadata_patterns is not None: metadata_data_files_list = DataFilesList.from_patterns( metadata_patterns, download_config=self.download_config, base_path=base_path ) if metadata_data_files_list: data_files = DataFilesDict( { split: data_files_list + metadata_data_files_list for split, data_files_list in data_files.items() } ) module_path, _ = _PACKAGED_DATASETS_MODULES[module_name] if metadata_configs: builder_configs, default_config_name = create_builder_configs_from_metadata_configs( module_path, metadata_configs, base_path=base_path, supports_metadata=supports_metadata, default_builder_kwargs=default_builder_kwargs, download_config=self.download_config, ) else: builder_configs: List[BuilderConfig] = [ import_main_class(module_path).BUILDER_CONFIG_CLASS( data_files=data_files, **default_builder_kwargs, ) ] default_config_name = None builder_kwargs = { "base_path": hf_hub_url(self.name, "", revision=revision).rstrip("/"), "repo_id": self.name, "dataset_name": camelcase_to_snakecase(Path(self.name).name), } download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading metadata" try: # this file is deprecated and was created automatically in old versions of push_to_hub dataset_infos_path = cached_path( hf_hub_url(self.name, config.DATASETDICT_INFOS_FILENAME, revision=revision), download_config=download_config, ) with open(dataset_infos_path, encoding="utf-8") as f: legacy_dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(dataset_info_dict) for config_name, dataset_info_dict in json.load(f).items() } ) if len(legacy_dataset_infos) == 1: # old config e.g. named "username--dataset_name" legacy_config_name = next(iter(legacy_dataset_infos)) legacy_dataset_infos["default"] = legacy_dataset_infos.pop(legacy_config_name) legacy_dataset_infos.update(dataset_infos) dataset_infos = legacy_dataset_infos except FileNotFoundError: pass if default_config_name is None and len(dataset_infos) == 1: default_config_name = next(iter(dataset_infos)) hash = revision return DatasetModule( module_path, hash, builder_kwargs, dataset_infos=dataset_infos, builder_configs_parameters=BuilderConfigsParameters( metadata_configs=metadata_configs, builder_configs=builder_configs, default_config_name=default_config_name, ), ) class HubDatasetModuleFactoryWithParquetExport(_DatasetModuleFactory): """ Get the module of a dataset loaded from parquet files of a dataset repository parquet export. """ def __init__( self, name: str, revision: Optional[str] = None, download_config: Optional[DownloadConfig] = None, ): self.name = name self.revision = revision self.download_config = download_config or DownloadConfig() increase_load_count(name, resource_type="dataset") def get_module(self) -> DatasetModule: exported_parquet_files = _datasets_server.get_exported_parquet_files( dataset=self.name, revision=self.revision, token=self.download_config.token ) exported_dataset_infos = _datasets_server.get_exported_dataset_infos( dataset=self.name, revision=self.revision, token=self.download_config.token ) dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(exported_dataset_infos[config_name]) for config_name in exported_dataset_infos } ) hfh_dataset_info = HfApi(config.HF_ENDPOINT).dataset_info( self.name, revision="refs/convert/parquet", token=self.download_config.token, timeout=100.0, ) revision = hfh_dataset_info.sha # fix the revision in case there are new commits in the meantime metadata_configs = MetadataConfigs._from_exported_parquet_files_and_dataset_infos( revision=revision, exported_parquet_files=exported_parquet_files, dataset_infos=dataset_infos ) module_path, _ = _PACKAGED_DATASETS_MODULES["parquet"] builder_configs, default_config_name = create_builder_configs_from_metadata_configs( module_path, metadata_configs, supports_metadata=False, download_config=self.download_config, ) hash = self.revision builder_kwargs = { "repo_id": self.name, "dataset_name": camelcase_to_snakecase(Path(self.name).name), } return DatasetModule( module_path, hash, builder_kwargs, dataset_infos=dataset_infos, builder_configs_parameters=BuilderConfigsParameters( metadata_configs=metadata_configs, builder_configs=builder_configs, default_config_name=default_config_name, ), ) class HubDatasetModuleFactoryWithScript(_DatasetModuleFactory): """ Get the module of a dataset from a dataset repository. The dataset script comes from the script inside the dataset repository. """ def __init__( self, name: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[bool] = None, ): self.name = name self.revision = revision self.download_config = download_config or DownloadConfig() self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code increase_load_count(name, resource_type="dataset") def download_loading_script(self) -> str: file_path = hf_hub_url(self.name, self.name.split("/")[-1] + ".py", revision=self.revision) download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading builder script" return cached_path(file_path, download_config=download_config) def download_dataset_infos_file(self) -> str: dataset_infos = hf_hub_url(self.name, config.DATASETDICT_INFOS_FILENAME, revision=self.revision) # Download the dataset infos file if available download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading metadata" try: return cached_path( dataset_infos, download_config=download_config, ) except (FileNotFoundError, ConnectionError): return None def download_dataset_readme_file(self) -> str: readme_url = hf_hub_url(self.name, config.REPOCARD_FILENAME, revision=self.revision) # Download the dataset infos file if available download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading readme" try: return cached_path( readme_url, download_config=download_config, ) except (FileNotFoundError, ConnectionError): return None def get_module(self) -> DatasetModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at https://hf.co/datasets/{self.name}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.", FutureWarning, ) # get script and other files local_path = self.download_loading_script() dataset_infos_path = self.download_dataset_infos_file() dataset_readme_path = self.download_dataset_readme_file() imports = get_imports(local_path) local_imports = _download_additional_modules( name=self.name, base_path=hf_hub_url(self.name, "", revision=self.revision), imports=imports, download_config=self.download_config, ) additional_files = [] if dataset_infos_path: additional_files.append((config.DATASETDICT_INFOS_FILENAME, dataset_infos_path)) if dataset_readme_path: additional_files.append((config.REPOCARD_FILENAME, dataset_readme_path)) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([local_path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=local_path, local_imports=local_imports, additional_files=additional_files, dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() builder_kwargs = { "base_path": hf_hub_url(self.name, "", revision=self.revision).rstrip("/"), "repo_id": self.name, } return DatasetModule(module_path, hash, builder_kwargs) class CachedDatasetModuleFactory(_DatasetModuleFactory): """ Get the module of a dataset that has been loaded once already and cached. The script that is loaded from the cache is the most recent one with a matching name. """ def __init__( self, name: str, cache_dir: Optional[str] = None, dynamic_modules_path: Optional[str] = None, ): self.name = name self.cache_dir = cache_dir self.dynamic_modules_path = dynamic_modules_path assert self.name.count("/") <= 1 def get_module(self) -> DatasetModule: dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() importable_directory_path = os.path.join(dynamic_modules_path, "datasets", self.name.replace("/", "--")) hashes = ( [h for h in os.listdir(importable_directory_path) if len(h) == 64] if os.path.isdir(importable_directory_path) else None ) if hashes: # get most recent def _get_modification_time(module_hash): return ( (Path(importable_directory_path) / module_hash / (self.name.split("/")[-1] + ".py")) .stat() .st_mtime ) hash = sorted(hashes, key=_get_modification_time)[-1] warning_msg = ( f"Using the latest cached version of the module from {os.path.join(importable_directory_path, hash)} " f"(last modified on {time.ctime(_get_modification_time(hash))}) since it " f"couldn't be found locally at {self.name}" ) if not config.HF_DATASETS_OFFLINE: warning_msg += ", or remotely on the Hugging Face Hub." logger.warning(warning_msg) # make the new module to be noticed by the import system module_path = ".".join( [ os.path.basename(dynamic_modules_path), "datasets", self.name.replace("/", "--"), hash, self.name.split("/")[-1], ] ) importlib.invalidate_caches() builder_kwargs = { "repo_id": self.name, } return DatasetModule(module_path, hash, builder_kwargs) cache_dir = os.path.expanduser(str(self.cache_dir or config.HF_DATASETS_CACHE)) cached_datasets_directory_path_root = os.path.join(cache_dir, self.name.replace("/", "___")) cached_directory_paths = [ cached_directory_path for cached_directory_path in glob.glob(os.path.join(cached_datasets_directory_path_root, "*", "*", "*")) if os.path.isdir(cached_directory_path) ] if cached_directory_paths: builder_kwargs = { "repo_id": self.name, "dataset_name": self.name.split("/")[-1], } warning_msg = f"Using the latest cached version of the dataset since {self.name} couldn't be found on the Hugging Face Hub" if config.HF_DATASETS_OFFLINE: warning_msg += " (offline mode is enabled)." logger.warning(warning_msg) return DatasetModule( "datasets.packaged_modules.cache.cache", "auto", {**builder_kwargs, "version": "auto"}, ) raise FileNotFoundError(f"Dataset {self.name} is not cached in {self.cache_dir}") class CachedMetricModuleFactory(_MetricModuleFactory): """ Get the module of a metric that has been loaded once already and cached. The script that is loaded from the cache is the most recent one with a matching name. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, name: str, dynamic_modules_path: Optional[str] = None, ): self.name = name self.dynamic_modules_path = dynamic_modules_path assert self.name.count("/") == 0 def get_module(self) -> MetricModule: dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() importable_directory_path = os.path.join(dynamic_modules_path, "metrics", self.name) hashes = ( [h for h in os.listdir(importable_directory_path) if len(h) == 64] if os.path.isdir(importable_directory_path) else None ) if not hashes: raise FileNotFoundError(f"Metric {self.name} is not cached in {dynamic_modules_path}") # get most recent def _get_modification_time(module_hash): return (Path(importable_directory_path) / module_hash / (self.name + ".py")).stat().st_mtime hash = sorted(hashes, key=_get_modification_time)[-1] logger.warning( f"Using the latest cached version of the module from {os.path.join(importable_directory_path, hash)} " f"(last modified on {time.ctime(_get_modification_time(hash))}) since it " f"couldn't be found locally at {self.name}, or remotely on the Hugging Face Hub." ) # make the new module to be noticed by the import system module_path = ".".join([os.path.basename(dynamic_modules_path), "metrics", self.name, hash, self.name]) importlib.invalidate_caches() return MetricModule(module_path, hash) def dataset_module_factory( path: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[Dict, List, str, DataFilesDict]] = None, cache_dir: Optional[str] = None, trust_remote_code: Optional[bool] = None, _require_default_config_name=True, _require_custom_configs=False, **download_kwargs, ) -> DatasetModule: """ Download/extract/cache a dataset module. Dataset codes are cached inside the dynamic modules cache to allow easy import (avoid ugly sys.path tweaks). Args: path (str): Path or name of the dataset. Depending on ``path``, the dataset builder that is used comes from a generic dataset script (JSON, CSV, Parquet, text etc.) or from the dataset script (a python file) inside the dataset directory. For local datasets: - if ``path`` is a local directory (containing data files only) -> load a generic dataset builder (csv, json, text etc.) based on the content of the directory e.g. ``'./path/to/directory/with/my/csv/data'``. - if ``path`` is a local dataset script or a directory containing a local dataset script (if the script has the same name as the directory): -> load the dataset builder from the dataset script e.g. ``'./dataset/squad'`` or ``'./dataset/squad/squad.py'``. For datasets on the Hugging Face Hub (list all available datasets with ``huggingface_hub.list_datasets()``) - if ``path`` is a dataset repository on the HF hub (containing data files only) -> load a generic dataset builder (csv, text etc.) based on the content of the repository e.g. ``'username/dataset_name'``, a dataset repository on the HF hub containing your data files. - if ``path`` is a dataset repository on the HF hub with a dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script in the dataset repository e.g. ``glue``, ``squad``, ``'username/dataset_name'``, a dataset repository on the HF hub containing a dataset script `'dataset_name.py'`. revision (:class:`~utils.Version` or :obj:`str`, optional): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. download_config (:class:`DownloadConfig`, optional): Specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. dynamic_modules_path (Optional str, defaults to HF_MODULES_CACHE / "datasets_modules", i.e. ~/.cache/huggingface/modules/datasets_modules): Optional path to the directory in which the dynamic modules are saved. It must have been initialized with :obj:`init_dynamic_modules`. By default, the datasets and metrics are stored inside the `datasets_modules` module. data_dir (:obj:`str`, optional): Directory with the data files. Used only if `data_files` is not specified, in which case it's equal to pass `os.path.join(data_dir, "**")` as `data_files`. data_files (:obj:`Union[Dict, List, str]`, optional): Defining the data_files of the dataset configuration. cache_dir (`str`, *optional*): Directory to read/write data. Defaults to `"~/.cache/huggingface/datasets"`. <Added version="2.16.0"/> trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **download_kwargs (additional keyword arguments): optional attributes for DownloadConfig() which will override the attributes in download_config if supplied. Returns: DatasetModule """ if download_config is None: download_config = DownloadConfig(**download_kwargs) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) download_config.extract_compressed_file = True download_config.force_extract = True download_config.force_download = download_mode == DownloadMode.FORCE_REDOWNLOAD filename = list(filter(lambda x: x, path.replace(os.sep, "/").split("/")))[-1] if not filename.endswith(".py"): filename = filename + ".py" combined_path = os.path.join(path, filename) # We have several ways to get a dataset builder: # # - if path is the name of a packaged dataset module # -> use the packaged module (json, csv, etc.) # # - if os.path.join(path, name) is a local python file # -> use the module from the python file # - if path is a local directory (but no python file) # -> use a packaged module (csv, text etc.) based on content of the directory # # - if path has one "/" and is dataset repository on the HF hub with a python file # -> the module from the python file in the dataset repository # - if path has one "/" and is dataset repository on the HF hub without a python file # -> use a packaged module (csv, text etc.) based on content of the repository # Try packaged if path in _PACKAGED_DATASETS_MODULES: return PackagedDatasetModuleFactory( path, data_dir=data_dir, data_files=data_files, download_config=download_config, download_mode=download_mode, ).get_module() # Try locally elif path.endswith(filename): if os.path.isfile(path): return LocalDatasetModuleFactoryWithScript( path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() else: raise FileNotFoundError(f"Couldn't find a dataset script at {relative_to_absolute_path(path)}") elif os.path.isfile(combined_path): return LocalDatasetModuleFactoryWithScript( combined_path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() elif os.path.isdir(path): return LocalDatasetModuleFactoryWithoutScript( path, data_dir=data_dir, data_files=data_files, download_mode=download_mode ).get_module() # Try remotely elif is_relative_path(path) and path.count("/") <= 1: try: _raise_if_offline_mode_is_enabled() hf_api = HfApi(config.HF_ENDPOINT) try: dataset_info = hf_api.dataset_info( repo_id=path, revision=revision, token=download_config.token, timeout=100.0, ) except Exception as e: # noqa catch any exception of hf_hub and consider that the dataset doesn't exist if isinstance( e, ( OfflineModeIsEnabled, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError, ), ): raise ConnectionError(f"Couldn't reach '{path}' on the Hub ({type(e).__name__})") elif "404" in str(e): msg = f"Dataset '{path}' doesn't exist on the Hub" raise DatasetNotFoundError(msg + f" at revision '{revision}'" if revision else msg) elif "401" in str(e): msg = f"Dataset '{path}' doesn't exist on the Hub" msg = msg + f" at revision '{revision}'" if revision else msg raise DatasetNotFoundError( msg + ". If the repo is private or gated, make sure to log in with `huggingface-cli login`." ) else: raise e if filename in [sibling.rfilename for sibling in dataset_info.siblings]: # contains a dataset script fs = HfFileSystem(endpoint=config.HF_ENDPOINT, token=download_config.token) if _require_custom_configs: can_load_config_from_parquet_export = False elif _require_default_config_name: with fs.open(f"datasets/{path}/{filename}", "r", revision=revision, encoding="utf-8") as f: can_load_config_from_parquet_export = "DEFAULT_CONFIG_NAME" not in f.read() else: can_load_config_from_parquet_export = True if config.USE_PARQUET_EXPORT and can_load_config_from_parquet_export: # If the parquet export is ready (parquet files + info available for the current sha), we can use it instead # This fails when the dataset has multiple configs and a default config and # the user didn't specify a configuration name (_require_default_config_name=True). try: return HubDatasetModuleFactoryWithParquetExport( path, download_config=download_config, revision=dataset_info.sha ).get_module() except _datasets_server.DatasetsServerError: pass # Otherwise we must use the dataset script if the user trusts it return HubDatasetModuleFactoryWithScript( path, revision=revision, download_config=download_config, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() else: return HubDatasetModuleFactoryWithoutScript( path, revision=revision, data_dir=data_dir, data_files=data_files, download_config=download_config, download_mode=download_mode, ).get_module() except Exception as e1: # All the attempts failed, before raising the error we should check if the module is already cached try: return CachedDatasetModuleFactory( path, dynamic_modules_path=dynamic_modules_path, cache_dir=cache_dir ).get_module() except Exception: # If it's not in the cache, then it doesn't exist. if isinstance(e1, OfflineModeIsEnabled): raise ConnectionError(f"Couldn't reach the Hugging Face Hub for dataset '{path}': {e1}") from None if isinstance(e1, (DataFilesNotFoundError, DatasetNotFoundError, EmptyDatasetError)): raise e1 from None if isinstance(e1, FileNotFoundError): raise FileNotFoundError( f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory. " f"Couldn't find '{path}' on the Hugging Face Hub either: {type(e1).__name__}: {e1}" ) from None raise e1 from None else: raise FileNotFoundError( f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory." ) @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def metric_module_factory( path: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[bool] = None, **download_kwargs, ) -> MetricModule: """ Download/extract/cache a metric module. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> Metrics codes are cached inside the dynamic modules cache to allow easy import (avoid ugly sys.path tweaks). Args: path (str): Path or name of the metric script. - if ``path`` is a local metric script or a directory containing a local metric script (if the script has the same name as the directory): -> load the module from the metric script e.g. ``'./metrics/accuracy'`` or ``'./metrics/accuracy/accuracy.py'``. - if ``path`` is a metric on the Hugging Face Hub (ex: `glue`, `squad`) -> load the module from the metric script in the GitHub repository at huggingface/datasets e.g. ``'accuracy'`` or ``'rouge'``. revision (Optional ``Union[str, datasets.Version]``): If specified, the module will be loaded from the datasets repository at this version. By default: - it is set to the local version of the lib. - it will also try to load it from the main branch if it's not available at the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. download_config (:class:`DownloadConfig`, optional): Specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. dynamic_modules_path (Optional str, defaults to HF_MODULES_CACHE / "datasets_modules", i.e. ~/.cache/huggingface/modules/datasets_modules): Optional path to the directory in which the dynamic modules are saved. It must have been initialized with :obj:`init_dynamic_modules`. By default, the datasets and metrics are stored inside the `datasets_modules` module. trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **download_kwargs (additional keyword arguments): optional attributes for DownloadConfig() which will override the attributes in download_config if supplied. Returns: MetricModule """ with warnings.catch_warnings(): # Ignore equivalent warnings to the one already issued warnings.filterwarnings("ignore", message=".*https://huggingface.co/docs/evaluate$", category=FutureWarning) if download_config is None: download_config = DownloadConfig(**download_kwargs) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) download_config.extract_compressed_file = True download_config.force_extract = True filename = list(filter(lambda x: x, path.replace(os.sep, "/").split("/")))[-1] if not filename.endswith(".py"): filename = filename + ".py" combined_path = os.path.join(path, filename) # Try locally if path.endswith(filename): if os.path.isfile(path): return LocalMetricModuleFactory( path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() else: raise FileNotFoundError(f"Couldn't find a metric script at {relative_to_absolute_path(path)}") elif os.path.isfile(combined_path): return LocalMetricModuleFactory( combined_path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path ).get_module() elif is_relative_path(path) and path.count("/") == 0: try: return GithubMetricModuleFactory( path, revision=revision, download_config=download_config, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() except Exception as e1: # noqa all the attempts failed, before raising the error we should check if the module is already cached. try: return CachedMetricModuleFactory(path, dynamic_modules_path=dynamic_modules_path).get_module() except Exception: # noqa if it's not in the cache, then it doesn't exist. if not isinstance(e1, FileNotFoundError): raise e1 from None raise FileNotFoundError( f"Couldn't find a metric script at {relative_to_absolute_path(combined_path)}. " f"Metric '{path}' doesn't exist on the Hugging Face Hub either." ) from None else: raise FileNotFoundError(f"Couldn't find a metric script at {relative_to_absolute_path(combined_path)}.") @deprecated("Use 'evaluate.load' instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate") def load_metric( path: str, config_name: Optional[str] = None, process_id: int = 0, num_process: int = 1, cache_dir: Optional[str] = None, experiment_id: Optional[str] = None, keep_in_memory: bool = False, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, trust_remote_code: Optional[bool] = None, **metric_init_kwargs, ) -> Metric: """Load a `datasets.Metric`. <Deprecated version="2.5.0"> Use `evaluate.load` instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate </Deprecated> Args: path (``str``): path to the metric processing script with the metric builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. ``'./metrics/rouge'`` or ``'./metrics/rogue/rouge.py'`` - a metric identifier on the HuggingFace datasets repo (list all available metrics with ``datasets.list_metrics()``) e.g. ``'rouge'`` or ``'bleu'`` config_name (:obj:`str`, optional): selecting a configuration for the metric (e.g. the GLUE metric has a configuration for each subset) process_id (:obj:`int`, optional): for distributed evaluation: id of the process num_process (:obj:`int`, optional): for distributed evaluation: total number of processes cache_dir (Optional str): path to store the temporary predictions and references (default to `~/.cache/huggingface/metrics/`) experiment_id (``str``): A specific experiment id. This is used if several distributed evaluations share the same file system. This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1). keep_in_memory (bool): Whether to store the temporary results in memory (defaults to False) download_config (Optional ``datasets.DownloadConfig``: specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. revision (Optional ``Union[str, datasets.Version]``): if specified, the module will be loaded from the datasets repository at this version. By default, it is set to the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> Returns: `datasets.Metric` Example: ```py >>> from datasets import load_metric >>> accuracy = load_metric('accuracy') >>> accuracy.compute(references=[1, 0], predictions=[1, 1]) {'accuracy': 0.5} ``` """ with warnings.catch_warnings(): # Ignore equivalent warnings to the one already issued warnings.filterwarnings("ignore", message=".*https://huggingface.co/docs/evaluate$", category=FutureWarning) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) metric_module = metric_module_factory( path, revision=revision, download_config=download_config, download_mode=download_mode, trust_remote_code=trust_remote_code, ).module_path metric_cls = import_main_class(metric_module, dataset=False) metric = metric_cls( config_name=config_name, process_id=process_id, num_process=num_process, cache_dir=cache_dir, keep_in_memory=keep_in_memory, experiment_id=experiment_id, **metric_init_kwargs, ) # Download and prepare resources for the metric metric.download_and_prepare(download_config=download_config) return metric def load_dataset_builder( path: str, name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, cache_dir: Optional[str] = None, features: Optional[Features] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", storage_options: Optional[Dict] = None, trust_remote_code: Optional[bool] = None, _require_default_config_name=True, **config_kwargs, ) -> DatasetBuilder: """Load a dataset builder from the Hugging Face Hub, or a local dataset. A dataset builder can be used to inspect general information that is required to build a dataset (cache directory, config, dataset info, etc.) without downloading the dataset itself. You can find the list of datasets on the [Hub](https://huggingface.co/datasets) or with [`huggingface_hub.list_datasets`]. A dataset is a directory that contains: - some data files in generic formats (JSON, CSV, Parquet, text, etc.) - and optionally a dataset script, if it requires some code to read the data files. This is used to load any kind of formats or structures. Note that dataset scripts can also download and read data files from anywhere - in case your data files already exist online. Args: path (`str`): Path or name of the dataset. Depending on `path`, the dataset builder that is used comes from a generic dataset script (JSON, CSV, Parquet, text etc.) or from the dataset script (a python file) inside the dataset directory. For local datasets: - if `path` is a local directory (containing data files only) -> load a generic dataset builder (csv, json, text etc.) based on the content of the directory e.g. `'./path/to/directory/with/my/csv/data'`. - if `path` is a local dataset script or a directory containing a local dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'`. For datasets on the Hugging Face Hub (list all available datasets with [`huggingface_hub.list_datasets`]) - if `path` is a dataset repository on the HF hub (containing data files only) -> load a generic dataset builder (csv, text etc.) based on the content of the repository e.g. `'username/dataset_name'`, a dataset repository on the HF hub containing your data files. - if `path` is a dataset repository on the HF hub with a dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script in the dataset repository e.g. `glue`, `squad`, `'username/dataset_name'`, a dataset repository on the HF hub containing a dataset script `'dataset_name.py'`. name (`str`, *optional*): Defining the name of the dataset configuration. data_dir (`str`, *optional*): Defining the `data_dir` of the dataset configuration. If specified for the generic builders (csv, text etc.) or the Hub datasets and `data_files` is `None`, the behavior is equal to passing `os.path.join(data_dir, **)` as `data_files` to reference all the files in a directory. data_files (`str` or `Sequence` or `Mapping`, *optional*): Path(s) to source data file(s). cache_dir (`str`, *optional*): Directory to read/write data. Defaults to `"~/.cache/huggingface/datasets"`. features ([`Features`], *optional*): Set the features type to use for this dataset. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. revision ([`Version`] or `str`, *optional*): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. 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 version="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. </Deprecated> storage_options (`dict`, *optional*, defaults to `None`): **Experimental**. Key/value pairs to be passed on to the dataset file-system backend, if any. <Added version="2.11.0"/> trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **config_kwargs (additional keyword arguments): Keyword arguments to be passed to the [`BuilderConfig`] and used in the [`DatasetBuilder`]. Returns: [`DatasetBuilder`] Example: ```py >>> from datasets import load_dataset_builder >>> ds_builder = load_dataset_builder('rotten_tomatoes') >>> ds_builder.info.features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} ``` """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) if token is not None: download_config = download_config.copy() if download_config else DownloadConfig() download_config.token = token if storage_options is not None: download_config = download_config.copy() if download_config else DownloadConfig() download_config.storage_options.update(storage_options) dataset_module = dataset_module_factory( path, revision=revision, download_config=download_config, download_mode=download_mode, data_dir=data_dir, data_files=data_files, cache_dir=cache_dir, trust_remote_code=trust_remote_code, _require_default_config_name=_require_default_config_name, _require_custom_configs=bool(config_kwargs), ) # Get dataset builder class from the processing script builder_kwargs = dataset_module.builder_kwargs data_dir = builder_kwargs.pop("data_dir", data_dir) data_files = builder_kwargs.pop("data_files", data_files) config_name = builder_kwargs.pop( "config_name", name or dataset_module.builder_configs_parameters.default_config_name ) dataset_name = builder_kwargs.pop("dataset_name", None) info = dataset_module.dataset_infos.get(config_name) if dataset_module.dataset_infos else None if ( path in _PACKAGED_DATASETS_MODULES and data_files is None and dataset_module.builder_configs_parameters.builder_configs[0].data_files is None ): error_msg = f"Please specify the data files or data directory to load for the {path} dataset builder." example_extensions = [ extension for extension in _EXTENSION_TO_MODULE if _EXTENSION_TO_MODULE[extension] == path ] if example_extensions: error_msg += f'\nFor example `data_files={{"train": "path/to/data/train/*.{example_extensions[0]}"}}`' raise ValueError(error_msg) builder_cls = get_dataset_builder_class(dataset_module, dataset_name=dataset_name) # Instantiate the dataset builder builder_instance: DatasetBuilder = builder_cls( cache_dir=cache_dir, dataset_name=dataset_name, config_name=config_name, data_dir=data_dir, data_files=data_files, hash=dataset_module.hash, info=info, features=features, token=token, storage_options=storage_options, **builder_kwargs, **config_kwargs, ) builder_instance._use_legacy_cache_dir_if_possible(dataset_module) return builder_instance def load_dataset( path: str, name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, split: Optional[Union[str, Split]] = None, cache_dir: Optional[str] = None, features: Optional[Features] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, verification_mode: Optional[Union[VerificationMode, str]] = None, ignore_verifications="deprecated", keep_in_memory: Optional[bool] = None, save_infos: bool = False, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", task="deprecated", streaming: bool = False, num_proc: Optional[int] = None, storage_options: Optional[Dict] = None, trust_remote_code: bool = None, **config_kwargs, ) -> Union[DatasetDict, Dataset, IterableDatasetDict, IterableDataset]: """Load a dataset from the Hugging Face Hub, or a local dataset. You can find the list of datasets on the [Hub](https://huggingface.co/datasets) or with [`huggingface_hub.list_datasets`]. A dataset is a directory that contains: - some data files in generic formats (JSON, CSV, Parquet, text, etc.). - and optionally a dataset script, if it requires some code to read the data files. This is used to load any kind of formats or structures. Note that dataset scripts can also download and read data files from anywhere - in case your data files already exist online. This function does the following under the hood: 1. Download and import in the library the dataset script from `path` if it's not already cached inside the library. If the dataset has no dataset script, then a generic dataset script is imported instead (JSON, CSV, Parquet, text, etc.) Dataset scripts are small python scripts that define dataset builders. They define the citation, info and format of the dataset, contain the path or URL to the original data files and the code to load examples from the original data files. You can find the complete list of datasets in the Datasets [Hub](https://huggingface.co/datasets). 2. Run the dataset script which will: * Download the dataset file from the original URL (see the script) if it's not already available locally or cached. * Process and cache the dataset in typed Arrow tables for caching. Arrow table are arbitrarily long, typed tables which can store nested objects and be mapped to numpy/pandas/python generic types. They can be directly accessed from disk, loaded in RAM or even streamed over the web. 3. Return a dataset built from the requested splits in `split` (default: all). It also allows to load a dataset from a local directory or a dataset repository on the Hugging Face Hub without dataset script. In this case, it automatically loads all the data files from the directory or the dataset repository. Args: path (`str`): Path or name of the dataset. Depending on `path`, the dataset builder that is used comes from a generic dataset script (JSON, CSV, Parquet, text etc.) or from the dataset script (a python file) inside the dataset directory. For local datasets: - if `path` is a local directory (containing data files only) -> load a generic dataset builder (csv, json, text etc.) based on the content of the directory e.g. `'./path/to/directory/with/my/csv/data'`. - if `path` is a local dataset script or a directory containing a local dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'`. For datasets on the Hugging Face Hub (list all available datasets with [`huggingface_hub.list_datasets`]) - if `path` is a dataset repository on the HF hub (containing data files only) -> load a generic dataset builder (csv, text etc.) based on the content of the repository e.g. `'username/dataset_name'`, a dataset repository on the HF hub containing your data files. - if `path` is a dataset repository on the HF hub with a dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script in the dataset repository e.g. `glue`, `squad`, `'username/dataset_name'`, a dataset repository on the HF hub containing a dataset script `'dataset_name.py'`. name (`str`, *optional*): Defining the name of the dataset configuration. data_dir (`str`, *optional*): Defining the `data_dir` of the dataset configuration. If specified for the generic builders (csv, text etc.) or the Hub datasets and `data_files` is `None`, the behavior is equal to passing `os.path.join(data_dir, **)` as `data_files` to reference all the files in a directory. data_files (`str` or `Sequence` or `Mapping`, *optional*): Path(s) to source data file(s). split (`Split` or `str`): Which split of the data to load. If `None`, will return a `dict` with all splits (typically `datasets.Split.TRAIN` and `datasets.Split.TEST`). If given, will return a single Dataset. Splits can be combined and specified like in tensorflow-datasets. cache_dir (`str`, *optional*): Directory to read/write data. Defaults to `"~/.cache/huggingface/datasets"`. features (`Features`, *optional*): Set the features type to use for this dataset. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. verification_mode ([`VerificationMode`] or `str`, defaults to `BASIC_CHECKS`): Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/...). <Added version="2.9.1"/> ignore_verifications (`bool`, defaults to `False`): Ignore the verifications of the downloaded/processed dataset information (checksums/size/splits/...). <Deprecated version="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. </Deprecated> keep_in_memory (`bool`, defaults to `None`): Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](../cache#improve-performance) section. save_infos (`bool`, defaults to `False`): Save the dataset information (checksums/size/splits/...). revision ([`Version`] or `str`, *optional*): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. 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 version="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. </Deprecated> task (`str`): The task to prepare the dataset for during training and evaluation. Casts the dataset's [`Features`] to standardized column names and types as detailed in `datasets.tasks`. <Deprecated version="2.13.0"> `task` was deprecated in version 2.13.0 and will be removed in 3.0.0. </Deprecated> streaming (`bool`, defaults to `False`): If set to `True`, don't download the data files. Instead, it streams the data progressively while iterating on the dataset. An [`IterableDataset`] or [`IterableDatasetDict`] is returned instead in this case. Note that streaming works for datasets that use data formats that support being iterated over like txt, csv, jsonl for example. Json files may be downloaded completely. Also streaming from remote zip or gzip files is supported but other compressed formats like rar and xz are not yet supported. The tgz format doesn't allow streaming. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default. <Added version="2.7.0"/> storage_options (`dict`, *optional*, defaults to `None`): **Experimental**. Key/value pairs to be passed on to the dataset file-system backend, if any. <Added version="2.11.0"/> trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **config_kwargs (additional keyword arguments): Keyword arguments to be passed to the `BuilderConfig` and used in the [`DatasetBuilder`]. Returns: [`Dataset`] or [`DatasetDict`]: - if `split` is not `None`: the dataset requested, - if `split` is `None`, a [`~datasets.DatasetDict`] with each split. or [`IterableDataset`] or [`IterableDatasetDict`]: if `streaming=True` - if `split` is not `None`, the dataset is requested - if `split` is `None`, a [`~datasets.streaming.IterableDatasetDict`] with each split. Example: Load a dataset from the Hugging Face Hub: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes', split='train') # Map data files to splits >>> data_files = {'train': 'train.csv', 'test': 'test.csv'} >>> ds = load_dataset('namespace/your_dataset_name', data_files=data_files) ``` Load a local dataset: ```py # Load a CSV file >>> from datasets import load_dataset >>> ds = load_dataset('csv', data_files='path/to/local/my_dataset.csv') # Load a JSON file >>> from datasets import load_dataset >>> ds = load_dataset('json', data_files='path/to/local/my_dataset.json') # Load from a local loading script >>> from datasets import load_dataset >>> ds = load_dataset('path/to/local/loading_script/loading_script.py', split='train') ``` Load an [`~datasets.IterableDataset`]: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes', split='train', streaming=True) ``` Load an image dataset with the `ImageFolder` dataset builder: ```py >>> from datasets import load_dataset >>> ds = load_dataset('imagefolder', data_dir='/path/to/images', split='train') ``` """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token if ignore_verifications != "deprecated": verification_mode = VerificationMode.NO_CHECKS if ignore_verifications else VerificationMode.ALL_CHECKS warnings.warn( "'ignore_verifications' was deprecated in favor of 'verification_mode' in version 2.9.1 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'verification_mode={verification_mode.value}' instead.", FutureWarning, ) if task != "deprecated": warnings.warn( "'task' was deprecated in version 2.13.0 and will be removed in 3.0.0.\n", FutureWarning, ) else: task = None if data_files is not None and not data_files: raise ValueError(f"Empty 'data_files': '{data_files}'. It should be either non-empty or None (default).") if Path(path, config.DATASET_STATE_JSON_FILENAME).exists(): raise ValueError( "You are trying to load a dataset that was saved using `save_to_disk`. " "Please use `load_from_disk` instead." ) if streaming and num_proc is not None: raise NotImplementedError( "Loading a streaming dataset in parallel with `num_proc` is not implemented. " "To parallelize streaming, you can wrap the dataset with a PyTorch DataLoader using `num_workers` > 1 instead." ) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) verification_mode = VerificationMode( (verification_mode or VerificationMode.BASIC_CHECKS) if not save_infos else VerificationMode.ALL_CHECKS ) # Create a dataset builder builder_instance = load_dataset_builder( path=path, name=name, data_dir=data_dir, data_files=data_files, cache_dir=cache_dir, features=features, download_config=download_config, download_mode=download_mode, revision=revision, token=token, storage_options=storage_options, trust_remote_code=trust_remote_code, _require_default_config_name=name is None, **config_kwargs, ) # Return iterable dataset in case of streaming if streaming: return builder_instance.as_streaming_dataset(split=split) # Some datasets are already processed on the HF google storage # Don't try downloading from Google storage for the packaged datasets as text, json, csv or pandas try_from_hf_gcs = path not in _PACKAGED_DATASETS_MODULES # Download and prepare data builder_instance.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, try_from_hf_gcs=try_from_hf_gcs, num_proc=num_proc, storage_options=storage_options, ) # Build dataset for splits keep_in_memory = ( keep_in_memory if keep_in_memory is not None else is_small_dataset(builder_instance.info.dataset_size) ) ds = builder_instance.as_dataset(split=split, verification_mode=verification_mode, in_memory=keep_in_memory) # Rename and cast features to match task schema if task is not None: # To avoid issuing the same warning twice with warnings.catch_warnings(): warnings.simplefilter("ignore", FutureWarning) ds = ds.prepare_for_task(task) if save_infos: builder_instance._save_infos() return ds def load_from_disk( dataset_path: str, fs="deprecated", keep_in_memory: Optional[bool] = None, storage_options: Optional[dict] = None ) -> Union[Dataset, DatasetDict]: """ Loads a dataset that was previously saved using [`~Dataset.save_to_disk`] from a dataset directory, or from a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`. Args: dataset_path (`str`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3://my-bucket/dataset/train"`) of the [`Dataset`] or [`DatasetDict`] directory where the dataset will be loaded from. fs (`~filesystems.S3FileSystem` or `fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem used to download the files from. <Deprecated version="2.9.0"> `fs` was deprecated in version 2.9.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`. </Deprecated> keep_in_memory (`bool`, defaults to `None`): Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](../cache#improve-performance) section. storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.9.0"/> Returns: [`Dataset`] or [`DatasetDict`]: - If `dataset_path` is a path of a dataset directory: the dataset requested. - If `dataset_path` is a path of a dataset dict directory, a [`DatasetDict`] with each split. Example: ```py >>> from datasets import load_from_disk >>> ds = load_from_disk('path/to/dataset/directory') ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.9.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, _, _ = fsspec.get_fs_token_paths(dataset_path, storage_options=storage_options) if not fs.exists(dataset_path): raise FileNotFoundError(f"Directory {dataset_path} not found") if fs.isfile(posixpath.join(dataset_path, config.DATASET_INFO_FILENAME)) and fs.isfile( posixpath.join(dataset_path, config.DATASET_STATE_JSON_FILENAME) ): return Dataset.load_from_disk(dataset_path, keep_in_memory=keep_in_memory, storage_options=storage_options) elif fs.isfile(posixpath.join(dataset_path, config.DATASETDICT_JSON_FILENAME)): return DatasetDict.load_from_disk(dataset_path, keep_in_memory=keep_in_memory, storage_options=storage_options) else: raise FileNotFoundError( f"Directory {dataset_path} is neither a `Dataset` directory nor a `DatasetDict` directory." )
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/info.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """ DatasetInfo and MetricInfo record information we know about a dataset and a metric. This includes things that we know about the dataset statically, i.e.: - description - canonical location - does it have validation and tests splits - size - etc. This also includes the things that can and should be computed once we've processed the dataset as well: - number of examples (in each split) - etc. """ import copy import dataclasses import json import os import posixpath import warnings from dataclasses import dataclass from pathlib import Path from typing import ClassVar, Dict, List, Optional, Union import fsspec from huggingface_hub import DatasetCard, DatasetCardData from . import config from .features import Features, Value from .splits import SplitDict from .tasks import TaskTemplate, task_template_from_dict from .utils import Version from .utils.logging import get_logger from .utils.py_utils import asdict, unique_values logger = get_logger(__name__) @dataclass class SupervisedKeysData: input: str = "" output: str = "" @dataclass class DownloadChecksumsEntryData: key: str = "" value: str = "" class MissingCachedSizesConfigError(Exception): """The expected cached sizes of the download file are missing.""" class NonMatchingCachedSizesError(Exception): """The prepared split doesn't have expected sizes.""" @dataclass class PostProcessedInfo: features: Optional[Features] = None resources_checksums: Optional[dict] = None def __post_init__(self): # Convert back to the correct classes when we reload from dict if self.features is not None and not isinstance(self.features, Features): self.features = Features.from_dict(self.features) @classmethod def from_dict(cls, post_processed_info_dict: dict) -> "PostProcessedInfo": field_names = {f.name for f in dataclasses.fields(cls)} return cls(**{k: v for k, v in post_processed_info_dict.items() if k in field_names}) @dataclass class DatasetInfo: """Information about a dataset. `DatasetInfo` documents datasets, including its name, version, and features. See the constructor arguments and properties for a full list. Not all fields are known on construction and may be updated later. Attributes: description (`str`): A description of the dataset. citation (`str`): A BibTeX citation of the dataset. homepage (`str`): A URL to the official homepage for the dataset. license (`str`): The dataset's license. It can be the name of the license or a paragraph containing the terms of the license. features ([`Features`], *optional*): The features used to specify the dataset's column types. post_processed (`PostProcessedInfo`, *optional*): Information regarding the resources of a possible post-processing of a dataset. For example, it can contain the information of an index. supervised_keys (`SupervisedKeysData`, *optional*): Specifies the input feature and the label for supervised learning if applicable for the dataset (legacy from TFDS). builder_name (`str`, *optional*): The name of the `GeneratorBasedBuilder` subclass used to create the dataset. Usually matched to the corresponding script name. It is also the snake_case version of the dataset builder class name. config_name (`str`, *optional*): The name of the configuration derived from [`BuilderConfig`]. version (`str` or [`Version`], *optional*): The version of the dataset. splits (`dict`, *optional*): The mapping between split name and metadata. download_checksums (`dict`, *optional*): The mapping between the URL to download the dataset's checksums and corresponding metadata. download_size (`int`, *optional*): The size of the files to download to generate the dataset, in bytes. post_processing_size (`int`, *optional*): Size of the dataset in bytes after post-processing, if any. dataset_size (`int`, *optional*): The combined size in bytes of the Arrow tables for all splits. size_in_bytes (`int`, *optional*): The combined size in bytes of all files associated with the dataset (downloaded files + Arrow files). task_templates (`List[TaskTemplate]`, *optional*): The task templates to prepare the dataset for during training and evaluation. Each template casts the dataset's [`Features`] to standardized column names and types as detailed in `datasets.tasks`. **config_kwargs (additional keyword arguments): Keyword arguments to be passed to the [`BuilderConfig`] and used in the [`DatasetBuilder`]. """ # Set in the dataset scripts description: str = dataclasses.field(default_factory=str) citation: str = dataclasses.field(default_factory=str) homepage: str = dataclasses.field(default_factory=str) license: str = dataclasses.field(default_factory=str) features: Optional[Features] = None post_processed: Optional[PostProcessedInfo] = None supervised_keys: Optional[SupervisedKeysData] = None task_templates: Optional[List[TaskTemplate]] = None # Set later by the builder builder_name: Optional[str] = None dataset_name: Optional[str] = None # for packaged builders, to be different from builder_name config_name: Optional[str] = None version: Optional[Union[str, Version]] = None # Set later by `download_and_prepare` splits: Optional[dict] = None download_checksums: Optional[dict] = None download_size: Optional[int] = None post_processing_size: Optional[int] = None dataset_size: Optional[int] = None size_in_bytes: Optional[int] = None _INCLUDED_INFO_IN_YAML: ClassVar[List[str]] = [ "config_name", "download_size", "dataset_size", "features", "splits", ] def __post_init__(self): # Convert back to the correct classes when we reload from dict if self.features is not None and not isinstance(self.features, Features): self.features = Features.from_dict(self.features) if self.post_processed is not None and not isinstance(self.post_processed, PostProcessedInfo): self.post_processed = PostProcessedInfo.from_dict(self.post_processed) if self.version is not None and not isinstance(self.version, Version): if isinstance(self.version, str): self.version = Version(self.version) else: self.version = Version.from_dict(self.version) if self.splits is not None and not isinstance(self.splits, SplitDict): self.splits = SplitDict.from_split_dict(self.splits) if self.supervised_keys is not None and not isinstance(self.supervised_keys, SupervisedKeysData): if isinstance(self.supervised_keys, (tuple, list)): self.supervised_keys = SupervisedKeysData(*self.supervised_keys) else: self.supervised_keys = SupervisedKeysData(**self.supervised_keys) # Parse and make a list of templates if self.task_templates is not None: if isinstance(self.task_templates, (list, tuple)): templates = [ template if isinstance(template, TaskTemplate) else task_template_from_dict(template) for template in self.task_templates ] self.task_templates = [template for template in templates if template is not None] elif isinstance(self.task_templates, TaskTemplate): self.task_templates = [self.task_templates] else: template = task_template_from_dict(self.task_templates) self.task_templates = [template] if template is not None else [] # Align task templates with features if self.task_templates is not None: self.task_templates = list(self.task_templates) if self.features is not None: self.task_templates = [ template.align_with_features(self.features) for template in (self.task_templates) ] def write_to_directory( self, dataset_info_dir, pretty_print=False, fs="deprecated", storage_options: Optional[dict] = None ): """Write `DatasetInfo` and license (if present) as JSON files to `dataset_info_dir`. Args: dataset_info_dir (`str`): Destination directory. pretty_print (`bool`, defaults to `False`): If `True`, the JSON will be pretty-printed with the indent level of 4. fs (`fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem used to download the files from. <Deprecated version="2.9.0"> `fs` was deprecated in version 2.9.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`. </Deprecated> storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.9.0"/> Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.info.write_to_directory("/path/to/directory/") ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.9.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, _, _ = fsspec.get_fs_token_paths(dataset_info_dir, storage_options=storage_options) with fs.open(posixpath.join(dataset_info_dir, config.DATASET_INFO_FILENAME), "wb") as f: self._dump_info(f, pretty_print=pretty_print) if self.license: with fs.open(posixpath.join(dataset_info_dir, config.LICENSE_FILENAME), "wb") as f: self._dump_license(f) def _dump_info(self, file, pretty_print=False): """Dump info in `file` file-like object open in bytes mode (to support remote files)""" file.write(json.dumps(asdict(self), indent=4 if pretty_print else None).encode("utf-8")) def _dump_license(self, file): """Dump license in `file` file-like object open in bytes mode (to support remote files)""" file.write(self.license.encode("utf-8")) @classmethod def from_merge(cls, dataset_infos: List["DatasetInfo"]): dataset_infos = [dset_info.copy() for dset_info in dataset_infos if dset_info is not None] description = "\n\n".join(unique_values(info.description for info in dataset_infos)).strip() citation = "\n\n".join(unique_values(info.citation for info in dataset_infos)).strip() homepage = "\n\n".join(unique_values(info.homepage for info in dataset_infos)).strip() license = "\n\n".join(unique_values(info.license for info in dataset_infos)).strip() features = None supervised_keys = None task_templates = None # Find common task templates across all dataset infos all_task_templates = [info.task_templates for info in dataset_infos if info.task_templates is not None] if len(all_task_templates) > 1: task_templates = list(set(all_task_templates[0]).intersection(*all_task_templates[1:])) elif len(all_task_templates): task_templates = list(set(all_task_templates[0])) # If no common task templates found, replace empty list with None task_templates = task_templates if task_templates else None return cls( description=description, citation=citation, homepage=homepage, license=license, features=features, supervised_keys=supervised_keys, task_templates=task_templates, ) @classmethod def from_directory( cls, dataset_info_dir: str, fs="deprecated", storage_options: Optional[dict] = None ) -> "DatasetInfo": """Create [`DatasetInfo`] from the JSON file in `dataset_info_dir`. This function updates all the dynamically generated fields (num_examples, hash, time of creation,...) of the [`DatasetInfo`]. This will overwrite all previous metadata. Args: dataset_info_dir (`str`): The directory containing the metadata file. This should be the root directory of a specific dataset version. fs (`fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem used to download the files from. <Deprecated version="2.9.0"> `fs` was deprecated in version 2.9.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`. </Deprecated> storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.9.0"/> Example: ```py >>> from datasets import DatasetInfo >>> ds_info = DatasetInfo.from_directory("/path/to/directory/") ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.9.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, _, _ = fsspec.get_fs_token_paths(dataset_info_dir, storage_options=storage_options) logger.info(f"Loading Dataset info from {dataset_info_dir}") if not dataset_info_dir: raise ValueError("Calling DatasetInfo.from_directory() with undefined dataset_info_dir.") with fs.open(posixpath.join(dataset_info_dir, config.DATASET_INFO_FILENAME), "r", encoding="utf-8") as f: dataset_info_dict = json.load(f) return cls.from_dict(dataset_info_dict) @classmethod def from_dict(cls, dataset_info_dict: dict) -> "DatasetInfo": field_names = {f.name for f in dataclasses.fields(cls)} return cls(**{k: v for k, v in dataset_info_dict.items() if k in field_names}) def update(self, other_dataset_info: "DatasetInfo", ignore_none=True): self_dict = self.__dict__ self_dict.update( **{ k: copy.deepcopy(v) for k, v in other_dataset_info.__dict__.items() if (v is not None or not ignore_none) } ) def copy(self) -> "DatasetInfo": return self.__class__(**{k: copy.deepcopy(v) for k, v in self.__dict__.items()}) def _to_yaml_dict(self) -> dict: yaml_dict = {} dataset_info_dict = asdict(self) for key in dataset_info_dict: if key in self._INCLUDED_INFO_IN_YAML: value = getattr(self, key) if hasattr(value, "_to_yaml_list"): # Features, SplitDict yaml_dict[key] = value._to_yaml_list() elif hasattr(value, "_to_yaml_string"): # Version yaml_dict[key] = value._to_yaml_string() else: yaml_dict[key] = value return yaml_dict @classmethod def _from_yaml_dict(cls, yaml_data: dict) -> "DatasetInfo": yaml_data = copy.deepcopy(yaml_data) if yaml_data.get("features") is not None: yaml_data["features"] = Features._from_yaml_list(yaml_data["features"]) if yaml_data.get("splits") is not None: yaml_data["splits"] = SplitDict._from_yaml_list(yaml_data["splits"]) field_names = {f.name for f in dataclasses.fields(cls)} return cls(**{k: v for k, v in yaml_data.items() if k in field_names}) class DatasetInfosDict(Dict[str, DatasetInfo]): def write_to_directory(self, dataset_infos_dir, overwrite=False, pretty_print=False) -> None: total_dataset_infos = {} dataset_infos_path = os.path.join(dataset_infos_dir, config.DATASETDICT_INFOS_FILENAME) dataset_readme_path = os.path.join(dataset_infos_dir, config.REPOCARD_FILENAME) if not overwrite: total_dataset_infos = self.from_directory(dataset_infos_dir) total_dataset_infos.update(self) if os.path.exists(dataset_infos_path): # for backward compatibility, let's update the JSON file if it exists with open(dataset_infos_path, "w", encoding="utf-8") as f: dataset_infos_dict = { config_name: asdict(dset_info) for config_name, dset_info in total_dataset_infos.items() } json.dump(dataset_infos_dict, f, indent=4 if pretty_print else None) # Dump the infos in the YAML part of the README.md file if os.path.exists(dataset_readme_path): dataset_card = DatasetCard.load(dataset_readme_path) dataset_card_data = dataset_card.data else: dataset_card = None dataset_card_data = DatasetCardData() if total_dataset_infos: total_dataset_infos.to_dataset_card_data(dataset_card_data) dataset_card = ( DatasetCard("---\n" + str(dataset_card_data) + "\n---\n") if dataset_card is None else dataset_card ) dataset_card.save(Path(dataset_readme_path)) @classmethod def from_directory(cls, dataset_infos_dir) -> "DatasetInfosDict": logger.info(f"Loading Dataset Infos from {dataset_infos_dir}") # Load the info from the YAML part of README.md if os.path.exists(os.path.join(dataset_infos_dir, config.REPOCARD_FILENAME)): dataset_card_data = DatasetCard.load(Path(dataset_infos_dir) / config.REPOCARD_FILENAME).data if "dataset_info" in dataset_card_data: return cls.from_dataset_card_data(dataset_card_data) if os.path.exists(os.path.join(dataset_infos_dir, config.DATASETDICT_INFOS_FILENAME)): # this is just to have backward compatibility with dataset_infos.json files with open(os.path.join(dataset_infos_dir, config.DATASETDICT_INFOS_FILENAME), encoding="utf-8") as f: return cls( { config_name: DatasetInfo.from_dict(dataset_info_dict) for config_name, dataset_info_dict in json.load(f).items() } ) else: return cls() @classmethod def from_dataset_card_data(cls, dataset_card_data: DatasetCardData) -> "DatasetInfosDict": if isinstance(dataset_card_data.get("dataset_info"), (list, dict)): if isinstance(dataset_card_data["dataset_info"], list): return cls( { dataset_info_yaml_dict.get("config_name", "default"): DatasetInfo._from_yaml_dict( dataset_info_yaml_dict ) for dataset_info_yaml_dict in dataset_card_data["dataset_info"] } ) else: dataset_info = DatasetInfo._from_yaml_dict(dataset_card_data["dataset_info"]) dataset_info.config_name = dataset_card_data["dataset_info"].get("config_name", "default") return cls({dataset_info.config_name: dataset_info}) else: return cls() def to_dataset_card_data(self, dataset_card_data: DatasetCardData) -> None: if self: # first get existing metadata info if "dataset_info" in dataset_card_data and isinstance(dataset_card_data["dataset_info"], dict): dataset_metadata_infos = { dataset_card_data["dataset_info"].get("config_name", "default"): dataset_card_data["dataset_info"] } elif "dataset_info" in dataset_card_data and isinstance(dataset_card_data["dataset_info"], list): dataset_metadata_infos = { config_metadata["config_name"]: config_metadata for config_metadata in dataset_card_data["dataset_info"] } else: dataset_metadata_infos = {} # update/rewrite existing metadata info with the one to dump total_dataset_infos = { **dataset_metadata_infos, **{config_name: dset_info._to_yaml_dict() for config_name, dset_info in self.items()}, } # the config_name from the dataset_infos_dict takes over the config_name of the DatasetInfo for config_name, dset_info_yaml_dict in total_dataset_infos.items(): dset_info_yaml_dict["config_name"] = config_name if len(total_dataset_infos) == 1: # use a struct instead of a list of configurations, since there's only one dataset_card_data["dataset_info"] = next(iter(total_dataset_infos.values())) config_name = dataset_card_data["dataset_info"].pop("config_name", None) if config_name != "default": # if config_name is not "default" preserve it and put at the first position dataset_card_data["dataset_info"] = { "config_name": config_name, **dataset_card_data["dataset_info"], } else: dataset_card_data["dataset_info"] = [] for config_name, dataset_info_yaml_dict in sorted(total_dataset_infos.items()): # add the config_name field in first position dataset_info_yaml_dict.pop("config_name", None) dataset_info_yaml_dict = {"config_name": config_name, **dataset_info_yaml_dict} dataset_card_data["dataset_info"].append(dataset_info_yaml_dict) @dataclass class MetricInfo: """Information about a metric. `MetricInfo` documents a metric, including its name, version, and features. See the constructor arguments and properties for a full list. Note: Not all fields are known on construction and may be updated later. """ # Set in the dataset scripts description: str citation: str features: Features inputs_description: str = dataclasses.field(default_factory=str) homepage: str = dataclasses.field(default_factory=str) license: str = dataclasses.field(default_factory=str) codebase_urls: List[str] = dataclasses.field(default_factory=list) reference_urls: List[str] = dataclasses.field(default_factory=list) streamable: bool = False format: Optional[str] = None # Set later by the builder metric_name: Optional[str] = None config_name: Optional[str] = None experiment_id: Optional[str] = None def __post_init__(self): if self.format is not None: for key, value in self.features.items(): if not isinstance(value, Value): raise ValueError( f"When using 'numpy' format, all features should be a `datasets.Value` feature. " f"Here {key} is an instance of {value.__class__.__name__}" ) def write_to_directory(self, metric_info_dir, pretty_print=False): """Write `MetricInfo` as JSON to `metric_info_dir`. Also save the license separately in LICENCE. If `pretty_print` is True, the JSON will be pretty-printed with the indent level of 4. Example: ```py >>> from datasets import load_metric >>> metric = load_metric("accuracy") >>> metric.info.write_to_directory("/path/to/directory/") ``` """ with open(os.path.join(metric_info_dir, config.METRIC_INFO_FILENAME), "w", encoding="utf-8") as f: json.dump(asdict(self), f, indent=4 if pretty_print else None) if self.license: with open(os.path.join(metric_info_dir, config.LICENSE_FILENAME), "w", encoding="utf-8") as f: f.write(self.license) @classmethod def from_directory(cls, metric_info_dir) -> "MetricInfo": """Create MetricInfo from the JSON file in `metric_info_dir`. Args: metric_info_dir: `str` The directory containing the metadata file. This should be the root directory of a specific dataset version. Example: ```py >>> from datasets import MetricInfo >>> metric_info = MetricInfo.from_directory("/path/to/directory/") ``` """ logger.info(f"Loading Metric info from {metric_info_dir}") if not metric_info_dir: raise ValueError("Calling MetricInfo.from_directory() with undefined metric_info_dir.") with open(os.path.join(metric_info_dir, config.METRIC_INFO_FILENAME), encoding="utf-8") as f: metric_info_dict = json.load(f) return cls.from_dict(metric_info_dict) @classmethod def from_dict(cls, metric_info_dict: dict) -> "MetricInfo": field_names = {f.name for f in dataclasses.fields(cls)} return cls(**{k: v for k, v in metric_info_dict.items() if k in field_names})
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/arrow_dataset.py
# Copyright 2020 The HuggingFace 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. # Lint as: python3 """ Simple Dataset wrapping an Arrow Table.""" import contextlib import copy import fnmatch import itertools import json import math import os import posixpath import re import shutil import sys import tempfile import time import warnings import weakref from collections import Counter from collections.abc import Mapping from copy import deepcopy from functools import partial, wraps from io import BytesIO from math import ceil, floor from pathlib import Path from random import sample from typing import ( TYPE_CHECKING, Any, BinaryIO, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, overload, ) from typing import Sequence as Sequence_ import fsspec import numpy as np import pandas as pd import pyarrow as pa import pyarrow.compute as pc from huggingface_hub import CommitInfo, CommitOperationAdd, CommitOperationDelete, DatasetCard, DatasetCardData, HfApi from multiprocess import Pool from . import config from .arrow_reader import ArrowReader from .arrow_writer import ArrowWriter, OptimizedTypedSequence from .data_files import sanitize_patterns from .download.streaming_download_manager import xgetsize from .features import Audio, ClassLabel, Features, Image, Sequence, Value from .features.features import ( FeatureType, _align_features, _check_if_features_can_be_aligned, generate_from_arrow_type, pandas_types_mapper, require_decoding, ) from .filesystems import is_remote_filesystem from .fingerprint import ( fingerprint_transform, format_kwargs_for_fingerprint, format_transform_for_fingerprint, generate_fingerprint, generate_random_fingerprint, get_temporary_cache_files_directory, is_caching_enabled, maybe_register_dataset_for_temp_dir_deletion, update_fingerprint, validate_fingerprint, ) from .formatting import format_table, get_format_type_from_alias, get_formatter, query_table from .formatting.formatting import LazyDict, _is_range_contiguous from .info import DatasetInfo, DatasetInfosDict from .naming import _split_re from .search import IndexableMixin from .splits import NamedSplit, Split, SplitDict, SplitInfo from .table import ( InMemoryTable, MemoryMappedTable, Table, _memory_mapped_record_batch_reader_from_file, cast_array_to_feature, concat_tables, embed_table_storage, list_table_cache_files, table_cast, table_iter, table_visitor, ) from .tasks import TaskTemplate from .utils import logging from .utils import tqdm as hf_tqdm from .utils.deprecation_utils import deprecated from .utils.file_utils import estimate_dataset_size from .utils.hub import list_files_info, preupload_lfs_files from .utils.info_utils import is_small_dataset from .utils.metadata import MetadataConfigs from .utils.py_utils import ( Literal, asdict, convert_file_size_to_int, glob_pattern_to_regex, iflatmap_unordered, string_to_dict, unique_values, ) from .utils.stratify import stratified_shuffle_split_generate_indices from .utils.tf_utils import dataset_to_tf, minimal_tf_collate_fn, multiprocess_dataset_to_tf from .utils.typing import ListLike, PathLike if TYPE_CHECKING: import sqlite3 import pyspark import sqlalchemy from .dataset_dict import DatasetDict from .iterable_dataset import IterableDataset logger = logging.get_logger(__name__) PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED = ( "data/{split}-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.parquet" ) class DatasetInfoMixin: """This base class exposes some attributes of DatasetInfo at the base level of the Dataset for easy access. """ def __init__(self, info: DatasetInfo, split: Optional[NamedSplit]): self._info = info self._split = split @property def info(self): """[`~datasets.DatasetInfo`] object containing all the metadata in the dataset.""" return self._info @property def split(self): """[`~datasets.NamedSplit`] object corresponding to a named dataset split.""" return self._split @property def builder_name(self) -> str: return self._info.builder_name @property def citation(self) -> str: return self._info.citation @property def config_name(self) -> str: return self._info.config_name @property def dataset_size(self) -> Optional[int]: return self._info.dataset_size @property def description(self) -> str: return self._info.description @property def download_checksums(self) -> Optional[dict]: return self._info.download_checksums @property def download_size(self) -> Optional[int]: return self._info.download_size @property def features(self) -> Optional[Features]: return self._info.features.copy() if self._info.features is not None else None @property def homepage(self) -> Optional[str]: return self._info.homepage @property def license(self) -> Optional[str]: return self._info.license @property def size_in_bytes(self) -> Optional[int]: return self._info.size_in_bytes @property def supervised_keys(self): return self._info.supervised_keys @property def task_templates(self): return self._info.task_templates @property def version(self): return self._info.version class TensorflowDatasetMixin: _TF_DATASET_REFS = set() @staticmethod def _get_output_signature( dataset: "Dataset", collate_fn: Callable, collate_fn_args: dict, cols_to_retain: Optional[List[str]] = None, batch_size: Optional[int] = None, num_test_batches: int = 20, ): """Private method used by `to_tf_dataset()` to find the shapes and dtypes of samples from this dataset after being passed through the collate_fn. Tensorflow needs an exact signature for tf.numpy_function, so the only way to do this is to run test batches - the collator may add or rename columns, so we can't figure it out just by inspecting the dataset. Args: dataset (`Dataset`): Dataset to load samples from. collate_fn(`bool`): Shuffle the dataset order when loading. Recommended True for training, False for validation/evaluation. collate_fn(`Callable`): A function or callable object (such as a `DataCollator`) that will collate lists of samples into a batch. collate_fn_args (`Dict`): A `dict` of keyword arguments to be passed to the `collate_fn`. batch_size (`int`, optional): The size of batches loaded from the dataset. Used for shape inference. Can be None, which indicates that batch sizes can be variable. num_test_batches (`int`): The number of batches to load from the dataset for shape inference. Returns: `dict`: Dict mapping column names to tf.Tensorspec objects `dict`: Dict mapping column names to np.dtype objects """ if config.TF_AVAILABLE: import tensorflow as tf else: raise ImportError("Called a Tensorflow-specific function but Tensorflow is not installed.") if len(dataset) == 0: raise ValueError("Unable to get the output signature because the dataset is empty.") if batch_size is not None: batch_size = min(len(dataset), batch_size) test_batch_size = 1 if cols_to_retain is not None: cols_to_retain = list(set(cols_to_retain + ["label_ids", "label", "labels"])) test_batches = [] for _ in range(num_test_batches): indices = sample(range(len(dataset)), test_batch_size) test_batch = dataset[indices] if cols_to_retain is not None: test_batch = {key: value for key, value in test_batch.items() if key in cols_to_retain} test_batch = [{key: value[i] for key, value in test_batch.items()} for i in range(test_batch_size)] test_batch = collate_fn(test_batch, **collate_fn_args) test_batches.append(test_batch) tf_columns_to_signatures = {} np_columns_to_dtypes = {} for column in test_batches[0].keys(): raw_arrays = [batch[column] for batch in test_batches] # In case the collate_fn returns something strange np_arrays = [] for array in raw_arrays: if isinstance(array, np.ndarray): np_arrays.append(array) elif isinstance(array, tf.Tensor): np_arrays.append(array.numpy()) else: np_arrays.append(np.array(array)) if np.issubdtype(np_arrays[0].dtype, np.integer) or np_arrays[0].dtype == bool: tf_dtype = tf.int64 np_dtype = np.int64 elif np.issubdtype(np_arrays[0].dtype, np.number): tf_dtype = tf.float32 np_dtype = np.float32 elif np_arrays[0].dtype.kind == "U": # Unicode strings np_dtype = np.unicode_ tf_dtype = tf.string else: raise RuntimeError( f"Unrecognized array dtype {np_arrays[0].dtype}. \n" "Nested types and image/audio types are not supported yet." ) shapes = [array.shape for array in np_arrays] static_shape = [] for dim in range(len(shapes[0])): sizes = {shape[dim] for shape in shapes} if dim == 0: static_shape.append(batch_size) continue if len(sizes) == 1: # This dimension looks constant static_shape.append(sizes.pop()) else: # Use None for variable dimensions static_shape.append(None) tf_columns_to_signatures[column] = tf.TensorSpec(shape=static_shape, dtype=tf_dtype) np_columns_to_dtypes[column] = np_dtype return tf_columns_to_signatures, np_columns_to_dtypes def to_tf_dataset( self, batch_size: Optional[int] = None, columns: Optional[Union[str, List[str]]] = None, shuffle: bool = False, collate_fn: Optional[Callable] = None, drop_remainder: bool = False, collate_fn_args: Optional[Dict[str, Any]] = None, label_cols: Optional[Union[str, List[str]]] = None, prefetch: bool = True, num_workers: int = 0, num_test_batches: int = 20, ): """Create a `tf.data.Dataset` from the underlying Dataset. This `tf.data.Dataset` will load and collate batches from the Dataset, and is suitable for passing to methods like `model.fit()` or `model.predict()`. The dataset will yield `dicts` for both inputs and labels unless the `dict` would contain only a single key, in which case a raw `tf.Tensor` is yielded instead. Args: batch_size (`int`, *optional*): Size of batches to load from the dataset. Defaults to `None`, which implies that the dataset won't be batched, but the returned dataset can be batched later with `tf_dataset.batch(batch_size)`. columns (`List[str]` or `str`, *optional*): Dataset column(s) to load in the `tf.data.Dataset`. Column names that are created by the `collate_fn` and that do not exist in the original dataset can be used. shuffle(`bool`, defaults to `False`): Shuffle the dataset order when loading. Recommended `True` for training, `False` for validation/evaluation. drop_remainder(`bool`, defaults to `False`): Drop the last incomplete batch when loading. Ensures that all batches yielded by the dataset will have the same length on the batch dimension. collate_fn(`Callable`, *optional*): A function or callable object (such as a `DataCollator`) that will collate lists of samples into a batch. collate_fn_args (`Dict`, *optional*): An optional `dict` of keyword arguments to be passed to the `collate_fn`. label_cols (`List[str]` or `str`, defaults to `None`): Dataset column(s) to load as labels. Note that many models compute loss internally rather than letting Keras do it, in which case passing the labels here is optional, as long as they're in the input `columns`. prefetch (`bool`, defaults to `True`): Whether to run the dataloader in a separate thread and maintain a small buffer of batches for training. Improves performance by allowing data to be loaded in the background while the model is training. num_workers (`int`, defaults to `0`): Number of workers to use for loading the dataset. Only supported on Python versions >= 3.8. num_test_batches (`int`, defaults to `20`): Number of batches to use to infer the output signature of the dataset. The higher this number, the more accurate the signature will be, but the longer it will take to create the dataset. Returns: `tf.data.Dataset` Example: ```py >>> ds_train = ds["train"].to_tf_dataset( ... columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'], ... shuffle=True, ... batch_size=16, ... collate_fn=data_collator, ... ) ``` """ if config.TF_AVAILABLE: import tensorflow as tf else: raise ImportError("Called a Tensorflow-specific function but Tensorflow is not installed.") if (isinstance(columns, list) and len(columns) == 1) or ( isinstance(label_cols, list) and len(label_cols) == 1 ): warnings.warn( "The output of `to_tf_dataset` will change when a passing single element list for `labels` or " "`columns` in the next datasets version. To return a tuple structure rather than dict, pass a " "single string.\n" "Old behaviour: columns=['a'], labels=['labels'] -> (tf.Tensor, tf.Tensor) \n" " : columns='a', labels='labels' -> (tf.Tensor, tf.Tensor) \n" "New behaviour: columns=['a'],labels=['labels'] -> ({'a': tf.Tensor}, {'labels': tf.Tensor}) \n" " : columns='a', labels='labels' -> (tf.Tensor, tf.Tensor) ", FutureWarning, ) if isinstance(tf.distribute.get_strategy(), tf.distribute.TPUStrategy): logger.warning( "Note that to_tf_dataset() loads the data with a generator rather than a full tf.data " "pipeline and is not compatible with remote TPU connections. If you encounter errors, please " "try using a TPU VM or, if your data can fit in memory, loading it into memory as a dict of " "Tensors instead of streaming with to_tf_dataset()." ) if collate_fn is None: # Set a very simple default collator that just stacks things together collate_fn = minimal_tf_collate_fn if collate_fn_args is None: collate_fn_args = {} if label_cols and not columns: raise ValueError("Cannot specify label_cols without specifying columns!") if label_cols is None: label_cols = [] elif isinstance(label_cols, str): label_cols = [label_cols] if len(set(label_cols)) < len(label_cols): raise ValueError("List of label_cols contains duplicates.") if columns: if isinstance(columns, str): columns = [columns] if len(set(columns)) < len(columns): raise ValueError("List of columns contains duplicates.") cols_to_retain = list(set(columns + label_cols)) else: cols_to_retain = None # Indicates keeping all valid columns columns = [] if self.format["type"] not in ["custom", "numpy"]: dataset = self.with_format("numpy") else: dataset = self # TODO(Matt, QL): deprecate the retention of label_ids and label output_signature, columns_to_np_types = dataset._get_output_signature( dataset, collate_fn=collate_fn, collate_fn_args=collate_fn_args, cols_to_retain=cols_to_retain, batch_size=batch_size if drop_remainder else None, num_test_batches=num_test_batches, ) if "labels" in output_signature: if ("label_ids" in columns or "label" in columns) and "labels" not in columns: columns = [col for col in columns if col not in ["label_ids", "label"]] + ["labels"] if ("label_ids" in label_cols or "label" in label_cols) and "labels" not in label_cols: label_cols = [col for col in label_cols if col not in ["label_ids", "label"]] + ["labels"] for col in columns: if col not in output_signature: raise ValueError(f"Column {col} not found in dataset!") for col in label_cols: if col not in output_signature: raise ValueError(f"Label column {col} not found in dataset!") if num_workers == 0: tf_dataset = dataset_to_tf( dataset=dataset, cols_to_retain=cols_to_retain, collate_fn=collate_fn, collate_fn_args=collate_fn_args, columns_to_np_types=columns_to_np_types, output_signature=output_signature, shuffle=shuffle, batch_size=batch_size, drop_remainder=drop_remainder, ) elif num_workers > 0: if batch_size is None: raise NotImplementedError( "`batch_size` must be specified when using multiple workers, as unbatched multiprocessing " "is not supported yet. Please provide a `batch_size` if `num_workers` is greater than 0." ) tf_dataset = multiprocess_dataset_to_tf( dataset=dataset, cols_to_retain=cols_to_retain, collate_fn=collate_fn, collate_fn_args=collate_fn_args, columns_to_np_types=columns_to_np_types, output_signature=output_signature, shuffle=shuffle, batch_size=batch_size, drop_remainder=drop_remainder, num_workers=num_workers, ) else: raise ValueError("num_workers must be >= 0") def split_features_and_labels(input_batch): # TODO(Matt, QL): deprecate returning the dict content when there's only one key features = {key: tensor for key, tensor in input_batch.items() if key in columns} labels = {key: tensor for key, tensor in input_batch.items() if key in label_cols} if len(features) == 1: features = list(features.values())[0] if len(labels) == 1: labels = list(labels.values())[0] if isinstance(labels, dict) and len(labels) == 0: return features else: return features, labels if cols_to_retain is not None: tf_dataset = tf_dataset.map(split_features_and_labels) if prefetch: tf_dataset = tf_dataset.prefetch(tf.data.experimental.AUTOTUNE) # Remove a reference to the open Arrow file on delete def cleanup_callback(ref): dataset.__del__() self._TF_DATASET_REFS.remove(ref) self._TF_DATASET_REFS.add(weakref.ref(tf_dataset, cleanup_callback)) return tf_dataset class DatasetTransformationNotAllowedError(Exception): pass def transmit_format(func): """Wrapper for dataset transforms that recreate a new Dataset to transmit the format of the original dataset to the new dataset""" @wraps(func) def wrapper(*args, **kwargs): if args: self: "Dataset" = args[0] args = args[1:] else: self: "Dataset" = kwargs.pop("self") # don't use self.format since it returns a list of columns for 'columns' even if self_format_columns is None unformatted_columns = set(self.column_names) - set(self._format_columns or []) self_format = { "type": self._format_type, "format_kwargs": self._format_kwargs, "columns": self._format_columns, "output_all_columns": self._output_all_columns, } # apply actual function out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) datasets: List["Dataset"] = list(out.values()) if isinstance(out, dict) else [out] # re-apply format to the output for dataset in datasets: new_format = self_format.copy() if new_format["columns"] is not None: # new formatted columns = (columns - previously unformatted columns) # sort the columns to have a deterministic list of columns that we can compare with `out_format` new_format["columns"] = sorted(set(dataset.column_names) - unformatted_columns) out_format = { "type": dataset._format_type, "format_kwargs": dataset._format_kwargs, "columns": sorted(dataset._format_columns) if dataset._format_columns is not None else None, "output_all_columns": dataset._output_all_columns, } if out_format != new_format: fingerprint = dataset._fingerprint dataset.set_format(**new_format) dataset._fingerprint = fingerprint return out wrapper._decorator_name_ = "transmit_format" return wrapper def transmit_tasks(func): """Wrapper for dataset transforms that recreate a new Dataset to transmit the task templates of the original dataset to the new dataset""" @wraps(func) def wrapper(*args, **kwargs): if args: self: "Dataset" = args[0] args = args[1:] else: self: "Dataset" = kwargs.pop("self") # apply actual function out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs) datasets: List["Dataset"] = list(out.values()) if isinstance(out, dict) else [out] for dataset in datasets: # Remove task templates if a column mapping of the template is no longer valid if self.info.task_templates is not None: dataset.info.task_templates = [ template for template in self.info.task_templates if all( dataset._info.features.get(k) == self._info.features.get(k) for k in template.column_mapping.keys() ) ] return out wrapper._decorator_name_ = "transmit_tasks" return wrapper def update_metadata_with_features(table: Table, features: Features): """To be used in dataset transforms that modify the features of the dataset, in order to update the features stored in the metadata of its schema.""" features = Features({col_name: features[col_name] for col_name in table.column_names}) if table.schema.metadata is None or b"huggingface" not in table.schema.metadata: pa_metadata = ArrowWriter._build_metadata(DatasetInfo(features=features)) else: metadata = json.loads(table.schema.metadata[b"huggingface"].decode()) if "info" not in metadata: metadata["info"] = asdict(DatasetInfo(features=features)) else: metadata["info"]["features"] = asdict(DatasetInfo(features=features))["features"] pa_metadata = {"huggingface": json.dumps(metadata)} table = table.replace_schema_metadata(pa_metadata) return table def _check_table(table) -> Table: """We check the table type to make sure it's an instance of :class:`datasets.table.Table`""" if isinstance(table, pa.Table): # for a pyarrow table, we can just consider it as a in-memory table # this is here for backward compatibility return InMemoryTable(table) elif isinstance(table, Table): return table else: raise TypeError(f"Expected a pyarrow.Table or a datasets.table.Table object, but got {table}.") def _check_column_names(column_names: List[str]): """Check the column names to make sure they don't contain duplicates.""" counter = Counter(column_names) if not all(count == 1 for count in counter.values()): duplicated_columns = [col for col in counter if counter[col] > 1] raise ValueError(f"The table can't have duplicated columns but columns {duplicated_columns} are duplicated.") def _check_valid_indices_value(index, size): if (index < 0 and index + size < 0) or (index >= size): raise IndexError(f"Index {index} out of range for dataset of size {size}.") class NonExistentDatasetError(Exception): """Used when we expect the existence of a dataset""" pass class Dataset(DatasetInfoMixin, IndexableMixin, TensorflowDatasetMixin): """A Dataset backed by an Arrow table.""" def __init__( self, arrow_table: Table, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, indices_table: Optional[Table] = None, fingerprint: Optional[str] = None, ): info = info.copy() if info is not None else DatasetInfo() DatasetInfoMixin.__init__(self, info=info, split=split) IndexableMixin.__init__(self) self._data: Table = _check_table(arrow_table) self._indices: Optional[Table] = _check_table(indices_table) if indices_table is not None else None maybe_register_dataset_for_temp_dir_deletion(self) self._format_type: Optional[str] = None self._format_kwargs: dict = {} self._format_columns: Optional[list] = None self._output_all_columns: bool = False self._fingerprint: str = fingerprint # Read metadata if self._data.schema.metadata is not None and b"huggingface" in self._data.schema.metadata: metadata = json.loads(self._data.schema.metadata[b"huggingface"].decode()) if ( "fingerprint" in metadata and self._fingerprint is None ): # try to load fingerprint from the arrow file metadata self._fingerprint = metadata["fingerprint"] # Infer features if None inferred_features = Features.from_arrow_schema(arrow_table.schema) if self.info.features is None: self.info.features = inferred_features else: # make sure the nested columns are in the right order try: self.info.features = self.info.features.reorder_fields_as(inferred_features) except ValueError as e: raise ValueError( f"{e}\nThe 'source' features come from dataset_info.json, and the 'target' ones are those of the dataset arrow file." ) # Infer fingerprint if None if self._fingerprint is None: self._fingerprint = generate_fingerprint(self) # Sanity checks if self._info.features is None: raise ValueError("Features can't be None in a Dataset object") if self._fingerprint is None: raise ValueError("Fingerprint can't be None in a Dataset object") if self.info.features.type != inferred_features.type: raise ValueError( f"External features info don't match the dataset:\nGot\n{self.info.features}\nwith type\n{self.info.features.type}\n\nbut expected something like\n{inferred_features}\nwith type\n{inferred_features.type}" ) if self._indices is not None: if not pa.types.is_unsigned_integer(self._indices.column(0).type): raise ValueError( f"indices must be an Arrow table of unsigned integers, current type is {self._indices.column(0).type}" ) _check_column_names(self._data.column_names) self._data = update_metadata_with_features(self._data, self._info.features) @property def features(self) -> Features: features = super().features if features is None: # this is already checked in __init__ raise ValueError("Features can't be None in a Dataset object") return features @classmethod def from_file( cls, filename: str, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, indices_filename: Optional[str] = None, in_memory: bool = False, ) -> "Dataset": """Instantiate a Dataset backed by an Arrow table at filename. Args: filename (`str`): File name of the dataset. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`NamedSplit`, *optional*): Name of the dataset split. indices_filename (`str`, *optional*): File names of the indices. in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. Returns: [`Dataset`] """ table = ArrowReader.read_table(filename, in_memory=in_memory) if indices_filename is not None: indices_pa_table = ArrowReader.read_table(indices_filename, in_memory=in_memory) else: indices_pa_table = None return cls( arrow_table=table, info=info, split=split, indices_table=indices_pa_table, ) @classmethod def from_buffer( cls, buffer: pa.Buffer, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, indices_buffer: Optional[pa.Buffer] = None, ) -> "Dataset": """Instantiate a Dataset backed by an Arrow buffer. Args: buffer (`pyarrow.Buffer`): Arrow buffer. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`NamedSplit`, *optional*): Name of the dataset split. indices_buffer (`pyarrow.Buffer`, *optional*): Indices Arrow buffer. Returns: [`Dataset`] """ table = InMemoryTable.from_buffer(buffer) if indices_buffer is not None: indices_table = InMemoryTable.from_buffer(buffer) else: indices_table = None return cls(table, info=info, split=split, indices_table=indices_table) @classmethod def from_pandas( cls, df: pd.DataFrame, features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, preserve_index: Optional[bool] = None, ) -> "Dataset": """ Convert `pandas.DataFrame` to a `pyarrow.Table` to create a [`Dataset`]. The column types in the resulting Arrow Table are inferred from the dtypes of the `pandas.Series` in the DataFrame. In the case of non-object Series, the NumPy dtype is translated to its Arrow equivalent. In the case of `object`, we need to guess the datatype by looking at the Python objects in this Series. Be aware that Series of the `object` dtype don't carry enough information to always lead to a meaningful Arrow type. In the case that we cannot infer a type, e.g. because the DataFrame is of length 0 or the Series only contains `None/nan` objects, the type is set to `null`. This behavior can be avoided by constructing explicit features and passing it to this function. Args: df (`pandas.DataFrame`): Dataframe that contains the dataset. features ([`Features`], *optional*): Dataset features. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`NamedSplit`, *optional*): Name of the dataset split. preserve_index (`bool`, *optional*): Whether to store the index as an additional column in the resulting Dataset. The default of `None` will store the index as a column, except for `RangeIndex` which is stored as metadata only. Use `preserve_index=True` to force it to be stored as a column. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_pandas(df) ``` """ if info is not None and features is not None and info.features != features: raise ValueError( f"Features specified in `features` and `info.features` can't be different:\n{features}\n{info.features}" ) features = features if features is not None else info.features if info is not None else None if info is None: info = DatasetInfo() info.features = features table = InMemoryTable.from_pandas( df=df, preserve_index=preserve_index, ) if features is not None: # more expensive cast than InMemoryTable.from_pandas(..., schema=features.arrow_schema) # needed to support the str to Audio conversion for instance table = table.cast(features.arrow_schema) return cls(table, info=info, split=split) @classmethod def from_dict( cls, mapping: dict, features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, ) -> "Dataset": """ Convert `dict` to a `pyarrow.Table` to create a [`Dataset`]. Args: mapping (`Mapping`): Mapping of strings to Arrays or Python lists. features ([`Features`], *optional*): Dataset features. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`NamedSplit`, *optional*): Name of the dataset split. Returns: [`Dataset`] """ if info is not None and features is not None and info.features != features: raise ValueError( f"Features specified in `features` and `info.features` can't be different:\n{features}\n{info.features}" ) features = features if features is not None else info.features if info is not None else None arrow_typed_mapping = {} for col, data in mapping.items(): if isinstance(data, (pa.Array, pa.ChunkedArray)): data = cast_array_to_feature(data, features[col]) if features is not None else data else: data = OptimizedTypedSequence( features.encode_column(data, col) if features is not None else data, type=features[col] if features is not None else None, col=col, ) arrow_typed_mapping[col] = data mapping = arrow_typed_mapping pa_table = InMemoryTable.from_pydict(mapping=mapping) if info is None: info = DatasetInfo() info.features = features if info.features is None: info.features = Features( { col: generate_from_arrow_type(data.type) if isinstance(data, (pa.Array, pa.ChunkedArray)) else data.get_inferred_type() for col, data in mapping.items() } ) return cls(pa_table, info=info, split=split) @classmethod def from_list( cls, mapping: List[dict], features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, ) -> "Dataset": """ Convert a list of dicts to a `pyarrow.Table` to create a [`Dataset`]`. Note that the keys of the first entry will be used to determine the dataset columns, regardless of what is passed to features. Args: mapping (`List[dict]`): A list of mappings of strings to row values. features (`Features`, optional): Dataset features. info (`DatasetInfo`, optional): Dataset information, like description, citation, etc. split (`NamedSplit`, optional): Name of the dataset split. Returns: [`Dataset`] """ # for simplicity and consistency wrt OptimizedTypedSequence we do not use InMemoryTable.from_pylist here mapping = {k: [r.get(k) for r in mapping] for k in mapping[0]} if mapping else {} return cls.from_dict(mapping, features, info, split) @staticmethod def from_csv( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, num_proc: Optional[int] = None, **kwargs, ): """Create Dataset from CSV file(s). Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the CSV file(s). split ([`NamedSplit`], *optional*): Split name to be assigned to the dataset. features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default. <Added version="2.8.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to [`pandas.read_csv`]. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_csv('path/to/dataset.csv') ``` """ # Dynamic import to avoid circular dependency from .io.csv import CsvDatasetReader return CsvDatasetReader( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, num_proc=num_proc, **kwargs, ).read() @staticmethod def from_generator( generator: Callable, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, gen_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, **kwargs, ): """Create a Dataset from a generator. Args: generator (:`Callable`): A generator function that `yields` examples. features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. gen_kwargs(`dict`, *optional*): Keyword arguments to be passed to the `generator` callable. You can define a sharded dataset by passing the list of shards in `gen_kwargs` and setting `num_proc` greater than 1. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default. If `num_proc` is greater than one, then all list values in `gen_kwargs` must be the same length. These values will be split between calls to the generator. The number of shards will be the minimum of the shortest list in `gen_kwargs` and `num_proc`. <Added version="2.7.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to :[`GeneratorConfig`]. Returns: [`Dataset`] Example: ```py >>> def gen(): ... yield {"text": "Good", "label": 0} ... yield {"text": "Bad", "label": 1} ... >>> ds = Dataset.from_generator(gen) ``` ```py >>> def gen(shards): ... for shard in shards: ... with open(shard) as f: ... for line in f: ... yield {"line": line} ... >>> shards = [f"data{i}.txt" for i in range(32)] >>> ds = Dataset.from_generator(gen, gen_kwargs={"shards": shards}) ``` """ from .io.generator import GeneratorDatasetInputStream return GeneratorDatasetInputStream( generator=generator, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, gen_kwargs=gen_kwargs, num_proc=num_proc, **kwargs, ).read() @staticmethod def from_json( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, field: Optional[str] = None, num_proc: Optional[int] = None, **kwargs, ): """Create Dataset from JSON or JSON Lines file(s). Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the JSON or JSON Lines file(s). split ([`NamedSplit`], *optional*): Split name to be assigned to the dataset. features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. field (`str`, *optional*): Field name of the JSON file where the dataset is contained in. num_proc (`int`, *optional* defaults to `None`): Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default. <Added version="2.8.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to [`JsonConfig`]. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_json('path/to/dataset.json') ``` """ # Dynamic import to avoid circular dependency from .io.json import JsonDatasetReader return JsonDatasetReader( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, field=field, num_proc=num_proc, **kwargs, ).read() @staticmethod def from_parquet( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, columns: Optional[List[str]] = None, num_proc: Optional[int] = None, **kwargs, ): """Create Dataset from Parquet file(s). Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the Parquet file(s). split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. columns (`List[str]`, *optional*): If not `None`, only these columns will be read from the file. A column name may be a prefix of a nested field, e.g. 'a' will select 'a.b', 'a.c', and 'a.d.e'. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default. <Added version="2.8.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to [`ParquetConfig`]. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_parquet('path/to/dataset.parquet') ``` """ # Dynamic import to avoid circular dependency from .io.parquet import ParquetDatasetReader return ParquetDatasetReader( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, columns=columns, num_proc=num_proc, **kwargs, ).read() @staticmethod def from_text( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, num_proc: Optional[int] = None, **kwargs, ): """Create Dataset from text file(s). Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the text file(s). split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default. <Added version="2.8.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to [`TextConfig`]. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_text('path/to/dataset.txt') ``` """ # Dynamic import to avoid circular dependency from .io.text import TextDatasetReader return TextDatasetReader( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, num_proc=num_proc, **kwargs, ).read() @staticmethod def from_spark( df: "pyspark.sql.DataFrame", split: Optional[NamedSplit] = None, features: Optional[Features] = None, keep_in_memory: bool = False, cache_dir: str = None, working_dir: str = None, load_from_cache_file: bool = True, **kwargs, ): """Create a Dataset from Spark DataFrame. Dataset downloading is distributed over Spark workers. Args: df (`pyspark.sql.DataFrame`): The DataFrame containing the desired data. split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. When using a multi-node Spark cluster, the cache_dir must be accessible to both workers and the driver. keep_in_memory (`bool`): Whether to copy the data in-memory. working_dir (`str`, *optional*) Intermediate directory for each Spark worker to write data to before moving it to `cache_dir`. Setting a non-NFS intermediate directory may improve performance. load_from_cache_file (`bool`): Whether to load the dataset from the cache if possible. Returns: [`Dataset`] Example: ```py >>> df = spark.createDataFrame( >>> data=[[1, "Elia"], [2, "Teo"], [3, "Fang"]], >>> columns=["id", "name"], >>> ) >>> ds = Dataset.from_spark(df) ``` """ # Dynamic import to avoid circular dependency from .io.spark import SparkDatasetReader if sys.platform == "win32": raise EnvironmentError("Dataset.from_spark is not currently supported on Windows") return SparkDatasetReader( df, split=split, features=features, streaming=False, cache_dir=cache_dir, keep_in_memory=keep_in_memory, working_dir=working_dir, load_from_cache_file=load_from_cache_file, **kwargs, ).read() @staticmethod def from_sql( sql: Union[str, "sqlalchemy.sql.Selectable"], con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, **kwargs, ): """Create Dataset from SQL query or database table. Args: sql (`str` or `sqlalchemy.sql.Selectable`): SQL query to be executed or a table name. con (`str` or `sqlite3.Connection` or `sqlalchemy.engine.Connection` or `sqlalchemy.engine.Connection`): A [URI string](https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls) used to instantiate a database connection or a SQLite3/SQLAlchemy connection object. features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. **kwargs (additional keyword arguments): Keyword arguments to be passed to [`SqlConfig`]. Returns: [`Dataset`] Example: ```py >>> # Fetch a database table >>> ds = Dataset.from_sql("test_data", "postgres:///db_name") >>> # Execute a SQL query on the table >>> ds = Dataset.from_sql("SELECT sentence FROM test_data", "postgres:///db_name") >>> # Use a Selectable object to specify the query >>> from sqlalchemy import select, text >>> stmt = select([text("sentence")]).select_from(text("test_data")) >>> ds = Dataset.from_sql(stmt, "postgres:///db_name") ``` <Tip> The returned dataset can only be cached if `con` is specified as URI string. </Tip> """ from .io.sql import SqlDatasetReader return SqlDatasetReader( sql, con, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs, ).read() def __setstate__(self, state): self.__dict__.update(state) maybe_register_dataset_for_temp_dir_deletion(self) return self def __del__(self): if hasattr(self, "_data"): del self._data if hasattr(self, "_indices"): del self._indices def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # Here `del` is used to del the pyarrow tables. This properly closes the files used for memory mapped tables self.__del__() def save_to_disk( self, dataset_path: PathLike, fs="deprecated", max_shard_size: Optional[Union[str, int]] = None, num_shards: Optional[int] = None, num_proc: Optional[int] = None, storage_options: Optional[dict] = None, ): """ Saves a dataset to a dataset directory, or in a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`. For [`Image`] and [`Audio`] data: All the Image() and Audio() data are stored in the arrow files. If you want to store paths or urls, please use the Value("string") type. Args: dataset_path (`str`): Path (e.g. `dataset/train`) or remote URI (e.g. `s3://my-bucket/dataset/train`) of the dataset directory where the dataset will be saved to. fs (`fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem where the dataset will be saved to. <Deprecated version="2.8.0"> `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options` </Deprecated> max_shard_size (`int` or `str`, *optional*, defaults to `"500MB"`): The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"50MB"`). num_shards (`int`, *optional*): Number of shards to write. By default the number of shards depends on `max_shard_size` and `num_proc`. <Added version="2.8.0"/> num_proc (`int`, *optional*): Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default. <Added version="2.8.0"/> storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.8.0"/> Example: ```py >>> ds.save_to_disk("path/to/dataset/directory") >>> ds.save_to_disk("path/to/dataset/directory", max_shard_size="1GB") >>> ds.save_to_disk("path/to/dataset/directory", num_shards=1024) ``` """ if max_shard_size is not None and num_shards is not None: raise ValueError( "Failed to push_to_hub: please specify either max_shard_size or num_shards, but not both." ) if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.8.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options if self.list_indexes(): raise ValueError("please remove all the indexes using `dataset.drop_index` before saving a dataset") if num_shards is None: dataset_nbytes = self._estimate_nbytes() max_shard_size = convert_file_size_to_int(max_shard_size or config.MAX_SHARD_SIZE) num_shards = int(dataset_nbytes / max_shard_size) + 1 num_shards = max(num_shards, num_proc or 1) num_proc = num_proc if num_proc is not None else 1 num_shards = num_shards if num_shards is not None else num_proc fs: fsspec.AbstractFileSystem fs, _, _ = fsspec.get_fs_token_paths(dataset_path, storage_options=storage_options) if not is_remote_filesystem(fs): parent_cache_files_paths = { Path(cache_filename["filename"]).resolve().parent for cache_filename in self.cache_files } # Check that the dataset doesn't overwrite iself. It can cause a permission error on Windows and a segfault on linux. if Path(dataset_path).expanduser().resolve() in parent_cache_files_paths: raise PermissionError( f"Tried to overwrite {Path(dataset_path).expanduser().resolve()} but a dataset can't overwrite itself." ) fs.makedirs(dataset_path, exist_ok=True) # Get json serializable state state = { key: self.__dict__[key] for key in [ "_fingerprint", "_format_columns", "_format_kwargs", "_format_type", "_output_all_columns", ] } state["_split"] = str(self.split) if self.split is not None else self.split state["_data_files"] = [ {"filename": f"data-{shard_idx:05d}-of-{num_shards:05d}.arrow"} for shard_idx in range(num_shards) ] for k in state["_format_kwargs"].keys(): try: json.dumps(state["_format_kwargs"][k]) except TypeError as e: raise TypeError( str(e) + f"\nThe format kwargs must be JSON serializable, but key '{k}' isn't." ) from None # Get json serializable dataset info dataset_info = asdict(self._info) shards_done = 0 pbar = hf_tqdm( unit=" examples", total=len(self), desc=f"Saving the dataset ({shards_done}/{num_shards} shards)", ) kwargs_per_job = ( { "job_id": shard_idx, "shard": self.shard(num_shards=num_shards, index=shard_idx, contiguous=True), "fpath": posixpath.join(dataset_path, f"data-{shard_idx:05d}-of-{num_shards:05d}.arrow"), "storage_options": storage_options, } for shard_idx in range(num_shards) ) shard_lengths = [None] * num_shards shard_sizes = [None] * num_shards if num_proc > 1: with Pool(num_proc) as pool: with pbar: for job_id, done, content in iflatmap_unordered( pool, Dataset._save_to_disk_single, kwargs_iterable=kwargs_per_job ): if done: shards_done += 1 pbar.set_description(f"Saving the dataset ({shards_done}/{num_shards} shards)") logger.debug(f"Finished writing shard number {job_id} of {num_shards}.") shard_lengths[job_id], shard_sizes[job_id] = content else: pbar.update(content) else: with pbar: for kwargs in kwargs_per_job: for job_id, done, content in Dataset._save_to_disk_single(**kwargs): if done: shards_done += 1 pbar.set_description(f"Saving the dataset ({shards_done}/{num_shards} shards)") logger.debug(f"Finished writing shard number {job_id} of {num_shards}.") shard_lengths[job_id], shard_sizes[job_id] = content else: pbar.update(content) with fs.open( posixpath.join(dataset_path, config.DATASET_STATE_JSON_FILENAME), "w", encoding="utf-8" ) as state_file: json.dump(state, state_file, indent=2, sort_keys=True) with fs.open( posixpath.join(dataset_path, config.DATASET_INFO_FILENAME), "w", encoding="utf-8" ) as dataset_info_file: # Sort only the first level of keys, or we might shuffle fields of nested features if we use sort_keys=True sorted_keys_dataset_info = {key: dataset_info[key] for key in sorted(dataset_info)} json.dump(sorted_keys_dataset_info, dataset_info_file, indent=2) @staticmethod def _save_to_disk_single(job_id: int, shard: "Dataset", fpath: str, storage_options: Optional[dict]): batch_size = config.DEFAULT_MAX_BATCH_SIZE num_examples_progress_update = 0 writer = ArrowWriter( features=shard.features, path=fpath, storage_options=storage_options, embed_local_files=True, ) try: _time = time.time() for pa_table in shard.with_format("arrow").iter(batch_size): writer.write_table(pa_table) num_examples_progress_update += len(pa_table) if time.time() > _time + config.PBAR_REFRESH_TIME_INTERVAL: _time = time.time() yield job_id, False, num_examples_progress_update num_examples_progress_update = 0 finally: yield job_id, False, num_examples_progress_update num_examples, num_bytes = writer.finalize() writer.close() yield job_id, True, (num_examples, num_bytes) @staticmethod def _build_local_temp_path(uri_or_path: str) -> Path: """ Builds and returns a Path concatenating a local temporary dir with the dir path (or absolute/relative path extracted from the uri) passed. Args: uri_or_path (`str`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3://my-bucket/dataset/train"`) to concatenate. Returns: :class:`Path`: the concatenated path (temp dir + path) """ src_dataset_path = Path(uri_or_path) tmp_dir = get_temporary_cache_files_directory() return Path(tmp_dir, src_dataset_path.relative_to(src_dataset_path.anchor)) @staticmethod def load_from_disk( dataset_path: str, fs="deprecated", keep_in_memory: Optional[bool] = None, storage_options: Optional[dict] = None, ) -> "Dataset": """ Loads a dataset that was previously saved using [`save_to_disk`] from a dataset directory, or from a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`. Args: dataset_path (`str`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3//my-bucket/dataset/train"`) of the dataset directory where the dataset will be loaded from. fs (`fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem where the dataset will be saved to. <Deprecated version="2.8.0"> `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options` </Deprecated> keep_in_memory (`bool`, defaults to `None`): Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](../cache#improve-performance) section. storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.8.0"/> Returns: [`Dataset`] or [`DatasetDict`]: - If `dataset_path` is a path of a dataset directory, the dataset requested. - If `dataset_path` is a path of a dataset dict directory, a `datasets.DatasetDict` with each split. Example: ```py >>> ds = load_from_disk("path/to/dataset/directory") ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.8.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, _, [dataset_path] = fsspec.get_fs_token_paths(dataset_path, storage_options=storage_options) dest_dataset_path = dataset_path dataset_dict_json_path = posixpath.join(dest_dataset_path, config.DATASETDICT_JSON_FILENAME) dataset_state_json_path = posixpath.join(dest_dataset_path, config.DATASET_STATE_JSON_FILENAME) dataset_info_path = posixpath.join(dest_dataset_path, config.DATASET_INFO_FILENAME) dataset_dict_is_file = fs.isfile(dataset_dict_json_path) dataset_info_is_file = fs.isfile(dataset_info_path) dataset_state_is_file = fs.isfile(dataset_state_json_path) if not dataset_info_is_file and not dataset_state_is_file: if dataset_dict_is_file: raise FileNotFoundError( f"No such files: '{dataset_info_path}', nor '{dataset_state_json_path}' found. Expected to load a `Dataset` object, but got a `DatasetDict`. Please use either `datasets.load_from_disk` or `DatasetDict.load_from_disk` instead." ) raise FileNotFoundError( f"No such files: '{dataset_info_path}', nor '{dataset_state_json_path}' found. Expected to load a `Dataset` object but provided path is not a `Dataset`." ) if not dataset_info_is_file: if dataset_dict_is_file: raise FileNotFoundError( f"No such file: '{dataset_info_path}' found. Expected to load a `Dataset` object, but got a `DatasetDict`. Please use either `datasets.load_from_disk` or `DatasetDict.load_from_disk` instead." ) raise FileNotFoundError( f"No such file: '{dataset_info_path}'. Expected to load a `Dataset` object but provided path is not a `Dataset`." ) if not dataset_state_is_file: if dataset_dict_is_file: raise FileNotFoundError( f"No such file: '{dataset_state_json_path}' found. Expected to load a `Dataset` object, but got a `DatasetDict`. Please use either `datasets.load_from_disk` or `DatasetDict.load_from_disk` instead." ) raise FileNotFoundError( f"No such file: '{dataset_state_json_path}'. Expected to load a `Dataset` object but provided path is not a `Dataset`." ) # copies file from filesystem if it is remote filesystem to local filesystem and modifies dataset_path to temp directory containing local copies if is_remote_filesystem(fs): src_dataset_path = dest_dataset_path dest_dataset_path = Dataset._build_local_temp_path(src_dataset_path) fs.download(src_dataset_path, dest_dataset_path.as_posix(), recursive=True) dataset_state_json_path = posixpath.join(dest_dataset_path, config.DATASET_STATE_JSON_FILENAME) dataset_info_path = posixpath.join(dest_dataset_path, config.DATASET_INFO_FILENAME) with open(dataset_state_json_path, encoding="utf-8") as state_file: state = json.load(state_file) with open(dataset_info_path, encoding="utf-8") as dataset_info_file: dataset_info = DatasetInfo.from_dict(json.load(dataset_info_file)) dataset_size = estimate_dataset_size( Path(dest_dataset_path, data_file["filename"]) for data_file in state["_data_files"] ) keep_in_memory = keep_in_memory if keep_in_memory is not None else is_small_dataset(dataset_size) table_cls = InMemoryTable if keep_in_memory else MemoryMappedTable arrow_table = concat_tables( table_cls.from_file(posixpath.join(dest_dataset_path, data_file["filename"])) for data_file in state["_data_files"] ) split = state["_split"] split = Split(split) if split is not None else split dataset = Dataset( arrow_table=arrow_table, info=dataset_info, split=split, fingerprint=state["_fingerprint"], ) format = { "type": state["_format_type"], "format_kwargs": state["_format_kwargs"], "columns": state["_format_columns"], "output_all_columns": state["_output_all_columns"], } dataset = dataset.with_format(**format) return dataset @property def data(self) -> Table: """The Apache Arrow table backing the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.data MemoryMappedTable text: string label: int64 ---- text: [["compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .","the soundtrack alone is worth the price of admission .","rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .","beneath the film's obvious determination to shock at any cost lies considerable skill and determination , backed by sheer nerve .","bielinsky is a filmmaker of impressive talent .","so beautifully acted and directed , it's clear that washington most certainly has a new career ahead of him if he so chooses .","a visual spectacle full of stunning images and effects .","a gentle and engrossing character study .","it's enough to watch huppert scheming , with her small , intelligent eyes as steady as any noir villain , and to enjoy the perfectly pitched web of tension that chabrol spins .","an engrossing portrait of uncompromising artists trying to create something original against the backdrop of a corporate music industry that only seems to care about the bottom line .",...,"ultimately , jane learns her place as a girl , softens up and loses some of the intensity that made her an interesting character to begin with .","ah-nuld's action hero days might be over .","it's clear why deuces wild , which was shot two years ago , has been gathering dust on mgm's shelf .","feels like nothing quite so much as a middle-aged moviemaker's attempt to surround himself with beautiful , half-naked women .","when the precise nature of matthew's predicament finally comes into sharp focus , the revelation fails to justify the build-up .","this picture is murder by numbers , and as easy to be bored by as your abc's , despite a few whopping shootouts .","hilarious musical comedy though stymied by accents thick as mud .","if you are into splatter movies , then you will probably have a reasonably good time with the salton sea .","a dull , simple-minded and stereotypical tale of drugs , death and mind-numbing indifference on the inner-city streets .","the feature-length stretch . . . strains the show's concept ."]] label: [[1,1,1,1,1,1,1,1,1,1,...,0,0,0,0,0,0,0,0,0,0]] ``` """ return self._data @property def cache_files(self) -> List[dict]: """The cache files containing the Apache Arrow table backing the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.cache_files [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}] ``` """ cache_files = list_table_cache_files(self._data) if self._indices is not None: cache_files += list_table_cache_files(self._indices) return [{"filename": cache_filename} for cache_filename in cache_files] @property def num_columns(self) -> int: """Number of columns in the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.num_columns 2 ``` """ return self._data.num_columns @property def num_rows(self) -> int: """Number of rows in the dataset (same as [`Dataset.__len__`]). Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.num_rows 1066 ``` """ if self._indices is not None: return self._indices.num_rows return self._data.num_rows @property def column_names(self) -> List[str]: """Names of the columns in the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.column_names ['text', 'label'] ``` """ return self._data.column_names @property def shape(self) -> Tuple[int, int]: """Shape of the dataset (number of columns, number of rows). Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.shape (1066, 2) ``` """ if self._indices is not None: return (self._indices.num_rows, self._data.num_columns) return self._data.shape def unique(self, column: str) -> List: """Return a list of the unique elements in a column. This is implemented in the low-level backend and as such, very fast. Args: column (`str`): Column name (list all the column names with [`~datasets.Dataset.column_names`]). Returns: `list`: List of unique elements in the given column. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.unique('label') [1, 0] ``` """ if column not in self._data.column_names: raise ValueError(f"Column ({column}) not in table columns ({self._data.column_names}).") if self._indices is not None and self._indices.num_rows != self._data.num_rows: dataset = self.flatten_indices() else: dataset = self return dataset._data.column(column).unique().to_pylist() def class_encode_column(self, column: str, include_nulls: bool = False) -> "Dataset": """Casts the given column as [`~datasets.features.ClassLabel`] and updates the table. Args: column (`str`): The name of the column to cast (list all the column names with [`~datasets.Dataset.column_names`]) include_nulls (`bool`, defaults to `False`): Whether to include null values in the class labels. If `True`, the null values will be encoded as the `"None"` class label. <Added version="1.14.2"/> Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("boolq", split="validation") >>> ds.features {'answer': Value(dtype='bool', id=None), 'passage': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None)} >>> ds = ds.class_encode_column('answer') >>> ds.features {'answer': ClassLabel(num_classes=2, names=['False', 'True'], id=None), 'passage': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None)} ``` """ # Sanity checks if column not in self._data.column_names: raise ValueError(f"Column ({column}) not in table columns ({self._data.column_names}).") src_feat = self._info.features[column] if not isinstance(src_feat, Value): raise ValueError( f"Class encoding is only supported for {Value.__name__} column, and column {column} is {type(src_feat).__name__}." ) if src_feat.dtype != "string" or (include_nulls and None in self.unique(column)): def stringify_column(batch): batch[column] = [ str(sample) if include_nulls or sample is not None else None for sample in batch[column] ] return batch dset = self.map( stringify_column, batched=True, desc="Stringifying the column", ) else: dset = self # Create the new feature class_names = sorted(str(sample) for sample in dset.unique(column) if include_nulls or sample is not None) dst_feat = ClassLabel(names=class_names) def cast_to_class_labels(batch): batch[column] = [ dst_feat.str2int(str(sample)) if include_nulls or sample is not None else None for sample in batch[column] ] return batch new_features = dset.features.copy() new_features[column] = dst_feat dset = dset.map( cast_to_class_labels, batched=True, features=new_features, desc="Casting to class labels", ) return dset @fingerprint_transform(inplace=False) def flatten(self, new_fingerprint: Optional[str] = None, max_depth=16) -> "Dataset": """Flatten the table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Returns: [`Dataset`]: A copy of the dataset with flattened columns. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("squad", split="train") >>> ds.features {'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None), 'context': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None), 'title': Value(dtype='string', id=None)} >>> ds.flatten() Dataset({ features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'], num_rows: 87599 }) ``` """ dataset = copy.deepcopy(self) for depth in range(1, max_depth): if any(isinstance(field.type, pa.StructType) for field in dataset._data.schema): dataset._data = dataset._data.flatten() else: break dataset.info.features = self._info.features.flatten(max_depth=max_depth) dataset.info.features = Features({col: dataset.info.features[col] for col in dataset.data.column_names}) dataset._data = update_metadata_with_features(dataset._data, dataset.features) logger.info(f'Flattened dataset from depth {depth} to depth {1 if depth + 1 < max_depth else "unknown"}.') dataset._fingerprint = new_fingerprint return dataset def cast( self, features: Features, batch_size: Optional[int] = 1000, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, num_proc: Optional[int] = None, ) -> "Dataset": """ Cast the dataset to a new set of features. Args: features ([`Features`]): New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `str` <-> `ClassLabel` you should use [`~datasets.Dataset.map`] to update the Dataset. batch_size (`int`, defaults to `1000`): Number of examples per batch provided to cast. If `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to cast. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. load_from_cache_file (`bool`, defaults to `True` if caching is enabled): If a cache file storing the current computation from `function` can be identified, use it instead of recomputing. cache_file_name (`str`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running [`~datasets.Dataset.map`]. num_proc (`int`, *optional*, defaults to `None`): Number of processes for multiprocessing. By default it doesn't use multiprocessing. Returns: [`Dataset`]: A copy of the dataset with casted features. Example: ```py >>> from datasets import load_dataset, ClassLabel, Value >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds.features.copy() >>> new_features['label'] = ClassLabel(names=['bad', 'good']) >>> new_features['text'] = Value('large_string') >>> ds = ds.cast(new_features) >>> ds.features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='large_string', id=None)} ``` """ if sorted(features) != sorted(self._data.column_names): raise ValueError( f"The columns in features ({list(features)}) must be identical " f"as the columns in the dataset: {self._data.column_names}" ) schema = features.arrow_schema format = self.format dataset = self.with_format("arrow") # capture the PyArrow version here to make the lambda serializable on Windows dataset = dataset.map( partial(table_cast, schema=schema), batched=True, batch_size=batch_size, keep_in_memory=keep_in_memory, load_from_cache_file=load_from_cache_file, cache_file_name=cache_file_name, writer_batch_size=writer_batch_size, num_proc=num_proc, features=features, desc="Casting the dataset", ) dataset = dataset.with_format(**format) return dataset @fingerprint_transform(inplace=False) def cast_column(self, column: str, feature: FeatureType, new_fingerprint: Optional[str] = None) -> "Dataset": """Cast column to feature for decoding. Args: column (`str`): Column name. feature (`FeatureType`): Target feature. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Returns: [`Dataset`] Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good'])) >>> ds.features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='string', id=None)} ``` """ if hasattr(feature, "decode_example"): dataset = copy.deepcopy(self) dataset._info.features[column] = feature dataset._fingerprint = new_fingerprint dataset._data = dataset._data.cast(dataset.features.arrow_schema) dataset._data = update_metadata_with_features(dataset._data, dataset.features) return dataset else: features = self.features features[column] = feature return self.cast(features) @transmit_tasks @transmit_format @fingerprint_transform(inplace=False) def remove_columns(self, column_names: Union[str, List[str]], new_fingerprint: Optional[str] = None) -> "Dataset": """ Remove one or several column(s) in the dataset and the features associated to them. You can also remove a column using [`~datasets.Dataset.map`] with `remove_columns` but the present method is in-place (doesn't copy the data to a new dataset) and is thus faster. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to remove. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Returns: [`Dataset`]: A copy of the dataset object without the columns to remove. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.remove_columns('label') Dataset({ features: ['text'], num_rows: 1066 }) >>> ds.remove_columns(column_names=ds.column_names) # Removing all the columns returns an empty dataset with the `num_rows` property set to 0 Dataset({ features: [], num_rows: 0 }) ``` """ dataset = copy.deepcopy(self) if isinstance(column_names, str): column_names = [column_names] for column_name in column_names: if column_name not in dataset._data.column_names: raise ValueError( f"Column name {column_name} not in the dataset. " f"Current columns in the dataset: {dataset._data.column_names}" ) for column_name in column_names: del dataset._info.features[column_name] dataset._data = dataset._data.drop(column_names) dataset._data = update_metadata_with_features(dataset._data, dataset.features) dataset._fingerprint = new_fingerprint return dataset @transmit_tasks @fingerprint_transform(inplace=False) def rename_column( self, original_column_name: str, new_column_name: str, new_fingerprint: Optional[str] = None ) -> "Dataset": """ Rename a column in the dataset, and move the features associated to the original column under the new column name. Args: original_column_name (`str`): Name of the column to rename. new_column_name (`str`): New name for the column. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Returns: [`Dataset`]: A copy of the dataset with a renamed column. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.rename_column('label', 'label_new') Dataset({ features: ['text', 'label_new'], num_rows: 1066 }) ``` """ dataset = copy.deepcopy(self) if original_column_name not in dataset._data.column_names: raise ValueError( f"Original column name {original_column_name} not in the dataset. " f"Current columns in the dataset: {dataset._data.column_names}" ) if new_column_name in dataset._data.column_names: raise ValueError( f"New column name {new_column_name} already in the dataset. " f"Please choose a column name which is not already in the dataset. " f"Current columns in the dataset: {dataset._data.column_names}" ) if not new_column_name: raise ValueError("New column name is empty.") def rename(columns): return [new_column_name if col == original_column_name else col for col in columns] new_column_names = rename(self._data.column_names) if self._format_columns is not None: dataset._format_columns = rename(self._format_columns) dataset._info.features = Features( { new_column_name if col == original_column_name else col: feature for col, feature in self._info.features.items() } ) dataset._data = dataset._data.rename_columns(new_column_names) dataset._data = update_metadata_with_features(dataset._data, dataset.features) dataset._fingerprint = new_fingerprint return dataset @transmit_tasks @fingerprint_transform(inplace=False) def rename_columns(self, column_mapping: Dict[str, str], new_fingerprint: Optional[str] = None) -> "Dataset": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. Args: column_mapping (`Dict[str, str]`): A mapping of columns to rename to their new names new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Returns: [`Dataset`]: A copy of the dataset with renamed columns Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'}) Dataset({ features: ['text_new', 'label_new'], num_rows: 1066 }) ``` """ dataset = copy.deepcopy(self) extra_columns = set(column_mapping.keys()) - set(dataset.column_names) if extra_columns: raise ValueError( f"Original column names {extra_columns} not in the dataset. " f"Current columns in the dataset: {dataset._data.column_names}" ) number_of_duplicates_in_new_columns = len(column_mapping.values()) - len(set(column_mapping.values())) if number_of_duplicates_in_new_columns != 0: raise ValueError( "New column names must all be different, but this column mapping " f"has {number_of_duplicates_in_new_columns} duplicates" ) empty_new_columns = [new_col for new_col in column_mapping.values() if not new_col] if empty_new_columns: raise ValueError(f"New column names {empty_new_columns} are empty.") def rename(columns): return [column_mapping[col] if col in column_mapping else col for col in columns] new_column_names = rename(self._data.column_names) if self._format_columns is not None: dataset._format_columns = rename(self._format_columns) dataset._info.features = Features( { column_mapping[col] if col in column_mapping else col: feature for col, feature in (self._info.features or {}).items() } ) dataset._data = dataset._data.rename_columns(new_column_names) dataset._data = update_metadata_with_features(dataset._data, dataset.features) dataset._fingerprint = new_fingerprint return dataset @transmit_tasks @transmit_format @fingerprint_transform(inplace=False) def select_columns(self, column_names: Union[str, List[str]], new_fingerprint: Optional[str] = None) -> "Dataset": """Select one or several column(s) in the dataset and the features associated to them. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to keep. new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Returns: [`Dataset`]: A copy of the dataset object which only consists of selected columns. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.select_columns(['text']) Dataset({ features: ['text'], num_rows: 1066 }) ``` """ if isinstance(column_names, str): column_names = [column_names] for column_name in column_names: if column_name not in self._data.column_names: raise ValueError( f"Column name {column_name} not in the " "dataset. Current columns in the dataset: " f"{self._data.column_names}." ) dataset = copy.deepcopy(self) dataset._data = dataset._data.select(column_names) dataset._info.features = Features({col: self._info.features[col] for col in dataset._data.column_names}) dataset._data = update_metadata_with_features(dataset._data, dataset.features) dataset._fingerprint = new_fingerprint return dataset def __len__(self): """Number of rows in the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.__len__ <bound method Dataset.__len__ of Dataset({ features: ['text', 'label'], num_rows: 1066 })> ``` """ return self.num_rows def __iter__(self): """Iterate through the examples. If a formatting is set with :meth:`Dataset.set_format` rows will be returned with the selected format. """ if self._indices is None: # Fast iteration # Benchmark: https://gist.github.com/mariosasko/0248288a2e3a7556873969717c1fe52b (fast_iter_batch) format_kwargs = self._format_kwargs if self._format_kwargs is not None else {} formatter = get_formatter(self._format_type, features=self._info.features, **format_kwargs) batch_size = config.ARROW_READER_BATCH_SIZE_IN_DATASET_ITER for pa_subtable in table_iter(self.data, batch_size=batch_size): for i in range(pa_subtable.num_rows): pa_subtable_ex = pa_subtable.slice(i, 1) formatted_output = format_table( pa_subtable_ex, 0, formatter=formatter, format_columns=self._format_columns, output_all_columns=self._output_all_columns, ) yield formatted_output else: for i in range(self.num_rows): yield self._getitem( i, ) def iter(self, batch_size: int, drop_last_batch: bool = False): """Iterate through the batches of size `batch_size`. If a formatting is set with [`~datasets.Dataset.set_format`] rows will be returned with the selected format. Args: batch_size (:obj:`int`): size of each batch to yield. drop_last_batch (:obj:`bool`, default `False`): Whether a last batch smaller than the batch_size should be dropped """ if self._indices is None: # Fast iteration # Benchmark: https://gist.github.com/mariosasko/0248288a2e3a7556873969717c1fe52b (fast_iter_batch) format_kwargs = self._format_kwargs if self._format_kwargs is not None else {} formatter = get_formatter(self._format_type, features=self._info.features, **format_kwargs) for pa_subtable in table_iter(self.data, batch_size=batch_size, drop_last_batch=drop_last_batch): formatted_batch = format_table( pa_subtable, range(pa_subtable.num_rows), formatter=formatter, format_columns=self._format_columns, output_all_columns=self._output_all_columns, ) yield formatted_batch else: num_rows = self.num_rows if not drop_last_batch else self.num_rows // batch_size * batch_size for i in range(0, num_rows, batch_size): yield self._getitem( slice(i, i + batch_size), ) def __repr__(self): return f"Dataset({{\n features: {list(self._info.features.keys())},\n num_rows: {self.num_rows}\n}})" @property def format(self): return { "type": self._format_type, "format_kwargs": self._format_kwargs, "columns": self.column_names if self._format_columns is None else self._format_columns, "output_all_columns": self._output_all_columns, } @contextlib.contextmanager def formatted_as( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """To be used in a `with` statement. Set `__getitem__` return format (type and columns). Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__`` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the output. `None` means `__getitem__` returns all columns (default). output_all_columns (`bool`, defaults to `False`): Keep un-formatted columns as well in the output (as python objects). **format_kwargs (additional keyword arguments): Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`. """ old_format_type = self._format_type old_format_kwargs = self._format_kwargs old_format_columns = self._format_columns old_output_all_columns = self._output_all_columns try: self.set_format(type, columns, output_all_columns, **format_kwargs) yield finally: self.set_format(old_format_type, old_format_columns, old_output_all_columns, **old_format_kwargs) @fingerprint_transform(inplace=True) def set_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for example "numpy") is used to format batches when using `__getitem__`. It's also possible to use custom transforms for formatting using [`~datasets.Dataset.set_transform`]. Args: type (`str`, *optional*): Either output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the output. `None` means `__getitem__` returns all columns (default). output_all_columns (`bool`, defaults to `False`): Keep un-formatted columns as well in the output (as python objects). **format_kwargs (additional keyword arguments): Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`. It is possible to call [`~datasets.Dataset.map`] after calling `set_format`. Since `map` may add new columns, then the list of formatted columns gets updated. In this case, if you apply `map` on a dataset to add a new column, then this column will be formatted as: ``` new formatted columns = (all columns - previously unformatted columns) ``` Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True) >>> ds.set_format(type='numpy', columns=['text', 'label']) >>> ds.format {'type': 'numpy', 'format_kwargs': {}, 'columns': ['text', 'label'], 'output_all_columns': False} ``` """ format_kwargs.update(format_kwargs.pop("format_kwargs", {})) # allow to use self.set_format(**self.format) # Check that the format_type and format_kwargs are valid and make it possible to have a Formatter type = get_format_type_from_alias(type) get_formatter(type, features=self._info.features, **format_kwargs) # Check filter column if isinstance(columns, str): columns = [columns] if isinstance(columns, tuple): columns = list(columns) if columns is not None and any(col not in self._data.column_names for col in columns): raise ValueError( f"Columns {list(filter(lambda col: col not in self._data.column_names, columns))} not in the dataset. Current columns in the dataset: {self._data.column_names}" ) if columns is not None: columns = columns.copy() # Ensures modifications made to the list after this call don't cause bugs self._format_type = type self._format_kwargs = format_kwargs self._format_columns = columns self._output_all_columns = output_all_columns logger.debug( "Set __getitem__(key) output type to %s for %s columns " " (when key is int or slice) and %s output other (un-formatted) columns.", "python objects" if type is None else type, "no" if columns is None else str(columns), "do" if output_all_columns else "don't", ) def reset_format(self): """Reset `__getitem__` return format to python objects and all columns. Same as `self.set_format()` Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True) >>> ds.set_format(type='numpy', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label']) >>> ds.format {'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'], 'format_kwargs': {}, 'output_all_columns': False, 'type': 'numpy'} >>> ds.reset_format() >>> ds.format {'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'], 'format_kwargs': {}, 'output_all_columns': False, 'type': None} ``` """ self.set_format() def set_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ): """Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. As [`~datasets.Dataset.set_format`], this can be reset using [`~datasets.Dataset.reset_format`]. Args: transform (`Callable`, *optional*): User-defined formatting transform, replaces the format defined by [`~datasets.Dataset.set_format`]. A formatting function is a callable that takes a batch (as a `dict`) as input and returns a batch. This function is applied right before returning the objects in `__getitem__`. columns (`List[str]`, *optional*): Columns to format in the output. If specified, then the input batch of the transform only contains those columns. output_all_columns (`bool`, defaults to `False`): Keep un-formatted columns as well in the output (as python objects). If set to True, then the other un-formatted columns are kept with the output of the transform. Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased') >>> def encode(batch): ... return tokenizer(batch['text'], padding=True, truncation=True, return_tensors='pt') >>> ds.set_transform(encode) >>> ds[0] {'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), 'input_ids': tensor([ 101, 29353, 2135, 15102, 1996, 9428, 20868, 2890, 8663, 6895, 20470, 2571, 3663, 2090, 4603, 3017, 3008, 1998, 2037, 24211, 5637, 1998, 11690, 2336, 1012, 102]), 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])} ``` """ self.set_format("custom", columns=columns, output_all_columns=output_all_columns, transform=transform) def with_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for example "numpy") is used to format batches when using `__getitem__`. It's also possible to use custom transforms for formatting using [`~datasets.Dataset.with_transform`]. Contrary to [`~datasets.Dataset.set_format`], `with_format` returns a new [`Dataset`] object. Args: type (`str`, *optional*): Either output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the output. `None` means `__getitem__` returns all columns (default). output_all_columns (`bool`, defaults to `False`): Keep un-formatted columns as well in the output (as python objects). **format_kwargs (additional keyword arguments): Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`. Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True) >>> ds.format {'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'], 'format_kwargs': {}, 'output_all_columns': False, 'type': None} >>> ds = ds.with_format(type='tensorflow', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label']) >>> ds.format {'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'], 'format_kwargs': {}, 'output_all_columns': False, 'type': 'tensorflow'} ``` """ dataset = copy.deepcopy(self) dataset.set_format(type=type, columns=columns, output_all_columns=output_all_columns, **format_kwargs) return dataset def with_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ): """Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. As [`~datasets.Dataset.set_format`], this can be reset using [`~datasets.Dataset.reset_format`]. Contrary to [`~datasets.Dataset.set_transform`], `with_transform` returns a new [`Dataset`] object. Args: transform (`Callable`, `optional`): User-defined formatting transform, replaces the format defined by [`~datasets.Dataset.set_format`]. A formatting function is a callable that takes a batch (as a `dict`) as input and returns a batch. This function is applied right before returning the objects in `__getitem__`. columns (`List[str]`, `optional`): Columns to format in the output. If specified, then the input batch of the transform only contains those columns. output_all_columns (`bool`, defaults to `False`): Keep un-formatted columns as well in the output (as python objects). If set to `True`, then the other un-formatted columns are kept with the output of the transform. Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> def encode(example): ... return tokenizer(example["text"], padding=True, truncation=True, return_tensors='pt') >>> ds = ds.with_transform(encode) >>> ds[0] {'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), 'input_ids': tensor([ 101, 18027, 16310, 16001, 1103, 9321, 178, 11604, 7235, 6617, 1742, 2165, 2820, 1206, 6588, 22572, 12937, 1811, 2153, 1105, 1147, 12890, 19587, 6463, 1105, 15026, 1482, 119, 102]), 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])} ``` """ dataset = copy.deepcopy(self) dataset.set_transform(transform=transform, columns=columns, output_all_columns=output_all_columns) return dataset @deprecated() def prepare_for_task(self, task: Union[str, TaskTemplate], id: int = 0) -> "Dataset": """ Prepare a dataset for the given task by casting the dataset's [`Features`] to standardized column names and types as detailed in [`datasets.tasks`](./task_templates). Casts [`datasets.DatasetInfo.features`] according to a task-specific schema. Intended for single-use only, so all task templates are removed from [`datasets.DatasetInfo.task_templates`] after casting. Args: task (`Union[str, TaskTemplate]`): The task to prepare the dataset for during training and evaluation. If `str`, supported tasks include: - `"text-classification"` - `"question-answering"` If [`TaskTemplate`], must be one of the task templates in [`datasets.tasks`](./task_templates). id (`int`, defaults to `0`): The id required to unambiguously identify the task template when multiple task templates of the same type are supported. """ # TODO(lewtun): Add support for casting nested features like answers.text and answers.answer_start in SQuAD if isinstance(task, str): tasks = [template.task for template in (self.info.task_templates or [])] compatible_templates = [template for template in (self.info.task_templates or []) if template.task == task] if not compatible_templates: raise ValueError( f"Task {task} is not compatible with this dataset! Available tasks: {list(unique_values(tasks))}" ) if not 0 <= id < len(compatible_templates): templates_list_str = "\n".join( f"- `{idx}` for task {template}" for idx, template in enumerate(compatible_templates) ) raise ValueError( f"Id {id} for task {task} is not in a valid range. Supported ids:\n{templates_list_str}" ) template = compatible_templates[id] elif isinstance(task, TaskTemplate): template = task else: raise ValueError( f"Expected a `str` or `datasets.TaskTemplate` object but got task {task} with type {type(task)}." ) template = template.align_with_features(self.info.features) column_mapping = template.column_mapping columns_to_drop = [column for column in self.column_names if column not in column_mapping] dataset = self.remove_columns(columns_to_drop) dataset = dataset.rename_columns(column_mapping) # We found a template so now flush `DatasetInfo` to skip the template update in `DatasetInfo.__post_init__` dataset.info.task_templates = None dataset = dataset.cast(features=template.features) return dataset def _getitem(self, key: Union[int, slice, str, ListLike[int]], **kwargs) -> Union[Dict, List]: """ Can be used to index columns (by string names) or rows (by integer, slice, or list-like of integer indices) """ if isinstance(key, bool): raise TypeError("dataset index must be int, str, slice or collection of int, not bool") format_type = kwargs["format_type"] if "format_type" in kwargs else self._format_type format_columns = kwargs["format_columns"] if "format_columns" in kwargs else self._format_columns output_all_columns = ( kwargs["output_all_columns"] if "output_all_columns" in kwargs else self._output_all_columns ) format_kwargs = kwargs["format_kwargs"] if "format_kwargs" in kwargs else self._format_kwargs format_kwargs = format_kwargs if format_kwargs is not None else {} formatter = get_formatter(format_type, features=self._info.features, **format_kwargs) pa_subtable = query_table(self._data, key, indices=self._indices) formatted_output = format_table( pa_subtable, key, formatter=formatter, format_columns=format_columns, output_all_columns=output_all_columns ) return formatted_output @overload def __getitem__(self, key: Union[int, slice, Iterable[int]]) -> Dict: # noqa: F811 ... @overload def __getitem__(self, key: str) -> List: # noqa: F811 ... def __getitem__(self, key): # noqa: F811 """Can be used to index columns (by string names) or rows (by integer index or iterable of indices or bools).""" return self._getitem(key) def __getitems__(self, keys: List) -> List: """Can be used to get a batch using a list of integers indices.""" batch = self.__getitem__(keys) n_examples = len(batch[next(iter(batch))]) return [{col: array[i] for col, array in batch.items()} for i in range(n_examples)] def cleanup_cache_files(self) -> int: """Clean up all cache files in the dataset cache directory, excepted the currently used cache file if there is one. Be careful when running this command that no other process is currently using other cache files. Returns: `int`: Number of removed files. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.cleanup_cache_files() 10 ``` """ current_cache_files = [os.path.abspath(cache_file["filename"]) for cache_file in self.cache_files] if not current_cache_files: return 0 cache_directory = os.path.dirname(current_cache_files[0]) logger.info(f"Listing files in {cache_directory}") files: List[str] = os.listdir(cache_directory) files_to_remove = [] for f_name in files: full_name = os.path.abspath(os.path.join(cache_directory, f_name)) if f_name.startswith("cache-") and f_name.endswith(".arrow"): if full_name in current_cache_files: logger.info(f"Keeping currently used cache file at {full_name}") continue files_to_remove.append(full_name) for file_path in files_to_remove: logger.info(f"Removing {file_path}") os.remove(file_path) return len(files_to_remove) def _get_cache_file_path(self, fingerprint): if is_caching_enabled() and self.cache_files: cache_file_name = "cache-" + fingerprint + ".arrow" cache_directory = os.path.dirname(self.cache_files[0]["filename"]) else: cache_file_name = "cache-" + generate_random_fingerprint() + ".arrow" cache_directory = get_temporary_cache_files_directory() cache_file_path = os.path.join(cache_directory, cache_file_name) return cache_file_path @transmit_tasks @transmit_format def map( self, function: Optional[Callable] = None, with_indices: bool = False, with_rank: bool = False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: bool = False, remove_columns: Optional[Union[str, List[str]]] = None, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, features: Optional[Features] = None, disable_nullable: bool = False, fn_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, suffix_template: str = "_{rank:05d}_of_{num_proc:05d}", new_fingerprint: Optional[str] = None, desc: Optional[str] = None, ) -> "Dataset": """ Apply a function to all the examples in the table (individually or in batches) and update the table. If your function returns a column that already exists, then it overwrites it. You can specify whether the function should be batched or not with the `batched` parameter: - If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`. - If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is `{"text": ["Hello there !"]}`. - If batched is `True` and `batch_size` is `n > 1`, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. Note that the last batch may have less than `n` examples. A batch is a dictionary, e.g. a batch of `n` examples is `{"text": ["Hello there !"] * n}`. Args: function (`Callable`): Function with one of the following signatures: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` and `with_rank=False` - `function(example: Dict[str, Any], *extra_args) -> Dict[str, Any]` if `batched=False` and `with_indices=True` and/or `with_rank=True` (one extra arg for each) - `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False` and `with_rank=False` - `function(batch: Dict[str, List], *extra_args) -> Dict[str, List]` if `batched=True` and `with_indices=True` and/or `with_rank=True` (one extra arg for each) For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`. with_rank (`bool`, defaults to `False`): Provide process rank to `function`. Note that in this case the signature of `function` should be `def function(example[, idx], rank): ...`. input_columns (`Optional[Union[str, List[str]]]`, defaults to `None`): The columns to be passed into `function` as positional arguments. If `None`, a `dict` mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`. If `batch_size <= 0` or `batch_size == None`, provide the full dataset as a single batch to `function`. drop_last_batch (`bool`, defaults to `False`): Whether a last batch smaller than the batch_size should be dropped instead of being processed by the function. remove_columns (`Optional[Union[str, List[str]]]`, defaults to `None`): Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the current computation from `function` can be identified, use it instead of recomputing. cache_file_name (`str`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. features (`Optional[datasets.Features]`, defaults to `None`): Use a specific Features to store the cache file instead of the automatically generated one. disable_nullable (`bool`, defaults to `False`): Disallow null values in the table. fn_kwargs (`Dict`, *optional*, defaults to `None`): Keyword arguments to be passed to `function`. num_proc (`int`, *optional*, defaults to `None`): Max number of processes when generating cache. Already cached shards are loaded sequentially. suffix_template (`str`): If `cache_file_name` is specified, then this suffix will be added at the end of the base name of each. Defaults to `"_{rank:05d}_of_{num_proc:05d}"`. For example, if `cache_file_name` is "processed.arrow", then for `rank=1` and `num_proc=4`, the resulting file would be `"processed_00001_of_00004.arrow"` for the default suffix. new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. desc (`str`, *optional*, defaults to `None`): Meaningful description to be displayed alongside with the progress bar while mapping examples. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> def add_prefix(example): ... example["text"] = "Review: " + example["text"] ... return example >>> ds = ds.map(add_prefix) >>> ds[0:3]["text"] ['Review: compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .', 'Review: the soundtrack alone is worth the price of admission .', 'Review: rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .'] # process a batch of examples >>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True) # set number of processors >>> ds = ds.map(add_prefix, num_proc=4) ``` """ if keep_in_memory and cache_file_name is not None: raise ValueError("Please use either `keep_in_memory` or `cache_file_name` but not both.") if num_proc is not None and num_proc <= 0: raise ValueError("num_proc must be an integer > 0.") # If the array is empty we do nothing (but we make sure to handle an empty indices mapping and remove the requested columns anyway) if len(self) == 0: if self._indices is not None: # empty indices mapping self = Dataset( self.data.slice(0, 0), info=self.info.copy(), split=self.split, fingerprint=new_fingerprint, ) if remove_columns: return self.remove_columns(remove_columns) else: return self if function is None: function = lambda x: x # noqa: E731 if isinstance(input_columns, str): input_columns = [input_columns] if input_columns is not None: for input_column in input_columns: if input_column not in self._data.column_names: raise ValueError( f"Input column {input_column} not in the dataset. Current columns in the dataset: {self._data.column_names}" ) if isinstance(remove_columns, str): remove_columns = [remove_columns] if remove_columns is not None and any(col not in self._data.column_names for col in remove_columns): raise ValueError( f"Column to remove {list(filter(lambda col: col not in self._data.column_names, remove_columns))} not in the dataset. Current columns in the dataset: {self._data.column_names}" ) load_from_cache_file = load_from_cache_file if load_from_cache_file is not None else is_caching_enabled() if fn_kwargs is None: fn_kwargs = {} if num_proc is not None and num_proc > len(self): num_proc = len(self) logger.warning( f"num_proc must be <= {len(self)}. Reducing num_proc to {num_proc} for dataset of size {len(self)}." ) dataset_kwargs = { "shard": self, "function": function, "with_indices": with_indices, "with_rank": with_rank, "input_columns": input_columns, "batched": batched, "batch_size": batch_size, "drop_last_batch": drop_last_batch, "remove_columns": remove_columns, "keep_in_memory": keep_in_memory, "writer_batch_size": writer_batch_size, "features": features, "disable_nullable": disable_nullable, "fn_kwargs": fn_kwargs, } if new_fingerprint is None: # we create a unique hash from the function, # current dataset file and the mapping args transform = format_transform_for_fingerprint(Dataset._map_single) kwargs_for_fingerprint = format_kwargs_for_fingerprint(Dataset._map_single, (), dataset_kwargs) kwargs_for_fingerprint["fingerprint_name"] = "new_fingerprint" new_fingerprint = update_fingerprint(self._fingerprint, transform, kwargs_for_fingerprint) else: validate_fingerprint(new_fingerprint) dataset_kwargs["new_fingerprint"] = new_fingerprint if self.cache_files: if cache_file_name is None: cache_file_name = self._get_cache_file_path(new_fingerprint) dataset_kwargs["cache_file_name"] = cache_file_name def load_processed_shard_from_cache(shard_kwargs): """Load a processed shard from cache if it exists, otherwise throw an error.""" shard = shard_kwargs["shard"] # Check if we've already cached this computation (indexed by a hash) if shard_kwargs["cache_file_name"] is not None: if os.path.exists(shard_kwargs["cache_file_name"]) and load_from_cache_file: info = shard.info.copy() info.features = features info.task_templates = None return Dataset.from_file(shard_kwargs["cache_file_name"], info=info, split=shard.split) raise NonExistentDatasetError num_shards = num_proc if num_proc is not None else 1 if batched and drop_last_batch: pbar_total = len(self) // num_shards // batch_size * num_shards * batch_size else: pbar_total = len(self) shards_done = 0 if num_proc is None or num_proc == 1: transformed_dataset = None try: transformed_dataset = load_processed_shard_from_cache(dataset_kwargs) logger.info(f"Loading cached processed dataset at {dataset_kwargs['cache_file_name']}") except NonExistentDatasetError: pass if transformed_dataset is None: with hf_tqdm( unit=" examples", total=pbar_total, desc=desc or "Map", ) as pbar: for rank, done, content in Dataset._map_single(**dataset_kwargs): if done: shards_done += 1 logger.debug(f"Finished processing shard number {rank} of {num_shards}.") transformed_dataset = content else: pbar.update(content) assert transformed_dataset is not None, "Failed to retrieve the result from map" # update fingerprint if the dataset changed if transformed_dataset._fingerprint != self._fingerprint: transformed_dataset._fingerprint = new_fingerprint return transformed_dataset else: def format_cache_file_name( cache_file_name: Optional[str], rank: Union[int, Literal["*"]], # noqa: F722 ) -> Optional[str]: if not cache_file_name: return cache_file_name sep = cache_file_name.rindex(".") base_name, extension = cache_file_name[:sep], cache_file_name[sep:] if isinstance(rank, int): cache_file_name = base_name + suffix_template.format(rank=rank, num_proc=num_proc) + extension logger.info(f"Process #{rank} will write at {cache_file_name}") else: cache_file_name = ( base_name + suffix_template.replace("{rank:05d}", "{rank}").format(rank=rank, num_proc=num_proc) + extension ) return cache_file_name def format_new_fingerprint(new_fingerprint: str, rank: int) -> str: new_fingerprint = new_fingerprint + suffix_template.format(rank=rank, num_proc=num_proc) validate_fingerprint(new_fingerprint) return new_fingerprint prev_env = deepcopy(os.environ) # check if parallelism if off # from https://github.com/huggingface/tokenizers/blob/bb668bc439dc34389b71dbb8ce0c597f15707b53/tokenizers/src/utils/parallelism.rs#L22 if prev_env.get("TOKENIZERS_PARALLELISM", "false").lower() not in ( "", "off", "false", "f", "no", "n", "0", ): logger.warning("Setting TOKENIZERS_PARALLELISM=false for forked processes.") os.environ["TOKENIZERS_PARALLELISM"] = "false" shards = [ self.shard(num_shards=num_proc, index=rank, contiguous=True, keep_in_memory=keep_in_memory) for rank in range(num_proc) ] kwargs_per_job = [ { **dataset_kwargs, "shard": shards[rank], "cache_file_name": format_cache_file_name(cache_file_name, rank), "rank": rank, "offset": sum(len(s) for s in shards[:rank]), "new_fingerprint": format_new_fingerprint(new_fingerprint, rank), } for rank in range(num_shards) ] transformed_shards = [None] * num_shards for rank in range(num_shards): try: transformed_shards[rank] = load_processed_shard_from_cache(kwargs_per_job[rank]) kwargs_per_job[rank] = None except NonExistentDatasetError: pass kwargs_per_job = [kwargs for kwargs in kwargs_per_job if kwargs is not None] # We try to create a pool with as many workers as dataset not yet cached. if kwargs_per_job: if len(kwargs_per_job) < num_shards: logger.info( f"Reprocessing {len(kwargs_per_job)}/{num_shards} shards because some of them were missing from the cache." ) with Pool(len(kwargs_per_job)) as pool: os.environ = prev_env logger.info(f"Spawning {num_proc} processes") with hf_tqdm( unit=" examples", total=pbar_total, desc=(desc or "Map") + f" (num_proc={num_proc})", ) as pbar: for rank, done, content in iflatmap_unordered( pool, Dataset._map_single, kwargs_iterable=kwargs_per_job ): if done: shards_done += 1 logger.debug(f"Finished processing shard number {rank} of {num_shards}.") transformed_shards[rank] = content else: pbar.update(content) # Avoids PermissionError on Windows (the error: https://github.com/huggingface/datasets/actions/runs/4026734820/jobs/6921621805) for kwargs in kwargs_per_job: del kwargs["shard"] else: logger.info(f"Loading cached processed dataset at {format_cache_file_name(cache_file_name, '*')}") assert ( None not in transformed_shards ), f"Failed to retrieve results from map: result list {transformed_shards} still contains None - at least one worker failed to return its results" logger.info(f"Concatenating {num_proc} shards") result = _concatenate_map_style_datasets(transformed_shards) # update fingerprint if the dataset changed if any( transformed_shard._fingerprint != shard._fingerprint for transformed_shard, shard in zip(transformed_shards, shards) ): result._fingerprint = new_fingerprint else: result._fingerprint = self._fingerprint return result @staticmethod def _map_single( shard: "Dataset", function: Optional[Callable] = None, with_indices: bool = False, with_rank: bool = False, input_columns: Optional[List[str]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: bool = False, remove_columns: Optional[List[str]] = None, keep_in_memory: bool = False, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, features: Optional[Features] = None, disable_nullable: bool = False, fn_kwargs: Optional[dict] = None, new_fingerprint: Optional[str] = None, rank: Optional[int] = None, offset: int = 0, ) -> Iterable[Tuple[int, bool, Union[int, "Dataset"]]]: """Apply a function to all the elements in the table (individually or in batches) and update the table (if function does update examples). Args: shard (`datasets.Dataset`): Dataset to map the transform on. function (`Callable`): with one of the following signature: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` and `with_rank=False` - `function(example: Dict[str, Any], *extra_args) -> Dict[str, Any]` if `batched=False` and `with_indices=True` and/or `with_rank=True` (one extra arg for each) - `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False` and `with_rank=False` - `function(batch: Dict[str, List], *extra_args) -> Dict[str, List]` if `batched=True` and `with_indices=True` and/or `with_rank=True` (one extra arg for each) For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: lambda x: x with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`. with_rank (`bool`, default `False`): Provide process rank to `function`. Note that in this case the signature of `function` should be `def function(example[, idx], rank): ...`. input_columns (`Optional[List[str]]`, defaults to `None`): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function` batch_size (`int`, optional, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True` `batch_size <= 0` or `batch_size == None`: Provide the full dataset as a single batch to `function` drop_last_batch (`bool`, default: `False`): Whether a last batch smaller than the batch_size should be dropped instead of being processed by the function. remove_columns (`Optional[List[str]]`, defaults to `None`): Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. cache_file_name (`str`, optional, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, default `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `.map()`. features (`Optional[datasets.Features]`, defaults to `None`): Use a specific Features to store the cache file instead of the automatically generated one. disable_nullable (`bool`, defaults to `False`): Disallow null values in the table. fn_kwargs (`Dict`, optional, defaults to `None`): Keyword arguments to be passed to `function` new_fingerprint (`str`, optional, defaults to `None`): the new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments rank: (`int`, optional, defaults to `None`): If specified, this is the process rank when doing multiprocessing offset: (`int`, defaults to 0): If specified, this is an offset applied to the indices passed to `function` if `with_indices=True`. """ if fn_kwargs is None: fn_kwargs = {} # If we do batch computation but no batch size is provided, default to the full dataset if batched and (batch_size is None or batch_size <= 0): batch_size = shard.num_rows # We set this variable to True after processing the first example/batch in # `apply_function_on_filtered_inputs` if the map function returns a dict. # If set to False, no new arrow table will be created update_data = None format_kwargs = shard._format_kwargs.copy() # Lazy formatting is only available for the default format (None/python) if not input_columns and shard._format_type is None: format_kwargs["lazy"] = True input_formatter = get_formatter( shard._format_type, features=shard.features, **format_kwargs, ) class NumExamplesMismatchError(Exception): pass def validate_function_output(processed_inputs, indices): """Validate output of the map function.""" if processed_inputs is not None and not isinstance(processed_inputs, (Mapping, pa.Table, pd.DataFrame)): raise TypeError( f"Provided `function` which is applied to all elements of table returns a variable of type {type(processed_inputs)}. Make sure provided `function` returns a variable of type `dict` (or a pyarrow table) to update the dataset or `None` if you are only interested in side effects." ) elif isinstance(indices, list) and isinstance(processed_inputs, Mapping): allowed_batch_return_types = (list, np.ndarray, pd.Series) if config.TF_AVAILABLE and "tensorflow" in sys.modules: import tensorflow as tf allowed_batch_return_types += (tf.Tensor,) if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch allowed_batch_return_types += (torch.Tensor,) if config.JAX_AVAILABLE and "jax" in sys.modules: import jax.numpy as jnp allowed_batch_return_types += (jnp.ndarray,) all_dict_values_are_lists = all( isinstance(value, allowed_batch_return_types) for value in processed_inputs.values() ) if all_dict_values_are_lists is False: raise TypeError( f"Provided `function` which is applied to all elements of table returns a `dict` of types {[type(x) for x in processed_inputs.values()]}. When using `batched=True`, make sure provided `function` returns a `dict` of types like `{allowed_batch_return_types}`." ) def apply_function_on_filtered_inputs(pa_inputs, indices, check_same_num_examples=False, offset=0): """Utility to apply the function on a selection of columns.""" nonlocal update_data inputs = format_table( pa_inputs, 0 if not batched else range(pa_inputs.num_rows), format_columns=input_columns, formatter=input_formatter, ) fn_args = [inputs] if input_columns is None else [inputs[col] for col in input_columns] if offset == 0: effective_indices = indices else: effective_indices = [i + offset for i in indices] if isinstance(indices, list) else indices + offset additional_args = () if with_indices: additional_args += (effective_indices,) if with_rank: additional_args += (rank,) processed_inputs = function(*fn_args, *additional_args, **fn_kwargs) if isinstance(processed_inputs, LazyDict): processed_inputs = { k: v for k, v in processed_inputs.data.items() if k not in processed_inputs.keys_to_format } returned_lazy_dict = True else: returned_lazy_dict = False if update_data is None: # Check if the function returns updated examples update_data = isinstance(processed_inputs, (Mapping, pa.Table, pd.DataFrame)) validate_function_output(processed_inputs, indices) if not update_data: return None # Nothing to update, let's move on if shard._format_type or input_columns: # TODO(QL, MS): ideally the behavior should be the same even if the dataset is formatted (may require major release) inputs_to_merge = dict(zip(pa_inputs.column_names, pa_inputs.itercolumns())) elif isinstance(inputs, LazyDict): inputs_to_merge = { k: (v if k not in inputs.keys_to_format else pa_inputs[k]) for k, v in inputs.data.items() } else: inputs_to_merge = inputs if remove_columns is not None: for column in remove_columns: # `function` can modify input in-place causing column to be already removed. if column in inputs_to_merge: inputs_to_merge.pop(column) if returned_lazy_dict and column in processed_inputs: processed_inputs.pop(column) if check_same_num_examples: input_num_examples = len(pa_inputs) processed_inputs_num_examples = len(processed_inputs[next(iter(processed_inputs.keys()))]) if input_num_examples != processed_inputs_num_examples: raise NumExamplesMismatchError() if isinstance(inputs, Mapping) and isinstance(processed_inputs, Mapping): # The .map() transform *updates* the dataset: # the output dictionary contains both the the input data and the output data. # The output dictionary may contain Arrow values from `inputs_to_merge` so that we can re-write them efficiently. return {**inputs_to_merge, **processed_inputs} else: return processed_inputs def init_buffer_and_writer(): # Prepare output buffer and batched writer in memory or on file if we update the table writer_features = features if writer_features is None: writer_features = shard.features update_features = True else: update_features = False if keep_in_memory or cache_file_name is None: buf_writer = pa.BufferOutputStream() tmp_file = None writer = ArrowWriter( features=writer_features, stream=buf_writer, writer_batch_size=writer_batch_size, update_features=update_features, fingerprint=new_fingerprint, disable_nullable=disable_nullable, ) else: buf_writer = None logger.info(f"Caching processed dataset at {cache_file_name}") tmp_file = tempfile.NamedTemporaryFile("wb", dir=os.path.dirname(cache_file_name), delete=False) writer = ArrowWriter( features=writer_features, path=tmp_file.name, writer_batch_size=writer_batch_size, update_features=update_features, fingerprint=new_fingerprint, disable_nullable=disable_nullable, ) return buf_writer, writer, tmp_file num_examples_progress_update = 0 # If `update_data` is True after processing the first example/batch, initalize these resources with `init_buffer_and_writer` buf_writer, writer, tmp_file = None, None, None # Optionally initialize the writer as a context manager with contextlib.ExitStack() as stack: try: arrow_formatted_shard = shard.with_format("arrow") # Loop over single examples or batches and write to buffer/file if examples are to be updated if not batched: shard_iterable = enumerate(arrow_formatted_shard) else: num_rows = len(shard) if not drop_last_batch else len(shard) // batch_size * batch_size shard_iterable = zip( range(0, num_rows, batch_size), arrow_formatted_shard.iter(batch_size, drop_last_batch=drop_last_batch), ) if not batched: _time = time.time() for i, example in shard_iterable: example = apply_function_on_filtered_inputs(example, i, offset=offset) if update_data: if i == 0: buf_writer, writer, tmp_file = init_buffer_and_writer() stack.enter_context(writer) if isinstance(example, pa.Table): writer.write_row(example) elif isinstance(example, pd.DataFrame): writer.write_row(pa.Table.from_pandas(example)) else: writer.write(example) num_examples_progress_update += 1 if time.time() > _time + config.PBAR_REFRESH_TIME_INTERVAL: _time = time.time() yield rank, False, num_examples_progress_update num_examples_progress_update = 0 else: _time = time.time() for i, batch in shard_iterable: num_examples_in_batch = len(batch) indices = list( range(*(slice(i, i + batch_size).indices(shard.num_rows))) ) # Something simpler? try: batch = apply_function_on_filtered_inputs( batch, indices, check_same_num_examples=len(shard.list_indexes()) > 0, offset=offset, ) except NumExamplesMismatchError: raise DatasetTransformationNotAllowedError( "Using `.map` in batched mode on a dataset with attached indexes is allowed only if it doesn't create or remove existing examples. You can first run `.drop_index() to remove your index and then re-add it." ) from None if update_data: if i == 0: buf_writer, writer, tmp_file = init_buffer_and_writer() stack.enter_context(writer) if isinstance(batch, pa.Table): writer.write_table(batch) elif isinstance(batch, pd.DataFrame): writer.write_table(pa.Table.from_pandas(batch)) else: writer.write_batch(batch) num_examples_progress_update += num_examples_in_batch if time.time() > _time + config.PBAR_REFRESH_TIME_INTERVAL: _time = time.time() yield rank, False, num_examples_progress_update num_examples_progress_update = 0 if update_data and writer is not None: writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file except (Exception, KeyboardInterrupt): yield rank, False, num_examples_progress_update if update_data: if writer is not None: writer.finalize() if tmp_file is not None: tmp_file.close() if os.path.exists(tmp_file.name): os.remove(tmp_file.name) raise yield rank, False, num_examples_progress_update if update_data and tmp_file is not None: tmp_file.close() shutil.move(tmp_file.name, cache_file_name) umask = os.umask(0o666) os.umask(umask) os.chmod(cache_file_name, 0o666 & ~umask) if update_data: # Create new Dataset from buffer or file info = shard.info.copy() info.features = writer._features info.task_templates = None if buf_writer is None: yield rank, True, Dataset.from_file(cache_file_name, info=info, split=shard.split) else: yield rank, True, Dataset.from_buffer(buf_writer.getvalue(), info=info, split=shard.split) else: yield rank, True, shard @transmit_format @fingerprint_transform( inplace=False, ignore_kwargs=["load_from_cache_file", "cache_file_name", "desc"], version="2.0.1" ) def filter( self, function: Optional[Callable] = None, with_indices=False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, fn_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, suffix_template: str = "_{rank:05d}_of_{num_proc:05d}", new_fingerprint: Optional[str] = None, desc: Optional[str] = None, ) -> "Dataset": """Apply a filter function to all the elements in the table in batches and update the table so that the dataset only includes examples according to the filter function. Args: function (`Callable`): Callable with one of the following signatures: - `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False` - `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False` - `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True` - `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if `with_indices=True, batched=True` If no function is provided, defaults to an always `True` function: `lambda x: True`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`. input_columns (`str` or `List[str]`, *optional*): The columns to be passed into `function` as positional arguments. If `None`, a `dict` mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched = True`. If `batched = False`, one example per batch is passed to `function`. If `batch_size <= 0` or `batch_size == None`, provide the full dataset as a single batch to `function`. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the current computation from `function` can be identified, use it instead of recomputing. cache_file_name (`str`, *optional*): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. fn_kwargs (`dict`, *optional*): Keyword arguments to be passed to `function`. num_proc (`int`, *optional*): Number of processes for multiprocessing. By default it doesn't use multiprocessing. suffix_template (`str`): If `cache_file_name` is specified, then this suffix will be added at the end of the base name of each. For example, if `cache_file_name` is `"processed.arrow"`, then for `rank = 1` and `num_proc = 4`, the resulting file would be `"processed_00001_of_00004.arrow"` for the default suffix (default `_{rank:05d}_of_{num_proc:05d}`). new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. desc (`str`, *optional*, defaults to `None`): Meaningful description to be displayed alongside with the progress bar while filtering examples. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.filter(lambda x: x["label"] == 1) Dataset({ features: ['text', 'label'], num_rows: 533 }) ``` """ if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.filter` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it.`" ) if function is None: function = lambda x: True # noqa: E731 if len(self) == 0: return self indices = self.map( function=partial( get_indices_from_mask_function, function, batched, with_indices, input_columns, self._indices ), with_indices=True, features=Features({"indices": Value("uint64")}), batched=True, batch_size=batch_size, remove_columns=self.column_names, keep_in_memory=keep_in_memory, load_from_cache_file=load_from_cache_file, cache_file_name=cache_file_name, writer_batch_size=writer_batch_size, fn_kwargs=fn_kwargs, num_proc=num_proc, suffix_template=suffix_template, new_fingerprint=new_fingerprint, input_columns=input_columns, desc=desc or "Filter", ) new_dataset = copy.deepcopy(self) new_dataset._indices = indices.data new_dataset._fingerprint = new_fingerprint return new_dataset @transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["cache_file_name"]) def flatten_indices( self, keep_in_memory: bool = False, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, features: Optional[Features] = None, disable_nullable: bool = False, num_proc: Optional[int] = None, new_fingerprint: Optional[str] = None, ) -> "Dataset": """Create and cache a new Dataset by flattening the indices mapping. Args: keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. cache_file_name (`str`, *optional*, default `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. features (`Optional[datasets.Features]`, defaults to `None`): Use a specific [`Features`] to store the cache file instead of the automatically generated one. disable_nullable (`bool`, defaults to `False`): Allow null values in the table. num_proc (`int`, optional, default `None`): Max number of processes when generating cache. Already cached shards are loaded sequentially new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments """ return self.map( batched=True, # for speed keep_in_memory=keep_in_memory, cache_file_name=cache_file_name, writer_batch_size=writer_batch_size, features=features, disable_nullable=disable_nullable, new_fingerprint=new_fingerprint, desc="Flattening the indices", num_proc=num_proc, ) def _new_dataset_with_indices( self, indices_cache_file_name: Optional[str] = None, indices_buffer: Optional[pa.Buffer] = None, fingerprint: Optional[str] = None, ) -> "Dataset": """Return a new Dataset obtained by adding indices (provided in indices_cache_file_name or in a buffer) to the current Dataset. """ if indices_cache_file_name is None and indices_buffer is None: raise ValueError("At least one of indices_cache_file_name or indices_buffer must be provided.") if fingerprint is None: raise ValueError("please specify a fingerprint for the dataset with indices") if indices_cache_file_name is not None: indices_table = MemoryMappedTable.from_file(indices_cache_file_name) else: indices_table = InMemoryTable.from_buffer(indices_buffer) # Return new Dataset object # don't forget to copy the objects return Dataset( self._data, info=self.info.copy(), split=self.split, indices_table=indices_table, fingerprint=fingerprint, ) @transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["indices_cache_file_name"]) def select( self, indices: Iterable, keep_in_memory: bool = False, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, new_fingerprint: Optional[str] = None, ) -> "Dataset": """Create a new dataset with rows selected following the list/array of indices. Args: indices (`range`, `list`, `iterable`, `ndarray` or `Series`): Range, list or 1D-array of integer indices for indexing. If the indices correspond to a contiguous range, the Arrow table is simply sliced. However passing a list of indices that are not contiguous creates indices mapping, which is much less efficient, but still faster than recreating an Arrow table made of the requested rows. keep_in_memory (`bool`, defaults to `False`): Keep the indices mapping in memory instead of writing it to a cache file. indices_cache_file_name (`str`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the indices mapping instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.select(range(4)) Dataset({ features: ['text', 'label'], num_rows: 4 }) ``` """ if keep_in_memory and indices_cache_file_name is not None: raise ValueError("Please use either `keep_in_memory` or `indices_cache_file_name` but not both.") if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.select` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing if len(self) == 0: return self # If indices is a PyArrow array, we convert to NumPy if isinstance(indices, (pa.Array, pa.ChunkedArray)): indices = indices.to_numpy().astype(np.int64) # Convert generator objects to lists if isinstance(indices, Iterator): indices = list(indices) # If the indices are contiguous, simply slice the arrow table if isinstance(indices, range): if _is_range_contiguous(indices) and indices.start >= 0: start, length = indices.start, indices.stop - indices.start return self._select_contiguous(start, length, new_fingerprint=new_fingerprint) else: try: start = next(iter(indices)) except StopIteration: # if `indices` is an empty iterable, we return an empty dataset return self._select_contiguous(0, 0, new_fingerprint=new_fingerprint) if start >= 0: counter_from_start = itertools.count(start=start) if all(i == j for i, j in zip(indices, counter_from_start)): length = next(counter_from_start) - start return self._select_contiguous(start, length, new_fingerprint=new_fingerprint) # If not contiguous, we need to create a new indices mapping return self._select_with_indices_mapping( indices, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name, writer_batch_size=writer_batch_size, new_fingerprint=new_fingerprint, ) @transmit_format @fingerprint_transform(inplace=False) def _select_contiguous( self, start: int, length: int, new_fingerprint: Optional[str] = None, ) -> "Dataset": """Create a new dataset with rows from a contiguous slice of data. The slice is defined by that start index and its length. Args: start (`int`): start index. length (`int`): length of the slice to select. new_fingerprint (`str`, optional, default `None`): the new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds._select_contiguous(0, 4) Dataset({ features: ['text', 'label'], num_rows: 4 }) ``` """ if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.select` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing if len(self) == 0: return self _check_valid_indices_value(start, len(self)) _check_valid_indices_value(start + length - 1, len(self)) if self._indices is None or length == 0: return Dataset( self.data.slice(start, length), info=self.info.copy(), split=self.split, fingerprint=new_fingerprint, ) else: return Dataset( self.data, info=self.info.copy(), split=self.split, indices_table=self._indices.slice(start, length), fingerprint=new_fingerprint, ) @transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["indices_cache_file_name"]) def _select_with_indices_mapping( self, indices: Iterable, keep_in_memory: bool = False, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, new_fingerprint: Optional[str] = None, ) -> "Dataset": """Create a new dataset with rows selected following the list/array of indices. The new dataset is made by creating a new indices mapping on top of the main arrow table. Args: indices (sequence, iterable, range, ndarray or Series): List or 1D-array of integer indices for indexing. keep_in_memory (`bool`, default `False`): Keep the indices mapping in memory instead of writing it to a cache file. indices_cache_file_name (`str`, optional, default `None`): Provide the name of a path for the cache file. It is used to store the indices mapping instead of the automatically generated cache file name. writer_batch_size (`int`, default `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `.map()`. new_fingerprint (`str`, optional, default `None`): the new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds._select_with_indices_mapping(range(4)) Dataset({ features: ['text', 'label'], num_rows: 4 }) ``` """ if keep_in_memory and indices_cache_file_name is not None: raise ValueError("Please use either `keep_in_memory` or `indices_cache_file_name` but not both.") if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.select` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing if len(self) == 0: return self # Prepare the writer for our indices arrow table if keep_in_memory or indices_cache_file_name is None: buf_writer = pa.BufferOutputStream() tmp_file = None writer = ArrowWriter( stream=buf_writer, writer_batch_size=writer_batch_size, fingerprint=new_fingerprint, unit="indices" ) else: buf_writer = None logger.info(f"Caching indices mapping at {indices_cache_file_name}") tmp_file = tempfile.NamedTemporaryFile("wb", dir=os.path.dirname(indices_cache_file_name), delete=False) writer = ArrowWriter( path=tmp_file.name, writer_batch_size=writer_batch_size, fingerprint=new_fingerprint, unit="indices" ) indices = indices if isinstance(indices, list) else list(indices) size = len(self) if indices: _check_valid_indices_value(int(max(indices)), size=size) _check_valid_indices_value(int(min(indices)), size=size) else: return self._select_contiguous(0, 0, new_fingerprint=new_fingerprint) indices_array = pa.array(indices, type=pa.uint64()) # Check if we need to convert indices if self._indices is not None: indices_array = self._indices.column(0).take(indices_array) indices_table = pa.Table.from_arrays([indices_array], names=["indices"]) with writer: try: writer.write_table(indices_table) writer.finalize() # close_stream=bool(buf_writer is None)) We only close if we are writing in a file except (Exception, KeyboardInterrupt): if tmp_file is not None: tmp_file.close() if os.path.exists(tmp_file.name): os.remove(tmp_file.name) raise if tmp_file is not None: tmp_file.close() shutil.move(tmp_file.name, indices_cache_file_name) umask = os.umask(0o666) os.umask(umask) os.chmod(indices_cache_file_name, 0o666 & ~umask) # Return new Dataset object if buf_writer is None: return self._new_dataset_with_indices( indices_cache_file_name=indices_cache_file_name, fingerprint=new_fingerprint ) else: return self._new_dataset_with_indices(indices_buffer=buf_writer.getvalue(), fingerprint=new_fingerprint) @transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["load_from_cache_file", "indices_cache_file_name"]) def sort( self, column_names: Union[str, Sequence_[str]], reverse: Union[bool, Sequence_[bool]] = False, kind="deprecated", null_placement: str = "at_end", keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, new_fingerprint: Optional[str] = None, ) -> "Dataset": """Create a new dataset sorted according to a single or multiple columns. Args: column_names (`Union[str, Sequence[str]]`): Column name(s) to sort by. reverse (`Union[bool, Sequence[bool]]`, defaults to `False`): If `True`, sort by descending order rather than ascending. If a single bool is provided, the value is applied to the sorting of all column names. Otherwise a list of bools with the same length and order as column_names must be provided. kind (`str`, *optional*): Pandas algorithm for sorting selected in `{quicksort, mergesort, heapsort, stable}`, The default is `quicksort`. Note that both `stable` and `mergesort` use `timsort` under the covers and, in general, the actual implementation will vary with data type. The `mergesort` option is retained for backwards compatibility. <Deprecated version="2.8.0"> `kind` was deprecated in version 2.10.0 and will be removed in 3.0.0. </Deprecated> null_placement (`str`, defaults to `at_end`): Put `None` values at the beginning if `at_start` or `first` or at the end if `at_end` or `last` <Added version="1.14.2"/> keep_in_memory (`bool`, defaults to `False`): Keep the sorted indices in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the sorted indices can be identified, use it instead of recomputing. indices_cache_file_name (`str`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the sorted indices instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. Higher value gives smaller cache files, lower value consume less temporary memory. new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes', split='validation') >>> ds['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> sorted_ds = ds.sort('label') >>> sorted_ds['label'][:10] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False]) >>> another_sorted_ds['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ``` """ if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.sort` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing if len(self) == 0: return self # Deprecation warning if kind != "deprecated": warnings.warn( "'kind' was deprecated in version 2.10.0 and will be removed in 3.0.0.", category=FutureWarning, ) # Check proper format of and for duplicates in column_names if isinstance(column_names, str): column_names = [column_names] # Check proper format and length of reverse if not isinstance(reverse, bool): if len(reverse) != len(column_names): raise ValueError( "Parameter 'reverse' should be either a boolean or a list of booleans with the same length as 'column_names'." ) else: reverse = [reverse] * len(column_names) # Check whether column name(s) exist in dataset for column in column_names: if not isinstance(column, str) or column not in self._data.column_names: raise ValueError( f"Column '{column}' not found in the dataset. Please provide a column selected in: {self._data.column_names}" ) # Change null_placement to conform to pyarrow's sort_indices() while ensuring backwards compatability if null_placement not in ["at_start", "at_end"]: if null_placement == "first": null_placement = "at_start" elif null_placement == "last": null_placement = "at_end" else: raise ValueError( f"null_placement '{null_placement}' is an invalid parameter value. Must be either 'last', 'at_end', 'first' or 'at_start'." ) load_from_cache_file = load_from_cache_file if load_from_cache_file is not None else is_caching_enabled() # Check if we've already cached this computation (indexed by a hash) if self.cache_files: if indices_cache_file_name is None: # we create a unique hash from the function, current dataset file and the mapping args indices_cache_file_name = self._get_cache_file_path(new_fingerprint) if os.path.exists(indices_cache_file_name) and load_from_cache_file: logger.info(f"Loading cached sorted indices for dataset at {indices_cache_file_name}") return self._new_dataset_with_indices( fingerprint=new_fingerprint, indices_cache_file_name=indices_cache_file_name ) sort_table = query_table( table=self._data, key=slice(0, len(self)), indices=self._indices, ) sort_keys = [ (col, "ascending" if not col_reverse else "descending") for col, col_reverse in zip(column_names, reverse) ] indices = pc.sort_indices(sort_table, sort_keys=sort_keys, null_placement=null_placement) return self.select( indices=indices, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name, writer_batch_size=writer_batch_size, new_fingerprint=new_fingerprint, ) @transmit_format @fingerprint_transform( inplace=False, randomized_function=True, ignore_kwargs=["load_from_cache_file", "indices_cache_file_name"] ) def shuffle( self, seed: Optional[int] = None, generator: Optional[np.random.Generator] = None, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, new_fingerprint: Optional[str] = None, ) -> "Dataset": """Create a new Dataset where the rows are shuffled. Currently shuffling uses numpy random generators. You can either supply a NumPy BitGenerator to use, or a seed to initiate NumPy's default random generator (PCG64). Shuffling takes the list of indices `[0:len(my_dataset)]` and shuffles it to create an indices mapping. However as soon as your [`Dataset`] has an indices mapping, the speed can become 10x slower. This is because there is an extra step to get the row index to read using the indices mapping, and most importantly, you aren't reading contiguous chunks of data anymore. To restore the speed, you'd need to rewrite the entire dataset on your disk again using [`Dataset.flatten_indices`], which removes the indices mapping. This may take a lot of time depending of the size of your dataset though: ```python my_dataset[0] # fast my_dataset = my_dataset.shuffle(seed=42) my_dataset[0] # up to 10x slower my_dataset = my_dataset.flatten_indices() # rewrite the shuffled dataset on disk as contiguous chunks of data my_dataset[0] # fast again ``` In this case, we recommend switching to an [`IterableDataset`] and leveraging its fast approximate shuffling method [`IterableDataset.shuffle`]. It only shuffles the shards order and adds a shuffle buffer to your dataset, which keeps the speed of your dataset optimal: ```python my_iterable_dataset = my_dataset.to_iterable_dataset(num_shards=128) for example in enumerate(my_iterable_dataset): # fast pass shuffled_iterable_dataset = my_iterable_dataset.shuffle(seed=42, buffer_size=100) for example in enumerate(shuffled_iterable_dataset): # as fast as before pass ``` Args: seed (`int`, *optional*): A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. If an `int` or `array_like[ints]` is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. generator (`numpy.random.Generator`, *optional*): Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy). keep_in_memory (`bool`, default `False`): Keep the shuffled indices in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the shuffled indices can be identified, use it instead of recomputing. indices_cache_file_name (`str`, *optional*): Provide the name of a path for the cache file. It is used to store the shuffled indices instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # set a seed >>> shuffled_ds = ds.shuffle(seed=42) >>> shuffled_ds['label'][:10] [1, 0, 1, 1, 0, 0, 0, 0, 0, 0] ``` """ if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.shuffle` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing if len(self) == 0: return self if keep_in_memory and indices_cache_file_name is not None: raise ValueError("Please use either `keep_in_memory` or `indices_cache_file_name` but not both.") if seed is not None and generator is not None: raise ValueError("Both `seed` and `generator` were provided. Please specify just one of them.") if generator is not None and not isinstance(generator, np.random.Generator): raise ValueError("The provided generator must be an instance of numpy.random.Generator") load_from_cache_file = load_from_cache_file if load_from_cache_file is not None else is_caching_enabled() if generator is None: if seed is None: _, seed, pos, *_ = np.random.get_state() seed = seed[pos] if pos < 624 else seed[0] _ = np.random.random() # do 1 step of rng generator = np.random.default_rng(seed) # Check if we've already cached this computation (indexed by a hash) if self.cache_files: if indices_cache_file_name is None: # we create a unique hash from the function, current dataset file and the mapping args indices_cache_file_name = self._get_cache_file_path(new_fingerprint) if os.path.exists(indices_cache_file_name) and load_from_cache_file: logger.info(f"Loading cached shuffled indices for dataset at {indices_cache_file_name}") return self._new_dataset_with_indices( fingerprint=new_fingerprint, indices_cache_file_name=indices_cache_file_name ) permutation = generator.permutation(len(self)) return self.select( indices=permutation, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name if not keep_in_memory else None, writer_batch_size=writer_batch_size, new_fingerprint=new_fingerprint, ) @transmit_format @fingerprint_transform( inplace=False, randomized_function=True, fingerprint_names=["train_new_fingerprint", "test_new_fingerprint"], ignore_kwargs=["load_from_cache_file", "train_indices_cache_file_name", "test_indices_cache_file_name"], ) def train_test_split( self, test_size: Union[float, int, None] = None, train_size: Union[float, int, None] = None, shuffle: bool = True, stratify_by_column: Optional[str] = None, seed: Optional[int] = None, generator: Optional[np.random.Generator] = None, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, train_indices_cache_file_name: Optional[str] = None, test_indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, train_new_fingerprint: Optional[str] = None, test_new_fingerprint: Optional[str] = None, ) -> "DatasetDict": """Return a dictionary ([`datasets.DatasetDict`]) with two random train and test subsets (`train` and `test` `Dataset` splits). Splits are created from the dataset according to `test_size`, `train_size` and `shuffle`. This method is similar to scikit-learn `train_test_split`. Args: test_size (`numpy.random.Generator`, *optional*): Size of the test split If `float`, should be between `0.0` and `1.0` and represent the proportion of the dataset to include in the test split. If `int`, represents the absolute number of test samples. If `None`, the value is set to the complement of the train size. If `train_size` is also `None`, it will be set to `0.25`. train_size (`numpy.random.Generator`, *optional*): Size of the train split If `float`, should be between `0.0` and `1.0` and represent the proportion of the dataset to include in the train split. If `int`, represents the absolute number of train samples. If `None`, the value is automatically set to the complement of the test size. shuffle (`bool`, *optional*, defaults to `True`): Whether or not to shuffle the data before splitting. stratify_by_column (`str`, *optional*, defaults to `None`): The column name of labels to be used to perform stratified split of data. seed (`int`, *optional*): A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. If an `int` or `array_like[ints]` is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. generator (`numpy.random.Generator`, *optional*): Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy). keep_in_memory (`bool`, defaults to `False`): Keep the splits indices in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the splits indices can be identified, use it instead of recomputing. train_cache_file_name (`str`, *optional*): Provide the name of a path for the cache file. It is used to store the train split indices instead of the automatically generated cache file name. test_cache_file_name (`str`, *optional*): Provide the name of a path for the cache file. It is used to store the test split indices instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. train_new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the train set after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments test_new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the test set after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds = ds.train_test_split(test_size=0.2, shuffle=True) DatasetDict({ train: Dataset({ features: ['text', 'label'], num_rows: 852 }) test: Dataset({ features: ['text', 'label'], num_rows: 214 }) }) # set a seed >>> ds = ds.train_test_split(test_size=0.2, seed=42) # stratified split >>> ds = load_dataset("imdb",split="train") Dataset({ features: ['text', 'label'], num_rows: 25000 }) >>> ds = ds.train_test_split(test_size=0.2, stratify_by_column="label") DatasetDict({ train: Dataset({ features: ['text', 'label'], num_rows: 20000 }) test: Dataset({ features: ['text', 'label'], num_rows: 5000 }) }) ``` """ from .dataset_dict import DatasetDict # import here because of circular dependency if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.train_test_split` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing if len(self) == 0: return DatasetDict({"train": self, "test": self}) if test_size is None and train_size is None: test_size = 0.25 # Safety checks similar to scikit-learn's ones. # (adapted from https://github.com/scikit-learn/scikit-learn/blob/fd237278e895b42abe8d8d09105cbb82dc2cbba7/sklearn/model_selection/_split.py#L1750) n_samples = len(self) if ( isinstance(test_size, int) and (test_size >= n_samples or test_size <= 0) or isinstance(test_size, float) and (test_size <= 0 or test_size >= 1) ): raise ValueError( f"test_size={test_size} should be either positive and smaller " f"than the number of samples {n_samples} or a float in the (0, 1) range" ) if ( isinstance(train_size, int) and (train_size >= n_samples or train_size <= 0) or isinstance(train_size, float) and (train_size <= 0 or train_size >= 1) ): raise ValueError( f"train_size={train_size} should be either positive and smaller " f"than the number of samples {n_samples} or a float in the (0, 1) range" ) if train_size is not None and not isinstance(train_size, (int, float)): raise ValueError(f"Invalid value for train_size: {train_size} of type {type(train_size)}") if test_size is not None and not isinstance(test_size, (int, float)): raise ValueError(f"Invalid value for test_size: {test_size} of type {type(test_size)}") if isinstance(train_size, float) and isinstance(test_size, float) and train_size + test_size > 1: raise ValueError( f"The sum of test_size and train_size = {train_size + test_size}, should be in the (0, 1)" " range. Reduce test_size and/or train_size." ) if isinstance(test_size, float): n_test = ceil(test_size * n_samples) elif isinstance(test_size, int): n_test = float(test_size) if isinstance(train_size, float): n_train = floor(train_size * n_samples) elif isinstance(train_size, int): n_train = float(train_size) if train_size is None: n_train = n_samples - n_test elif test_size is None: n_test = n_samples - n_train if n_train + n_test > n_samples: raise ValueError( f"The sum of train_size and test_size = {n_train + n_test}, " "should be smaller than the number of " f"samples {n_samples}. Reduce test_size and/or " "train_size." ) n_train, n_test = int(n_train), int(n_test) if n_train == 0: raise ValueError( f"With n_samples={n_samples}, test_size={test_size} and train_size={train_size}, the " "resulting train set will be empty. Adjust any of the " "aforementioned parameters." ) load_from_cache_file = load_from_cache_file if load_from_cache_file is not None else is_caching_enabled() if generator is None and shuffle is True: if seed is None: _, seed, pos, *_ = np.random.get_state() seed = seed[pos] if pos < 624 else seed[0] _ = np.random.random() # do 1 step of rng generator = np.random.default_rng(seed) # Check if we've already cached this computation (indexed by a hash) if self.cache_files: if train_indices_cache_file_name is None or test_indices_cache_file_name is None: # we create a unique hash from the function, current dataset file and the mapping args if train_indices_cache_file_name is None: train_indices_cache_file_name = self._get_cache_file_path(train_new_fingerprint) if test_indices_cache_file_name is None: test_indices_cache_file_name = self._get_cache_file_path(test_new_fingerprint) if ( os.path.exists(train_indices_cache_file_name) and os.path.exists(test_indices_cache_file_name) and load_from_cache_file ): logger.info( f"Loading cached split indices for dataset at {train_indices_cache_file_name} and {test_indices_cache_file_name}" ) return DatasetDict( { "train": self._new_dataset_with_indices( fingerprint=train_new_fingerprint, indices_cache_file_name=train_indices_cache_file_name ), "test": self._new_dataset_with_indices( fingerprint=test_new_fingerprint, indices_cache_file_name=test_indices_cache_file_name ), } ) if not shuffle: if stratify_by_column is not None: raise ValueError("Stratified train/test split is not implemented for `shuffle=False`") train_indices = np.arange(n_train) test_indices = np.arange(n_train, n_train + n_test) else: # stratified partition if stratify_by_column is not None: if stratify_by_column not in self._info.features.keys(): raise ValueError(f"Key {stratify_by_column} not found in {self._info.features.keys()}") if not isinstance(self._info.features[stratify_by_column], ClassLabel): raise ValueError( f"Stratifying by column is only supported for {ClassLabel.__name__} column, and column {stratify_by_column} is {type(self._info.features[stratify_by_column]).__name__}." ) try: train_indices, test_indices = next( stratified_shuffle_split_generate_indices( self.with_format("numpy")[stratify_by_column], n_train, n_test, rng=generator ) ) except Exception as error: if str(error) == "Minimum class count error": raise ValueError( f"The least populated class in {stratify_by_column} column has only 1" " member, which is too few. The minimum" " number of groups for any class cannot" " be less than 2." ) else: raise error # random partition else: permutation = generator.permutation(len(self)) test_indices = permutation[:n_test] train_indices = permutation[n_test : (n_test + n_train)] train_split = self.select( indices=train_indices, keep_in_memory=keep_in_memory, indices_cache_file_name=train_indices_cache_file_name, writer_batch_size=writer_batch_size, new_fingerprint=train_new_fingerprint, ) test_split = self.select( indices=test_indices, keep_in_memory=keep_in_memory, indices_cache_file_name=test_indices_cache_file_name, writer_batch_size=writer_batch_size, new_fingerprint=test_new_fingerprint, ) return DatasetDict({"train": train_split, "test": test_split}) def shard( self, num_shards: int, index: int, contiguous: bool = False, keep_in_memory: bool = False, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, ) -> "Dataset": """Return the `index`-nth shard from dataset split into `num_shards` pieces. This shards deterministically. `dset.shard(n, i)` will contain all elements of dset whose index mod `n = i`. `dset.shard(n, i, contiguous=True)` will instead split dset into contiguous chunks, so it can be easily concatenated back together after processing. If `n % i == l`, then the first `l` shards will have length `(n // i) + 1`, and the remaining shards will have length `(n // i)`. `datasets.concatenate([dset.shard(n, i, contiguous=True) for i in range(n)])` will return a dataset with the same order as the original. Be sure to shard before using any randomizing operator (such as `shuffle`). It is best if the shard operator is used early in the dataset pipeline. Args: num_shards (`int`): How many shards to split the dataset into. index (`int`): Which shard to select and return. contiguous: (`bool`, defaults to `False`): Whether to select contiguous blocks of indices for shards. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. indices_cache_file_name (`str`, *optional*): Provide the name of a path for the cache file. It is used to store the indices of each shard instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds Dataset({ features: ['text', 'label'], num_rows: 1066 }) >>> ds.shard(num_shards=2, index=0) Dataset({ features: ['text', 'label'], num_rows: 533 }) ``` """ if not 0 <= index < num_shards: raise ValueError("index should be in [0, num_shards-1]") if contiguous: div = len(self) // num_shards mod = len(self) % num_shards start = div * index + min(index, mod) end = start + div + (1 if index < mod else 0) indices = range(start, end) else: indices = np.arange(index, len(self), num_shards) return self.select( indices=indices, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name, writer_batch_size=writer_batch_size, ) @deprecated() def export( self, filename: str, format: str = "tfrecord", ): """Writes the Arrow dataset to a TFRecord file. The dataset must already be in tensorflow format. The records will be written with keys from `dataset._format_columns`. Args: filename (`str`): The filename, including the `.tfrecord` extension, to write to. format (`str`, optional, default `"tfrecord"`): The type of output file. Currently this is a no-op, as TFRecords are the only option. This enables a more flexible function signature later. """ try: import tensorflow as tf # noqa: F401 except ImportError: logger.error("Tensorflow needs to be installed to be able to return Tensorflow tensors.") # From https://www.tensorflow.org/tutorials/load_data/tfrecord def _bytes_feature(values): """Returns a bytes_list from a list of string / byte.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=values)) def _float_feature(values): """Returns a float_list from a list of float / double.""" return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def _int64_feature(values): """Returns an int64_list from a list of bool / enum / int / uint.""" return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def _feature(values: Union[float, int, str, np.ndarray, list]) -> "tf.train.Feature": """Typechecks `values` and returns the corresponding tf.train.Feature.""" if isinstance(values, list): if values and isinstance(values[0], str): return _bytes_feature([v.encode() for v in values]) else: raise ValueError(f"values={values} is empty or contains items that cannot be serialized") elif isinstance(values, np.ndarray): if values.dtype == np.dtype(float): return _float_feature(values) elif values.dtype == np.int64: return _int64_feature(values) elif values.dtype == np.dtype(str) or ( values.dtype == np.dtype(object) and len(values) > 0 and isinstance(values[0], str) ): return _bytes_feature([v.encode() for v in values]) else: raise ValueError( f"values={values} is empty or is an np.ndarray with items of dtype {values[0].dtype}, which cannot be serialized" ) elif hasattr(values, "dtype"): if np.issubdtype(values.dtype, np.floating): return _float_feature([values.item()]) elif np.issubdtype(values.dtype, np.integer): return _int64_feature([values.item()]) elif np.issubdtype(values.dtype, str): return _bytes_feature([values.item().encode()]) else: raise ValueError(f"values={values} has dtype {values.dtype}, which cannot be serialized") else: raise ValueError(f"values={values} are not numpy objects or strings, and so cannot be serialized") def serialize_example(ex): feature = {key: _feature(value) for key, value in ex.items()} example_proto = tf.train.Example(features=tf.train.Features(feature=feature)) return example_proto.SerializeToString() def tf_serialize_example(ex): tf_string = tf.py_function(serialize_example, (ex,), tf.string) return tf.reshape(tf_string, ()) def generator(): for ex in self: yield serialize_example(ex) if self._format_type != "numpy": raise ValueError("Dataset format must be numpy before exporting") if not filename.endswith(".tfrecord"): raise ValueError("filename {filename} must end with .tfrecord") tf_dataset = tf.data.Dataset.from_generator(generator, output_types=tf.string, output_shapes=()) writer = tf.data.experimental.TFRecordWriter(filename) logger.info(f"Writing TFRecord to {filename}") writer.write(tf_dataset) logger.info(f"Finished writing TFRecord to {filename}") self = None # delete the dataset reference used by tf_dataset def to_csv( self, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[int] = None, num_proc: Optional[int] = None, **to_csv_kwargs, ) -> int: """Exports the dataset to csv Args: path_or_buf (`PathLike` or `FileOrBuffer`): Either a path to a file or a BinaryIO. batch_size (`int`, *optional*): Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`. num_proc (`int`, *optional*): Number of processes for multiprocessing. By default it doesn't use multiprocessing. `batch_size` in this case defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE` but feel free to make it 5x or 10x of the default value if you have sufficient compute power. **to_csv_kwargs (additional keyword arguments): Parameters to pass to pandas's [`pandas.DataFrame.to_csv`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html). <Changed version="2.10.0"> Now, `index` defaults to `False` if not specified. If you would like to write the index, pass `index=True` and also set a name for the index column by passing `index_label`. </Changed> Returns: `int`: The number of characters or bytes written. Example: ```py >>> ds.to_csv("path/to/dataset/directory") ``` """ # Dynamic import to avoid circular dependency from .io.csv import CsvDatasetWriter return CsvDatasetWriter(self, path_or_buf, batch_size=batch_size, num_proc=num_proc, **to_csv_kwargs).write() def to_dict(self, batch_size: Optional[int] = None, batched="deprecated") -> Union[dict, Iterator[dict]]: """Returns the dataset as a Python dict. Can also return a generator for large datasets. Args: batched (`bool`): Set to `True` to return a generator that yields the dataset as batches of `batch_size` rows. Defaults to `False` (returns the whole datasets once). <Deprecated version="2.11.0"> Use `.iter(batch_size=batch_size)` followed by `.to_dict()` on the individual batches instead. </Deprecated> batch_size (`int`, *optional*): The size (number of rows) of the batches if `batched` is `True`. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`. Returns: `dict` or `Iterator[dict]` Example: ```py >>> ds.to_dict() ``` """ if batched != "deprecated": warnings.warn( "'batched' was deprecated in version 2.11.0 and will be removed in version 3.0.0. Use `.iter(batch_size=batch_size)` followed by `.to_dict()` on the individual batches instead.", FutureWarning, ) else: batched = False if not batched: return query_table( table=self._data, key=slice(0, len(self)), indices=self._indices, ).to_pydict() else: batch_size = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE return ( query_table( table=self._data, key=slice(offset, offset + batch_size), indices=self._indices, ).to_pydict() for offset in range(0, len(self), batch_size) ) def to_list(self) -> list: """Returns the dataset as a Python list. Returns: `list` Example: ```py >>> ds.to_list() ``` """ return query_table( table=self._data, key=slice(0, len(self)), indices=self._indices, ).to_pylist() def to_json( self, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[int] = None, num_proc: Optional[int] = None, **to_json_kwargs, ) -> int: """Export the dataset to JSON Lines or JSON. Args: path_or_buf (`PathLike` or `FileOrBuffer`): Either a path to a file or a BinaryIO. batch_size (`int`, *optional*): Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`. num_proc (`int`, *optional*): Number of processes for multiprocessing. By default it doesn't use multiprocessing. `batch_size` in this case defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE` but feel free to make it 5x or 10x of the default value if you have sufficient compute power. **to_json_kwargs (additional keyword arguments): Parameters to pass to pandas's [`pandas.DataFrame.to_json`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html). <Changed version="2.11.0"> Now, `index` defaults to `False` if `orient` is `"split"` or `"table"`. If you would like to write the index, pass `index=True`. </Changed> Returns: `int`: The number of characters or bytes written. Example: ```py >>> ds.to_json("path/to/dataset/directory") ``` """ # Dynamic import to avoid circular dependency from .io.json import JsonDatasetWriter return JsonDatasetWriter(self, path_or_buf, batch_size=batch_size, num_proc=num_proc, **to_json_kwargs).write() def to_pandas( self, batch_size: Optional[int] = None, batched: bool = False ) -> Union[pd.DataFrame, Iterator[pd.DataFrame]]: """Returns the dataset as a `pandas.DataFrame`. Can also return a generator for large datasets. Args: batched (`bool`): Set to `True` to return a generator that yields the dataset as batches of `batch_size` rows. Defaults to `False` (returns the whole datasets once). batch_size (`int`, *optional*): The size (number of rows) of the batches if `batched` is `True`. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`. Returns: `pandas.DataFrame` or `Iterator[pandas.DataFrame]` Example: ```py >>> ds.to_pandas() ``` """ if not batched: return query_table( table=self._data, key=slice(0, len(self)), indices=self._indices, ).to_pandas(types_mapper=pandas_types_mapper) else: batch_size = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE return ( query_table( table=self._data, key=slice(offset, offset + batch_size), indices=self._indices, ).to_pandas(types_mapper=pandas_types_mapper) for offset in range(0, len(self), batch_size) ) def to_parquet( self, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[int] = None, **parquet_writer_kwargs, ) -> int: """Exports the dataset to parquet Args: path_or_buf (`PathLike` or `FileOrBuffer`): Either a path to a file or a BinaryIO. batch_size (`int`, *optional*): Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`. **parquet_writer_kwargs (additional keyword arguments): Parameters to pass to PyArrow's `pyarrow.parquet.ParquetWriter`. Returns: `int`: The number of characters or bytes written. Example: ```py >>> ds.to_parquet("path/to/dataset/directory") ``` """ # Dynamic import to avoid circular dependency from .io.parquet import ParquetDatasetWriter return ParquetDatasetWriter(self, path_or_buf, batch_size=batch_size, **parquet_writer_kwargs).write() def to_sql( self, name: str, con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"], batch_size: Optional[int] = None, **sql_writer_kwargs, ) -> int: """Exports the dataset to a SQL database. Args: name (`str`): Name of SQL table. con (`str` or `sqlite3.Connection` or `sqlalchemy.engine.Connection` or `sqlalchemy.engine.Connection`): A [URI string](https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls) or a SQLite3/SQLAlchemy connection object used to write to a database. batch_size (`int`, *optional*): Size of the batch to load in memory and write at once. Defaults to `datasets.config.DEFAULT_MAX_BATCH_SIZE`. **sql_writer_kwargs (additional keyword arguments): Parameters to pass to pandas's [`pandas.DataFrame.to_sql`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html). <Changed version="2.11.0"> Now, `index` defaults to `False` if not specified. If you would like to write the index, pass `index=True` and also set a name for the index column by passing `index_label`. </Changed> Returns: `int`: The number of records written. Example: ```py >>> # con provided as a connection URI string >>> ds.to_sql("data", "sqlite:///my_own_db.sql") >>> # con provided as a sqlite3 connection object >>> import sqlite3 >>> con = sqlite3.connect("my_own_db.sql") >>> with con: ... ds.to_sql("data", con) ``` """ # Dynamic import to avoid circular dependency from .io.sql import SqlDatasetWriter return SqlDatasetWriter(self, name, con, batch_size=batch_size, **sql_writer_kwargs).write() def _estimate_nbytes(self) -> int: dataset_nbytes = self.data.nbytes # Find decodable columns, because if there are any, we need to # adjust the dataset size computation (needed for sharding) to account for possible external files decodable_columns = [ k for k, v in self._info.features.items() if require_decoding(v, ignore_decode_attribute=True) ] if decodable_columns: # Approximate the space needed to store the bytes from the external files by analyzing the first 1000 examples extra_nbytes = 0 def extra_nbytes_visitor(array, feature): nonlocal extra_nbytes if isinstance(feature, (Audio, Image)): for x in array.to_pylist(): if x is not None and x["bytes"] is None and x["path"] is not None: size = xgetsize(x["path"]) extra_nbytes += size extra_nbytes -= array.field("path").nbytes table = self.with_format("arrow")[:1000] table_visitor(table, extra_nbytes_visitor) extra_nbytes = extra_nbytes * len(self.data) / len(table) dataset_nbytes = dataset_nbytes + extra_nbytes if self._indices is not None: dataset_nbytes = dataset_nbytes * len(self._indices) / len(self.data) return dataset_nbytes @staticmethod def _generate_tables_from_shards(shards: List["Dataset"], batch_size: int): for shard_idx, shard in enumerate(shards): for pa_table in shard.with_format("arrow").iter(batch_size): yield shard_idx, pa_table @staticmethod def _generate_tables_from_cache_file(filename: str): for batch_idx, batch in enumerate(_memory_mapped_record_batch_reader_from_file(filename)): yield batch_idx, pa.Table.from_batches([batch]) def to_iterable_dataset(self, num_shards: Optional[int] = 1) -> "IterableDataset": """Get an [`datasets.IterableDataset`] from a map-style [`datasets.Dataset`]. This is equivalent to loading a dataset in streaming mode with [`datasets.load_dataset`], but much faster since the data is streamed from local files. Contrary to map-style datasets, iterable datasets are lazy and can only be iterated over (e.g. using a for loop). Since they are read sequentially in training loops, iterable datasets are much faster than map-style datasets. All the transformations applied to iterable datasets like filtering or processing are done on-the-fly when you start iterating over the dataset. Still, it is possible to shuffle an iterable dataset using [`datasets.IterableDataset.shuffle`]. This is a fast approximate shuffling that works best if you have multiple shards and if you specify a buffer size that is big enough. To get the best speed performance, make sure your dataset doesn't have an indices mapping. If this is the case, the data are not read contiguously, which can be slow sometimes. You can use `ds = ds.flatten_indices()` to write your dataset in contiguous chunks of data and have optimal speed before switching to an iterable dataset. Args: num_shards (`int`, default to `1`): Number of shards to define when instantiating the iterable dataset. This is especially useful for big datasets to be able to shuffle properly, and also to enable fast parallel loading using a PyTorch DataLoader or in distributed setups for example. Shards are defined using [`datasets.Dataset.shard`]: it simply slices the data without writing anything on disk. Returns: [`datasets.IterableDataset`] Example: Basic usage: ```python >>> ids = ds.to_iterable_dataset() >>> for example in ids: ... pass ``` With lazy filtering and processing: ```python >>> ids = ds.to_iterable_dataset() >>> ids = ids.filter(filter_fn).map(process_fn) # will filter and process on-the-fly when you start iterating over the iterable dataset >>> for example in ids: ... pass ``` With sharding to enable efficient shuffling: ```python >>> ids = ds.to_iterable_dataset(num_shards=64) # the dataset is split into 64 shards to be iterated over >>> ids = ids.shuffle(buffer_size=10_000) # will shuffle the shards order and use a shuffle buffer for fast approximate shuffling when you start iterating >>> for example in ids: ... pass ``` With a PyTorch DataLoader: ```python >>> import torch >>> ids = ds.to_iterable_dataset(num_shards=64) >>> ids = ids.filter(filter_fn).map(process_fn) >>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4) # will assign 64 / 4 = 16 shards to each worker to load, filter and process when you start iterating >>> for example in ids: ... pass ``` With a PyTorch DataLoader and shuffling: ```python >>> import torch >>> ids = ds.to_iterable_dataset(num_shards=64) >>> ids = ids.shuffle(buffer_size=10_000) # will shuffle the shards order and use a shuffle buffer when you start iterating >>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4) # will assign 64 / 4 = 16 shards from the shuffled list of shards to each worker when you start iterating >>> for example in ids: ... pass ``` In a distributed setup like PyTorch DDP with a PyTorch DataLoader and shuffling ```python >>> from datasets.distributed import split_dataset_by_node >>> ids = ds.to_iterable_dataset(num_shards=512) >>> ids = ids.shuffle(buffer_size=10_000) # will shuffle the shards order and use a shuffle buffer when you start iterating >>> ids = split_dataset_by_node(ds, world_size=8, rank=0) # will keep only 512 / 8 = 64 shards from the shuffled lists of shards when you start iterating >>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4) # will assign 64 / 4 = 16 shards from this node's list of shards to each worker when you start iterating >>> for example in ids: ... pass ``` With shuffling and multiple epochs: ```python >>> ids = ds.to_iterable_dataset(num_shards=64) >>> ids = ids.shuffle(buffer_size=10_000, seed=42) # will shuffle the shards order and use a shuffle buffer when you start iterating >>> for epoch in range(n_epochs): ... ids.set_epoch(epoch) # will use effective_seed = seed + epoch to shuffle the shards and for the shuffle buffer when you start iterating ... for example in ids: ... pass ``` Feel free to also use [`IterableDataset.set_epoch`] when using a PyTorch DataLoader or in distributed setups. """ from .iterable_dataset import ArrowExamplesIterable, IterableDataset if self._format_type is not None: raise NotImplementedError( "Converting a formatted dataset to a formatted iterable dataset is not implemented yet. Please run `my_dataset = my_dataset.with_format(None)` before calling to_iterable_dataset" ) if num_shards > len(self): raise ValueError( f"Unable to shard a dataset of size {len(self)} into {num_shards} shards (the number of shards exceeds the number of samples)." ) if self._indices is not None: logger.info( "Converting an Arrow dataset to iterable but it has an indices mapping that can make it slower. " "You can use `ds = ds.flatten_indices()` to write your dataset in contiguous chunks of data and have optimal speed." ) shards = ( [copy.deepcopy(self)] if num_shards == 1 else [ self.shard(num_shards=num_shards, index=shard_idx, contiguous=True) for shard_idx in range(num_shards) ] ) ex_iterable = ArrowExamplesIterable( Dataset._generate_tables_from_shards, kwargs={"shards": shards, "batch_size": config.DEFAULT_MAX_BATCH_SIZE}, ) return IterableDataset(ex_iterable, info=DatasetInfo(features=self.features)) def _push_parquet_shards_to_hub( self, repo_id: str, data_dir: str = "data", split: Optional[str] = None, token: Optional[str] = None, revision: Optional[str] = None, create_pr: Optional[bool] = False, max_shard_size: Optional[Union[int, str]] = None, num_shards: Optional[int] = None, embed_external_files: bool = True, ) -> Tuple[str, str, int, int, List[str], int]: """Pushes the dataset shards as Parquet files to the hub. Returns: additions (`List[CommitOperation]`): list of the `CommitOperationAdd` of the uploaded shards uploaded_size (`int`): number of uploaded bytes to the repository dataset_nbytes (`int`): approximate size in bytes of the uploaded dataset afer uncompression """ # Find decodable columns, because if there are any, we need to: # embed the bytes from the files in the shards decodable_columns = ( [k for k, v in self._info.features.items() if require_decoding(v, ignore_decode_attribute=True)] if embed_external_files else [] ) dataset_nbytes = self._estimate_nbytes() if num_shards is None: max_shard_size = convert_file_size_to_int(max_shard_size or config.MAX_SHARD_SIZE) num_shards = int(dataset_nbytes / max_shard_size) + 1 num_shards = max(num_shards, 1) shards = (self.shard(num_shards=num_shards, index=i, contiguous=True) for i in range(num_shards)) if decodable_columns: def shards_with_embedded_external_files(shards): for shard in shards: format = shard.format shard = shard.with_format("arrow") shard = shard.map( embed_table_storage, batched=True, batch_size=1000, keep_in_memory=True, ) shard = shard.with_format(**format) yield shard shards = shards_with_embedded_external_files(shards) api = HfApi(endpoint=config.HF_ENDPOINT, token=token) uploaded_size = 0 additions = [] for index, shard in hf_tqdm( enumerate(shards), desc="Uploading the dataset shards", total=num_shards, ): shard_path_in_repo = f"{data_dir}/{split}-{index:05d}-of-{num_shards:05d}.parquet" buffer = BytesIO() shard.to_parquet(buffer) uploaded_size += buffer.tell() shard_addition = CommitOperationAdd(path_in_repo=shard_path_in_repo, path_or_fileobj=buffer) preupload_lfs_files( api, repo_id=repo_id, additions=[shard_addition], token=token, repo_type="dataset", revision=revision, create_pr=create_pr, ) additions.append(shard_addition) return additions, uploaded_size, dataset_nbytes def push_to_hub( self, repo_id: str, config_name: str = "default", set_default: Optional[bool] = None, split: Optional[str] = None, commit_message: Optional[str] = None, commit_description: Optional[str] = None, private: Optional[bool] = False, token: Optional[str] = None, revision: Optional[str] = None, branch="deprecated", create_pr: Optional[bool] = False, max_shard_size: Optional[Union[int, str]] = None, num_shards: Optional[int] = None, embed_external_files: bool = True, ) -> CommitInfo: """Pushes the dataset to the hub as a Parquet dataset. The dataset is pushed using HTTP requests and does not need to have neither git or git-lfs installed. The resulting Parquet files are self-contained by default. If your dataset contains [`Image`] or [`Audio`] data, the Parquet files will store the bytes of your images or audio files. You can disable this by setting `embed_external_files` to `False`. Args: repo_id (`str`): The ID of the repository to push to in the following format: `<user>/<dataset_name>` or `<org>/<dataset_name>`. Also accepts `<dataset_name>`, which will default to the namespace of the logged-in user. config_name (`str`, defaults to "default"): The configuration name (or subset) of a dataset. Defaults to "default". set_default (`bool`, *optional*): Whether to set this configuration as the default one. Otherwise, the default configuration is the one named "default". split (`str`, *optional*): The name of the split that will be given to that dataset. Defaults to `self.split`. commit_message (`str`, *optional*): Message to commit while pushing. Will default to `"Upload dataset"`. commit_description (`str`, *optional*): Description of the commit that will be created. Additionally, description of the PR if a PR is created (`create_pr` is True). <Added version="2.16.0"/> private (`bool`, *optional*, defaults to `False`): Whether the dataset repository should be set to private or not. Only affects repository creation: a repository that already exists will not be affected by that parameter. token (`str`, *optional*): An optional authentication token for the Hugging Face Hub. If no token is passed, will default to the token saved locally when logging in with `huggingface-cli login`. Will raise an error if no token is passed and the user is not logged-in. revision (`str`, *optional*): Branch to push the uploaded files to. Defaults to the `"main"` branch. <Added version="2.15.0"/> branch (`str`, *optional*): The git branch on which to push the dataset. This defaults to the default branch as specified in your repository, which defaults to `"main"`. <Deprecated version="2.15.0"> `branch` was deprecated in favor of `revision` in version 2.15.0 and will be removed in 3.0.0. </Deprecated> create_pr (`bool`, *optional*, defaults to `False`): Whether to create a PR with the uploaded files or directly commit. <Added version="2.15.0"/> max_shard_size (`int` or `str`, *optional*, defaults to `"500MB"`): The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). num_shards (`int`, *optional*): Number of shards to write. By default, the number of shards depends on `max_shard_size`. <Added version="2.8.0"/> embed_external_files (`bool`, defaults to `True`): Whether to embed file bytes in the shards. In particular, this will do the following before the push for the fields of type: - [`Audio`] and [`Image`]: remove local path information and embed file content in the Parquet files. Return: huggingface_hub.CommitInfo Example: ```python >>> dataset.push_to_hub("<organization>/<dataset_id>") >>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True) >>> dataset.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB") >>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024) ``` If your dataset has multiple splits (e.g. train/validation/test): ```python >>> train_dataset.push_to_hub("<organization>/<dataset_id>", split="train") >>> val_dataset.push_to_hub("<organization>/<dataset_id>", split="validation") >>> # later >>> dataset = load_dataset("<organization>/<dataset_id>") >>> train_dataset = dataset["train"] >>> val_dataset = dataset["validation"] ``` If you want to add a new configuration (or subset) to a dataset (e.g. if the dataset has multiple tasks/versions/languages): ```python >>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en") >>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr") >>> # later >>> english_dataset = load_dataset("<organization>/<dataset_id>", "en") >>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr") ``` """ if config_name == "data": raise ValueError("`config_name` cannot be 'data'. Please, choose another name for configuration.") if max_shard_size is not None and num_shards is not None: raise ValueError( "Failed to push_to_hub: please specify either max_shard_size or num_shards, but not both." ) if split is None: split = str(self.split) if self.split is not None else "train" if not re.match(_split_re, split): raise ValueError(f"Split name should match '{_split_re}' but got '{split}'.") if branch != "deprecated": warnings.warn( "'branch' was deprecated in favor of 'revision' in version 2.15.0 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'revision={branch}' instead.", FutureWarning, ) revision = branch api = HfApi(endpoint=config.HF_ENDPOINT, token=token) _ = api.create_repo( repo_id, token=token, repo_type="dataset", private=private, exist_ok=True, ) if revision is not None: api.create_branch(repo_id, branch=revision, token=token, repo_type="dataset", exist_ok=True) data_dir = config_name if config_name != "default" else "data" # for backward compatibility additions, uploaded_size, dataset_nbytes = self._push_parquet_shards_to_hub( repo_id=repo_id, data_dir=data_dir, split=split, token=token, revision=revision, max_shard_size=max_shard_size, num_shards=num_shards, create_pr=create_pr, embed_external_files=embed_external_files, ) # Check if the repo already has a README.md and/or a dataset_infos.json to update them with the new split info (size and pattern) # and delete old split shards (if they exist) repo_with_dataset_card, repo_with_dataset_infos = False, False deletions, deleted_size = [], 0 repo_splits = [] # use a list to keep the order of the splits repo_files_to_add = [addition.path_in_repo for addition in additions] for repo_file in list_files_info(api, repo_id=repo_id, revision=revision, repo_type="dataset", token=token): if repo_file.rfilename == config.REPOCARD_FILENAME: repo_with_dataset_card = True elif repo_file.rfilename == config.DATASETDICT_INFOS_FILENAME: repo_with_dataset_infos = True elif ( repo_file.rfilename.startswith(f"{data_dir}/{split}-") and repo_file.rfilename not in repo_files_to_add ): deletions.append(CommitOperationDelete(path_in_repo=repo_file.rfilename)) deleted_size += repo_file.size elif fnmatch.fnmatch( repo_file.rfilename, PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED.replace("{split}", "*") ): repo_split = string_to_dict( repo_file.rfilename, glob_pattern_to_regex(PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED), )["split"] if repo_split not in repo_splits: repo_splits.append(repo_split) organization, dataset_name = repo_id.split("/") if "/" in repo_id else (None, repo_id) info_to_dump = self.info.copy() info_to_dump.download_checksums = None info_to_dump.download_size = uploaded_size info_to_dump.dataset_size = dataset_nbytes info_to_dump.size_in_bytes = uploaded_size + dataset_nbytes info_to_dump.config_name = config_name info_to_dump.splits = SplitDict( {split: SplitInfo(split, num_bytes=dataset_nbytes, num_examples=len(self), dataset_name=dataset_name)} ) # get the info from the README to update them if repo_with_dataset_card: dataset_card_path = api.hf_hub_download( repo_id, config.REPOCARD_FILENAME, repo_type="dataset", revision=revision ) dataset_card = DatasetCard.load(Path(dataset_card_path)) dataset_card_data = dataset_card.data metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card_data) dataset_infos: DatasetInfosDict = DatasetInfosDict.from_dataset_card_data(dataset_card_data) if dataset_infos and config_name in dataset_infos: repo_info = dataset_infos[config_name] else: repo_info = None # get the deprecated dataset_infos.json to update them elif repo_with_dataset_infos: dataset_card = None dataset_card_data = DatasetCardData() metadata_configs = MetadataConfigs() dataset_infos_path = api.hf_hub_download( repo_id, config.DATASETDICT_INFOS_FILENAME, repo_type="dataset", revision=revision ) with open(dataset_infos_path, encoding="utf-8") as f: dataset_infos: dict = json.load(f) dataset_info = dataset_infos.get(config_name, None) if dataset_infos else None repo_info = DatasetInfo.from_dict(dataset_info) if dataset_info else None else: dataset_card = None dataset_card_data = DatasetCardData() metadata_configs = MetadataConfigs() repo_info = None # update the total info to dump from existing info if repo_info is not None: logger.info("Updating downloaded metadata with the new split.") if repo_info.splits and list(repo_info.splits) != [split]: if self._info.features != repo_info.features: raise ValueError( f"Features of the new split don't match the features of the existing splits on the hub: {self._info.features} != {repo_info.features}" ) if split in repo_info.splits: repo_info.download_size -= deleted_size repo_info.dataset_size -= repo_info.splits.get(split, SplitInfo()).num_bytes or 0 repo_info.download_checksums = None repo_info.download_size = (repo_info.download_size or 0) + uploaded_size repo_info.dataset_size = (repo_info.dataset_size or 0) + dataset_nbytes repo_info.size_in_bytes = repo_info.download_size + repo_info.dataset_size repo_info.splits.pop(split, None) repo_info.splits[split] = SplitInfo( split, num_bytes=dataset_nbytes, num_examples=len(self), dataset_name=dataset_name ) info_to_dump = repo_info # create the metadata configs if it was uploaded with push_to_hub before metadata configs existed if not metadata_configs and repo_splits: default_metadata_configs_to_dump = { "data_files": [{"split": split, "path": f"data/{split}-*"} for split in repo_splits] } MetadataConfigs({"default": default_metadata_configs_to_dump}).to_dataset_card_data(dataset_card_data) # update the metadata configs if config_name in metadata_configs: metadata_config = metadata_configs[config_name] if "data_files" in metadata_config: data_files_to_dump = sanitize_patterns(metadata_config["data_files"]) else: data_files_to_dump = {} # add the new split data_files_to_dump[split] = [f"{data_dir}/{split}-*"] metadata_config_to_dump = { "data_files": [ { "split": _split, "path": _pattern[0] if len(_pattern) == 1 else _pattern, } for _split, _pattern in data_files_to_dump.items() ] } else: metadata_config_to_dump = {"data_files": [{"split": split, "path": f"{data_dir}/{split}-*"}]} if set_default and config_name != "default": if metadata_configs: default_config_name = metadata_configs.get_default_config_name() if default_config_name == "default": raise ValueError( "There exists a configuration named 'default'. To set a different configuration as default, " "rename the 'default' one first." ) else: _ = metadata_configs[default_config_name].pop("default") metadata_config_to_dump["default"] = True # push to the deprecated dataset_infos.json if repo_with_dataset_infos: dataset_infos_path = api.hf_hub_download( repo_id, config.DATASETDICT_INFOS_FILENAME, repo_type="dataset", revision=revision ) with open(dataset_infos_path, encoding="utf-8") as f: dataset_infos: dict = json.load(f) dataset_infos[config_name] = asdict(info_to_dump) buffer = BytesIO() buffer.write(json.dumps(dataset_infos, indent=4).encode("utf-8")) additions.append( CommitOperationAdd(path_in_repo=config.DATASETDICT_INFOS_FILENAME, path_or_fileobj=buffer) ) # push to README DatasetInfosDict({config_name: info_to_dump}).to_dataset_card_data(dataset_card_data) MetadataConfigs({config_name: metadata_config_to_dump}).to_dataset_card_data(dataset_card_data) dataset_card = DatasetCard(f"---\n{dataset_card_data}\n---\n") if dataset_card is None else dataset_card additions.append( CommitOperationAdd(path_in_repo=config.REPOCARD_FILENAME, path_or_fileobj=str(dataset_card).encode()) ) commit_message = commit_message if commit_message is not None else "Upload dataset" if len(additions) <= config.UPLOADS_MAX_NUMBER_PER_COMMIT: commit_info = api.create_commit( repo_id, operations=additions + deletions, commit_message=commit_message, commit_description=commit_description, token=token, repo_type="dataset", revision=revision, create_pr=create_pr, ) else: logger.info( f"Number of files to upload is larger than {config.UPLOADS_MAX_NUMBER_PER_COMMIT}. Splitting the push into multiple commits." ) num_commits = math.ceil(len(additions) / config.UPLOADS_MAX_NUMBER_PER_COMMIT) for i in range(0, num_commits): operations = additions[ i * config.UPLOADS_MAX_NUMBER_PER_COMMIT : (i + 1) * config.UPLOADS_MAX_NUMBER_PER_COMMIT ] + (deletions if i == 0 else []) commit_info = api.create_commit( repo_id, operations=operations, commit_message=commit_message + f" (part {i:05d}-of-{num_commits:05d})", commit_description=commit_description, token=token, repo_type="dataset", revision=revision, create_pr=create_pr, ) logger.info( f"Commit #{i+1} completed" + (f" (still {num_commits - i - 1} to go)" if num_commits - i - 1 else "") + "." ) return commit_info @transmit_format @fingerprint_transform(inplace=False) def add_column(self, name: str, column: Union[list, np.array], new_fingerprint: str): """Add column to Dataset. <Added version="1.7"/> Args: name (`str`): Column name. column (`list` or `np.array`): Column data to be added. Returns: [`Dataset`] Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> more_text = ds["text"] >>> ds.add_column(name="text_2", column=more_text) Dataset({ features: ['text', 'label', 'text_2'], num_rows: 1066 }) ``` """ column_table = InMemoryTable.from_pydict({name: column}) _check_column_names(self._data.column_names + column_table.column_names) dataset = self.flatten_indices() if self._indices is not None else self # Concatenate tables horizontally table = concat_tables([dataset._data, column_table], axis=1) # Update features info = dataset.info.copy() info.features.update(Features.from_arrow_schema(column_table.schema)) table = update_metadata_with_features(table, info.features) return Dataset(table, info=info, split=self.split, indices_table=None, fingerprint=new_fingerprint) def add_faiss_index( self, column: str, index_name: Optional[str] = None, device: Optional[int] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, # noqa: F821 batch_size: int = 1000, train_size: Optional[int] = None, faiss_verbose: bool = False, dtype=np.float32, ): """Add a dense index using Faiss for fast retrieval. By default the index is done over the vectors of the specified column. You can specify `device` if you want to run it on GPU (`device` must be the GPU index). You can find more information about Faiss here: - For [string factory](https://github.com/facebookresearch/faiss/wiki/The-index-factory) Args: column (`str`): The column of the vectors to add to the index. index_name (`str`, *optional*): The `index_name`/identifier of the index. This is the `index_name` that is used to call [`~datasets.Dataset.get_nearest_examples`] or [`~datasets.Dataset.search`]. By default it corresponds to `column`. device (`Union[int, List[int]]`, *optional*): If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU. string_factory (`str`, *optional*): This is passed to the index factory of Faiss to create the index. Default index class is `IndexFlat`. metric_type (`int`, *optional*): Type of metric. Ex: `faiss.METRIC_INNER_PRODUCT` or `faiss.METRIC_L2`. custom_index (`faiss.Index`, *optional*): Custom Faiss index that you already have instantiated and configured for your needs. batch_size (`int`): Size of the batch to use while adding vectors to the `FaissIndex`. Default value is `1000`. <Added version="2.4.0"/> train_size (`int`, *optional*): If the index needs a training step, specifies how many vectors will be used to train the index. faiss_verbose (`bool`, defaults to `False`): Enable the verbosity of the Faiss index. dtype (`data-type`): The dtype of the numpy arrays that are indexed. Default is `np.float32`. Example: ```python >>> ds = datasets.load_dataset('crime_and_punish', split='train') >>> ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']})) >>> ds_with_embeddings.add_faiss_index(column='embeddings') >>> # query >>> scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10) >>> # save index >>> ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss') >>> ds = datasets.load_dataset('crime_and_punish', split='train') >>> # load index >>> ds.load_faiss_index('embeddings', 'my_index.faiss') >>> # query >>> scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10) ``` """ with self.formatted_as(type="numpy", columns=[column], dtype=dtype): super().add_faiss_index( column=column, index_name=index_name, device=device, string_factory=string_factory, metric_type=metric_type, custom_index=custom_index, batch_size=batch_size, train_size=train_size, faiss_verbose=faiss_verbose, ) return self def add_faiss_index_from_external_arrays( self, external_arrays: np.array, index_name: str, device: Optional[int] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, # noqa: F821 batch_size: int = 1000, train_size: Optional[int] = None, faiss_verbose: bool = False, dtype=np.float32, ): """Add a dense index using Faiss for fast retrieval. The index is created using the vectors of `external_arrays`. You can specify `device` if you want to run it on GPU (`device` must be the GPU index). You can find more information about Faiss here: - For [string factory](https://github.com/facebookresearch/faiss/wiki/The-index-factory) Args: external_arrays (`np.array`): If you want to use arrays from outside the lib for the index, you can set `external_arrays`. It will use `external_arrays` to create the Faiss index instead of the arrays in the given `column`. index_name (`str`): The `index_name`/identifier of the index. This is the `index_name` that is used to call [`~datasets.Dataset.get_nearest_examples`] or [`~datasets.Dataset.search`]. device (Optional `Union[int, List[int]]`, *optional*): If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU. string_factory (`str`, *optional*): This is passed to the index factory of Faiss to create the index. Default index class is `IndexFlat`. metric_type (`int`, *optional*): Type of metric. Ex: `faiss.faiss.METRIC_INNER_PRODUCT` or `faiss.METRIC_L2`. custom_index (`faiss.Index`, *optional*): Custom Faiss index that you already have instantiated and configured for your needs. batch_size (`int`, *optional*): Size of the batch to use while adding vectors to the FaissIndex. Default value is 1000. <Added version="2.4.0"/> train_size (`int`, *optional*): If the index needs a training step, specifies how many vectors will be used to train the index. faiss_verbose (`bool`, defaults to False): Enable the verbosity of the Faiss index. dtype (`numpy.dtype`): The dtype of the numpy arrays that are indexed. Default is np.float32. """ super().add_faiss_index_from_external_arrays( external_arrays=external_arrays.astype(dtype), index_name=index_name, device=device, string_factory=string_factory, metric_type=metric_type, custom_index=custom_index, batch_size=batch_size, train_size=train_size, faiss_verbose=faiss_verbose, ) def add_elasticsearch_index( self, column: str, index_name: Optional[str] = None, host: Optional[str] = None, port: Optional[int] = None, es_client: Optional["elasticsearch.Elasticsearch"] = None, # noqa: F821 es_index_name: Optional[str] = None, es_index_config: Optional[dict] = None, ): """Add a text index using ElasticSearch for fast retrieval. This is done in-place. Args: column (`str`): The column of the documents to add to the index. index_name (`str`, *optional*): The `index_name`/identifier of the index. This is the index name that is used to call [`~Dataset.get_nearest_examples`] or [`Dataset.search`]. By default it corresponds to `column`. host (`str`, *optional*, defaults to `localhost`): Host of where ElasticSearch is running. port (`str`, *optional*, defaults to `9200`): Port of where ElasticSearch is running. es_client (`elasticsearch.Elasticsearch`, *optional*): The elasticsearch client used to create the index if host and port are `None`. es_index_name (`str`, *optional*): The elasticsearch index name used to create the index. es_index_config (`dict`, *optional*): The configuration of the elasticsearch index. Default config is: ``` { "settings": { "number_of_shards": 1, "analysis": {"analyzer": {"stop_standard": {"type": "standard", " stopwords": "_english_"}}}, }, "mappings": { "properties": { "text": { "type": "text", "analyzer": "standard", "similarity": "BM25" }, } }, } ``` Example: ```python >>> es_client = elasticsearch.Elasticsearch() >>> ds = datasets.load_dataset('crime_and_punish', split='train') >>> ds.add_elasticsearch_index(column='line', es_client=es_client, es_index_name="my_es_index") >>> scores, retrieved_examples = ds.get_nearest_examples('line', 'my new query', k=10) ``` """ with self.formatted_as(type=None, columns=[column]): super().add_elasticsearch_index( column=column, index_name=index_name, host=host, port=port, es_client=es_client, es_index_name=es_index_name, es_index_config=es_index_config, ) return self @transmit_format @fingerprint_transform(inplace=False) def add_item(self, item: dict, new_fingerprint: str): """Add item to Dataset. <Added version="1.7"/> Args: item (`dict`): Item data to be added. Returns: [`Dataset`] Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> new_review = {'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'} >>> ds = ds.add_item(new_review) >>> ds[-1] {'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'} ``` """ item_table = InMemoryTable.from_pydict({k: [v] for k, v in item.items()}) # We don't call _check_if_features_can_be_aligned here so this cast is "unsafe" dset_features, item_features = _align_features( [self._info.features, Features.from_arrow_schema(item_table.schema)] ) # Cast to align the schemas of the tables and concatenate the tables table = concat_tables( [ self._data.cast(dset_features.arrow_schema) if self._info.features != dset_features else self._data, item_table.cast(item_features.arrow_schema), ] ) if self._indices is None: indices_table = None else: item_indices_array = pa.array([len(self._data)], type=pa.uint64()) item_indices_table = InMemoryTable.from_arrays([item_indices_array], names=["indices"]) indices_table = concat_tables([self._indices, item_indices_table]) info = self.info.copy() info.features.update(item_features) table = update_metadata_with_features(table, info.features) return Dataset( table, info=info, split=self.split, indices_table=indices_table, fingerprint=new_fingerprint, ) def align_labels_with_mapping(self, label2id: Dict, label_column: str) -> "Dataset": """Align the dataset's label ID and label name mapping to match an input `label2id` mapping. This is useful when you want to ensure that a model's predicted labels are aligned with the dataset. The alignment in done using the lowercase label names. Args: label2id (`dict`): The label name to ID mapping to align the dataset with. label_column (`str`): The column name of labels to align on. Example: ```python >>> # dataset with mapping {'entailment': 0, 'neutral': 1, 'contradiction': 2} >>> ds = load_dataset("glue", "mnli", split="train") >>> # mapping to align with >>> label2id = {'CONTRADICTION': 0, 'NEUTRAL': 1, 'ENTAILMENT': 2} >>> ds_aligned = ds.align_labels_with_mapping(label2id, "label") ``` """ # Sanity checks if label_column not in self._data.column_names: raise ValueError(f"Column ({label_column}) not in table columns ({self._data.column_names}).") label_feature = self._info.features[label_column] if not ( isinstance(label_feature, ClassLabel) or (isinstance(label_feature, Sequence) and isinstance(label_feature.feature, ClassLabel)) ): raise ValueError( f"Aligning labels with a mapping is only supported for {ClassLabel.__name__} column or {Sequence.__name__} column with the inner type {ClassLabel.__name__}, and column {label_feature} is of type {type(label_feature).__name__}." ) # Sort input mapping by ID value to ensure the label names are aligned label2id = dict(sorted(label2id.items(), key=lambda item: item[1])) label_names = list(label2id.keys()) # Some label mappings use uppercase label names so we lowercase them during alignment label2id = {k.lower(): v for k, v in label2id.items()} int2str_function = ( label_feature.int2str if isinstance(label_feature, ClassLabel) else label_feature.feature.int2str ) if isinstance(label_feature, ClassLabel): def process_label_ids(batch): dset_label_names = [ int2str_function(label_id).lower() if label_id is not None else None for label_id in batch[label_column] ] batch[label_column] = [ label2id[label_name] if label_name is not None else None for label_name in dset_label_names ] return batch else: def process_label_ids(batch): dset_label_names = [ [int2str_function(label_id).lower() if label_id is not None else None for label_id in seq] for seq in batch[label_column] ] batch[label_column] = [ [label2id[label_name] if label_name is not None else None for label_name in seq] for seq in dset_label_names ] return batch features = self.features features[label_column] = ( ClassLabel(num_classes=len(label_names), names=label_names) if isinstance(label_feature, ClassLabel) else Sequence(ClassLabel(num_classes=len(label_names), names=label_names)) ) return self.map(process_label_ids, features=features, batched=True, desc="Aligning the labels") def _concatenate_map_style_datasets( dsets: List[Dataset], info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, axis: int = 0, ): """ Converts a list of :class:`Dataset` with the same schema into a single :class:`Dataset`. When you concatenate on axis 0, missing data are filled with None values. Args: dsets (`List[datasets.Dataset]`): List of Datasets to concatenate. info (:class:`DatasetInfo`, optional): Dataset information, like description, citation, etc. split (:class:`NamedSplit`, optional): Name of the dataset split. axis (``{0, 1}``, default ``0``, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). *New in version 1.6.0* Example: ```py >>> ds3 = _concatenate_map_style_datasets([ds1, ds2]) ``` """ # Ignore datasets with no rows if any(dset.num_rows > 0 for dset in dsets): dsets = [dset for dset in dsets if dset.num_rows > 0] else: # Return first dataset if all datasets are empty return dsets[0] # Perform checks (and a potentional cast if axis=0) if axis == 0: _check_if_features_can_be_aligned([dset.features for dset in dsets]) else: if not all(dset.num_rows == dsets[0].num_rows for dset in dsets): raise ValueError("Number of rows must match for all datasets") _check_column_names([col_name for dset in dsets for col_name in dset._data.column_names]) # Find common format or reset format format = dsets[0].format if any(dset.format != format for dset in dsets): format = {} logger.info("Some of the datasets have disparate format. Resetting the format of the concatenated dataset.") def apply_offset_to_indices_table(table, offset): if offset == 0: return table else: array = table["indices"] new_array = pc.add(array, pa.scalar(offset, type=pa.uint64())) return InMemoryTable.from_arrays([new_array], names=["indices"]) # Concatenate indices if they exist if any(dset._indices is not None for dset in dsets): if axis == 0: # Datasets with no indices tables are replaced with a dataset with an indices table in memory. # Applying an offset to an indices table also brings the table in memory. indices_tables = [] for i in range(len(dsets)): if dsets[i]._indices is None: dsets[i] = dsets[i]._select_with_indices_mapping(range(len(dsets[i]))) indices_tables.append(dsets[i]._indices) # An offset needs to be applied to the indices before concatenating offset = 0 for i in range(len(dsets)): indices_tables[i] = apply_offset_to_indices_table(indices_tables[i], offset) offset += len(dsets[i]._data) # Concatenate indices indices_tables = [t for t in indices_tables if len(t) > 0] if indices_tables: indices_table = concat_tables(indices_tables) else: indices_table = InMemoryTable.from_batches([], schema=pa.schema({"indices": pa.int64()})) else: if len(dsets) == 1: indices_table = dsets[0]._indices else: for i in range(len(dsets)): dsets[i] = dsets[i].flatten_indices() indices_table = None else: indices_table = None table = concat_tables([dset._data for dset in dsets], axis=axis) if axis == 0: features_list = _align_features([dset.features for dset in dsets]) else: features_list = [dset.features for dset in dsets] table = update_metadata_with_features(table, {k: v for features in features_list for k, v in features.items()}) # Concatenate infos if info is None: info = DatasetInfo.from_merge([dset.info for dset in dsets]) fingerprint = update_fingerprint( "".join(dset._fingerprint for dset in dsets), _concatenate_map_style_datasets, {"info": info, "split": split} ) # Make final concatenated dataset concatenated_dataset = Dataset( table, info=info, split=split, indices_table=indices_table, fingerprint=fingerprint, ) concatenated_dataset.set_format(**format) return concatenated_dataset def _interleave_map_style_datasets( datasets: List["Dataset"], probabilities: Optional[List[float]] = None, seed: Optional[int] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "first_exhausted", **kwargs, ) -> "Dataset": """ Interleave several map-style datasets (sources) into a single map-style dataset. The new dataset is constructed by alternating between the sources to get the examples. If `probabilities = None` (default) the new dataset is constructed by cycling between each source to get the examples. If `probabilities` is not `None, the new dataset is constructed by getting examples from a random source at a time according to the provided probabilities. Args: datasets (`List[Dataset]`): list of datasets to interleave probabilities (`List[float]`, optional, default None): If specified, the new dataset is constructed by sampling examples from one source at a time according to these probabilities. seed (`int`, optional, default None): The random seed used to choose a source for each example. info (:class:`DatasetInfo`, optional): Dataset information, like description, citation, etc. split (:class:`NamedSplit`, optional): Name of the dataset split. stopping_strategy (`str`, defaults to `first_exhausted`): Two strategies are proposed right now. By default, `first_exhausted` is an undersampling strategy, i.e the dataset construction is stopped as soon as one dataset has ran out of samples. If the strategy is `all_exhausted`, we use an oversampling strategy, i.e the dataset construction is stopped as soon as every samples of every dataset has been added at least once. Note that if the strategy is `all_exhausted`, the interleaved dataset size can get enormous: - with no probabilities, the resulting dataset will have max_length_datasets*nb_dataset samples. - with given probabilities, the resulting dataset will have more samples if some datasets have really low probability of visiting. **kwargs (additional keyword arguments): Keyword arguments to be passed to :meth:`datasets.Datasets.select` when selecting the indices used to interleave the datasets. Output: :class:`datasets.Dataset` """ if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError( f"{stopping_strategy} stopping strategy in `interleave_datasets` is not implemented yet with a list of {type(datasets[0])}" ) # To interleave the datasets, we concatenate them and then we re-order the indices concatenated_datasets = _concatenate_map_style_datasets(datasets, info=info, split=split) # Let's now build the indices to pass to .select() lengths = [len(dset) for dset in datasets] offsets = np.cumsum([0] + lengths[:-1]) # if stopping_strategy is "first_exhausted", it is an undersampling situation whereas it is an oversampling situation if it is "all_exhausted" oversampling = stopping_strategy == "all_exhausted" if probabilities is None and not oversampling: # Undersampling situation with cycling between each sources # Example:: If lengths of the datasets are [3, 4, 5] # Then the resulting indices should be [0, 3, 7, 1, 4, 8, 2, 6, 9] # Note that we only have 3 examples per dataset since the first dataset ran out of examples # Reasoning behind the following operation: keeping the min_length first indices of each dataset # while offsetting in order to correspond to the right indices of the concatenated dataset # and flattening to effectively interleave the datasets indices = (offsets.reshape(1, -1) + np.arange(min(lengths)).reshape(-1, 1)).flatten().tolist() elif probabilities is None: # Oversampling situation with cycling between each sources # Then the resulting indices should be [0, 3, 7, 1, 4, 8, 2, 5, 9, 0, 6, 10, 1, 3, 11] # Note that we have 5 examples per dataset with a rolling window since the longest dataset has 5 samples # Reasoning behind the following operation: for each dataset indices (i.e column) repeat the indices to have max_length indices per dataset # For example, if the max_length is 5 and the i-th dataset has 3 samples, the i-th column will be [0,1,2,0,1] indices = np.mod(np.arange(max(lengths)).reshape(-1, 1), np.array(lengths).reshape(1, -1)) # We have to keep the indices to their respective dataset offsets and to flatten to effectively interleave the datasets indices = (indices + offsets).flatten().tolist() else: # boolean array indicating if at index i if the dataset_i has been fully exhausted is_exhausted = np.full(len(lengths), False) # if undersampling ("first_exhausted"), we stop as soon as one dataset is exhausted # if oversampling ("all_exhausted"), we stop as soons as every dataset is exhausted, i.e as soon as every samples of every dataset has been visited at least once bool_strategy_func = np.all if oversampling else np.any def iter_random_indices(): """Get an infinite iterator that randomly samples the index of the source to pick examples from.""" rng = np.random.default_rng(seed) while True: yield from (int(i) for i in rng.choice(len(datasets), size=1000, p=probabilities)) current_index = [0] * len(datasets) indices = [] for source_idx in iter_random_indices(): # If no oversampling, we stop as soon as a dataset has ran out of examples (np.any) # Otherwise, we stop as soon as every dataset has ran out of examples (np.all) if bool_strategy_func(is_exhausted): # the stopping condition was reached, let's stop break # let's add the example at the current index of the `source_idx`-th dataset indices.append(current_index[source_idx] + offsets[source_idx]) current_index[source_idx] += 1 # we've ran out of examples for the current dataset, let's update our boolean array and bring the current_index back to 0 if current_index[source_idx] >= lengths[source_idx]: is_exhausted[source_idx] = True current_index[source_idx] = 0 return concatenated_datasets.select(indices, **kwargs) def _split_by_node_map_style_dataset(dataset: Dataset, rank: int, world_size: int) -> Dataset: """ Split a dataset for the node at rank `rank` in a pool of nodes of size `world_size`. Each node is assigned a chunk of data, e.g. rank 0 is given the first chunk of the dataset. To maximize data loading throughput, chunks are made of contiguous data on disk if possible. Args: dataset ([`Dataset`]): The dataset to split by node. rank (`int`): Rank of the current node. world_size (`int`): Total number of nodes. Returns: [`Dataset`]: The dataset to be used on the node at rank `rank`. """ return dataset.shard(num_shards=world_size, index=rank, contiguous=True) # This is outside Dataset.filter as it needs to be picklable for multiprocessing def get_indices_from_mask_function( function: Callable, batched: bool, with_indices: bool, input_columns: Optional[Union[str, List[str]]], indices_mapping: Optional[Table] = None, *args, **fn_kwargs, ): if batched: # we extract indices from args *inputs, indices = args if with_indices: mask = function(*inputs, indices, **fn_kwargs) else: mask = function(*inputs, **fn_kwargs) else: # we get batched data (to do less look-ups) but `function` only accepts one example # therefore we need to call `function` on each example of the batch to get the mask *inputs, indices = args mask = [] if input_columns is None: # inputs only contains a batch of examples batch: dict = inputs[0] num_examples = len(batch[next(iter(batch.keys()))]) for i in range(num_examples): example = {key: batch[key][i] for key in batch} mask.append( function(example, indices[i], **fn_kwargs) if with_indices else function(example, **fn_kwargs) ) else: # inputs is a list of columns columns: List[List] = inputs num_examples = len(columns[0]) for i in range(num_examples): input = [column[i] for column in columns] mask.append( function(*input, indices[i], **fn_kwargs) if with_indices else function(*input, **fn_kwargs) ) indices_array = [i for i, to_keep in zip(indices, mask) if to_keep] if indices_mapping is not None: indices_array = pa.array(indices_array, type=pa.uint64()) indices_array = indices_mapping.column(0).take(indices_array) indices_array = indices_array.to_pylist() return {"indices": indices_array}
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/builder.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """DatasetBuilder base class.""" import abc import contextlib import copy import inspect import os import posixpath import shutil import textwrap import time import urllib import warnings from dataclasses import dataclass from functools import partial from pathlib import Path from typing import TYPE_CHECKING, Dict, Iterable, Mapping, Optional, Tuple, Union from unittest.mock import patch import fsspec import pyarrow as pa from multiprocess import Pool from tqdm.contrib.concurrent import thread_map from . import config, utils from .arrow_dataset import Dataset from .arrow_reader import ( HF_GCP_BASE_URL, ArrowReader, DatasetNotOnHfGcsError, MissingFilesOnHfGcsError, ReadInstruction, ) from .arrow_writer import ArrowWriter, BeamWriter, ParquetWriter, SchemaInferenceError from .data_files import DataFilesDict, DataFilesPatternsDict, sanitize_patterns from .dataset_dict import DatasetDict, IterableDatasetDict from .download.download_config import DownloadConfig from .download.download_manager import DownloadManager, DownloadMode from .download.mock_download_manager import MockDownloadManager from .download.streaming_download_manager import StreamingDownloadManager, xjoin, xopen from .exceptions import DatasetGenerationCastError, DatasetGenerationError, FileFormatError, ManualDownloadError from .features import Features from .filesystems import ( is_remote_filesystem, rename, ) from .fingerprint import Hasher from .info import DatasetInfo, DatasetInfosDict, PostProcessedInfo from .iterable_dataset import ArrowExamplesIterable, ExamplesIterable, IterableDataset from .keyhash import DuplicatedKeysError from .naming import INVALID_WINDOWS_CHARACTERS_IN_PATH, camelcase_to_snakecase from .splits import Split, SplitDict, SplitGenerator, SplitInfo from .streaming import extend_dataset_builder_for_streaming from .table import CastError from .utils import logging from .utils import tqdm as hf_tqdm from .utils._filelock import FileLock from .utils.file_utils import cached_path, is_remote_url from .utils.info_utils import VerificationMode, get_size_checksum_dict, verify_checksums, verify_splits from .utils.py_utils import ( classproperty, convert_file_size_to_int, has_sufficient_disk_space, iflatmap_unordered, map_nested, memoize, size_str, temporary_assignment, ) from .utils.sharding import _number_of_shards_in_gen_kwargs, _split_gen_kwargs from .utils.track import tracked_list if TYPE_CHECKING: from .load import DatasetModule logger = logging.get_logger(__name__) class InvalidConfigName(ValueError): pass @dataclass class BuilderConfig: """Base class for `DatasetBuilder` data configuration. `DatasetBuilder` subclasses with data configuration options should subclass `BuilderConfig` and add their own properties. Attributes: 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. """ name: str = "default" version: Optional[Union[utils.Version, str]] = utils.Version("0.0.0") data_dir: Optional[str] = None data_files: Optional[Union[DataFilesDict, DataFilesPatternsDict]] = None description: Optional[str] = None def __post_init__(self): # The config name is used to name the cache directory. for invalid_char in INVALID_WINDOWS_CHARACTERS_IN_PATH: if invalid_char in self.name: raise InvalidConfigName( f"Bad characters from black list '{INVALID_WINDOWS_CHARACTERS_IN_PATH}' found in '{self.name}'. " f"They could create issues when creating a directory for this config on Windows filesystem." ) if self.data_files is not None and not isinstance(self.data_files, (DataFilesDict, DataFilesPatternsDict)): raise ValueError(f"Expected a DataFilesDict in data_files but got {self.data_files}") def __eq__(self, o): # we need to override the default dataclass __eq__ since it doesn't check for # other attributes that the ones of the signature. if set(self.__dict__.keys()) != set(o.__dict__.keys()): return False return all((k, getattr(self, k)) == (k, getattr(o, k)) for k in self.__dict__.keys()) def create_config_id( self, config_kwargs: dict, custom_features: Optional[Features] = None, ) -> str: """ 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. """ # Possibly add a suffix to the name to handle custom features/data_files/config_kwargs suffix: Optional[str] = None config_kwargs_to_add_to_suffix = config_kwargs.copy() # name and version are already used to build the cache directory config_kwargs_to_add_to_suffix.pop("name", None) config_kwargs_to_add_to_suffix.pop("version", None) # data dir handling (when specified it points to the manually downloaded data): # it was previously ignored before the introduction of config id because we didn't want # to change the config name. Now it's fine to take it into account for the config id. # config_kwargs_to_add_to_suffix.pop("data_dir", None) if "data_dir" in config_kwargs_to_add_to_suffix: if config_kwargs_to_add_to_suffix["data_dir"] is None: config_kwargs_to_add_to_suffix.pop("data_dir", None) else: # canonicalize the data dir to avoid two paths to the same location having different # hashes data_dir = config_kwargs_to_add_to_suffix["data_dir"] data_dir = os.path.normpath(data_dir) config_kwargs_to_add_to_suffix["data_dir"] = data_dir if config_kwargs_to_add_to_suffix: # we don't care about the order of the kwargs config_kwargs_to_add_to_suffix = { k: config_kwargs_to_add_to_suffix[k] for k in sorted(config_kwargs_to_add_to_suffix) } if all(isinstance(v, (str, bool, int, float)) for v in config_kwargs_to_add_to_suffix.values()): suffix = ",".join( str(k) + "=" + urllib.parse.quote_plus(str(v)) for k, v in config_kwargs_to_add_to_suffix.items() ) if len(suffix) > 32: # hash if too long suffix = Hasher.hash(config_kwargs_to_add_to_suffix) else: suffix = Hasher.hash(config_kwargs_to_add_to_suffix) if custom_features is not None: m = Hasher() if suffix: m.update(suffix) m.update(custom_features) suffix = m.hexdigest() if suffix: config_id = self.name + "-" + suffix if len(config_id) > config.MAX_DATASET_CONFIG_ID_READABLE_LENGTH: config_id = self.name + "-" + Hasher.hash(suffix) return config_id else: return self.name def _resolve_data_files(self, base_path: str, download_config: DownloadConfig) -> None: if isinstance(self.data_files, DataFilesPatternsDict): base_path = xjoin(base_path, self.data_dir) if self.data_dir else base_path self.data_files = self.data_files.resolve(base_path, download_config) class DatasetBuilder: """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`]: Downloads the source data and writes it to disk. - [`DatasetBuilder.as_dataset`]: Generates a [`Dataset`]. Some `DatasetBuilder`s expose multiple variants of the dataset by defining a [`BuilderConfig`] subclass and accepting a config object (or name) on construction. Configurable datasets expose a pre-defined set of configurations in [`DatasetBuilder.builder_configs`]. Args: 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 version="2.3.0"> Parameter `name` was renamed to `config_name`. </Added> 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`], *optional*): Features types to use with this dataset. It can be used to change the [`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 version="2.3.0"> Use `config_name` instead. </Deprecated> **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`]. The builder configuration class is [`BuilderConfig`] or a subclass of it. """ # Default version VERSION = None # Default version set in BuilderConfig # Class for the builder config. BUILDER_CONFIG_CLASS = BuilderConfig # Named configurations that modify the data generated by download_and_prepare. BUILDER_CONFIGS = [] # Optional default config name to be used when name is None DEFAULT_CONFIG_NAME = None # Default 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 DEFAULT_WRITER_BATCH_SIZE = None def __init__( self, cache_dir: Optional[str] = None, dataset_name: Optional[str] = None, config_name: Optional[str] = None, hash: Optional[str] = None, base_path: Optional[str] = None, info: Optional[DatasetInfo] = None, features: Optional[Features] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", repo_id: Optional[str] = None, data_files: Optional[Union[str, list, dict, DataFilesDict]] = None, data_dir: Optional[str] = None, storage_options: Optional[dict] = None, writer_batch_size: Optional[int] = None, name="deprecated", **config_kwargs, ): if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'token={use_auth_token}' instead.", FutureWarning, ) token = use_auth_token if name != "deprecated": warnings.warn( "Parameter 'name' was renamed to 'config_name' in version 2.3.0 and will be removed in 3.0.0.", category=FutureWarning, ) config_name = name # DatasetBuilder name self.name: str = camelcase_to_snakecase(self.__module__.split(".")[-1]) self.hash: Optional[str] = hash self.base_path = base_path self.token = token # For backwards compatibility (e.g. if accessed in a dataset script) self.use_auth_token = token self.repo_id = repo_id self.storage_options = storage_options or {} self.dataset_name = camelcase_to_snakecase(dataset_name) if dataset_name else self.name self._writer_batch_size = writer_batch_size or self.DEFAULT_WRITER_BATCH_SIZE if data_files is not None and not isinstance(data_files, DataFilesDict): data_files = DataFilesDict.from_patterns( sanitize_patterns(data_files), base_path=base_path, download_config=DownloadConfig(token=token, storage_options=self.storage_options), ) # Prepare config: DatasetConfig contains name, version and description but can be extended by each dataset if "features" in inspect.signature(self.BUILDER_CONFIG_CLASS.__init__).parameters and features is not None: config_kwargs["features"] = features if data_files is not None: config_kwargs["data_files"] = data_files if data_dir is not None: config_kwargs["data_dir"] = data_dir self.config, self.config_id = self._create_builder_config( config_name=config_name, custom_features=features, **config_kwargs, ) # prepare info: DatasetInfo are a standardized dataclass across all datasets # Prefill datasetinfo if info is None: # TODO FOR PACKAGED MODULES IT IMPORTS DATA FROM src/packaged_modules which doesn't make sense info = self.get_exported_dataset_info() info.update(self._info()) info.builder_name = self.name info.dataset_name = self.dataset_name info.config_name = self.config.name info.version = self.config.version self.info = info # update info with user specified infos if features is not None: self.info.features = features # Prepare data dirs: # cache_dir can be a remote bucket on GCS or S3 (when using BeamBasedBuilder for distributed data processing) self._cache_dir_root = str(cache_dir or config.HF_DATASETS_CACHE) self._cache_dir_root = ( self._cache_dir_root if is_remote_url(self._cache_dir_root) else os.path.expanduser(self._cache_dir_root) ) self._cache_downloaded_dir = ( posixpath.join(self._cache_dir_root, config.DOWNLOADED_DATASETS_DIR) if cache_dir else str(config.DOWNLOADED_DATASETS_PATH) ) self._cache_downloaded_dir = ( self._cache_downloaded_dir if is_remote_url(self._cache_downloaded_dir) else os.path.expanduser(self._cache_downloaded_dir) ) # In case there exists a legacy cache directory self._legacy_relative_data_dir = None self._cache_dir = self._build_cache_dir() if not is_remote_url(self._cache_dir_root): os.makedirs(self._cache_dir_root, exist_ok=True) lock_path = os.path.join( self._cache_dir_root, Path(self._cache_dir).as_posix().replace("/", "_") + ".lock" ) with FileLock(lock_path): if os.path.exists(self._cache_dir): # check if data exist if len(os.listdir(self._cache_dir)) > 0: if os.path.exists(os.path.join(self._cache_dir, config.DATASET_INFO_FILENAME)): logger.info("Overwrite dataset info from restored data version if exists.") self.info = DatasetInfo.from_directory(self._cache_dir) else: # dir exists but no data, remove the empty dir as data aren't available anymore logger.warning( f"Old caching folder {self._cache_dir} for dataset {self.dataset_name} exists but no data were found. Removing it. " ) os.rmdir(self._cache_dir) # Store in the cache by default unless the user specifies a custom output_dir to download_and_prepare self._output_dir = self._cache_dir self._fs: fsspec.AbstractFileSystem = fsspec.filesystem("file") # Set download manager self.dl_manager = None # Set to True by "datasets-cli test" to generate file checksums for (deprecated) dataset_infos.json independently of verification_mode value. self._record_infos = False # Set in `.download_and_prepare` once the format of the generated dataset is known self._file_format = None # Enable streaming (e.g. it patches "open" to work with remote files) extend_dataset_builder_for_streaming(self) def __getstate__(self): return self.__dict__ def __setstate__(self, d): self.__dict__ = d # Re-enable streaming, since patched functions are not kept when pickling extend_dataset_builder_for_streaming(self) # Must be set for datasets that use 'data_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. @property def manual_download_instructions(self) -> Optional[str]: return None def _check_legacy_cache(self) -> Optional[str]: """Check for the old cache directory template {cache_dir}/{namespace}___{builder_name} from 2.13""" if ( self.__module__.startswith("datasets.") and not is_remote_url(self._cache_dir_root) and self.config.name == "default" ): from .packaged_modules import _PACKAGED_DATASETS_MODULES namespace = self.repo_id.split("/")[0] if self.repo_id and self.repo_id.count("/") > 0 else None config_name = self.repo_id.replace("/", "--") if self.repo_id is not None else self.dataset_name config_id = config_name + self.config_id[len(self.config.name) :] hash = _PACKAGED_DATASETS_MODULES.get(self.name, "missing")[1] legacy_relative_data_dir = posixpath.join( self.dataset_name if namespace is None else f"{namespace}___{self.dataset_name}", config_id, "0.0.0", hash, ) legacy_cache_dir = posixpath.join(self._cache_dir_root, legacy_relative_data_dir) if os.path.isdir(legacy_cache_dir): return legacy_relative_data_dir def _check_legacy_cache2(self, dataset_module: "DatasetModule") -> Optional[str]: """Check for the old cache directory template {cache_dir}/{namespace}___{dataset_name}/{config_name}-xxx from 2.14 and 2.15""" if self.__module__.startswith("datasets.") and not is_remote_url(self._cache_dir_root): from .packaged_modules import _PACKAGED_DATASETS_MODULES from .utils._dill import Pickler def update_hash_with_config_parameters(hash: str, config_parameters: dict) -> str: """ Used to update hash of packaged modules which is used for creating unique cache directories to reflect different config parameters which are passed in metadata from readme. """ params_to_exclude = {"config_name", "version", "description"} params_to_add_to_hash = { param: value for param, value in sorted(config_parameters.items()) if param not in params_to_exclude } m = Hasher() m.update(hash) m.update(params_to_add_to_hash) return m.hexdigest() namespace = self.repo_id.split("/")[0] if self.repo_id and self.repo_id.count("/") > 0 else None with patch.object(Pickler, "_legacy_no_dict_keys_sorting", True): config_id = self.config.name + "-" + Hasher.hash({"data_files": self.config.data_files}) hash = _PACKAGED_DATASETS_MODULES.get(self.name, "missing")[1] if ( dataset_module.builder_configs_parameters.metadata_configs and self.config.name in dataset_module.builder_configs_parameters.metadata_configs ): hash = update_hash_with_config_parameters( hash, dataset_module.builder_configs_parameters.metadata_configs[self.config.name] ) legacy_relative_data_dir = posixpath.join( self.dataset_name if namespace is None else f"{namespace}___{self.dataset_name}", config_id, "0.0.0", hash, ) legacy_cache_dir = posixpath.join(self._cache_dir_root, legacy_relative_data_dir) if os.path.isdir(legacy_cache_dir): return legacy_relative_data_dir @classmethod def get_all_exported_dataset_infos(cls) -> DatasetInfosDict: """Empty dict if doesn't exist Example: ```py >>> 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.\nThis is a dataset of containing 5,331 positive and 5,331 negative processed\nsentences from Rotten Tomatoes movie reviews. This data was first used in Bo\nPang and Lillian Lee, ``Seeing stars: Exploiting class relationships for\nsentiment categorization with respect to rating scales.'', Proceedings of the\nACL, 2005.\n", citation='@InProceedings{Pang+Lee:05a,\n author = {Bo Pang and Lillian Lee},\n title = {Seeing stars: Exploiting class relationships for sentiment\n categorization with respect to rating scales},\n booktitle = {Proceedings of the ACL},\n year = 2005\n}\n', homepage='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)} ``` """ return DatasetInfosDict.from_directory(cls.get_imported_module_dir()) def get_exported_dataset_info(self) -> DatasetInfo: """Empty `DatasetInfo` if doesn't exist Example: ```py >>> from datasets import load_dataset_builder >>> ds_builder = load_dataset_builder('rotten_tomatoes') >>> ds_builder.get_exported_dataset_info() DatasetInfo(description="Movie Review Dataset.\nThis is a dataset of containing 5,331 positive and 5,331 negative processed\nsentences from Rotten Tomatoes movie reviews. This data was first used in Bo\nPang and Lillian Lee, ``Seeing stars: Exploiting class relationships for\nsentiment categorization with respect to rating scales.'', Proceedings of the\nACL, 2005.\n", citation='@InProceedings{Pang+Lee:05a,\n author = {Bo Pang and Lillian Lee},\n title = {Seeing stars: Exploiting class relationships for sentiment\n categorization with respect to rating scales},\n booktitle = {Proceedings of the ACL},\n year = 2005\n}\n', homepage='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) ``` """ return self.get_all_exported_dataset_infos().get(self.config.name, DatasetInfo()) def _create_builder_config( self, config_name=None, custom_features=None, **config_kwargs ) -> Tuple[BuilderConfig, str]: """Create and validate BuilderConfig object as well as a unique config id for this config. Raises ValueError if there are multiple builder configs and config_name and DEFAULT_CONFIG_NAME are None. config_kwargs override the defaults kwargs in config """ builder_config = None # try default config if config_name is None and self.BUILDER_CONFIGS: if self.DEFAULT_CONFIG_NAME is not None: builder_config = self.builder_configs.get(self.DEFAULT_CONFIG_NAME) logger.info(f"No config specified, defaulting to: {self.dataset_name}/{builder_config.name}") else: if len(self.BUILDER_CONFIGS) > 1: if not config_kwargs: example_of_usage = f"load_dataset('{self.dataset_name}', '{self.BUILDER_CONFIGS[0].name}')" raise ValueError( "Config name is missing." f"\nPlease pick one among the available configs: {list(self.builder_configs.keys())}" + f"\nExample of usage:\n\t`{example_of_usage}`" ) else: builder_config = self.BUILDER_CONFIGS[0] logger.info( f"No config specified, defaulting to the single config: {self.dataset_name}/{builder_config.name}" ) # try to get config by name if isinstance(config_name, str): builder_config = self.builder_configs.get(config_name) if builder_config is None and self.BUILDER_CONFIGS: raise ValueError( f"BuilderConfig '{config_name}' not found. Available: {list(self.builder_configs.keys())}" ) # if not using an existing config, then create a new config on the fly if not builder_config: if config_name is not None: config_kwargs["name"] = config_name elif self.DEFAULT_CONFIG_NAME and not config_kwargs: # Use DEFAULT_CONFIG_NAME only if no config_kwargs are passed config_kwargs["name"] = self.DEFAULT_CONFIG_NAME if "version" not in config_kwargs and hasattr(self, "VERSION") and self.VERSION: config_kwargs["version"] = self.VERSION builder_config = self.BUILDER_CONFIG_CLASS(**config_kwargs) # otherwise use the config_kwargs to overwrite the attributes else: builder_config = copy.deepcopy(builder_config) if config_kwargs else builder_config for key, value in config_kwargs.items(): if value is not None: if not hasattr(builder_config, key): raise ValueError(f"BuilderConfig {builder_config} doesn't have a '{key}' key.") setattr(builder_config, key, value) if not builder_config.name: raise ValueError(f"BuilderConfig must have a name, got {builder_config.name}") # resolve data files if needed builder_config._resolve_data_files( base_path=self.base_path, download_config=DownloadConfig(token=self.token, storage_options=self.storage_options), ) # compute the config id that is going to be used for caching config_id = builder_config.create_config_id( config_kwargs, custom_features=custom_features, ) is_custom = (config_id not in self.builder_configs) and config_id != "default" if is_custom: logger.info(f"Using custom data configuration {config_id}") else: if ( builder_config.name in self.builder_configs and builder_config != self.builder_configs[builder_config.name] ): raise ValueError( "Cannot name a custom BuilderConfig the same as an available " f"BuilderConfig. Change the name. Available BuilderConfigs: {list(self.builder_configs.keys())}" ) if not builder_config.version: raise ValueError(f"BuilderConfig {builder_config.name} must have a version") return builder_config, config_id @classproperty @classmethod @memoize() def builder_configs(cls) -> Dict[str, BuilderConfig]: """Dictionary of pre-defined configurations for this builder class.""" configs = {config.name: config for config in cls.BUILDER_CONFIGS} if len(configs) != len(cls.BUILDER_CONFIGS): names = [config.name for config in cls.BUILDER_CONFIGS] raise ValueError(f"Names in BUILDER_CONFIGS must not be duplicated. Got {names}") return configs @property def cache_dir(self): return self._cache_dir def _use_legacy_cache_dir_if_possible(self, dataset_module: "DatasetModule"): # Check for the legacy cache directory template (datasets<3.0.0) self._legacy_relative_data_dir = ( self._check_legacy_cache2(dataset_module) or self._check_legacy_cache() or None ) self._cache_dir = self._build_cache_dir() self._output_dir = self._cache_dir def _relative_data_dir(self, with_version=True, with_hash=True) -> str: """Relative path of this dataset in cache_dir: Will be: self.dataset_name/self.config.version/self.hash/ or if a repo_id with a namespace has been specified: self.namespace___self.dataset_name/self.config.version/self.hash/ If any of these element is missing or if ``with_version=False`` the corresponding subfolders are dropped. """ if self._legacy_relative_data_dir is not None and with_version and with_hash: return self._legacy_relative_data_dir namespace = self.repo_id.split("/")[0] if self.repo_id and self.repo_id.count("/") > 0 else None builder_data_dir = self.dataset_name if namespace is None else f"{namespace}___{self.dataset_name}" builder_data_dir = posixpath.join(builder_data_dir, self.config_id) if with_version: builder_data_dir = posixpath.join(builder_data_dir, str(self.config.version)) if with_hash and self.hash and isinstance(self.hash, str): builder_data_dir = posixpath.join(builder_data_dir, self.hash) return builder_data_dir def _build_cache_dir(self): """Return the data directory for the current version.""" builder_data_dir = posixpath.join(self._cache_dir_root, self._relative_data_dir(with_version=False)) version_data_dir = posixpath.join(self._cache_dir_root, self._relative_data_dir(with_version=True)) def _other_versions_on_disk(): """Returns previous versions on disk.""" if not os.path.exists(builder_data_dir): return [] version_dirnames = [] for dir_name in os.listdir(builder_data_dir): try: version_dirnames.append((utils.Version(dir_name), dir_name)) except ValueError: # Invalid version (ex: incomplete data dir) pass version_dirnames.sort(reverse=True) return version_dirnames # Check and warn if other versions exist if not is_remote_url(builder_data_dir): version_dirs = _other_versions_on_disk() if version_dirs: other_version = version_dirs[0][0] if other_version != self.config.version: warn_msg = ( f"Found a different version {str(other_version)} of dataset {self.dataset_name} in " f"cache_dir {self._cache_dir_root}. Using currently defined version " f"{str(self.config.version)}." ) logger.warning(warn_msg) return version_data_dir @abc.abstractmethod def _info(self) -> DatasetInfo: """Construct the DatasetInfo object. See `DatasetInfo` for details. Warning: This function is only called once and the result is cached for all following .info() calls. Returns: info: (DatasetInfo) The dataset information """ raise NotImplementedError @classmethod def get_imported_module_dir(cls): """Return the path of the module of this class or subclass.""" return os.path.dirname(inspect.getfile(inspect.getmodule(cls))) def _rename(self, src: str, dst: str): rename(self._fs, src, dst) def download_and_prepare( self, output_dir: Optional[str] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, verification_mode: Optional[Union[VerificationMode, str]] = None, ignore_verifications="deprecated", try_from_hf_gcs: bool = True, dl_manager: Optional[DownloadManager] = None, base_path: Optional[str] = None, use_auth_token="deprecated", file_format: str = "arrow", max_shard_size: Optional[Union[int, str]] = None, num_proc: Optional[int] = None, storage_options: Optional[dict] = None, **download_and_prepare_kwargs, ): """Downloads and prepares dataset for reading. Args: 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 version="2.5.0"/> download_config (`DownloadConfig`, *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, *optional*): Select the download/generate mode, default to `REUSE_DATASET_IF_EXISTS`. verification_mode ([`VerificationMode`] or `str`, defaults to `BASIC_CHECKS`): Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/...). <Added version="2.9.1"/> ignore_verifications (`bool`, defaults to `False`): Ignore the verifications of the downloaded/processed dataset information (checksums/size/splits/...). <Deprecated version="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. </Deprecated> 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 version="2.7.1"> Pass `use_auth_token` to `load_dataset_builder` instead. </Deprecated> 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 version="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 version="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 version="2.7.0"/> storage_options (`dict`, *optional*): Key/value pairs to be passed on to the caching file-system backend, if any. <Added version="2.5.0"/> **download_and_prepare_kwargs (additional keyword arguments): Keyword arguments. Example: Download and prepare the dataset as Arrow files that can be loaded as a Dataset using `builder.as_dataset()`: ```py >>> 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: ```py >>> 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: ```py >>> 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") ``` """ if ignore_verifications != "deprecated": verification_mode = VerificationMode.NO_CHECKS if ignore_verifications else VerificationMode.ALL_CHECKS warnings.warn( "'ignore_verifications' was deprecated in favor of 'verification_mode' in version 2.9.1 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'verification_mode={verification_mode.value}' instead.", FutureWarning, ) if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in version 2.7.1 and will be removed in 3.0.0. Pass `token` to `load_dataset_builder` instead.", FutureWarning, ) token = use_auth_token else: token = self.token output_dir = output_dir if output_dir is not None else self._cache_dir # output_dir can be a remote bucket on GCS or S3 (when using BeamBasedBuilder for distributed data processing) fs, _, [output_dir] = fsspec.get_fs_token_paths(output_dir, storage_options=storage_options) self._fs = fs self._output_dir = output_dir if not is_remote_filesystem(self._fs) else self._fs.unstrip_protocol(output_dir) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) verification_mode = VerificationMode(verification_mode or VerificationMode.BASIC_CHECKS) base_path = base_path if base_path is not None else self.base_path if file_format is not None and file_format not in ["arrow", "parquet"]: raise ValueError(f"Unsupported file_format: {file_format}. Expected 'arrow' or 'parquet'") self._file_format = file_format if self._fs._strip_protocol(self._output_dir) == "": # We don't support the root directory, because it has no dirname, # and we need a dirname to use a <dirname>.incomplete directory # when the dataset is being written raise RuntimeError( f"Unable to download and prepare the dataset at the root {self._output_dir}. " f"Please specify a subdirectory, e.g. '{self._output_dir + self.dataset_name}'" ) if dl_manager is None: if download_config is None: download_config = DownloadConfig( cache_dir=self._cache_downloaded_dir, force_download=download_mode == DownloadMode.FORCE_REDOWNLOAD, force_extract=download_mode == DownloadMode.FORCE_REDOWNLOAD, use_etag=False, num_proc=num_proc, token=token, storage_options=self.storage_options, ) # We don't use etag for data files to speed up the process dl_manager = DownloadManager( dataset_name=self.dataset_name, download_config=download_config, data_dir=self.config.data_dir, base_path=base_path, record_checksums=(self._record_infos or verification_mode == VerificationMode.ALL_CHECKS), ) is_local = not is_remote_filesystem(self._fs) if ( isinstance(dl_manager, MockDownloadManager) or not is_local or file_format != "arrow" or max_shard_size is not None ): try_from_hf_gcs = False self.dl_manager = dl_manager # Prevent parallel local disk operations if is_local: # Create parent directory of the output_dir to put the lock file in there Path(self._output_dir).parent.mkdir(parents=True, exist_ok=True) lock_path = self._output_dir + "_builder.lock" # File locking only with local paths; no file locking on GCS or S3 with FileLock(lock_path) if is_local else contextlib.nullcontext(): # Check if the data already exists data_exists = self._fs.exists(posixpath.join(self._output_dir, config.DATASET_INFO_FILENAME)) if data_exists and download_mode == DownloadMode.REUSE_DATASET_IF_EXISTS: logger.info(f"Found cached dataset {self.dataset_name} ({self._output_dir})") # We need to update the info in case some splits were added in the meantime # for example when calling load_dataset from multiple workers. self.info = self._load_info() self.download_post_processing_resources(dl_manager) return logger.info(f"Generating dataset {self.dataset_name} ({self._output_dir})") if is_local: # if cache dir is local, check for available space if not has_sufficient_disk_space( self.info.size_in_bytes or 0, directory=Path(self._output_dir).parent ): raise OSError( f"Not enough disk space. Needed: {size_str(self.info.size_in_bytes or 0)} (download: {size_str(self.info.download_size or 0)}, generated: {size_str(self.info.dataset_size or 0)}, post-processed: {size_str(self.info.post_processing_size or 0)})" ) @contextlib.contextmanager def incomplete_dir(dirname): """Create temporary dir for dirname and rename on exit.""" if not is_local: self._fs.makedirs(dirname, exist_ok=True) yield dirname else: tmp_dir = dirname + ".incomplete" os.makedirs(tmp_dir, exist_ok=True) try: yield tmp_dir if os.path.isdir(dirname): shutil.rmtree(dirname) # LocalFileSystem.mv does copy + rm, it is more efficient to simply rename a local directory shutil.move(tmp_dir, dirname) finally: if os.path.exists(tmp_dir): shutil.rmtree(tmp_dir) # Print is intentional: we want this to always go to stdout so user has # information needed to cancel download/preparation if needed. # This comes right before the progress bar. if self.info.size_in_bytes: logger.info( f"Downloading and preparing dataset {self.dataset_name}/{self.config.name} " f"(download: {size_str(self.info.download_size)}, generated: {size_str(self.info.dataset_size)}, " f"post-processed: {size_str(self.info.post_processing_size)}, " f"total: {size_str(self.info.size_in_bytes)}) to {self._output_dir}..." ) else: _dest = self._fs._strip_protocol(self._output_dir) if is_local else self._output_dir logger.info(f"Downloading and preparing dataset {self.dataset_name}/{self.config.name} to {_dest}...") self._check_manual_download(dl_manager) # Create a tmp dir and rename to self._output_dir on successful exit. with incomplete_dir(self._output_dir) as tmp_output_dir: # Temporarily assign _output_dir to tmp_data_dir to avoid having to forward # it to every sub function. with temporary_assignment(self, "_output_dir", tmp_output_dir): # Try to download the already prepared dataset files downloaded_from_gcs = False if try_from_hf_gcs: try: self._download_prepared_from_hf_gcs(dl_manager.download_config) downloaded_from_gcs = True except (DatasetNotOnHfGcsError, MissingFilesOnHfGcsError): logger.info("Dataset not on Hf google storage. Downloading and preparing it from source") except ConnectionError: logger.warning("HF google storage unreachable. Downloading and preparing it from source") if not downloaded_from_gcs: prepare_split_kwargs = {"file_format": file_format} if max_shard_size is not None: prepare_split_kwargs["max_shard_size"] = max_shard_size if num_proc is not None: prepare_split_kwargs["num_proc"] = num_proc self._download_and_prepare( dl_manager=dl_manager, verification_mode=verification_mode, **prepare_split_kwargs, **download_and_prepare_kwargs, ) # Sync info self.info.dataset_size = sum(split.num_bytes for split in self.info.splits.values()) self.info.download_checksums = dl_manager.get_recorded_sizes_checksums() self.info.size_in_bytes = self.info.dataset_size + self.info.download_size # Save info self._save_info() # Download post processing resources self.download_post_processing_resources(dl_manager) logger.info( f"Dataset {self.dataset_name} downloaded and prepared to {self._output_dir}. " f"Subsequent calls will reuse this data." ) def _check_manual_download(self, dl_manager): if self.manual_download_instructions is not None and dl_manager.manual_dir is None: raise ManualDownloadError( textwrap.dedent( f"""\ The dataset {self.dataset_name} with config {self.config.name} requires manual data. Please follow the manual download instructions: {self.manual_download_instructions} Manual data can be loaded with: datasets.load_dataset("{self.dataset_name}", data_dir="<path/to/manual/data>")""" ) ) def _download_prepared_from_hf_gcs(self, download_config: DownloadConfig): relative_data_dir = self._relative_data_dir(with_version=True, with_hash=False) reader = ArrowReader(self._output_dir, self.info) # use reader instructions to download the right files reader.download_from_hf_gcs(download_config, relative_data_dir) downloaded_info = DatasetInfo.from_directory(self._output_dir) self.info.update(downloaded_info) # download post processing resources remote_cache_dir = HF_GCP_BASE_URL + "/" + relative_data_dir.replace(os.sep, "/") for split in self.info.splits: for resource_file_name in self._post_processing_resources(split).values(): if os.sep in resource_file_name: raise ValueError(f"Resources shouldn't be in a sub-directory: {resource_file_name}") try: resource_path = cached_path(remote_cache_dir + "/" + resource_file_name) shutil.move(resource_path, os.path.join(self._output_dir, resource_file_name)) except ConnectionError: logger.info(f"Couldn't download resourse file {resource_file_name} from Hf google storage.") logger.info("Dataset downloaded from Hf google storage.") def _download_and_prepare(self, dl_manager, verification_mode, **prepare_split_kwargs): """Downloads and prepares dataset for reading. This is the internal implementation to overwrite called when user calls `download_and_prepare`. It should download all required data and generate the pre-processed datasets files. Args: dl_manager ([`DownloadManager`]): `DownloadManager` used to download and cache data. verification_mode ([`VerificationMode`]): if `ALL_CHECKS`, perform all the verifications including checksums. if `BASIC_CHECKS`, do not perform checksums, only perform split tests. if `NO_CHECKS`, do not perform any verification. prepare_split_kwargs: Additional options, such as `file_format`, `max_shard_size` """ # Generating data for all splits split_dict = SplitDict(dataset_name=self.dataset_name) split_generators_kwargs = self._make_split_generators_kwargs(prepare_split_kwargs) split_generators = self._split_generators(dl_manager, **split_generators_kwargs) # Checksums verification if verification_mode == VerificationMode.ALL_CHECKS and dl_manager.record_checksums: verify_checksums( self.info.download_checksums, dl_manager.get_recorded_sizes_checksums(), "dataset source files" ) # Build splits for split_generator in split_generators: if str(split_generator.split_info.name).lower() == "all": raise ValueError( "`all` is a special split keyword corresponding to the " "union of all splits, so cannot be used as key in " "._split_generator()." ) logger.info(f"Generating {split_generator.split_info.name} split") split_dict.add(split_generator.split_info) try: # Prepare split will record examples associated to the split self._prepare_split(split_generator, **prepare_split_kwargs) except OSError as e: raise OSError( "Cannot find data file. " + (self.manual_download_instructions or "") + "\nOriginal error:\n" + str(e) ) from None # If check_duplicates is set to True , then except DuplicatedKeysError except DuplicatedKeysError as e: raise DuplicatedKeysError( e.key, e.duplicate_key_indices, fix_msg=f"To avoid duplicate keys, please fix the dataset script {self.name}.py", ) from None dl_manager.manage_extracted_files() if verification_mode == VerificationMode.BASIC_CHECKS or verification_mode == VerificationMode.ALL_CHECKS: verify_splits(self.info.splits, split_dict) # Update the info object with the splits. self.info.splits = split_dict self.info.download_size = dl_manager.downloaded_size def download_post_processing_resources(self, dl_manager): for split in self.info.splits or []: for resource_name, resource_file_name in self._post_processing_resources(split).items(): if not not is_remote_filesystem(self._fs): raise NotImplementedError(f"Post processing is not supported on filesystem {self._fs}") if os.sep in resource_file_name: raise ValueError(f"Resources shouldn't be in a sub-directory: {resource_file_name}") resource_path = os.path.join(self._output_dir, resource_file_name) if not os.path.exists(resource_path): downloaded_resource_path = self._download_post_processing_resources( split, resource_name, dl_manager ) if downloaded_resource_path: logger.info(f"Downloaded post-processing resource {resource_name} as {resource_file_name}") shutil.move(downloaded_resource_path, resource_path) def _load_info(self) -> DatasetInfo: return DatasetInfo.from_directory(self._output_dir, storage_options=self._fs.storage_options) def _save_info(self): file_lock = ( FileLock(self._output_dir + "_info.lock") if not is_remote_filesystem(self._fs) else contextlib.nullcontext() ) with file_lock: self.info.write_to_directory(self._output_dir, storage_options=self._fs.storage_options) def _save_infos(self): file_lock = ( FileLock(self._output_dir + "_infos.lock") if not is_remote_filesystem(self._fs) else contextlib.nullcontext() ) with file_lock: DatasetInfosDict(**{self.config.name: self.info}).write_to_directory(self.get_imported_module_dir()) def _make_split_generators_kwargs(self, prepare_split_kwargs): """Get kwargs for `self._split_generators()` from `prepare_split_kwargs`.""" del prepare_split_kwargs return {} def as_dataset( self, split: Optional[Split] = None, run_post_process=True, verification_mode: Optional[Union[VerificationMode, str]] = None, ignore_verifications="deprecated", in_memory=False, ) -> Union[Dataset, DatasetDict]: """Return a Dataset for the specified split. Args: 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`] or `str`, defaults to `BASIC_CHECKS`): Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/...). <Added version="2.9.1"/> ignore_verifications (`bool`, defaults to `False`): Whether to ignore the verifications of the downloaded/processed dataset information (checksums/size/splits/...). <Deprecated version="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. </Deprecated> in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. Returns: datasets.Dataset Example: ```py >>> 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 }) ``` """ if ignore_verifications != "deprecated": verification_mode = verification_mode.NO_CHECKS if ignore_verifications else VerificationMode.ALL_CHECKS warnings.warn( "'ignore_verifications' was deprecated in favor of 'verification' in version 2.9.1 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'verification_mode={verification_mode.value}' instead.", FutureWarning, ) if self._file_format is not None and self._file_format != "arrow": raise FileFormatError('Loading a dataset not written in the "arrow" format is not supported.') if is_remote_filesystem(self._fs): raise NotImplementedError(f"Loading a dataset cached in a {type(self._fs).__name__} is not supported.") if not os.path.exists(self._output_dir): raise FileNotFoundError( f"Dataset {self.dataset_name}: could not find data in {self._output_dir}. Please make sure to call " "builder.download_and_prepare(), or use " "datasets.load_dataset() before trying to access the Dataset object." ) logger.debug(f'Constructing Dataset for split {split or ", ".join(self.info.splits)}, from {self._output_dir}') # By default, return all splits if split is None: split = {s: s for s in self.info.splits} verification_mode = VerificationMode(verification_mode or VerificationMode.BASIC_CHECKS) # Create a dataset for each of the given splits datasets = map_nested( partial( self._build_single_dataset, run_post_process=run_post_process, verification_mode=verification_mode, in_memory=in_memory, ), split, map_tuple=True, disable_tqdm=True, ) if isinstance(datasets, dict): datasets = DatasetDict(datasets) return datasets def _build_single_dataset( self, split: Union[str, ReadInstruction, Split], run_post_process: bool, verification_mode: VerificationMode, in_memory: bool = False, ): """as_dataset for a single split.""" if not isinstance(split, ReadInstruction): split = str(split) if split == "all": split = "+".join(self.info.splits.keys()) split = Split(split) # Build base dataset ds = self._as_dataset( split=split, in_memory=in_memory, ) if run_post_process: for resource_file_name in self._post_processing_resources(split).values(): if os.sep in resource_file_name: raise ValueError(f"Resources shouldn't be in a sub-directory: {resource_file_name}") resources_paths = { resource_name: os.path.join(self._output_dir, resource_file_name) for resource_name, resource_file_name in self._post_processing_resources(split).items() } post_processed = self._post_process(ds, resources_paths) if post_processed is not None: ds = post_processed recorded_checksums = {} record_checksums = False for resource_name, resource_path in resources_paths.items(): size_checksum = get_size_checksum_dict(resource_path) recorded_checksums[resource_name] = size_checksum if verification_mode == VerificationMode.ALL_CHECKS and record_checksums: if self.info.post_processed is None or self.info.post_processed.resources_checksums is None: expected_checksums = None else: expected_checksums = self.info.post_processed.resources_checksums.get(split) verify_checksums(expected_checksums, recorded_checksums, "post processing resources") if self.info.post_processed is None: self.info.post_processed = PostProcessedInfo() if self.info.post_processed.resources_checksums is None: self.info.post_processed.resources_checksums = {} self.info.post_processed.resources_checksums[str(split)] = recorded_checksums self.info.post_processing_size = sum( checksums_dict["num_bytes"] for split_checksums_dicts in self.info.post_processed.resources_checksums.values() for checksums_dict in split_checksums_dicts.values() ) if self.info.dataset_size is not None and self.info.download_size is not None: self.info.size_in_bytes = ( self.info.dataset_size + self.info.download_size + self.info.post_processing_size ) self._save_info() ds._info.post_processed = self.info.post_processed ds._info.post_processing_size = self.info.post_processing_size ds._info.size_in_bytes = self.info.size_in_bytes if self.info.post_processed.features is not None: if self.info.post_processed.features.type != ds.features.type: raise ValueError( f"Post-processed features info don't match the dataset:\nGot\n{self.info.post_processed.features}\nbut expected something like\n{ds.features}" ) else: ds.info.features = self.info.post_processed.features return ds def _as_dataset(self, split: Union[ReadInstruction, Split] = Split.TRAIN, in_memory: bool = False) -> Dataset: """Constructs a `Dataset`. This is the internal implementation to overwrite called when user calls `as_dataset`. It should read the pre-processed datasets files and generate the `Dataset` object. Args: split (`datasets.Split`): which subset of the data to read. in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. Returns: `Dataset` """ cache_dir = self._fs._strip_protocol(self._output_dir) dataset_name = self.dataset_name if self._check_legacy_cache(): dataset_name = self.name dataset_kwargs = ArrowReader(cache_dir, self.info).read( name=dataset_name, instructions=split, split_infos=self.info.splits.values(), in_memory=in_memory, ) fingerprint = self._get_dataset_fingerprint(split) return Dataset(fingerprint=fingerprint, **dataset_kwargs) def _get_dataset_fingerprint(self, split: Union[ReadInstruction, Split]) -> str: """The dataset fingerprint is the hash of the relative directory dataset_name/config_name/version/hash, as well as the split specs.""" hasher = Hasher() hasher.update(Path(self._relative_data_dir()).as_posix()) hasher.update(str(split)) # for example: train, train+test, train[:10%], test[:33%](pct1_dropremainder) fingerprint = hasher.hexdigest() return fingerprint def as_streaming_dataset( self, split: Optional[str] = None, base_path: Optional[str] = None, ) -> Union[Dict[str, IterableDataset], IterableDataset]: if is_remote_filesystem(self._fs): raise NotImplementedError( f"Loading a streaming dataset cached in a {type(self._fs).__name__} is not supported yet." ) dl_manager = StreamingDownloadManager( base_path=base_path or self.base_path, download_config=DownloadConfig(token=self.token, storage_options=self.storage_options), dataset_name=self.dataset_name, data_dir=self.config.data_dir, ) self._check_manual_download(dl_manager) splits_generators = {sg.name: sg for sg in self._split_generators(dl_manager)} # By default, return all splits if split is None: splits_generator = splits_generators elif split in splits_generators: splits_generator = splits_generators[split] else: raise ValueError(f"Bad split: {split}. Available splits: {list(splits_generators)}") # Create a dataset for each of the given splits datasets = map_nested( self._as_streaming_dataset_single, splits_generator, map_tuple=True, ) if isinstance(datasets, dict): datasets = IterableDatasetDict(datasets) return datasets def _as_streaming_dataset_single( self, splits_generator, ) -> IterableDataset: ex_iterable = self._get_examples_iterable_for_split(splits_generator) # add auth to be able to access and decode audio/image files from private repositories. token_per_repo_id = {self.repo_id: self.token} if self.repo_id else {} return IterableDataset( ex_iterable, info=self.info, split=splits_generator.name, token_per_repo_id=token_per_repo_id ) def _post_process(self, dataset: Dataset, resources_paths: Mapping[str, str]) -> Optional[Dataset]: """Run dataset transforms or add indexes""" return None def _post_processing_resources(self, split: str) -> Dict[str, str]: """Mapping resource_name -> resource_file_name""" return {} def _download_post_processing_resources( self, split: str, resource_name: str, dl_manager: DownloadManager ) -> Optional[str]: """Download the resource using the download manager and return the downloaded path.""" return None @abc.abstractmethod def _split_generators(self, dl_manager: DownloadManager): """Specify feature dictionary generators and dataset splits. This function returns a list of `SplitGenerator`s defining how to generate data and what splits to use. Example: return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={'file': 'train_data.zip'}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={'file': 'test_data.zip'}, ), ] The above code will first call `_generate_examples(file='train_data.zip')` to write the train data, then `_generate_examples(file='test_data.zip')` to write the test data. Datasets are typically split into different subsets to be used at various stages of training and evaluation. Note that for datasets without a `VALIDATION` split, you can use a fraction of the `TRAIN` data for evaluation as you iterate on your model so as not to overfit to the `TEST` data. For downloads and extractions, use the given `download_manager`. Note that the `DownloadManager` caches downloads, so it is fine to have each generator attempt to download the source data. A good practice is to download all data in this function, and then distribute the relevant parts to each split with the `gen_kwargs` argument Args: dl_manager (`DownloadManager`): Download manager to download the data Returns: `list<SplitGenerator>`. """ raise NotImplementedError() @abc.abstractmethod def _prepare_split( self, split_generator: SplitGenerator, file_format: str = "arrow", max_shard_size: Optional[Union[str, int]] = None, num_proc: Optional[int] = None, **kwargs, ): """Generate the examples and record them on disk. Args: split_generator (`SplitGenerator`): Split generator to process file_format (`str`, *optional*): format of the data files in which the dataset will be written. Supported formats: "arrow", "parquet". Default to "arrow" format. 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. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default. <Added version="2.7.0"/> **kwargs: Additional kwargs forwarded from _download_and_prepare (ex: beam pipeline) """ raise NotImplementedError() def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: """Generate the examples on the fly. Args: split_generator (`SplitGenerator`): Split generator to process """ raise NotImplementedError() class GeneratorBasedBuilder(DatasetBuilder): """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. """ @abc.abstractmethod def _generate_examples(self, **kwargs): """Default function generating examples for each `SplitGenerator`. This function preprocess the examples from the raw data to the preprocessed dataset files. This function is called once for each `SplitGenerator` defined in `_split_generators`. The examples yielded here will be written on disk. Args: **kwargs (additional keyword arguments): Arguments forwarded from the SplitGenerator.gen_kwargs Yields: key: `str` or `int`, a unique deterministic example identification key. * Unique: An error will be raised if two examples are yield with the same key. * Deterministic: When generating the dataset twice, the same example should have the same key. Good keys can be the image id, or line number if examples are extracted from a text file. The key will be hashed and sorted to shuffle examples deterministically, such as generating the dataset multiple times keep examples in the same order. example: `dict<str feature_name, feature_value>`, a feature dictionary ready to be encoded and written to disk. The example will be encoded with `self.info.features.encode_example({...})`. """ raise NotImplementedError() def _prepare_split( self, split_generator: SplitGenerator, check_duplicate_keys: bool, file_format="arrow", num_proc: Optional[int] = None, max_shard_size: Optional[Union[int, str]] = None, ): max_shard_size = convert_file_size_to_int(max_shard_size or config.MAX_SHARD_SIZE) if self.info.splits is not None: split_info = self.info.splits[split_generator.name] else: split_info = split_generator.split_info SUFFIX = "-JJJJJ-SSSSS-of-NNNNN" fname = f"{self.dataset_name}-{split_generator.name}{SUFFIX}.{file_format}" fpath = posixpath.join(self._output_dir, fname) if num_proc and num_proc > 1: num_input_shards = _number_of_shards_in_gen_kwargs(split_generator.gen_kwargs) if num_input_shards <= 1: logger.warning( f"Setting num_proc from {num_proc} back to 1 for the {split_info.name} split to disable multiprocessing as it only contains one shard." ) num_proc = 1 elif num_input_shards < num_proc: logger.warning( f"Setting num_proc from {num_proc} to {num_input_shards} for the {split_info.name} split as it only contains {num_input_shards} shards." ) num_proc = num_input_shards pbar = hf_tqdm( unit=" examples", total=split_info.num_examples, desc=f"Generating {split_info.name} split", ) _prepare_split_args = { "fpath": fpath, "file_format": file_format, "max_shard_size": max_shard_size, "split_info": split_info, "check_duplicate_keys": check_duplicate_keys, } if num_proc is None or num_proc == 1: result = None gen_kwargs = split_generator.gen_kwargs job_id = 0 with pbar: for job_id, done, content in self._prepare_split_single( gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args ): if done: result = content else: pbar.update(content) # wrapping everything into lists for consistency with the multiprocessed code path assert result is not None, "Failed to retrieve results from prepare_split" examples_per_job, bytes_per_job, features_per_job, shards_per_job, shard_lengths_per_job = [ [item] for item in result ] else: kwargs_per_job = [ {"gen_kwargs": gen_kwargs, "job_id": job_id, **_prepare_split_args} for job_id, gen_kwargs in enumerate( _split_gen_kwargs(split_generator.gen_kwargs, max_num_jobs=num_proc) ) ] num_jobs = len(kwargs_per_job) examples_per_job = [None] * num_jobs bytes_per_job = [None] * num_jobs features_per_job = [None] * num_jobs shards_per_job = [None] * num_jobs shard_lengths_per_job = [None] * num_jobs with Pool(num_proc) as pool: with pbar: for job_id, done, content in iflatmap_unordered( pool, self._prepare_split_single, kwargs_iterable=kwargs_per_job ): if done: # the content is the result of the job ( examples_per_job[job_id], bytes_per_job[job_id], features_per_job[job_id], shards_per_job[job_id], shard_lengths_per_job[job_id], ) = content else: # the content is the number of examples progress update pbar.update(content) assert ( None not in examples_per_job ), f"Failed to retrieve results from prepare_split: result list {examples_per_job} still contains None - at least one worker failed to return its results" total_shards = sum(shards_per_job) total_num_examples = sum(examples_per_job) total_num_bytes = sum(bytes_per_job) features = features_per_job[0] split_generator.split_info.num_examples = total_num_examples split_generator.split_info.num_bytes = total_num_bytes # should rename everything at the end logger.debug(f"Renaming {total_shards} shards.") if total_shards > 1: # use the -SSSSS-of-NNNNN pattern def _rename_shard(shard_and_job: Tuple[int]): shard_id, job_id = shard_and_job global_shard_id = sum(shards_per_job[:job_id]) + shard_id self._rename( fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), fpath.replace("JJJJJ-SSSSS", f"{global_shard_id:05d}").replace("NNNNN", f"{total_shards:05d}"), ) shards_and_jobs = [ (shard_id, job_id) for job_id, num_shards in enumerate(shards_per_job) for shard_id in range(num_shards) ] thread_map(_rename_shard, shards_and_jobs, disable=True, max_workers=64) split_generator.split_info.shard_lengths = [ shard_length for shard_lengths in shard_lengths_per_job for shard_length in shard_lengths ] else: # don't use any pattern shard_id, job_id = 0, 0 self._rename( fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), fpath.replace(SUFFIX, ""), ) if self.info.features is None: self.info.features = features def _prepare_split_single( self, gen_kwargs: dict, fpath: str, file_format: str, max_shard_size: int, split_info: SplitInfo, check_duplicate_keys: bool, job_id: int, ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: generator = self._generate_examples(**gen_kwargs) writer_class = ParquetWriter if file_format == "parquet" else ArrowWriter embed_local_files = file_format == "parquet" shard_lengths = [] total_num_examples, total_num_bytes = 0, 0 shard_id = 0 num_examples_progress_update = 0 try: writer = writer_class( features=self.info.features, path=fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), writer_batch_size=self._writer_batch_size, hash_salt=split_info.name, check_duplicates=check_duplicate_keys, storage_options=self._fs.storage_options, embed_local_files=embed_local_files, ) try: _time = time.time() for key, record in generator: if max_shard_size is not None and writer._num_bytes > max_shard_size: num_examples, num_bytes = writer.finalize() writer.close() shard_lengths.append(num_examples) total_num_examples += num_examples total_num_bytes += num_bytes shard_id += 1 writer = writer_class( features=writer._features, path=fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), writer_batch_size=self._writer_batch_size, hash_salt=split_info.name, check_duplicates=check_duplicate_keys, storage_options=self._fs.storage_options, embed_local_files=embed_local_files, ) example = self.info.features.encode_example(record) if self.info.features is not None else record writer.write(example, key) num_examples_progress_update += 1 if time.time() > _time + config.PBAR_REFRESH_TIME_INTERVAL: _time = time.time() yield job_id, False, num_examples_progress_update num_examples_progress_update = 0 finally: yield job_id, False, num_examples_progress_update num_shards = shard_id + 1 num_examples, num_bytes = writer.finalize() writer.close() shard_lengths.append(num_examples) total_num_examples += num_examples total_num_bytes += num_bytes except Exception as e: # Ignore the writer's error for no examples written to the file if this error was caused by the error in _generate_examples before the first example was yielded if isinstance(e, SchemaInferenceError) and e.__context__ is not None: e = e.__context__ raise DatasetGenerationError("An error occurred while generating the dataset") from e yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths) def _download_and_prepare(self, dl_manager, verification_mode, **prepare_splits_kwargs): super()._download_and_prepare( dl_manager, verification_mode, check_duplicate_keys=verification_mode == VerificationMode.BASIC_CHECKS or verification_mode == VerificationMode.ALL_CHECKS, **prepare_splits_kwargs, ) def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: return ExamplesIterable(self._generate_examples, split_generator.gen_kwargs) class ArrowBasedBuilder(DatasetBuilder): """Base class for datasets with data generation based on Arrow loading functions (CSV/JSON/Parquet).""" @abc.abstractmethod def _generate_tables(self, **kwargs): """Default function generating examples for each `SplitGenerator`. This function preprocess the examples from the raw data to the preprocessed dataset files. This function is called once for each `SplitGenerator` defined in `_split_generators`. The examples yielded here will be written on disk. Args: **kwargs (additional keyword arguments): Arguments forwarded from the SplitGenerator.gen_kwargs Yields: key: `str` or `int`, a unique deterministic example identification key. * Unique: An error will be raised if two examples are yield with the same key. * Deterministic: When generating the dataset twice, the same example should have the same key. Good keys can be the image id, or line number if examples are extracted from a text file. The key will be hashed and sorted to shuffle examples deterministically, such as generating the dataset multiple times keep examples in the same order. example: `pyarrow.Table`, a feature table ready to be encoded and written to disk. """ raise NotImplementedError() def _prepare_split( self, split_generator: SplitGenerator, file_format: str = "arrow", num_proc: Optional[int] = None, max_shard_size: Optional[Union[str, int]] = None, ): max_shard_size = convert_file_size_to_int(max_shard_size or config.MAX_SHARD_SIZE) try: split_info = self.info.splits[split_generator.name] except Exception: split_info = split_generator.split_info SUFFIX = "-JJJJJ-SSSSS-of-NNNNN" fname = f"{self.dataset_name}-{split_generator.name}{SUFFIX}.{file_format}" fpath = posixpath.join(self._output_dir, fname) if num_proc and num_proc > 1: num_input_shards = _number_of_shards_in_gen_kwargs(split_generator.gen_kwargs) if num_input_shards <= 1: logger.warning( f"Setting num_proc from {num_proc} back to 1 for the {split_info.name} split to disable multiprocessing as it only contains one shard." ) num_proc = 1 elif num_input_shards < num_proc: logger.warning( f"Setting num_proc from {num_proc} to {num_input_shards} for the {split_info.name} split as it only contains {num_input_shards} shards." ) num_proc = num_input_shards pbar = hf_tqdm( unit=" examples", total=split_info.num_examples, desc=f"Generating {split_info.name} split", ) _prepare_split_args = { "fpath": fpath, "file_format": file_format, "max_shard_size": max_shard_size, } if num_proc is None or num_proc == 1: result = None gen_kwargs = split_generator.gen_kwargs job_id = 0 with pbar: for job_id, done, content in self._prepare_split_single( gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args ): if done: result = content else: pbar.update(content) # wrapping everything into lists for consistency with the multiprocessed code path assert result is not None, "Failed to retrieve results from prepare_split" examples_per_job, bytes_per_job, features_per_job, shards_per_job, shard_lengths_per_job = [ [item] for item in result ] else: kwargs_per_job = [ {"gen_kwargs": gen_kwargs, "job_id": job_id, **_prepare_split_args} for job_id, gen_kwargs in enumerate( _split_gen_kwargs(split_generator.gen_kwargs, max_num_jobs=num_proc) ) ] num_jobs = len(kwargs_per_job) examples_per_job = [None] * num_jobs bytes_per_job = [None] * num_jobs features_per_job = [None] * num_jobs shards_per_job = [None] * num_jobs shard_lengths_per_job = [None] * num_jobs with Pool(num_proc) as pool: with pbar: for job_id, done, content in iflatmap_unordered( pool, self._prepare_split_single, kwargs_iterable=kwargs_per_job ): if done: # the content is the result of the job ( examples_per_job[job_id], bytes_per_job[job_id], features_per_job[job_id], shards_per_job[job_id], shard_lengths_per_job[job_id], ) = content else: # the content is the number of examples progress update pbar.update(content) assert ( None not in examples_per_job ), f"Failed to retrieve results from prepare_split: result list {examples_per_job} still contains None - at least one worker failed to return its results" total_shards = sum(shards_per_job) total_num_examples = sum(examples_per_job) total_num_bytes = sum(bytes_per_job) features = features_per_job[0] split_generator.split_info.num_examples = total_num_examples split_generator.split_info.num_bytes = total_num_bytes # should rename everything at the end logger.debug(f"Renaming {total_shards} shards.") if total_shards > 1: # use the -SSSSS-of-NNNNN pattern def _rename_shard(shard_id_and_job: Tuple[int]): shard_id, job_id = shard_id_and_job global_shard_id = sum(shards_per_job[:job_id]) + shard_id self._rename( fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), fpath.replace("JJJJJ-SSSSS", f"{global_shard_id:05d}").replace("NNNNN", f"{total_shards:05d}"), ) shard_ids_and_jobs = [ (shard_id, job_id) for job_id, num_shards in enumerate(shards_per_job) for shard_id in range(num_shards) ] thread_map(_rename_shard, shard_ids_and_jobs, disable=True, max_workers=64) split_generator.split_info.shard_lengths = [ shard_length for shard_lengths in shard_lengths_per_job for shard_length in shard_lengths ] else: # don't use any pattern shard_id, job_id = 0, 0 self._rename( fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), fpath.replace(SUFFIX, ""), ) if self.info.features is None: self.info.features = features def _prepare_split_single( self, gen_kwargs: dict, fpath: str, file_format: str, max_shard_size: int, job_id: int ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: gen_kwargs = {k: tracked_list(v) if isinstance(v, list) else v for k, v in gen_kwargs.items()} generator = self._generate_tables(**gen_kwargs) writer_class = ParquetWriter if file_format == "parquet" else ArrowWriter embed_local_files = file_format == "parquet" shard_lengths = [] total_num_examples, total_num_bytes = 0, 0 shard_id = 0 num_examples_progress_update = 0 try: writer = writer_class( features=self.info.features, path=fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), writer_batch_size=self._writer_batch_size, storage_options=self._fs.storage_options, embed_local_files=embed_local_files, ) try: _time = time.time() for _, table in generator: if max_shard_size is not None and writer._num_bytes > max_shard_size: num_examples, num_bytes = writer.finalize() writer.close() shard_lengths.append(num_examples) total_num_examples += num_examples total_num_bytes += num_bytes shard_id += 1 writer = writer_class( features=writer._features, path=fpath.replace("SSSSS", f"{shard_id:05d}").replace("JJJJJ", f"{job_id:05d}"), writer_batch_size=self._writer_batch_size, storage_options=self._fs.storage_options, embed_local_files=embed_local_files, ) try: writer.write_table(table) except CastError as cast_error: raise DatasetGenerationCastError.from_cast_error( cast_error=cast_error, builder_name=self.info.builder_name, gen_kwargs=gen_kwargs, token=self.token, ) num_examples_progress_update += len(table) if time.time() > _time + config.PBAR_REFRESH_TIME_INTERVAL: _time = time.time() yield job_id, False, num_examples_progress_update num_examples_progress_update = 0 finally: yield job_id, False, num_examples_progress_update num_shards = shard_id + 1 num_examples, num_bytes = writer.finalize() writer.close() shard_lengths.append(num_examples) total_num_examples += num_examples total_num_bytes += num_bytes except Exception as e: # Ignore the writer's error for no examples written to the file if this error was caused by the error in _generate_examples before the first example was yielded if isinstance(e, SchemaInferenceError) and e.__context__ is not None: e = e.__context__ if isinstance(e, DatasetGenerationError): raise raise DatasetGenerationError("An error occurred while generating the dataset") from e yield job_id, True, (total_num_examples, total_num_bytes, writer._features, num_shards, shard_lengths) def _get_examples_iterable_for_split(self, split_generator: SplitGenerator) -> ExamplesIterable: return ArrowExamplesIterable(self._generate_tables, kwargs=split_generator.gen_kwargs) class MissingBeamOptions(ValueError): pass class BeamBasedBuilder(DatasetBuilder): """Beam-based Builder.""" def __init__(self, *args, beam_runner=None, beam_options=None, **kwargs): self._beam_runner = beam_runner self._beam_options = beam_options self._beam_writers = {} # {split: beam_writer} mapping. super().__init__(*args, **kwargs) def _make_split_generators_kwargs(self, prepare_split_kwargs): # Pass `pipeline` into `_split_generators()` from `prepare_split_kwargs` if # it's in the call signature of `_split_generators()`. # This allows for global preprocessing in beam. split_generators_kwargs = {} split_generators_arg_names = inspect.signature(self._split_generators).parameters.keys() if "pipeline" in split_generators_arg_names: split_generators_kwargs["pipeline"] = prepare_split_kwargs["pipeline"] return split_generators_kwargs @abc.abstractmethod def _build_pcollection(self, pipeline, **kwargs): """Build the beam pipeline examples for each `SplitGenerator`. This function extracts examples from the raw data with parallel transforms in a Beam pipeline. It is called once for each `SplitGenerator` defined in `_split_generators`. The examples from the PCollection will be encoded and written to disk. <Tip warning={true}> Warning: When running in a distributed setup, make sure that the data which will be read (download_dir, manual_dir,...) and written (cache_dir) can be accessed by the workers jobs. The data should be located in a shared filesystem, like GCS. </Tip> Args: pipeline ([`utils.beam_utils.BeamPipeline`]): Apache Beam pipeline. **kwargs (additional keyword arguments): Arguments forwarded from the SplitGenerator.gen_kwargs. Returns: `beam.PCollection`: Apache Beam PCollection containing the example to send to `self.info.features.encode_example(...)`. Example: ``` def _build_pcollection(pipeline, extracted_dir=None): return ( pipeline | beam.Create(gfile.io.listdir(extracted_dir)) | beam.Map(_process_file) ) ``` """ raise NotImplementedError() def _download_and_prepare(self, dl_manager, verification_mode, **prepare_splits_kwargs): # Create the Beam pipeline and forward it to `_prepare_split` import apache_beam as beam import datasets.utils.beam_utils as beam_utils beam_runner = self._beam_runner beam_options = self._beam_options if not beam_runner and not beam_options: usage_example = f"load_dataset('{self.name}', '{self.config.name}', beam_runner='DirectRunner')" raise MissingBeamOptions( "Trying to generate a dataset using Apache Beam, yet no Beam Runner " "or PipelineOptions() has been provided in `load_dataset` or in the " "builder arguments. For big datasets it has to run on large-scale data " "processing tools like Dataflow, Spark, etc. More information about " "Apache Beam runners at " "https://beam.apache.org/documentation/runners/capability-matrix/" "\nIf you really want to run it locally because you feel like the " "Dataset is small enough, you can use the local beam runner called " "`DirectRunner` (you may run out of memory). \nExample of usage: " f"\n\t`{usage_example}`" ) if self._writer_batch_size is not None: logger.warning( "`writer_batch_size` is not supported for beam pipelines yet. Using the default chunk size for writing." ) # Beam type checking assumes transforms multiple outputs are of same type, # which is not our case. Plus it doesn't handle correctly all types, so we # are better without it. pipeline_options = {"pipeline_type_check": False} if "num_proc" in prepare_splits_kwargs: num_workers = prepare_splits_kwargs.pop("num_proc") pipeline_options["direct_num_workers"] = num_workers pipeline_options["num_workers"] = num_workers pipeline_options["direct_running_mode"] = "multi_processing" # TODO: Fix ModuleNotFoundError: No module named 'datasets_modules' when running multiprocessed DirectRunner raise NotImplementedError("Using a DirectRunner with `num_proc` for multiprocessing it not supported yet.") beam_options = beam_options or beam.options.pipeline_options.PipelineOptions.from_dictionary(pipeline_options) # Use a single pipeline for all splits pipeline = beam_utils.BeamPipeline( runner=beam_runner, options=beam_options, ) super()._download_and_prepare( dl_manager, verification_mode=VerificationMode.NO_CHECKS, pipeline=pipeline, **prepare_splits_kwargs ) # TODO handle verification_mode in beam datasets # Run pipeline pipeline_results = pipeline.run() pipeline_results.wait_until_finish() metrics = pipeline_results.metrics() # Update `info.splits`. split_dict = self.info.splits for split_name, beam_writer in self._beam_writers.items(): m_filter = beam.metrics.MetricsFilter().with_namespace(namespace=split_name) num_examples, num_bytes = beam_writer.finalize(metrics.query(m_filter)) split_info = split_dict[split_name] split_info.num_examples = num_examples split_info.num_bytes = num_bytes if hasattr(beam_writer, "_shard_lengths") and len(beam_writer._shard_lengths) > 1: # keep the -SSSSS-of-NNNNN pattern split_info.shard_lengths = beam_writer._shard_lengths else: # don't use any pattern file_format = prepare_splits_kwargs.get("file_format", "arrow") src_fname = f"{self.dataset_name}-{split_name}-00000-of-00001.{file_format}" dst_fname = f"{self.dataset_name}-{split_name}.{file_format}" src_fpath = posixpath.join(self._output_dir, src_fname) dst_fpath = posixpath.join(self._output_dir, dst_fname) self._rename(src_fpath, dst_fpath) def _save_info(self): download_config = ( self.dl_manager.download_config if self.dl_manager else DownloadConfig(token=self.token, storage_options=self._fs.storage_options) ) with xopen(f"{self._output_dir}/{config.DATASET_INFO_FILENAME}", "wb", download_config=download_config) as f: self.info._dump_info(f) if self.info.license: with xopen(f"{self._output_dir}/{config.LICENSE_FILENAME}", "wb", download_config=download_config) as f: self.info._dump_license(f) def _prepare_split( self, split_generator, pipeline, file_format="arrow", max_shard_size: Optional[Union[str, int]] = None ): import apache_beam as beam if max_shard_size is not None: raise NotImplementedError( "max_shard_size is not supported for Beam datasets." "Please set it to None to use the default Apache Beam sharding and get the best performance." ) # To write examples in filesystem: split_name = split_generator.split_info.name fname = f"{self.dataset_name}-{split_name}.{file_format}" fpath = posixpath.join(self._output_dir, fname) beam_writer = BeamWriter( features=self.info.features, path=fpath, namespace=split_name, cache_dir=self._output_dir ) self._beam_writers[split_name] = beam_writer encode_example = self.info.features.encode_example # Note: We need to wrap the pipeline in a PTransform to avoid re-using the # same label names for each split @beam.ptransform_fn def _build_pcollection(pipeline): """PTransformation which build a single split.""" # Encode the PCollection pcoll_examples = self._build_pcollection(pipeline, **split_generator.gen_kwargs) pcoll_examples |= "Encode" >> beam.Map(lambda key_ex: (key_ex[0], encode_example(key_ex[1]))) return beam_writer.write_from_pcollection(pcoll_examples) # Add the PCollection to the pipeline _ = pipeline | split_name >> _build_pcollection() # pylint: disable=no-value-for-parameter max_bytes_per_shard def as_streaming_dataset( self, split: Optional[str] = None, ) -> Union[Dict[str, IterableDataset], IterableDataset]: self._request_info_from_hf_gcs() datasets = { split.name: IterableDataset(self._get_examples_iterable_for_split(split), info=self.info, split=split.name) for split in self.info.splits.values() } if split: try: datasets = datasets[split] except KeyError: raise ValueError(f"Bad split: {split}. Available splits: {list(datasets)}") if isinstance(datasets, dict): datasets = IterableDatasetDict(datasets) return datasets def _get_examples_iterable_for_split(self, split: SplitInfo) -> ExamplesIterable: return ExamplesIterable(self._generate_examples_from_hf_gcs, {"split": split}) def _generate_examples_from_hf_gcs(self, split: SplitInfo): if split.shard_lengths: num_shards = len(split.shard_lengths) remote_prepared_urls = [ f"{self._remote_cache_dir_from_hf_gcs}/{self.name}-{split.name}-{shard_id:05d}-of-{num_shards:05d}.arrow" for shard_id in range(num_shards) ] else: remote_prepared_urls = [f"{self._remote_cache_dir_from_hf_gcs}/{self.name}-{split.name}.arrow"] key = 0 download_config = ( self.dl_manager.download_config if self.dl_manager else DownloadConfig(token=self.token, storage_options=self._fs.storage_options) ) for remote_prepared_url in remote_prepared_urls: with xopen(remote_prepared_url, "rb", download_config=download_config) as f: with pa.ipc.open_stream(f) as reader: for record_batch in reader: for record in record_batch.to_pylist(): yield key, record key += 1 def _request_info_from_hf_gcs(self): from .download.streaming_download_manager import xopen remote_dataset_info = f"{self._remote_cache_dir_from_hf_gcs}/{config.DATASET_INFO_FILENAME}" try: download_config = download_config = ( self.dl_manager.download_config if self.dl_manager else DownloadConfig(token=self.token, storage_options=self._fs.storage_options) ) with xopen(remote_dataset_info, download_config=download_config) as f: import json _info = json.load(f) except FileNotFoundError as err: raise DatasetNotOnHfGcsError(err) from None self.info.update(DatasetInfo.from_dict(_info)) @property def _remote_cache_dir_from_hf_gcs(self): relative_data_dir = self._relative_data_dir(with_hash=False) return HF_GCP_BASE_URL + "/" + Path(relative_data_dir).as_posix()
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/config.py
import importlib import importlib.metadata import logging import os import platform from pathlib import Path from typing import Optional from packaging import version logger = logging.getLogger(__name__.split(".", 1)[0]) # to avoid circular import from .utils.logging # Datasets S3_DATASETS_BUCKET_PREFIX = "https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets" CLOUDFRONT_DATASETS_DISTRIB_PREFIX = "https://cdn-datasets.huggingface.co/datasets/datasets" REPO_DATASETS_URL = "https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}" # Metrics S3_METRICS_BUCKET_PREFIX = "https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics" CLOUDFRONT_METRICS_DISTRIB_PREFIX = "https://cdn-datasets.huggingface.co/datasets/metric" REPO_METRICS_URL = "https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}" # Hub HF_ENDPOINT = os.environ.get("HF_ENDPOINT", "https://huggingface.co") HUB_DATASETS_URL = HF_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}" HUB_DATASETS_HFFS_URL = "hf://datasets/{repo_id}@{revision}/{path}" HUB_DEFAULT_VERSION = "main" PY_VERSION = version.parse(platform.python_version()) # General environment variables accepted values for booleans ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"} ENV_VARS_FALSE_VALUES = {"0", "OFF", "NO", "FALSE"} ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"}) ENV_VARS_FALSE_AND_AUTO_VALUES = ENV_VARS_FALSE_VALUES.union({"AUTO"}) # Imports DILL_VERSION = version.parse(importlib.metadata.version("dill")) FSSPEC_VERSION = version.parse(importlib.metadata.version("fsspec")) PANDAS_VERSION = version.parse(importlib.metadata.version("pandas")) PYARROW_VERSION = version.parse(importlib.metadata.version("pyarrow")) HF_HUB_VERSION = version.parse(importlib.metadata.version("huggingface_hub")) USE_TF = os.environ.get("USE_TF", "AUTO").upper() USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper() USE_JAX = os.environ.get("USE_JAX", "AUTO").upper() TORCH_VERSION = "N/A" TORCH_AVAILABLE = False if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES: TORCH_AVAILABLE = importlib.util.find_spec("torch") is not None if TORCH_AVAILABLE: try: TORCH_VERSION = version.parse(importlib.metadata.version("torch")) logger.info(f"PyTorch version {TORCH_VERSION} available.") except importlib.metadata.PackageNotFoundError: pass else: logger.info("Disabling PyTorch because USE_TF is set") TF_VERSION = "N/A" TF_AVAILABLE = False if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES: TF_AVAILABLE = importlib.util.find_spec("tensorflow") is not None if TF_AVAILABLE: # For the metadata, we have to look for both tensorflow and tensorflow-cpu for package in [ "tensorflow", "tensorflow-cpu", "tensorflow-gpu", "tf-nightly", "tf-nightly-cpu", "tf-nightly-gpu", "intel-tensorflow", "tensorflow-rocm", "tensorflow-macos", ]: try: TF_VERSION = version.parse(importlib.metadata.version(package)) except importlib.metadata.PackageNotFoundError: continue else: break else: TF_AVAILABLE = False if TF_AVAILABLE: if TF_VERSION.major < 2: logger.info(f"TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.") TF_AVAILABLE = False else: logger.info(f"TensorFlow version {TF_VERSION} available.") else: logger.info("Disabling Tensorflow because USE_TORCH is set") JAX_VERSION = "N/A" JAX_AVAILABLE = False if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES: JAX_AVAILABLE = importlib.util.find_spec("jax") is not None and importlib.util.find_spec("jaxlib") is not None if JAX_AVAILABLE: try: JAX_VERSION = version.parse(importlib.metadata.version("jax")) logger.info(f"JAX version {JAX_VERSION} available.") except importlib.metadata.PackageNotFoundError: pass else: logger.info("Disabling JAX because USE_JAX is set to False") USE_BEAM = os.environ.get("USE_BEAM", "AUTO").upper() BEAM_VERSION = "N/A" BEAM_AVAILABLE = False if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES: try: BEAM_VERSION = version.parse(importlib.metadata.version("apache_beam")) BEAM_AVAILABLE = True logger.info(f"Apache Beam version {BEAM_VERSION} available.") except importlib.metadata.PackageNotFoundError: pass else: logger.info("Disabling Apache Beam because USE_BEAM is set to False") # Optional tools for data loading SQLALCHEMY_AVAILABLE = importlib.util.find_spec("sqlalchemy") is not None # Optional tools for feature decoding PIL_AVAILABLE = importlib.util.find_spec("PIL") is not None IS_OPUS_SUPPORTED = importlib.util.find_spec("soundfile") is not None and version.parse( importlib.import_module("soundfile").__libsndfile_version__ ) >= version.parse("1.0.31") IS_MP3_SUPPORTED = importlib.util.find_spec("soundfile") is not None and version.parse( importlib.import_module("soundfile").__libsndfile_version__ ) >= version.parse("1.1.0") # Optional compression tools RARFILE_AVAILABLE = importlib.util.find_spec("rarfile") is not None ZSTANDARD_AVAILABLE = importlib.util.find_spec("zstandard") is not None LZ4_AVAILABLE = importlib.util.find_spec("lz4") is not None PY7ZR_AVAILABLE = importlib.util.find_spec("py7zr") is not None # Cache location DEFAULT_XDG_CACHE_HOME = "~/.cache" XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME) DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface") HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME)) DEFAULT_HF_DATASETS_CACHE = os.path.join(HF_CACHE_HOME, "datasets") HF_DATASETS_CACHE = Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE)) DEFAULT_HF_METRICS_CACHE = os.path.join(HF_CACHE_HOME, "metrics") HF_METRICS_CACHE = Path(os.getenv("HF_METRICS_CACHE", DEFAULT_HF_METRICS_CACHE)) DEFAULT_HF_MODULES_CACHE = os.path.join(HF_CACHE_HOME, "modules") HF_MODULES_CACHE = Path(os.getenv("HF_MODULES_CACHE", DEFAULT_HF_MODULES_CACHE)) DOWNLOADED_DATASETS_DIR = "downloads" DEFAULT_DOWNLOADED_DATASETS_PATH = os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR) DOWNLOADED_DATASETS_PATH = Path(os.getenv("HF_DATASETS_DOWNLOADED_DATASETS_PATH", DEFAULT_DOWNLOADED_DATASETS_PATH)) EXTRACTED_DATASETS_DIR = "extracted" DEFAULT_EXTRACTED_DATASETS_PATH = os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR) EXTRACTED_DATASETS_PATH = Path(os.getenv("HF_DATASETS_EXTRACTED_DATASETS_PATH", DEFAULT_EXTRACTED_DATASETS_PATH)) # Download count for the website HF_UPDATE_DOWNLOAD_COUNTS = ( os.environ.get("HF_UPDATE_DOWNLOAD_COUNTS", "AUTO").upper() in ENV_VARS_TRUE_AND_AUTO_VALUES ) # Remote dataset scripts support __HF_DATASETS_TRUST_REMOTE_CODE = os.environ.get("HF_DATASETS_TRUST_REMOTE_CODE", "1") HF_DATASETS_TRUST_REMOTE_CODE: Optional[bool] = ( True if __HF_DATASETS_TRUST_REMOTE_CODE.upper() in ENV_VARS_TRUE_VALUES else False if __HF_DATASETS_TRUST_REMOTE_CODE.upper() in ENV_VARS_FALSE_VALUES else None ) TIME_OUT_REMOTE_CODE = 15 # Datasets-server USE_PARQUET_EXPORT = True # Batch size constants. For more info, see: # https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations) DEFAULT_MAX_BATCH_SIZE = 1000 # Size of the preloaded record batch in `Dataset.__iter__` ARROW_READER_BATCH_SIZE_IN_DATASET_ITER = 10 # Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare) MAX_SHARD_SIZE = "500MB" # Parquet configuration PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS = 100 PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS = 100 PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS = 100 # Offline mode HF_DATASETS_OFFLINE = os.environ.get("HF_DATASETS_OFFLINE", "AUTO").upper() in ENV_VARS_TRUE_VALUES # Here, `True` will disable progress bars globally without possibility of enabling it # programmatically. `False` will enable them without possibility of disabling them. # If environment variable is not set (None), then the user is free to enable/disable # them programmatically. # TL;DR: env variable has priority over code __HF_DATASETS_DISABLE_PROGRESS_BARS = os.environ.get("HF_DATASETS_DISABLE_PROGRESS_BARS") HF_DATASETS_DISABLE_PROGRESS_BARS: Optional[bool] = ( __HF_DATASETS_DISABLE_PROGRESS_BARS.upper() in ENV_VARS_TRUE_VALUES if __HF_DATASETS_DISABLE_PROGRESS_BARS is not None else None ) # In-memory DEFAULT_IN_MEMORY_MAX_SIZE = 0 # Disabled IN_MEMORY_MAX_SIZE = float(os.environ.get("HF_DATASETS_IN_MEMORY_MAX_SIZE", DEFAULT_IN_MEMORY_MAX_SIZE)) # File names DATASET_ARROW_FILENAME = "dataset.arrow" DATASET_INDICES_FILENAME = "indices.arrow" DATASET_STATE_JSON_FILENAME = "state.json" DATASET_INFO_FILENAME = "dataset_info.json" DATASETDICT_INFOS_FILENAME = "dataset_infos.json" LICENSE_FILENAME = "LICENSE" METRIC_INFO_FILENAME = "metric_info.json" DATASETDICT_JSON_FILENAME = "dataset_dict.json" METADATA_CONFIGS_FIELD = "configs" REPOCARD_FILENAME = "README.md" REPOYAML_FILENAME = ".huggingface.yaml" MODULE_NAME_FOR_DYNAMIC_MODULES = "datasets_modules" MAX_DATASET_CONFIG_ID_READABLE_LENGTH = 255 # Temporary cache directory prefix TEMP_CACHE_DIR_PREFIX = "hf_datasets-" # Streaming STREAMING_READ_MAX_RETRIES = 20 STREAMING_READ_RETRY_INTERVAL = 5 # Datasets without script DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE = 200 GLOBBED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE = 10 ARCHIVED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE = 200 # Progress bars PBAR_REFRESH_TIME_INTERVAL = 0.05 # 20 progress updates per sec # Maximum number of uploaded files per commit UPLOADS_MAX_NUMBER_PER_COMMIT = 50 # Backward compatibiliy MAX_TABLE_NBYTES_FOR_PICKLING = 4 << 30
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/exceptions.py
# SPDX-License-Identifier: Apache-2.0 # Copyright 2023 The HuggingFace Authors. from typing import Any, Dict, List, Optional, Union from huggingface_hub import HfFileSystem from . import config from .table import CastError from .utils.track import TrackedIterable, tracked_list, tracked_str class DatasetsError(Exception): """Base class for exceptions in this library.""" class DefunctDatasetError(DatasetsError): """The dataset has been defunct.""" class FileNotFoundDatasetsError(DatasetsError, FileNotFoundError): """FileNotFoundError raised by this library.""" class DataFilesNotFoundError(FileNotFoundDatasetsError): """No (supported) data files found.""" class DatasetNotFoundError(FileNotFoundDatasetsError): """Dataset not found. Raised when trying to access: - a missing dataset, or - a private/gated dataset and the user is not authenticated. """ class DatasetBuildError(DatasetsError): pass class ManualDownloadError(DatasetBuildError): pass class FileFormatError(DatasetBuildError): pass class DatasetGenerationError(DatasetBuildError): pass class DatasetGenerationCastError(DatasetGenerationError): @classmethod def from_cast_error( cls, cast_error: CastError, builder_name: str, gen_kwargs: Dict[str, Any], token: Optional[Union[bool, str]], ) -> "DatasetGenerationCastError": explanation_message = ( f"\n\nAll the data files must have the same columns, but at some point {cast_error.details()}" ) formatted_tracked_gen_kwargs: List[str] = [] for gen_kwarg in gen_kwargs.values(): if not isinstance(gen_kwarg, (tracked_str, tracked_list, TrackedIterable)): continue while isinstance(gen_kwarg, (tracked_list, TrackedIterable)) and gen_kwarg.last_item is not None: gen_kwarg = gen_kwarg.last_item if isinstance(gen_kwarg, tracked_str): gen_kwarg = gen_kwarg.get_origin() if isinstance(gen_kwarg, str) and gen_kwarg.startswith("hf://"): resolved_path = HfFileSystem(endpoint=config.HF_ENDPOINT, token=token).resolve_path(gen_kwarg) gen_kwarg = "hf://" + resolved_path.unresolve() if "@" + resolved_path.revision in gen_kwarg: gen_kwarg = ( gen_kwarg.replace("@" + resolved_path.revision, "", 1) + f" (at revision {resolved_path.revision})" ) formatted_tracked_gen_kwargs.append(str(gen_kwarg)) if formatted_tracked_gen_kwargs: explanation_message += f"\n\nThis happened while the {builder_name} dataset builder was generating data using\n\n{', '.join(formatted_tracked_gen_kwargs)}" help_message = "\n\nPlease either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)" return cls("An error occurred while generating the dataset" + explanation_message + help_message)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/naming.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """Utilities for file names.""" import itertools import os import re _uppercase_uppercase_re = re.compile(r"([A-Z]+)([A-Z][a-z])") _lowercase_uppercase_re = re.compile(r"([a-z\d])([A-Z])") _single_underscore_re = re.compile(r"(?<!_)_(?!_)") _multiple_underscores_re = re.compile(r"(_{2,})") _split_re = r"^\w+(\.\w+)*$" INVALID_WINDOWS_CHARACTERS_IN_PATH = r"<>:/\|?*" def camelcase_to_snakecase(name): """Convert camel-case string to snake-case.""" name = _uppercase_uppercase_re.sub(r"\1_\2", name) name = _lowercase_uppercase_re.sub(r"\1_\2", name) return name.lower() def snakecase_to_camelcase(name): """Convert snake-case string to camel-case string.""" name = _single_underscore_re.split(name) name = [_multiple_underscores_re.split(n) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(name) if n != "") def filename_prefix_for_name(name): if os.path.basename(name) != name: raise ValueError(f"Should be a dataset name, not a path: {name}") return camelcase_to_snakecase(name) def filename_prefix_for_split(name, split): if os.path.basename(name) != name: raise ValueError(f"Should be a dataset name, not a path: {name}") if not re.match(_split_re, split): raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'.") return f"{filename_prefix_for_name(name)}-{split}" def filepattern_for_dataset_split(dataset_name, split, data_dir, filetype_suffix=None): prefix = filename_prefix_for_split(dataset_name, split) if filetype_suffix: prefix += f".{filetype_suffix}" filepath = os.path.join(data_dir, prefix) return f"{filepath}*" def filenames_for_dataset_split(path, dataset_name, split, filetype_suffix=None, shard_lengths=None): prefix = filename_prefix_for_split(dataset_name, split) prefix = os.path.join(path, prefix) if shard_lengths: num_shards = len(shard_lengths) filenames = [f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(num_shards)] if filetype_suffix: filenames = [filename + f".{filetype_suffix}" for filename in filenames] return filenames else: filename = prefix if filetype_suffix: filename += f".{filetype_suffix}" return [filename]
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/splits.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """Splits related API.""" import abc import collections import copy import dataclasses import re from dataclasses import dataclass from typing import Dict, List, Optional, Union from .arrow_reader import FileInstructions, make_file_instructions from .naming import _split_re from .utils.py_utils import NonMutableDict, asdict @dataclass class SplitInfo: name: str = dataclasses.field(default="", metadata={"include_in_asdict_even_if_is_default": True}) num_bytes: int = dataclasses.field(default=0, metadata={"include_in_asdict_even_if_is_default": True}) num_examples: int = dataclasses.field(default=0, metadata={"include_in_asdict_even_if_is_default": True}) shard_lengths: Optional[List[int]] = None # Deprecated # For backward compatibility, this field needs to always be included in files like # dataset_infos.json and dataset_info.json files # To do so, we always include it in the output of datasets.utils.py_utils.asdict(split_info) dataset_name: Optional[str] = dataclasses.field( default=None, metadata={"include_in_asdict_even_if_is_default": True} ) @property def file_instructions(self): """Returns the list of dict(filename, take, skip).""" # `self.dataset_name` is assigned in `SplitDict.add()`. instructions = make_file_instructions( name=self.dataset_name, split_infos=[self], instruction=str(self.name), ) return instructions.file_instructions @dataclass class SubSplitInfo: """Wrapper around a sub split info. This class expose info on the subsplit: ``` ds, info = datasets.load_dataset(..., split='train[75%:]', with_info=True) info.splits['train[75%:]'].num_examples ``` """ instructions: FileInstructions @property def num_examples(self): """Returns the number of example in the subsplit.""" return self.instructions.num_examples @property def file_instructions(self): """Returns the list of dict(filename, take, skip).""" return self.instructions.file_instructions class SplitBase(metaclass=abc.ABCMeta): # pylint: disable=line-too-long """Abstract base class for Split compositionality. See the [guide on splits](../loading#slice-splits) for more information. There are three parts to the composition: 1) The splits are composed (defined, merged, split,...) together before calling the `.as_dataset()` function. This is done with the `__add__`, `__getitem__`, which return a tree of `SplitBase` (whose leaf are the `NamedSplit` objects) ``` split = datasets.Split.TRAIN + datasets.Split.TEST.subsplit(datasets.percent[:50]) ``` 2) The `SplitBase` is forwarded to the `.as_dataset()` function to be resolved into actual read instruction. This is done by the `.get_read_instruction()` method which takes the real dataset splits (name, number of shards,...) and parse the tree to return a `SplitReadInstruction()` object ``` read_instruction = split.get_read_instruction(self.info.splits) ``` 3) The `SplitReadInstruction` is then used in the `tf.data.Dataset` pipeline to define which files to read and how to skip examples within file. """ # pylint: enable=line-too-long @abc.abstractmethod def get_read_instruction(self, split_dict): """Parse the descriptor tree and compile all read instructions together. Args: split_dict: `dict`, The `dict[split_name, SplitInfo]` of the dataset Returns: split_read_instruction: `SplitReadInstruction` """ raise NotImplementedError("Abstract method") def __eq__(self, other): """Equality: datasets.Split.TRAIN == 'train'.""" if isinstance(other, (NamedSplit, str)): return False raise NotImplementedError("Equality is not implemented between merged/sub splits.") def __ne__(self, other): """InEquality: datasets.Split.TRAIN != 'test'.""" return not self.__eq__(other) def __add__(self, other): """Merging: datasets.Split.TRAIN + datasets.Split.TEST.""" return _SplitMerged(self, other) def subsplit(self, arg=None, k=None, percent=None, weighted=None): # pylint: disable=redefined-outer-name """Divides this split into subsplits. There are 3 ways to define subsplits, which correspond to the 3 arguments `k` (get `k` even subsplits), `percent` (get a slice of the dataset with `datasets.percent`), and `weighted` (get subsplits with proportions specified by `weighted`). Example:: ``` # 50% train, 50% test train, test = split.subsplit(k=2) # 50% train, 25% test, 25% validation train, test, validation = split.subsplit(weighted=[2, 1, 1]) # Extract last 20% subsplit = split.subsplit(datasets.percent[-20:]) ``` Warning: k and weighted will be converted into percent which mean that values below the percent will be rounded up or down. The final split may be bigger to deal with remainders. For instance: ``` train, test, valid = split.subsplit(k=3) # 33%, 33%, 34% s1, s2, s3, s4 = split.subsplit(weighted=[2, 2, 1, 1]) # 33%, 33%, 16%, 18% ``` Args: arg: If no kwargs are given, `arg` will be interpreted as one of `k`, `percent`, or `weighted` depending on the type. For example: ``` split.subsplit(10) # Equivalent to split.subsplit(k=10) split.subsplit(datasets.percent[:-20]) # percent=datasets.percent[:-20] split.subsplit([1, 1, 2]) # weighted=[1, 1, 2] ``` k: `int` If set, subdivide the split into `k` equal parts. percent: `datasets.percent slice`, return a single subsplit corresponding to a slice of the original split. For example: `split.subsplit(datasets.percent[-20:]) # Last 20% of the dataset`. weighted: `list[int]`, return a list of subsplits whose proportions match the normalized sum of the list. For example: `split.subsplit(weighted=[1, 1, 2]) # 25%, 25%, 50%`. Returns: A subsplit or list of subsplits extracted from this split object. """ # Note that the percent kwargs redefine the outer name datasets.percent. This # is done for consistency (.subsplit(percent=datasets.percent[:40])) if sum(bool(x) for x in (arg, k, percent, weighted)) != 1: raise ValueError("Only one argument of subsplit should be set.") # Auto deduce k if isinstance(arg, int): k = arg elif isinstance(arg, slice): percent = arg elif isinstance(arg, list): weighted = arg if not (k or percent or weighted): raise ValueError( f"Invalid split argument {arg}. Only list, slice and int supported. " "One of k, weighted or percent should be set to a non empty value." ) def assert_slices_coverage(slices): # Ensure that the expended slices cover all percents. assert sum((list(range(*s.indices(100))) for s in slices), []) == list(range(100)) if k: if not 0 < k <= 100: raise ValueError(f"Subsplit k should be between 0 and 100, got {k}") shift = 100 // k slices = [slice(i * shift, (i + 1) * shift) for i in range(k)] # Round up last element to ensure all elements are taken slices[-1] = slice(slices[-1].start, 100) # Internal check to ensure full coverage assert_slices_coverage(slices) return tuple(_SubSplit(self, s) for s in slices) elif percent: return _SubSplit(self, percent) elif weighted: # Normalize the weighted sum total = sum(weighted) weighted = [100 * x // total for x in weighted] # Create the slice for each of the elements start = 0 stop = 0 slices = [] for v in weighted: stop += v slices.append(slice(start, stop)) start = stop # Round up last element to ensure all elements are taken slices[-1] = slice(slices[-1].start, 100) # Internal check to ensure full coverage assert_slices_coverage(slices) return tuple(_SubSplit(self, s) for s in slices) else: # Should not be possible raise ValueError("Could not determine the split") # 2 requirements: # 1. datasets.percent be sliceable # 2. datasets.percent be documented # # Instances are not documented, so we want datasets.percent to be a class, but to # have it be sliceable, we need this metaclass. class PercentSliceMeta(type): def __getitem__(cls, slice_value): if not isinstance(slice_value, slice): raise ValueError(f"datasets.percent should only be called with slice, not {slice_value}") return slice_value class PercentSlice(metaclass=PercentSliceMeta): # pylint: disable=line-too-long """Syntactic sugar for defining slice subsplits: `datasets.percent[75:-5]`. See the [guide on splits](../loading#slice-splits) for more information. """ # pylint: enable=line-too-long pass percent = PercentSlice # pylint: disable=invalid-name class _SplitMerged(SplitBase): """Represent two split descriptors merged together.""" def __init__(self, split1, split2): self._split1 = split1 self._split2 = split2 def get_read_instruction(self, split_dict): read_instruction1 = self._split1.get_read_instruction(split_dict) read_instruction2 = self._split2.get_read_instruction(split_dict) return read_instruction1 + read_instruction2 def __repr__(self): return f"({repr(self._split1)} + {repr(self._split2)})" class _SubSplit(SplitBase): """Represent a sub split of a split descriptor.""" def __init__(self, split, slice_value): self._split = split self._slice_value = slice_value def get_read_instruction(self, split_dict): return self._split.get_read_instruction(split_dict)[self._slice_value] def __repr__(self): slice_str = "{start}:{stop}" if self._slice_value.step is not None: slice_str += ":{step}" slice_str = slice_str.format( start="" if self._slice_value.start is None else self._slice_value.start, stop="" if self._slice_value.stop is None else self._slice_value.stop, step=self._slice_value.step, ) return f"{repr(self._split)}(datasets.percent[{slice_str}])" class NamedSplit(SplitBase): """Descriptor corresponding to a named split (train, test, ...). Example: Each descriptor can be composed with other using addition or slice: ```py 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: ```py 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: ```py 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: ```py 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]) ``` """ def __init__(self, name): self._name = name split_names_from_instruction = [split_instruction.split("[")[0] for split_instruction in name.split("+")] for split_name in split_names_from_instruction: if not re.match(_split_re, split_name): raise ValueError(f"Split name should match '{_split_re}' but got '{split_name}'.") def __str__(self): return self._name def __repr__(self): return f"NamedSplit({self._name!r})" def __eq__(self, other): """Equality: datasets.Split.TRAIN == 'train'.""" if isinstance(other, NamedSplit): return self._name == other._name # pylint: disable=protected-access elif isinstance(other, SplitBase): return False elif isinstance(other, str): # Other should be string return self._name == other else: raise ValueError(f"Equality not supported between split {self} and {other}") def __lt__(self, other): return self._name < other._name # pylint: disable=protected-access def __hash__(self): return hash(self._name) def get_read_instruction(self, split_dict): return SplitReadInstruction(split_dict[self._name]) class NamedSplitAll(NamedSplit): """Split corresponding to the union of all defined dataset splits.""" def __init__(self): super().__init__("all") def __repr__(self): return "NamedSplitAll()" def get_read_instruction(self, split_dict): # Merge all dataset split together read_instructions = [SplitReadInstruction(s) for s in split_dict.values()] return sum(read_instructions, SplitReadInstruction()) class Split: # pylint: disable=line-too-long """`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](../load_hub#splits) on splits for more information. Example: ```py >>> 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)}, ... ) ``` """ # pylint: enable=line-too-long TRAIN = NamedSplit("train") TEST = NamedSplit("test") VALIDATION = NamedSplit("validation") ALL = NamedSplitAll() def __new__(cls, name): """Create a custom split with datasets.Split('custom_name').""" return NamedSplitAll() if name == "all" else NamedSplit(name) # Similar to SplitInfo, but contain an additional slice info SlicedSplitInfo = collections.namedtuple( "SlicedSplitInfo", [ "split_info", "slice_value", ], ) # noqa: E231 class SplitReadInstruction: """Object containing the reading instruction for the dataset. Similarly to `SplitDescriptor` nodes, this object can be composed with itself, but the resolution happens instantaneously, instead of keeping track of the tree, such as all instructions are compiled and flattened in a single SplitReadInstruction object containing the list of files and slice to use. Once resolved, the instructions can be accessed with: ``` read_instructions.get_list_sliced_split_info() # List of splits to use ``` """ def __init__(self, split_info=None): self._splits = NonMutableDict(error_msg="Overlap between splits. Split {key} has been added with " "itself.") if split_info: self.add(SlicedSplitInfo(split_info=split_info, slice_value=None)) def add(self, sliced_split): """Add a SlicedSplitInfo the read instructions.""" # TODO(epot): Check that the number of examples per shard % 100 == 0 # Otherwise the slices value may be unbalanced and not exactly reflect the # requested slice. self._splits[sliced_split.split_info.name] = sliced_split def __add__(self, other): """Merging split together.""" # Will raise error if a split has already be added (NonMutableDict) # TODO(epot): If a split is already added but there is no overlap between # the slices, should merge the slices (ex: [:10] + [80:]) split_instruction = SplitReadInstruction() split_instruction._splits.update(self._splits) # pylint: disable=protected-access split_instruction._splits.update(other._splits) # pylint: disable=protected-access return split_instruction def __getitem__(self, slice_value): """Sub-splits.""" # Will raise an error if a split has already been sliced split_instruction = SplitReadInstruction() for v in self._splits.values(): if v.slice_value is not None: raise ValueError(f"Trying to slice Split {v.split_info.name} which has already been sliced") v = v._asdict() v["slice_value"] = slice_value split_instruction.add(SlicedSplitInfo(**v)) return split_instruction def get_list_sliced_split_info(self): return list(self._splits.values()) class SplitDict(dict): """Split info object.""" def __init__(self, *args, dataset_name=None, **kwargs): super().__init__(*args, **kwargs) self.dataset_name = dataset_name def __getitem__(self, key: Union[SplitBase, str]): # 1st case: The key exists: `info.splits['train']` if str(key) in self: return super().__getitem__(str(key)) # 2nd case: Uses instructions: `info.splits['train[50%]']` else: instructions = make_file_instructions( name=self.dataset_name, split_infos=self.values(), instruction=key, ) return SubSplitInfo(instructions) def __setitem__(self, key: Union[SplitBase, str], value: SplitInfo): if key != value.name: raise ValueError(f"Cannot add elem. (key mismatch: '{key}' != '{value.name}')") if key in self: raise ValueError(f"Split {key} already present") super().__setitem__(key, value) def add(self, split_info: SplitInfo): """Add the split info.""" if split_info.name in self: raise ValueError(f"Split {split_info.name} already present") split_info.dataset_name = self.dataset_name super().__setitem__(split_info.name, split_info) @property def total_num_examples(self): """Return the total number of examples.""" return sum(s.num_examples for s in self.values()) @classmethod def from_split_dict(cls, split_infos: Union[List, Dict], dataset_name: Optional[str] = None): """Returns a new SplitDict initialized from a Dict or List of `split_infos`.""" if isinstance(split_infos, dict): split_infos = list(split_infos.values()) if dataset_name is None: dataset_name = split_infos[0].get("dataset_name") if split_infos else None split_dict = cls(dataset_name=dataset_name) for split_info in split_infos: if isinstance(split_info, dict): split_info = SplitInfo(**split_info) split_dict.add(split_info) return split_dict def to_split_dict(self): """Returns a list of SplitInfo protos that we have.""" out = [] for split_name, split_info in self.items(): split_info = copy.deepcopy(split_info) split_info.name = split_name out.append(split_info) return out def copy(self): return SplitDict.from_split_dict(self.to_split_dict(), self.dataset_name) def _to_yaml_list(self) -> list: out = [asdict(s) for s in self.to_split_dict()] # we don't need the shard lengths in YAML, since it depends on max_shard_size and num_proc for split_info_dict in out: split_info_dict.pop("shard_lengths", None) # we don't need the dataset_name attribute that is deprecated for split_info_dict in out: split_info_dict.pop("dataset_name", None) return out @classmethod def _from_yaml_list(cls, yaml_data: list) -> "SplitDict": return cls.from_split_dict(yaml_data) @dataclass class SplitGenerator: """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. Args: 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. Example: ```py >>> datasets.SplitGenerator( ... name=datasets.Split.TRAIN, ... gen_kwargs={"split_key": "train", "files": dl_manager.download_and_extract(url)}, ... ) ``` """ name: str gen_kwargs: Dict = dataclasses.field(default_factory=dict) split_info: SplitInfo = dataclasses.field(init=False) def __post_init__(self): self.name = str(self.name) # Make sure we convert NamedSplits in strings NamedSplit(self.name) # check that it's a valid split name self.split_info = SplitInfo(name=self.name)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/metric.py
# Copyright 2020 The HuggingFace 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. # Lint as: python3 """ Metrics base class.""" import os import types import uuid from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import pyarrow as pa from filelock import BaseFileLock, Timeout from . import config from .arrow_dataset import Dataset from .arrow_reader import ArrowReader from .arrow_writer import ArrowWriter from .download.download_config import DownloadConfig from .download.download_manager import DownloadManager from .features import Features from .info import DatasetInfo, MetricInfo from .naming import camelcase_to_snakecase from .utils._filelock import FileLock from .utils.deprecation_utils import deprecated from .utils.logging import get_logger from .utils.py_utils import copyfunc, temp_seed logger = get_logger(__name__) class FileFreeLock(BaseFileLock): """Thread lock until a file **cannot** be locked""" def __init__(self, lock_file, *args, **kwargs): self.filelock = FileLock(lock_file) super().__init__(self.filelock.lock_file, *args, **kwargs) def _acquire(self): try: self.filelock.acquire(timeout=0.01, poll_intervall=0.02) # Try to lock once except Timeout: # We couldn't acquire the lock, the file is locked! self._context.lock_file_fd = self.filelock.lock_file else: # We were able to acquire the lock, the file is not yet locked! self.filelock.release() self._context.lock_file_fd = None def _release(self): self._context.lock_file_fd = None # lists - summarize long lists similarly to NumPy # arrays/tensors - let the frameworks control formatting def summarize_if_long_list(obj): if not type(obj) == list or len(obj) <= 6: # noqa: E721 return f"{obj}" def format_chunk(chunk): return ", ".join(repr(x) for x in chunk) return f"[{format_chunk(obj[:3])}, ..., {format_chunk(obj[-3:])}]" class MetricInfoMixin: """This base class exposes some attributes of MetricInfo at the base level of the Metric for easy access. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ def __init__(self, info: MetricInfo): self._metric_info = info @property def info(self): """:class:`datasets.MetricInfo` object containing all the metadata in the metric.""" return self._metric_info @property def name(self) -> str: return self._metric_info.metric_name @property def experiment_id(self) -> Optional[str]: return self._metric_info.experiment_id @property def description(self) -> str: return self._metric_info.description @property def citation(self) -> str: return self._metric_info.citation @property def features(self) -> Features: return self._metric_info.features @property def inputs_description(self) -> str: return self._metric_info.inputs_description @property def homepage(self) -> Optional[str]: return self._metric_info.homepage @property def license(self) -> str: return self._metric_info.license @property def codebase_urls(self) -> Optional[List[str]]: return self._metric_info.codebase_urls @property def reference_urls(self) -> Optional[List[str]]: return self._metric_info.reference_urls @property def streamable(self) -> bool: return self._metric_info.streamable @property def format(self) -> Optional[str]: return self._metric_info.format class Metric(MetricInfoMixin): """A Metric is the base class and common API for all metrics. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> Args: config_name (``str``): This is used to define a hash specific to a metrics computation script and prevents the metric's data to be overridden when the metric loading script is modified. keep_in_memory (:obj:`bool`): keep all predictions and references in memory. Not possible in distributed settings. cache_dir (``str``): Path to a directory in which temporary prediction/references data will be stored. The data directory should be located on a shared file-system in distributed setups. num_process (``int``): specify the total number of nodes in a distributed settings. This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1). process_id (``int``): specify the id of the current process in a distributed setup (between 0 and num_process-1) This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1). seed (:obj:`int`, optional): If specified, this will temporarily set numpy's random seed when :func:`datasets.Metric.compute` is run. experiment_id (``str``): A specific experiment id. This is used if several distributed evaluations share the same file system. This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1). max_concurrent_cache_files (``int``): Max number of concurrent metrics cache files (default 10000). timeout (``Union[int, float]``): Timeout in second for distributed setting synchronization. """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, config_name: Optional[str] = None, keep_in_memory: bool = False, cache_dir: Optional[str] = None, num_process: int = 1, process_id: int = 0, seed: Optional[int] = None, experiment_id: Optional[str] = None, max_concurrent_cache_files: int = 10000, timeout: Union[int, float] = 100, **kwargs, ): # prepare info self.config_name = config_name or "default" info = self._info() info.metric_name = camelcase_to_snakecase(self.__class__.__name__) info.config_name = self.config_name info.experiment_id = experiment_id or "default_experiment" MetricInfoMixin.__init__(self, info) # For easy access on low level # Safety checks on num_process and process_id if not isinstance(process_id, int) or process_id < 0: raise ValueError("'process_id' should be a number greater than 0") if not isinstance(num_process, int) or num_process <= process_id: raise ValueError("'num_process' should be a number greater than process_id") if keep_in_memory and num_process != 1: raise ValueError("Using 'keep_in_memory' is not possible in distributed setting (num_process > 1).") self.num_process = num_process self.process_id = process_id self.max_concurrent_cache_files = max_concurrent_cache_files self.keep_in_memory = keep_in_memory self._data_dir_root = os.path.expanduser(cache_dir or config.HF_METRICS_CACHE) self.data_dir = self._build_data_dir() if seed is None: _, seed, pos, *_ = np.random.get_state() self.seed: int = seed[pos] if pos < 624 else seed[0] else: self.seed: int = seed self.timeout: Union[int, float] = timeout # Update 'compute' and 'add' docstring # methods need to be copied otherwise it changes the docstrings of every instance self.compute = types.MethodType(copyfunc(self.compute), self) self.add_batch = types.MethodType(copyfunc(self.add_batch), self) self.add = types.MethodType(copyfunc(self.add), self) self.compute.__func__.__doc__ += self.info.inputs_description self.add_batch.__func__.__doc__ += self.info.inputs_description self.add.__func__.__doc__ += self.info.inputs_description # self.arrow_schema = pa.schema(field for field in self.info.features.type) self.buf_writer = None self.writer = None self.writer_batch_size = None self.data = None # This is the cache file we store our predictions/references in # Keep it None for now so we can (cloud)pickle the object self.cache_file_name = None self.filelock = None self.rendez_vous_lock = None # This is all the cache files on which we have a lock when we are in a distributed setting self.file_paths = None self.filelocks = None def __len__(self): """Return the number of examples (predictions or predictions/references pair) currently stored in the metric's cache. """ return 0 if self.writer is None else len(self.writer) def __repr__(self): return ( f'Metric(name: "{self.name}", features: {self.features}, ' f'usage: """{self.inputs_description}""", ' f"stored examples: {len(self)})" ) def _build_data_dir(self): """Path of this metric in cache_dir: Will be: self._data_dir_root/self.name/self.config_name/self.hash (if not none)/ If any of these element is missing or if ``with_version=False`` the corresponding subfolders are dropped. """ builder_data_dir = self._data_dir_root builder_data_dir = os.path.join(builder_data_dir, self.name, self.config_name) os.makedirs(builder_data_dir, exist_ok=True) return builder_data_dir def _create_cache_file(self, timeout=1) -> Tuple[str, FileLock]: """Create a new cache file. If the default cache file is used, we generated a new hash.""" file_path = os.path.join(self.data_dir, f"{self.experiment_id}-{self.num_process}-{self.process_id}.arrow") filelock = None for i in range(self.max_concurrent_cache_files): filelock = FileLock(file_path + ".lock") try: filelock.acquire(timeout=timeout) except Timeout: # If we have reached the max number of attempts or we are not allow to find a free name (distributed setup) # We raise an error if self.num_process != 1: raise ValueError( f"Error in _create_cache_file: another metric instance is already using the local cache file at {file_path}. " f"Please specify an experiment_id (currently: {self.experiment_id}) to avoid collision " f"between distributed metric instances." ) from None if i == self.max_concurrent_cache_files - 1: raise ValueError( f"Cannot acquire lock, too many metric instance are operating concurrently on this file system." f"You should set a larger value of max_concurrent_cache_files when creating the metric " f"(current value is {self.max_concurrent_cache_files})." ) from None # In other cases (allow to find new file name + not yet at max num of attempts) we can try to sample a new hashing name. file_uuid = str(uuid.uuid4()) file_path = os.path.join( self.data_dir, f"{self.experiment_id}-{file_uuid}-{self.num_process}-{self.process_id}.arrow" ) else: break return file_path, filelock def _get_all_cache_files(self) -> Tuple[List[str], List[FileLock]]: """Get a lock on all the cache files in a distributed setup. We wait for timeout second to let all the distributed node finish their tasks (default is 100 seconds). """ if self.num_process == 1: if self.cache_file_name is None: raise ValueError( "Metric cache file doesn't exist. Please make sure that you call `add` or `add_batch` " "at least once before calling `compute`." ) file_paths = [self.cache_file_name] else: file_paths = [ os.path.join(self.data_dir, f"{self.experiment_id}-{self.num_process}-{process_id}.arrow") for process_id in range(self.num_process) ] # Let's acquire a lock on each process files to be sure they are finished writing filelocks = [] for process_id, file_path in enumerate(file_paths): if process_id == 0: # process 0 already has its lock file filelocks.append(self.filelock) else: filelock = FileLock(file_path + ".lock") try: filelock.acquire(timeout=self.timeout) except Timeout: raise ValueError( f"Cannot acquire lock on cached file {file_path} for process {process_id}." ) from None else: filelocks.append(filelock) return file_paths, filelocks def _check_all_processes_locks(self): expected_lock_file_names = [ os.path.join(self.data_dir, f"{self.experiment_id}-{self.num_process}-{process_id}.arrow.lock") for process_id in range(self.num_process) ] for expected_lock_file_name in expected_lock_file_names: nofilelock = FileFreeLock(expected_lock_file_name) try: nofilelock.acquire(timeout=self.timeout) except Timeout: raise ValueError( f"Expected to find locked file {expected_lock_file_name} from process {self.process_id} but it doesn't exist." ) from None else: nofilelock.release() def _check_rendez_vous(self): expected_lock_file_name = os.path.join(self.data_dir, f"{self.experiment_id}-{self.num_process}-0.arrow.lock") nofilelock = FileFreeLock(expected_lock_file_name) try: nofilelock.acquire(timeout=self.timeout) except Timeout: raise ValueError( f"Expected to find locked file {expected_lock_file_name} from process {self.process_id} but it doesn't exist." ) from None else: nofilelock.release() lock_file_name = os.path.join(self.data_dir, f"{self.experiment_id}-{self.num_process}-rdv.lock") rendez_vous_lock = FileLock(lock_file_name) try: rendez_vous_lock.acquire(timeout=self.timeout) except Timeout: raise ValueError(f"Couldn't acquire lock on {lock_file_name} from process {self.process_id}.") from None else: rendez_vous_lock.release() def _finalize(self): """Close all the writing process and load/gather the data from all the nodes if main node or all_process is True. """ if self.writer is not None: self.writer.finalize() self.writer = None # release the locks of the processes > 0 so that process 0 can lock them to read + delete the data if self.filelock is not None and self.process_id > 0: self.filelock.release() if self.keep_in_memory: # Read the predictions and references reader = ArrowReader(path=self.data_dir, info=DatasetInfo(features=self.features)) self.data = Dataset.from_buffer(self.buf_writer.getvalue()) elif self.process_id == 0: # Let's acquire a lock on each node files to be sure they are finished writing file_paths, filelocks = self._get_all_cache_files() # Read the predictions and references try: reader = ArrowReader(path="", info=DatasetInfo(features=self.features)) self.data = Dataset(**reader.read_files([{"filename": f} for f in file_paths])) except FileNotFoundError: raise ValueError( "Error in finalize: another metric instance is already using the local cache file. " "Please specify an experiment_id to avoid collision between distributed metric instances." ) from None # Store file paths and locks and we will release/delete them after the computation. self.file_paths = file_paths self.filelocks = filelocks def compute(self, *, predictions=None, references=None, **kwargs) -> Optional[dict]: """Compute the metrics. Usage of positional arguments is not allowed to prevent mistakes. Args: predictions (list/array/tensor, optional): Predictions. references (list/array/tensor, optional): References. **kwargs (optional): Keyword arguments that will be forwarded to the metrics :meth:`_compute` method (see details in the docstring). Return: dict or None - Dictionary with the metrics if this metric is run on the main process (``process_id == 0``). - None if the metric is not run on the main process (``process_id != 0``). Example: ```py >>> from datasets import load_metric >>> metric = load_metric("accuracy") >>> accuracy = metric.compute(predictions=model_prediction, references=labels) ``` """ all_kwargs = {"predictions": predictions, "references": references, **kwargs} if predictions is None and references is None: missing_kwargs = {k: None for k in self.features if k not in all_kwargs} all_kwargs.update(missing_kwargs) else: missing_inputs = [k for k in self.features if k not in all_kwargs] if missing_inputs: raise ValueError( f"Metric inputs are missing: {missing_inputs}. All required inputs are {list(self.features)}" ) inputs = {input_name: all_kwargs[input_name] for input_name in self.features} compute_kwargs = {k: kwargs[k] for k in kwargs if k not in self.features} if any(v is not None for v in inputs.values()): self.add_batch(**inputs) self._finalize() self.cache_file_name = None self.filelock = None if self.process_id == 0: self.data.set_format(type=self.info.format) inputs = {input_name: self.data[input_name] for input_name in self.features} with temp_seed(self.seed): output = self._compute(**inputs, **compute_kwargs) if self.buf_writer is not None: self.buf_writer = None del self.data self.data = None else: # Release locks and delete all the cache files. Process 0 is released last. for filelock, file_path in reversed(list(zip(self.filelocks, self.file_paths))): logger.info(f"Removing {file_path}") del self.data self.data = None del self.writer self.writer = None os.remove(file_path) filelock.release() return output else: return None def add_batch(self, *, predictions=None, references=None, **kwargs): """Add a batch of predictions and references for the metric's stack. Args: predictions (list/array/tensor, optional): Predictions. references (list/array/tensor, optional): References. Example: ```py >>> from datasets import load_metric >>> metric = load_metric("accuracy") >>> metric.add_batch(predictions=model_prediction, references=labels) ``` """ bad_inputs = [input_name for input_name in kwargs if input_name not in self.features] if bad_inputs: raise ValueError(f"Bad inputs for metric: {bad_inputs}. All required inputs are {list(self.features)}") batch = {"predictions": predictions, "references": references, **kwargs} batch = {intput_name: batch[intput_name] for intput_name in self.features} batch = self.info.features.encode_batch(batch) if self.writer is None: self._init_writer() try: self.writer.write_batch(batch) except pa.ArrowInvalid: if any(len(batch[c]) != len(next(iter(batch.values()))) for c in batch): col0 = next(iter(batch)) bad_col = [c for c in batch if len(batch[c]) != len(batch[col0])][0] error_msg = ( f"Mismatch in the number of {col0} ({len(batch[col0])}) and {bad_col} ({len(batch[bad_col])})" ) elif sorted(self.features) != ["references", "predictions"]: error_msg = f"Metric inputs don't match the expected format.\n" f"Expected format: {self.features},\n" error_msg_inputs = ",\n".join( f"Input {input_name}: {summarize_if_long_list(batch[input_name])}" for input_name in self.features ) error_msg += error_msg_inputs else: error_msg = ( f"Predictions and/or references don't match the expected format.\n" f"Expected format: {self.features},\n" f"Input predictions: {summarize_if_long_list(predictions)},\n" f"Input references: {summarize_if_long_list(references)}" ) raise ValueError(error_msg) from None def add(self, *, prediction=None, reference=None, **kwargs): """Add one prediction and reference for the metric's stack. Args: prediction (list/array/tensor, optional): Predictions. reference (list/array/tensor, optional): References. Example: ```py >>> from datasets import load_metric >>> metric = load_metric("accuracy") >>> metric.add(predictions=model_predictions, references=labels) ``` """ bad_inputs = [input_name for input_name in kwargs if input_name not in self.features] if bad_inputs: raise ValueError(f"Bad inputs for metric: {bad_inputs}. All required inputs are {list(self.features)}") example = {"predictions": prediction, "references": reference, **kwargs} example = {intput_name: example[intput_name] for intput_name in self.features} example = self.info.features.encode_example(example) if self.writer is None: self._init_writer() try: self.writer.write(example) except pa.ArrowInvalid: error_msg = f"Metric inputs don't match the expected format.\n" f"Expected format: {self.features},\n" error_msg_inputs = ",\n".join( f"Input {input_name}: {summarize_if_long_list(example[input_name])}" for input_name in self.features ) error_msg += error_msg_inputs raise ValueError(error_msg) from None def _init_writer(self, timeout=1): if self.num_process > 1: if self.process_id == 0: file_path = os.path.join(self.data_dir, f"{self.experiment_id}-{self.num_process}-rdv.lock") self.rendez_vous_lock = FileLock(file_path) try: self.rendez_vous_lock.acquire(timeout=timeout) except TimeoutError: raise ValueError( f"Error in _init_writer: another metric instance is already using the local cache file at {file_path}. " f"Please specify an experiment_id (currently: {self.experiment_id}) to avoid collision " f"between distributed metric instances." ) from None if self.keep_in_memory: self.buf_writer = pa.BufferOutputStream() self.writer = ArrowWriter( features=self.info.features, stream=self.buf_writer, writer_batch_size=self.writer_batch_size ) else: self.buf_writer = None # Get cache file name and lock it if self.cache_file_name is None or self.filelock is None: cache_file_name, filelock = self._create_cache_file() # get ready self.cache_file_name = cache_file_name self.filelock = filelock self.writer = ArrowWriter( features=self.info.features, path=self.cache_file_name, writer_batch_size=self.writer_batch_size ) # Setup rendez-vous here if if self.num_process > 1: if self.process_id == 0: self._check_all_processes_locks() # wait for everyone to be ready self.rendez_vous_lock.release() # let everyone go else: self._check_rendez_vous() # wait for master to be ready and to let everyone go def _info(self) -> MetricInfo: """Construct the MetricInfo object. See `MetricInfo` for details. Warning: This function is only called once and the result is cached for all following .info() calls. Returns: info: (MetricInfo) The metrics information """ raise NotImplementedError def download_and_prepare( self, download_config: Optional[DownloadConfig] = None, dl_manager: Optional[DownloadManager] = None, ): """Downloads and prepares dataset for reading. Args: download_config (:class:`DownloadConfig`, optional): Specific download configuration parameters. dl_manager (:class:`DownloadManager`, optional): Specific download manager to use. """ if dl_manager is None: if download_config is None: download_config = DownloadConfig() download_config.cache_dir = os.path.join(self.data_dir, "downloads") download_config.force_download = False dl_manager = DownloadManager( dataset_name=self.name, download_config=download_config, data_dir=self.data_dir ) self._download_and_prepare(dl_manager) def _download_and_prepare(self, dl_manager): """Downloads and prepares resources for the metric. This is the internal implementation to overwrite called when user calls `download_and_prepare`. It should download all required resources for the metric. Args: dl_manager (:class:`DownloadManager`): `DownloadManager` used to download and cache data. """ return None def _compute(self, *, predictions=None, references=None, **kwargs) -> Dict[str, Any]: """This method defines the common API for all the metrics in the library""" raise NotImplementedError def __del__(self): if hasattr(self, "filelock") and self.filelock is not None: self.filelock.release() if hasattr(self, "rendez_vous_lock") and self.rendez_vous_lock is not None: self.rendez_vous_lock.release() if hasattr(self, "writer"): # in case it was already deleted del self.writer if hasattr(self, "data"): # in case it was already deleted del self.data
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/__init__.py
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __version__ = "2.16.2.dev0" from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_default_config_name, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _arrow_dataset.concatenate_datasets = concatenate_datasets _utils.DownloadConfig = DownloadConfig _utils.DownloadManager = DownloadManager _utils.DownloadMode = DownloadMode _deprecated_download_manager.DownloadConfig = DownloadConfig _deprecated_download_manager.DownloadMode = DownloadMode _deprecated_download_manager.DownloadManager = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/dataset_dict.py
import contextlib import copy import fnmatch import json import math import posixpath import re import warnings from io import BytesIO from pathlib import Path from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import fsspec import numpy as np from huggingface_hub import ( CommitInfo, CommitOperationAdd, CommitOperationDelete, DatasetCard, DatasetCardData, HfApi, ) from . import config from .arrow_dataset import PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED, Dataset from .features import Features from .features.features import FeatureType from .info import DatasetInfo, DatasetInfosDict from .naming import _split_re from .splits import NamedSplit, Split, SplitDict, SplitInfo from .table import Table from .tasks import TaskTemplate from .utils import logging from .utils.deprecation_utils import deprecated from .utils.doc_utils import is_documented_by from .utils.hub import list_files_info from .utils.metadata import MetadataConfigs from .utils.py_utils import asdict, glob_pattern_to_regex, string_to_dict from .utils.typing import PathLike logger = logging.get_logger(__name__) class DatasetDict(dict): """A dictionary (dict of str: datasets.Dataset) with dataset transforms methods (map, filter, etc.)""" def _check_values_type(self): for dataset in self.values(): if not isinstance(dataset, Dataset): raise TypeError(f"Values in `DatasetDict` should be of type `Dataset` but got type '{type(dataset)}'") def _check_values_features(self): items = list(self.items()) for item_a, item_b in zip(items[:-1], items[1:]): if item_a[1].features != item_b[1].features: raise ValueError( f"All datasets in `DatasetDict` should have the same features but features for '{item_a[0]}' and '{item_b[0]}' don't match: {item_a[1].features} != {item_b[1].features}" ) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # Here `del` is used to del the pyarrow tables. This properly closes the files used for memory mapped tables for dataset in self.values(): if hasattr(dataset, "_data"): del dataset._data if hasattr(dataset, "_indices"): del dataset._indices def __getitem__(self, k) -> Dataset: if isinstance(k, (str, NamedSplit)) or len(self) == 0: return super().__getitem__(k) else: available_suggested_splits = [ split for split in (Split.TRAIN, Split.TEST, Split.VALIDATION) if split in self ] suggested_split = available_suggested_splits[0] if available_suggested_splits else list(self)[0] raise KeyError( f"Invalid key: {k}. Please first select a split. For example: " f"`my_dataset_dictionary['{suggested_split}'][{k}]`. " f"Available splits: {sorted(self)}" ) @property def data(self) -> Dict[str, Table]: """The Apache Arrow tables backing each split. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.data ``` """ self._check_values_type() return {k: dataset.data for k, dataset in self.items()} @property def cache_files(self) -> Dict[str, Dict]: """The cache files containing the Apache Arrow table backing each split. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.cache_files {'test': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-test.arrow'}], 'train': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-train.arrow'}], 'validation': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]} ``` """ self._check_values_type() return {k: dataset.cache_files for k, dataset in self.items()} @property def num_columns(self) -> Dict[str, int]: """Number of columns in each split of the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.num_columns {'test': 2, 'train': 2, 'validation': 2} ``` """ self._check_values_type() return {k: dataset.num_columns for k, dataset in self.items()} @property def num_rows(self) -> Dict[str, int]: """Number of rows in each split of the dataset (same as :func:`datasets.Dataset.__len__`). Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.num_rows {'test': 1066, 'train': 8530, 'validation': 1066} ``` """ self._check_values_type() return {k: dataset.num_rows for k, dataset in self.items()} @property def column_names(self) -> Dict[str, List[str]]: """Names of the columns in each split of the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.column_names {'test': ['text', 'label'], 'train': ['text', 'label'], 'validation': ['text', 'label']} ``` """ self._check_values_type() return {k: dataset.column_names for k, dataset in self.items()} @property def shape(self) -> Dict[str, Tuple[int]]: """Shape of each split of the dataset (number of columns, number of rows). Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.shape {'test': (1066, 2), 'train': (8530, 2), 'validation': (1066, 2)} ``` """ self._check_values_type() return {k: dataset.shape for k, dataset in self.items()} def flatten(self, max_depth=16) -> "DatasetDict": """Flatten the Apache Arrow Table of each split (nested features are flatten). Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("squad") >>> ds["train"].features {'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None), 'context': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None), 'title': Value(dtype='string', id=None)} >>> ds.flatten() DatasetDict({ train: Dataset({ features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'], num_rows: 87599 }) validation: Dataset({ features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'], num_rows: 10570 }) }) ``` """ self._check_values_type() return DatasetDict({k: dataset.flatten(max_depth=max_depth) for k, dataset in self.items()}) def unique(self, column: str) -> Dict[str, List]: """Return a list of the unique elements in a column for each split. This is implemented in the low-level backend and as such, very fast. Args: column (`str`): column name (list all the column names with [`~datasets.Dataset.column_names`]) Returns: Dict[`str`, `list`]: Dictionary of unique elements in the given column. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.unique("label") {'test': [1, 0], 'train': [1, 0], 'validation': [1, 0]} ``` """ self._check_values_type() return {k: dataset.unique(column) for k, dataset in self.items()} def cleanup_cache_files(self) -> Dict[str, int]: """Clean up all cache files in the dataset cache directory, excepted the currently used cache file if there is one. Be careful when running this command that no other process is currently using other cache files. Return: `Dict` with the number of removed files for each split Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.cleanup_cache_files() {'test': 0, 'train': 0, 'validation': 0} ``` """ self._check_values_type() return {k: dataset.cleanup_cache_files() for k, dataset in self.items()} def __repr__(self): repr = "\n".join([f"{k}: {v}" for k, v in self.items()]) repr = re.sub(r"^", " " * 4, repr, 0, re.M) return f"DatasetDict({{\n{repr}\n}})" def cast(self, features: Features) -> "DatasetDict": """ Cast the dataset to a new set of features. The transformation is applied to all the datasets of the dataset dictionary. You can also remove a column using [`Dataset.map`] with `feature` but `cast` is in-place (doesn't copy the data to a new dataset) and is thus faster. Args: features ([`Features`]): New features to cast the dataset to. The name and order of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `string` <-> `ClassLabel` you should use [`~Dataset.map`] to update the Dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds["train"].features.copy() >>> new_features['label'] = ClassLabel(names=['bad', 'good']) >>> new_features['text'] = Value('large_string') >>> ds = ds.cast(new_features) >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='large_string', id=None)} ``` """ self._check_values_type() return DatasetDict({k: dataset.cast(features=features) for k, dataset in self.items()}) def cast_column(self, column: str, feature) -> "DatasetDict": """Cast column to feature for decoding. Args: column (`str`): Column name. feature ([`Feature`]): Target feature. Returns: [`DatasetDict`] Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good'])) >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='string', id=None)} ``` """ self._check_values_type() return DatasetDict({k: dataset.cast_column(column=column, feature=feature) for k, dataset in self.items()}) def remove_columns(self, column_names: Union[str, List[str]]) -> "DatasetDict": """ Remove one or several column(s) from each split in the dataset and the features associated to the column(s). The transformation is applied to all the splits of the dataset dictionary. You can also remove a column using [`Dataset.map`] with `remove_columns` but the present method is in-place (doesn't copy the data to a new dataset) and is thus faster. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to remove. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.remove_columns("label") DatasetDict({ train: Dataset({ features: ['text'], num_rows: 8530 }) validation: Dataset({ features: ['text'], num_rows: 1066 }) test: Dataset({ features: ['text'], num_rows: 1066 }) }) ``` """ self._check_values_type() return DatasetDict({k: dataset.remove_columns(column_names=column_names) for k, dataset in self.items()}) def rename_column(self, original_column_name: str, new_column_name: str) -> "DatasetDict": """ Rename a column in the dataset and move the features associated to the original column under the new column name. The transformation is applied to all the datasets of the dataset dictionary. You can also rename a column using [`~Dataset.map`] with `remove_columns` but the present method: - takes care of moving the original features under the new column name. - doesn't copy the data to a new dataset and is thus much faster. Args: original_column_name (`str`): Name of the column to rename. new_column_name (`str`): New name for the column. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.rename_column("label", "label_new") DatasetDict({ train: Dataset({ features: ['text', 'label_new'], num_rows: 8530 }) validation: Dataset({ features: ['text', 'label_new'], num_rows: 1066 }) test: Dataset({ features: ['text', 'label_new'], num_rows: 1066 }) }) ``` """ self._check_values_type() return DatasetDict( { k: dataset.rename_column(original_column_name=original_column_name, new_column_name=new_column_name) for k, dataset in self.items() } ) def rename_columns(self, column_mapping: Dict[str, str]) -> "DatasetDict": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. The transformation is applied to all the datasets of the dataset dictionary. Args: column_mapping (`Dict[str, str]`): A mapping of columns to rename to their new names. Returns: [`DatasetDict`]: A copy of the dataset with renamed columns. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'}) DatasetDict({ train: Dataset({ features: ['text_new', 'label_new'], num_rows: 8530 }) validation: Dataset({ features: ['text_new', 'label_new'], num_rows: 1066 }) test: Dataset({ features: ['text_new', 'label_new'], num_rows: 1066 }) }) ``` """ self._check_values_type() return DatasetDict({k: dataset.rename_columns(column_mapping=column_mapping) for k, dataset in self.items()}) def select_columns(self, column_names: Union[str, List[str]]) -> "DatasetDict": """Select one or several column(s) from each split in the dataset and the features associated to the column(s). The transformation is applied to all the splits of the dataset dictionary. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to keep. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.select_columns("text") DatasetDict({ train: Dataset({ features: ['text'], num_rows: 8530 }) validation: Dataset({ features: ['text'], num_rows: 1066 }) test: Dataset({ features: ['text'], num_rows: 1066 }) }) ``` """ self._check_values_type() return DatasetDict({k: dataset.select_columns(column_names=column_names) for k, dataset in self.items()}) def class_encode_column(self, column: str, include_nulls: bool = False) -> "DatasetDict": """Casts the given column as [`~datasets.features.ClassLabel`] and updates the tables. Args: column (`str`): The name of the column to cast. include_nulls (`bool`, defaults to `False`): Whether to include null values in the class labels. If `True`, the null values will be encoded as the `"None"` class label. <Added version="1.14.2"/> Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("boolq") >>> ds["train"].features {'answer': Value(dtype='bool', id=None), 'passage': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None)} >>> ds = ds.class_encode_column("answer") >>> ds["train"].features {'answer': ClassLabel(num_classes=2, names=['False', 'True'], id=None), 'passage': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None)} ``` """ self._check_values_type() return DatasetDict( {k: dataset.class_encode_column(column=column, include_nulls=include_nulls) for k, dataset in self.items()} ) @contextlib.contextmanager def formatted_as( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """To be used in a `with` statement. Set `__getitem__` return format (type and columns). The transformation is applied to all the datasets of the dataset dictionary. Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the output. `None` means `__getitem__` returns all columns (default). output_all_columns (`bool`, defaults to False): Keep un-formatted columns as well in the output (as python objects). **format_kwargs (additional keyword arguments): Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`. """ self._check_values_type() old_format_type = {k: dataset._format_type for k, dataset in self.items()} old_format_kwargs = {k: dataset._format_kwargs for k, dataset in self.items()} old_format_columns = {k: dataset._format_columns for k, dataset in self.items()} old_output_all_columns = {k: dataset._output_all_columns for k, dataset in self.items()} try: self.set_format(type, columns, output_all_columns, **format_kwargs) yield finally: for k, dataset in self.items(): dataset.set_format( old_format_type[k], old_format_columns[k], old_output_all_columns[k], **old_format_kwargs[k] ) def set_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """Set `__getitem__` return format (type and columns). The format is set for every dataset in the dataset dictionary. Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the output. `None` means `__getitem__` returns all columns (default). output_all_columns (`bool`, defaults to False): Keep un-formatted columns as well in the output (as python objects), **format_kwargs (additional keyword arguments): Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`. It is possible to call `map` after calling `set_format`. Since `map` may add new columns, then the list of formatted columns gets updated. In this case, if you apply `map` on a dataset to add a new column, then this column will be formatted: `new formatted columns = (all columns - previously unformatted columns)` Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True) >>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label']) >>> ds["train"].format {'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'], 'format_kwargs': {}, 'output_all_columns': False, 'type': 'numpy'} ``` """ self._check_values_type() for dataset in self.values(): dataset.set_format(type=type, columns=columns, output_all_columns=output_all_columns, **format_kwargs) def reset_format(self): """Reset `__getitem__` return format to python objects and all columns. The transformation is applied to all the datasets of the dataset dictionary. Same as `self.set_format()` Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True) >>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label']) >>> ds["train"].format {'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'], 'format_kwargs': {}, 'output_all_columns': False, 'type': 'numpy'} >>> ds.reset_format() >>> ds["train"].format {'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'], 'format_kwargs': {}, 'output_all_columns': False, 'type': None} ``` """ self._check_values_type() for dataset in self.values(): dataset.set_format() def set_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ): """Set ``__getitem__`` return format using this transform. The transform is applied on-the-fly on batches when ``__getitem__`` is called. The transform is set for every dataset in the dataset dictionary As :func:`datasets.Dataset.set_format`, this can be reset using :func:`datasets.Dataset.reset_format` Args: transform (`Callable`, optional): user-defined formatting transform, replaces the format defined by :func:`datasets.Dataset.set_format` A formatting function is a callable that takes a batch (as a dict) as input and returns a batch. This function is applied right before returning the objects in ``__getitem__``. columns (`List[str]`, optional): columns to format in the output If specified, then the input batch of the transform only contains those columns. output_all_columns (`bool`, default to False): keep un-formatted columns as well in the output (as python objects) If set to True, then the other un-formatted columns are kept with the output of the transform. """ self._check_values_type() for dataset in self.values(): dataset.set_format("custom", columns=columns, output_all_columns=output_all_columns, transform=transform) def with_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ) -> "DatasetDict": """Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The format `type` (for example "numpy") is used to format batches when using `__getitem__`. The format is set for every dataset in the dataset dictionary. It's also possible to use custom transforms for formatting using [`~datasets.Dataset.with_transform`]. Contrary to [`~datasets.DatasetDict.set_format`], `with_format` returns a new [`DatasetDict`] object with new [`Dataset`] objects. Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the output. `None` means `__getitem__` returns all columns (default). output_all_columns (`bool`, defaults to `False`): Keep un-formatted columns as well in the output (as python objects). **format_kwargs (additional keyword arguments): Keywords arguments passed to the convert function like `np.array`, `torch.tensor` or `tensorflow.ragged.constant`. Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True) >>> ds["train"].format {'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'], 'format_kwargs': {}, 'output_all_columns': False, 'type': None} >>> ds = ds.with_format(type='tensorflow', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label']) >>> ds["train"].format {'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'], 'format_kwargs': {}, 'output_all_columns': False, 'type': 'tensorflow'} ``` """ dataset = copy.deepcopy(self) dataset.set_format(type=type, columns=columns, output_all_columns=output_all_columns, **format_kwargs) return dataset def with_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ) -> "DatasetDict": """Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called. The transform is set for every dataset in the dataset dictionary As [`~datasets.Dataset.set_format`], this can be reset using [`~datasets.Dataset.reset_format`]. Contrary to [`~datasets.DatasetDict.set_transform`], `with_transform` returns a new [`DatasetDict`] object with new [`Dataset`] objects. Args: transform (`Callable`, *optional*): User-defined formatting transform, replaces the format defined by [`~datasets.Dataset.set_format`]. A formatting function is a callable that takes a batch (as a dict) as input and returns a batch. This function is applied right before returning the objects in `__getitem__`. columns (`List[str]`, *optional*): Columns to format in the output. If specified, then the input batch of the transform only contains those columns. output_all_columns (`bool`, defaults to False): Keep un-formatted columns as well in the output (as python objects). If set to `True`, then the other un-formatted columns are kept with the output of the transform. Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> def encode(example): ... return tokenizer(example['text'], truncation=True, padding=True, return_tensors="pt") >>> ds = ds.with_transform(encode) >>> ds["train"][0] {'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), 'input_ids': tensor([ 101, 1103, 2067, 1110, 17348, 1106, 1129, 1103, 6880, 1432, 112, 188, 1207, 107, 14255, 1389, 107, 1105, 1115, 1119, 112, 188, 1280, 1106, 1294, 170, 24194, 1256, 3407, 1190, 170, 11791, 5253, 188, 1732, 7200, 10947, 12606, 2895, 117, 179, 7766, 118, 172, 15554, 1181, 3498, 6961, 3263, 1137, 188, 1566, 7912, 14516, 6997, 119, 102]), 'token_type_ids': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])} ``` """ dataset = copy.deepcopy(self) dataset.set_transform(transform=transform, columns=columns, output_all_columns=output_all_columns) return dataset def map( self, function: Optional[Callable] = None, with_indices: bool = False, with_rank: bool = False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: bool = False, remove_columns: Optional[Union[str, List[str]]] = None, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, cache_file_names: Optional[Dict[str, Optional[str]]] = None, writer_batch_size: Optional[int] = 1000, features: Optional[Features] = None, disable_nullable: bool = False, fn_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, desc: Optional[str] = None, ) -> "DatasetDict": """Apply a function to all the elements in the table (individually or in batches) and update the table (if function does updated examples). The transformation is applied to all the datasets of the dataset dictionary. Args: function (`callable`): with one of the following signature: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` - `function(example: Dict[str, Any], indices: int) -> Dict[str, Any]` if `batched=False` and `with_indices=True` - `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False` - `function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]` if `batched=True` and `with_indices=True` For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`. with_rank (`bool`, defaults to `False`): Provide process rank to `function`. Note that in this case the signature of `function` should be `def function(example[, idx], rank): ...`. input_columns (`[Union[str, List[str]]]`, *optional*, defaults to `None`): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`, `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`. drop_last_batch (`bool`, defaults to `False`): Whether a last batch smaller than the batch_size should be dropped instead of being processed by the function. remove_columns (`[Union[str, List[str]]]`, *optional*, defaults to `None`): Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the current computation from `function` can be identified, use it instead of recomputing. cache_file_names (`[Dict[str, str]]`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary. writer_batch_size (`int`, default `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. features (`[datasets.Features]`, *optional*, defaults to `None`): Use a specific [`Features`] to store the cache file instead of the automatically generated one. disable_nullable (`bool`, defaults to `False`): Disallow null values in the table. fn_kwargs (`Dict`, *optional*, defaults to `None`): Keyword arguments to be passed to `function` num_proc (`int`, *optional*, defaults to `None`): Number of processes for multiprocessing. By default it doesn't use multiprocessing. desc (`str`, *optional*, defaults to `None`): Meaningful description to be displayed alongside with the progress bar while mapping examples. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> def add_prefix(example): ... example["text"] = "Review: " + example["text"] ... return example >>> ds = ds.map(add_prefix) >>> ds["train"][0:3]["text"] ['Review: the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'Review: the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .', 'Review: effective but too-tepid biopic'] # process a batch of examples >>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True) # set number of processors >>> ds = ds.map(add_prefix, num_proc=4) ``` """ self._check_values_type() if cache_file_names is None: cache_file_names = {k: None for k in self} return DatasetDict( { k: dataset.map( function=function, with_indices=with_indices, with_rank=with_rank, input_columns=input_columns, batched=batched, batch_size=batch_size, drop_last_batch=drop_last_batch, remove_columns=remove_columns, keep_in_memory=keep_in_memory, load_from_cache_file=load_from_cache_file, cache_file_name=cache_file_names[k], writer_batch_size=writer_batch_size, features=features, disable_nullable=disable_nullable, fn_kwargs=fn_kwargs, num_proc=num_proc, desc=desc, ) for k, dataset in self.items() } ) def filter( self, function, with_indices=False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, cache_file_names: Optional[Dict[str, Optional[str]]] = None, writer_batch_size: Optional[int] = 1000, fn_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, desc: Optional[str] = None, ) -> "DatasetDict": """Apply a filter function to all the elements in the table in batches and update the table so that the dataset only includes examples according to the filter function. The transformation is applied to all the datasets of the dataset dictionary. Args: function (`callable`): With one of the following signature: - `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False` - `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False` - `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True` - `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if ``with_indices=True, batched=True` with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`. input_columns (`[Union[str, List[str]]]`, *optional*, defaults to `None`): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True` `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if chaching is enabled): If a cache file storing the current computation from `function` can be identified, use it instead of recomputing. cache_file_names (`[Dict[str, str]]`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. fn_kwargs (`Dict`, *optional*, defaults to `None`): Keyword arguments to be passed to `function` num_proc (`int`, *optional*, defaults to `None`): Number of processes for multiprocessing. By default it doesn't use multiprocessing. desc (`str`, *optional*, defaults to `None`): Meaningful description to be displayed alongside with the progress bar while filtering examples. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.filter(lambda x: x["label"] == 1) DatasetDict({ train: Dataset({ features: ['text', 'label'], num_rows: 4265 }) validation: Dataset({ features: ['text', 'label'], num_rows: 533 }) test: Dataset({ features: ['text', 'label'], num_rows: 533 }) }) ``` """ self._check_values_type() if cache_file_names is None: cache_file_names = {k: None for k in self} return DatasetDict( { k: dataset.filter( function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, keep_in_memory=keep_in_memory, load_from_cache_file=load_from_cache_file, cache_file_name=cache_file_names[k], writer_batch_size=writer_batch_size, fn_kwargs=fn_kwargs, num_proc=num_proc, desc=desc, ) for k, dataset in self.items() } ) def flatten_indices( self, keep_in_memory: bool = False, cache_file_names: Optional[Dict[str, Optional[str]]] = None, writer_batch_size: Optional[int] = 1000, features: Optional[Features] = None, disable_nullable: bool = False, num_proc: Optional[int] = None, new_fingerprint: Optional[str] = None, ) -> "DatasetDict": """Create and cache a new Dataset by flattening the indices mapping. Args: keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. cache_file_names (`Dict[str, str]`, *optional*, default `None`): Provide the name of a path for the cache file. It is used to store the results of the computation instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. features (`Optional[datasets.Features]`, defaults to `None`): Use a specific [`Features`] to store the cache file instead of the automatically generated one. disable_nullable (`bool`, defaults to `False`): Allow null values in the table. num_proc (`int`, optional, default `None`): Max number of processes when generating cache. Already cached shards are loaded sequentially new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments """ self._check_values_type() if cache_file_names is None: cache_file_names = {k: None for k in self} return DatasetDict( { k: dataset.flatten_indices( keep_in_memory=keep_in_memory, cache_file_name=cache_file_names[k], writer_batch_size=writer_batch_size, features=features, disable_nullable=disable_nullable, num_proc=num_proc, new_fingerprint=new_fingerprint, ) for k, dataset in self.items() } ) def sort( self, column_names: Union[str, Sequence[str]], reverse: Union[bool, Sequence[bool]] = False, kind="deprecated", null_placement: str = "at_end", keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, indices_cache_file_names: Optional[Dict[str, Optional[str]]] = None, writer_batch_size: Optional[int] = 1000, ) -> "DatasetDict": """Create a new dataset sorted according to a single or multiple columns. Args: column_names (`Union[str, Sequence[str]]`): Column name(s) to sort by. reverse (`Union[bool, Sequence[bool]]`, defaults to `False`): If `True`, sort by descending order rather than ascending. If a single bool is provided, the value is applied to the sorting of all column names. Otherwise a list of bools with the same length and order as column_names must be provided. kind (`str`, *optional*): Pandas algorithm for sorting selected in `{quicksort, mergesort, heapsort, stable}`, The default is `quicksort`. Note that both `stable` and `mergesort` use timsort under the covers and, in general, the actual implementation will vary with data type. The `mergesort` option is retained for backwards compatibility. <Deprecated version="2.8.0"> `kind` was deprecated in version 2.10.0 and will be removed in 3.0.0. </Deprecated> null_placement (`str`, defaults to `at_end`): Put `None` values at the beginning if `at_start` or `first` or at the end if `at_end` or `last` keep_in_memory (`bool`, defaults to `False`): Keep the sorted indices in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the sorted indices can be identified, use it instead of recomputing. indices_cache_file_names (`[Dict[str, str]]`, *optional*, defaults to `None`): Provide the name of a path for the cache file. It is used to store the indices mapping instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. Higher value gives smaller cache files, lower value consume less temporary memory. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes') >>> ds['train']['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> sorted_ds = ds.sort('label') >>> sorted_ds['train']['label'][:10] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False]) >>> another_sorted_ds['train']['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ``` """ self._check_values_type() if indices_cache_file_names is None: indices_cache_file_names = {k: None for k in self} return DatasetDict( { k: dataset.sort( column_names=column_names, reverse=reverse, kind=kind, null_placement=null_placement, keep_in_memory=keep_in_memory, load_from_cache_file=load_from_cache_file, indices_cache_file_name=indices_cache_file_names[k], writer_batch_size=writer_batch_size, ) for k, dataset in self.items() } ) def shuffle( self, seeds: Optional[Union[int, Dict[str, Optional[int]]]] = None, seed: Optional[int] = None, generators: Optional[Dict[str, np.random.Generator]] = None, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, indices_cache_file_names: Optional[Dict[str, Optional[str]]] = None, writer_batch_size: Optional[int] = 1000, ) -> "DatasetDict": """Create a new Dataset where the rows are shuffled. The transformation is applied to all the datasets of the dataset dictionary. Currently shuffling uses numpy random generators. You can either supply a NumPy BitGenerator to use, or a seed to initiate NumPy's default random generator (PCG64). Args: seeds (`Dict[str, int]` or `int`, *optional*): A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. If an `int` or `array_like[ints]` is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. You can provide one `seed` per dataset in the dataset dictionary. seed (`int`, *optional*): A seed to initialize the default BitGenerator if `generator=None`. Alias for seeds (a `ValueError` is raised if both are provided). generators (`Dict[str, *optional*, np.random.Generator]`): Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy). You have to provide one `generator` per dataset in the dataset dictionary. keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the current computation from `function` can be identified, use it instead of recomputing. indices_cache_file_names (`Dict[str, str]`, *optional*): Provide the name of a path for the cache file. It is used to store the indices mappings instead of the automatically generated cache file name. You have to provide one `cache_file_name` per dataset in the dataset dictionary. writer_batch_size (`int`, defaults to `1000`): Number of rows per write operation for the cache file writer. This value is a good trade-off between memory usage during the processing, and processing speed. Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds["train"]["label"][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # set a seed >>> shuffled_ds = ds.shuffle(seed=42) >>> shuffled_ds["train"]["label"][:10] [0, 1, 0, 1, 0, 0, 0, 0, 0, 0] ``` """ self._check_values_type() if seed is not None and seeds is not None: raise ValueError("Please specify seed or seeds, but not both") seeds = seed if seed is not None else seeds if seeds is None: seeds = {k: None for k in self} elif not isinstance(seeds, dict): seeds = {k: seeds for k in self} if generators is None: generators = {k: None for k in self} if indices_cache_file_names is None: indices_cache_file_names = {k: None for k in self} return DatasetDict( { k: dataset.shuffle( seed=seeds[k], generator=generators[k], keep_in_memory=keep_in_memory, load_from_cache_file=load_from_cache_file, indices_cache_file_name=indices_cache_file_names[k], writer_batch_size=writer_batch_size, ) for k, dataset in self.items() } ) def save_to_disk( self, dataset_dict_path: PathLike, fs="deprecated", max_shard_size: Optional[Union[str, int]] = None, num_shards: Optional[Dict[str, int]] = None, num_proc: Optional[int] = None, storage_options: Optional[dict] = None, ): """ Saves a dataset dict to a filesystem using `fsspec.spec.AbstractFileSystem`. For [`Image`] and [`Audio`] data: All the Image() and Audio() data are stored in the arrow files. If you want to store paths or urls, please use the Value("string") type. Args: dataset_dict_path (`str`): Path (e.g. `dataset/train`) or remote URI (e.g. `s3://my-bucket/dataset/train`) of the dataset dict directory where the dataset dict will be saved to. fs (`fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem where the dataset will be saved to. <Deprecated version="2.8.0"> `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options` </Deprecated> max_shard_size (`int` or `str`, *optional*, defaults to `"500MB"`): The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"50MB"`). num_shards (`Dict[str, int]`, *optional*): Number of shards to write. By default the number of shards depends on `max_shard_size` and `num_proc`. You need to provide the number of shards for each dataset in the dataset dictionary. Use a dictionary to define a different num_shards for each split. <Added version="2.8.0"/> num_proc (`int`, *optional*, default `None`): Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default. <Added version="2.8.0"/> storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.8.0"/> Example: ```python >>> dataset_dict.save_to_disk("path/to/dataset/directory") >>> dataset_dict.save_to_disk("path/to/dataset/directory", max_shard_size="1GB") >>> dataset_dict.save_to_disk("path/to/dataset/directory", num_shards={"train": 1024, "test": 8}) ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.8.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, _, _ = fsspec.get_fs_token_paths(dataset_dict_path, storage_options=storage_options) if num_shards is None: num_shards = {k: None for k in self} elif not isinstance(num_shards, dict): raise ValueError( "Please provide one `num_shards` per dataset in the dataset dictionary, e.g. {{'train': 128, 'test': 4}}" ) fs.makedirs(dataset_dict_path, exist_ok=True) with fs.open(posixpath.join(dataset_dict_path, config.DATASETDICT_JSON_FILENAME), "w", encoding="utf-8") as f: json.dump({"splits": list(self)}, f) for k, dataset in self.items(): dataset.save_to_disk( posixpath.join(dataset_dict_path, k), num_shards=num_shards.get(k), max_shard_size=max_shard_size, num_proc=num_proc, storage_options=storage_options, ) @staticmethod def load_from_disk( dataset_dict_path: PathLike, fs="deprecated", keep_in_memory: Optional[bool] = None, storage_options: Optional[dict] = None, ) -> "DatasetDict": """ Load a dataset that was previously saved using [`save_to_disk`] from a filesystem using `fsspec.spec.AbstractFileSystem`. Args: dataset_dict_path (`str`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3//my-bucket/dataset/train"`) of the dataset dict directory where the dataset dict will be loaded from. fs (`fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem where the dataset will be saved to. <Deprecated version="2.8.0"> `fs` was deprecated in version 2.8.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options` </Deprecated> keep_in_memory (`bool`, defaults to `None`): Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](../cache#improve-performance) section. storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.8.0"/> Returns: [`DatasetDict`] Example: ```py >>> ds = load_from_disk('path/to/dataset/directory') ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.8.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, _, [dataset_dict_path] = fsspec.get_fs_token_paths(dataset_dict_path, storage_options=storage_options) dataset_dict_json_path = posixpath.join(dataset_dict_path, config.DATASETDICT_JSON_FILENAME) dataset_state_json_path = posixpath.join(dataset_dict_path, config.DATASET_STATE_JSON_FILENAME) dataset_info_path = posixpath.join(dataset_dict_path, config.DATASET_INFO_FILENAME) if not fs.isfile(dataset_dict_json_path): if fs.isfile(dataset_info_path) and fs.isfile(dataset_state_json_path): raise FileNotFoundError( f"No such file: '{dataset_dict_json_path}'. Expected to load a `DatasetDict` object, but got a `Dataset`. Please use either `datasets.load_from_disk` or `Dataset.load_from_disk` instead." ) raise FileNotFoundError( f"No such file: '{dataset_dict_json_path}'. Expected to load a `DatasetDict` object, but provided path is not a `DatasetDict`." ) with fs.open(dataset_dict_json_path, "r", encoding="utf-8") as f: splits = json.load(f)["splits"] dataset_dict = DatasetDict() for k in splits: dataset_dict_split_path = posixpath.join(fs.unstrip_protocol(dataset_dict_path), k) dataset_dict[k] = Dataset.load_from_disk( dataset_dict_split_path, keep_in_memory=keep_in_memory, storage_options=storage_options ) return dataset_dict @staticmethod def from_csv( path_or_paths: Dict[str, PathLike], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, **kwargs, ) -> "DatasetDict": """Create [`DatasetDict`] from CSV file(s). Args: path_or_paths (`dict` of path-like): Path(s) of the CSV file(s). features ([`Features`], *optional*): Dataset features. cache_dir (str, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. **kwargs (additional keyword arguments): Keyword arguments to be passed to [`pandas.read_csv`]. Returns: [`DatasetDict`] Example: ```py >>> from datasets import DatasetDict >>> ds = DatasetDict.from_csv({'train': 'path/to/dataset.csv'}) ``` """ # Dynamic import to avoid circular dependency from .io.csv import CsvDatasetReader return CsvDatasetReader( path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs ).read() @staticmethod def from_json( path_or_paths: Dict[str, PathLike], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, **kwargs, ) -> "DatasetDict": """Create [`DatasetDict`] from JSON Lines file(s). Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the JSON Lines file(s). features ([`Features`], *optional*): Dataset features. cache_dir (str, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. **kwargs (additional keyword arguments): Keyword arguments to be passed to [`JsonConfig`]. Returns: [`DatasetDict`] Example: ```py >>> from datasets import DatasetDict >>> ds = DatasetDict.from_json({'train': 'path/to/dataset.json'}) ``` """ # Dynamic import to avoid circular dependency from .io.json import JsonDatasetReader return JsonDatasetReader( path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs ).read() @staticmethod def from_parquet( path_or_paths: Dict[str, PathLike], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, columns: Optional[List[str]] = None, **kwargs, ) -> "DatasetDict": """Create [`DatasetDict`] from Parquet file(s). Args: path_or_paths (`dict` of path-like): Path(s) of the CSV file(s). features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. columns (`List[str]`, *optional*): If not `None`, only these columns will be read from the file. A column name may be a prefix of a nested field, e.g. 'a' will select 'a.b', 'a.c', and 'a.d.e'. **kwargs (additional keyword arguments): Keyword arguments to be passed to [`ParquetConfig`]. Returns: [`DatasetDict`] Example: ```py >>> from datasets import DatasetDict >>> ds = DatasetDict.from_parquet({'train': 'path/to/dataset/parquet'}) ``` """ # Dynamic import to avoid circular dependency from .io.parquet import ParquetDatasetReader return ParquetDatasetReader( path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, columns=columns, **kwargs, ).read() @staticmethod def from_text( path_or_paths: Dict[str, PathLike], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, **kwargs, ) -> "DatasetDict": """Create [`DatasetDict`] from text file(s). Args: path_or_paths (`dict` of path-like): Path(s) of the text file(s). features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. keep_in_memory (`bool`, defaults to `False`): Whether to copy the data in-memory. **kwargs (additional keyword arguments): Keyword arguments to be passed to [`TextConfig`]. Returns: [`DatasetDict`] Example: ```py >>> from datasets import DatasetDict >>> ds = DatasetDict.from_text({'train': 'path/to/dataset.txt'}) ``` """ # Dynamic import to avoid circular dependency from .io.text import TextDatasetReader return TextDatasetReader( path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs ).read() @deprecated() @is_documented_by(Dataset.prepare_for_task) def prepare_for_task(self, task: Union[str, TaskTemplate], id: int = 0) -> "DatasetDict": self._check_values_type() return DatasetDict({k: dataset.prepare_for_task(task=task, id=id) for k, dataset in self.items()}) @is_documented_by(Dataset.align_labels_with_mapping) def align_labels_with_mapping(self, label2id: Dict, label_column: str) -> "DatasetDict": self._check_values_type() return DatasetDict( { k: dataset.align_labels_with_mapping(label2id=label2id, label_column=label_column) for k, dataset in self.items() } ) def push_to_hub( self, repo_id, config_name: str = "default", set_default: Optional[bool] = None, commit_message: Optional[str] = None, commit_description: Optional[str] = None, private: Optional[bool] = False, token: Optional[str] = None, revision: Optional[str] = None, branch="deprecated", create_pr: Optional[bool] = False, max_shard_size: Optional[Union[int, str]] = None, num_shards: Optional[Dict[str, int]] = None, embed_external_files: bool = True, ) -> CommitInfo: """Pushes the [`DatasetDict`] to the hub as a Parquet dataset. The [`DatasetDict`] is pushed using HTTP requests and does not need to have neither git or git-lfs installed. Each dataset split will be pushed independently. The pushed dataset will keep the original split names. The resulting Parquet files are self-contained by default: if your dataset contains [`Image`] or [`Audio`] data, the Parquet files will store the bytes of your images or audio files. You can disable this by setting `embed_external_files` to False. Args: repo_id (`str`): The ID of the repository to push to in the following format: `<user>/<dataset_name>` or `<org>/<dataset_name>`. Also accepts `<dataset_name>`, which will default to the namespace of the logged-in user. config_name (`str`): Configuration name of a dataset. Defaults to "default". set_default (`bool`, *optional*): Whether to set this configuration as the default one. Otherwise, the default configuration is the one named "default". commit_message (`str`, *optional*): Message to commit while pushing. Will default to `"Upload dataset"`. commit_description (`str`, *optional*): Description of the commit that will be created. Additionally, description of the PR if a PR is created (`create_pr` is True). <Added version="2.16.0"/> private (`bool`, *optional*): Whether the dataset repository should be set to private or not. Only affects repository creation: a repository that already exists will not be affected by that parameter. token (`str`, *optional*): An optional authentication token for the Hugging Face Hub. If no token is passed, will default to the token saved locally when logging in with `huggingface-cli login`. Will raise an error if no token is passed and the user is not logged-in. revision (`str`, *optional*): Branch to push the uploaded files to. Defaults to the `"main"` branch. <Added version="2.15.0"/> branch (`str`, *optional*): The git branch on which to push the dataset. This defaults to the default branch as specified in your repository, which defaults to `"main"`. <Deprecated version="2.15.0"> `branch` was deprecated in favor of `revision` in version 2.15.0 and will be removed in 3.0.0. </Deprecated> create_pr (`bool`, *optional*, defaults to `False`): Whether to create a PR with the uploaded files or directly commit. <Added version="2.15.0"/> max_shard_size (`int` or `str`, *optional*, defaults to `"500MB"`): The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit (like `"500MB"` or `"1GB"`). num_shards (`Dict[str, int]`, *optional*): Number of shards to write. By default, the number of shards depends on `max_shard_size`. Use a dictionary to define a different num_shards for each split. <Added version="2.8.0"/> embed_external_files (`bool`, defaults to `True`): Whether to embed file bytes in the shards. In particular, this will do the following before the push for the fields of type: - [`Audio`] and [`Image`] removes local path information and embed file content in the Parquet files. Return: huggingface_hub.CommitInfo Example: ```python >>> dataset_dict.push_to_hub("<organization>/<dataset_id>") >>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True) >>> dataset_dict.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB") >>> dataset_dict.push_to_hub("<organization>/<dataset_id>", num_shards={"train": 1024, "test": 8}) ``` If you want to add a new configuration (or subset) to a dataset (e.g. if the dataset has multiple tasks/versions/languages): ```python >>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en") >>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr") >>> # later >>> english_dataset = load_dataset("<organization>/<dataset_id>", "en") >>> french_dataset = load_dataset("<organization>/<dataset_id>", "fr") ``` """ if num_shards is None: num_shards = {k: None for k in self} elif not isinstance(num_shards, dict): raise ValueError( "Please provide one `num_shards` per dataset in the dataset dictionary, e.g. {{'train': 128, 'test': 4}}" ) if branch != "deprecated": warnings.warn( "'branch' was deprecated in favor of 'revision' in version 2.15.0 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'revision={branch}' instead.", FutureWarning, ) revision = branch self._check_values_type() self._check_values_features() total_uploaded_size = 0 total_dataset_nbytes = 0 info_to_dump: DatasetInfo = next(iter(self.values())).info.copy() info_to_dump.config_name = config_name info_to_dump.splits = SplitDict() for split in self.keys(): if not re.match(_split_re, split): raise ValueError(f"Split name should match '{_split_re}' but got '{split}'.") api = HfApi(endpoint=config.HF_ENDPOINT, token=token) _ = api.create_repo( repo_id, token=token, repo_type="dataset", private=private, exist_ok=True, ) if revision is not None: api.create_branch(repo_id, branch=revision, token=token, repo_type="dataset", exist_ok=True) data_dir = config_name if config_name != "default" else "data" # for backward compatibility additions = [] for split in self.keys(): logger.info(f"Pushing split {split} to the Hub.") # The split=key needs to be removed before merging split_additions, uploaded_size, dataset_nbytes = self[split]._push_parquet_shards_to_hub( repo_id, data_dir=data_dir, split=split, token=token, revision=revision, create_pr=create_pr, max_shard_size=max_shard_size, num_shards=num_shards.get(split), embed_external_files=embed_external_files, ) additions += split_additions total_uploaded_size += uploaded_size total_dataset_nbytes += dataset_nbytes info_to_dump.splits[split] = SplitInfo(str(split), num_bytes=dataset_nbytes, num_examples=len(self[split])) info_to_dump.download_checksums = None info_to_dump.download_size = total_uploaded_size info_to_dump.dataset_size = total_dataset_nbytes info_to_dump.size_in_bytes = total_uploaded_size + total_dataset_nbytes # Check if the repo already has a README.md and/or a dataset_infos.json to update them with the new split info (size and pattern) # and delete old split shards (if they exist) repo_with_dataset_card, repo_with_dataset_infos = False, False repo_splits = [] # use a list to keep the order of the splits deletions = [] repo_files_to_add = [addition.path_in_repo for addition in additions] for repo_file in list_files_info(api, repo_id=repo_id, revision=revision, repo_type="dataset", token=token): if repo_file.rfilename == config.REPOCARD_FILENAME: repo_with_dataset_card = True elif repo_file.rfilename == config.DATASETDICT_INFOS_FILENAME: repo_with_dataset_infos = True elif ( repo_file.rfilename.startswith(tuple(f"{data_dir}/{split}-" for split in self.keys())) and repo_file.rfilename not in repo_files_to_add ): deletions.append(CommitOperationDelete(path_in_repo=repo_file.rfilename)) elif fnmatch.fnmatch( repo_file.rfilename, PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED.replace("{split}", "*") ): repo_split = string_to_dict( repo_file.rfilename, glob_pattern_to_regex(PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED), )["split"] if repo_split not in repo_splits: repo_splits.append(split) # get the info from the README to update them if repo_with_dataset_card: dataset_card_path = api.hf_hub_download( repo_id, config.REPOCARD_FILENAME, repo_type="dataset", revision=revision ) dataset_card = DatasetCard.load(Path(dataset_card_path)) dataset_card_data = dataset_card.data metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card_data) # get the deprecated dataset_infos.json to update them elif repo_with_dataset_infos: dataset_card = None dataset_card_data = DatasetCardData() metadata_configs = MetadataConfigs() else: dataset_card = None dataset_card_data = DatasetCardData() metadata_configs = MetadataConfigs() # create the metadata configs if it was uploaded with push_to_hub before metadata configs existed if not metadata_configs and repo_splits: default_metadata_configs_to_dump = { "data_files": [{"split": split, "path": f"data/{split}-*"} for split in repo_splits] } MetadataConfigs({"default": default_metadata_configs_to_dump}).to_dataset_card_data(dataset_card_data) metadata_config_to_dump = { "data_files": [{"split": split, "path": f"{data_dir}/{split}-*"} for split in self.keys()], } if set_default and config_name != "default": if metadata_configs: default_config_name = metadata_configs.get_default_config_name() if default_config_name == "default": raise ValueError( "There exists a configuration named 'default'. To set a different configuration as default, " "rename the 'default' one first." ) else: _ = metadata_configs[default_config_name].pop("default") metadata_config_to_dump["default"] = True # push to the deprecated dataset_infos.json if repo_with_dataset_infos: dataset_infos_path = api.hf_hub_download( repo_id, config.DATASETDICT_INFOS_FILENAME, repo_type="dataset", revision=revision ) with open(dataset_infos_path, encoding="utf-8") as f: dataset_infos: dict = json.load(f) dataset_infos[config_name] = asdict(info_to_dump) buffer = BytesIO() buffer.write(json.dumps(dataset_infos, indent=4).encode("utf-8")) additions.append( CommitOperationAdd(path_in_repo=config.DATASETDICT_INFOS_FILENAME, path_or_fileobj=buffer) ) # push to README DatasetInfosDict({config_name: info_to_dump}).to_dataset_card_data(dataset_card_data) MetadataConfigs({config_name: metadata_config_to_dump}).to_dataset_card_data(dataset_card_data) dataset_card = DatasetCard(f"---\n{dataset_card_data}\n---\n") if dataset_card is None else dataset_card additions.append( CommitOperationAdd(path_in_repo=config.REPOCARD_FILENAME, path_or_fileobj=str(dataset_card).encode()) ) commit_message = commit_message if commit_message is not None else "Upload dataset" if len(additions) <= config.UPLOADS_MAX_NUMBER_PER_COMMIT: commit_info = api.create_commit( repo_id, operations=additions + deletions, commit_message=commit_message, commit_description=commit_description, token=token, repo_type="dataset", revision=revision, create_pr=create_pr, ) else: logger.info( f"Number of files to upload is larger than {config.UPLOADS_MAX_NUMBER_PER_COMMIT}. Splitting the push into multiple commits." ) num_commits = math.ceil(len(additions) / config.UPLOADS_MAX_NUMBER_PER_COMMIT) for i in range(0, num_commits): operations = additions[ i * config.UPLOADS_MAX_NUMBER_PER_COMMIT : (i + 1) * config.UPLOADS_MAX_NUMBER_PER_COMMIT ] + (deletions if i == 0 else []) commit_info = api.create_commit( repo_id, operations=operations, commit_message=commit_message + f" (part {i:05d}-of-{num_commits:05d})", commit_description=commit_description, token=token, repo_type="dataset", revision=revision, create_pr=create_pr, ) logger.info( f"Commit #{i+1} completed" + (f" (still {num_commits - i - 1} to go)" if num_commits - i - 1 else "") + "." ) return commit_info class IterableDatasetDict(dict): def __repr__(self): repr = "\n".join([f"{k}: {v}" for k, v in self.items()]) repr = re.sub(r"^", " " * 4, repr, 0, re.M) return f"IterableDatasetDict({{\n{repr}\n}})" def with_format( self, type: Optional[str] = None, ) -> "IterableDatasetDict": """ Return a dataset with the specified format. This method only supports the "torch" format for now. The format is set to all the datasets of the dataset dictionary. Args: type (`str`, *optional*, defaults to `None`): If set to "torch", the returned dataset will be a subclass of `torch.utils.data.IterableDataset` to be used in a `DataLoader`. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") >>> def encode(example): ... return tokenizer(examples["text"], truncation=True, padding="max_length") >>> ds = ds.map(encode, batched=True, remove_columns=["text"]) >>> ds = ds.with_format("torch") ``` """ return IterableDatasetDict({k: dataset.with_format(type=type) for k, dataset in self.items()}) def map( self, function: Optional[Callable] = None, with_indices: bool = False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: int = 1000, drop_last_batch: bool = False, remove_columns: Optional[Union[str, List[str]]] = None, fn_kwargs: Optional[dict] = None, ) -> "IterableDatasetDict": """ Apply a function to all the examples in the iterable dataset (individually or in batches) and update them. If your function returns a column that already exists, then it overwrites it. The function is applied on-the-fly on the examples when iterating over the dataset. The transformation is applied to all the datasets of the dataset dictionary. You can specify whether the function should be batched or not with the `batched` parameter: - If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`. - If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is `{"text": ["Hello there !"]}`. - If batched is `True` and `batch_size` is `n` > 1, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. Note that the last batch may have less than `n` examples. A batch is a dictionary, e.g. a batch of `n` examples is `{"text": ["Hello there !"] * n}`. Args: function (`Callable`, *optional*, defaults to `None`): Function applied on-the-fly on the examples when you iterate on the dataset. It must have one of the following signatures: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` - `function(example: Dict[str, Any], idx: int) -> Dict[str, Any]` if `batched=False` and `with_indices=True` - `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False` - `function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]` if `batched=True` and `with_indices=True` For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`. input_columns (`[Union[str, List[str]]]`, *optional*, defaults to `None`): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`. drop_last_batch (`bool`, defaults to `False`): Whether a last batch smaller than the `batch_size` should be dropped instead of being processed by the function. remove_columns (`[List[str]]`, *optional*, defaults to `None`): Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept. fn_kwargs (`Dict`, *optional*, defaults to `None`): Keyword arguments to be passed to `function` Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> def add_prefix(example): ... example["text"] = "Review: " + example["text"] ... return example >>> ds = ds.map(add_prefix) >>> next(iter(ds["train"])) {'label': 1, 'text': 'Review: the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ return IterableDatasetDict( { k: dataset.map( function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, drop_last_batch=drop_last_batch, remove_columns=remove_columns, fn_kwargs=fn_kwargs, ) for k, dataset in self.items() } ) def filter( self, function: Optional[Callable] = None, with_indices=False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, fn_kwargs: Optional[dict] = None, ) -> "IterableDatasetDict": """Apply a filter function to all the elements so that the dataset only includes examples according to the filter function. The filtering is done on-the-fly when iterating over the dataset. The filtering is applied to all the datasets of the dataset dictionary. Args: function (`Callable`): Callable with one of the following signatures: - `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False` - `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False` - `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True` - `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if `with_indices=True, batched=True` If no function is provided, defaults to an always True function: `lambda x: True`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`. input_columns (`str` or `List[str]`, *optional*): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function` batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`. fn_kwargs (`Dict`, *optional*, defaults to `None`): Keyword arguments to be passed to `function` Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds = ds.filter(lambda x: x["label"] == 0) >>> list(ds["train"].take(3)) [{'label': 0, 'text': 'Review: simplistic , silly and tedious .'}, {'label': 0, 'text': "Review: it's so laddish and juvenile , only teenage boys could possibly find it funny ."}, {'label': 0, 'text': 'Review: exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}] ``` """ return IterableDatasetDict( { k: dataset.filter( function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, fn_kwargs=fn_kwargs, ) for k, dataset in self.items() } ) def shuffle( self, seed=None, generator: Optional[np.random.Generator] = None, buffer_size: int = 1000 ) -> "IterableDatasetDict": """ Randomly shuffles the elements of this dataset. The shuffling is applied to all the datasets of the dataset dictionary. This dataset fills a buffer with buffer_size elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required. For instance, if your dataset contains 10,000 elements but `buffer_size` is set to 1000, then `shuffle` will initially select a random element from only the first 1000 elements in the buffer. Once an element is selected, its space in the buffer is replaced by the next (i.e. 1,001-st) element, maintaining the 1000 element buffer. If the dataset is made of several shards, it also does `shuffle` the order of the shards. However if the order has been fixed by using [`~datasets.IterableDataset.skip`] or [`~datasets.IterableDataset.take`] then the order of the shards is kept unchanged. Args: seed (`int`, *optional*, defaults to `None`): Random seed that will be used to shuffle the dataset. It is used to sample from the shuffle buffer and also to shuffle the data shards. generator (`numpy.random.Generator`, *optional*): Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy). buffer_size (`int`, defaults to `1000`): Size of the buffer. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> list(ds["train"].take(3)) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}, {'label': 1, 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}, {'label': 1, 'text': 'effective but too-tepid biopic'}] >>> ds = ds.shuffle(seed=42) >>> list(ds["train"].take(3)) [{'label': 1, 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."}, {'label': 1, 'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'}, {'label': 1, 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}] ``` """ return IterableDatasetDict( { k: dataset.shuffle(seed=seed, generator=generator, buffer_size=buffer_size) for k, dataset in self.items() } ) def rename_column(self, original_column_name: str, new_column_name: str) -> "IterableDatasetDict": """ Rename a column in the dataset, and move the features associated to the original column under the new column name. The renaming is applied to all the datasets of the dataset dictionary. Args: original_column_name (`str`): Name of the column to rename. new_column_name (`str`): New name for the column. Returns: [`IterableDatasetDict`]: A copy of the dataset with a renamed column. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds = ds.rename_column("text", "movie_review") >>> next(iter(ds["train"])) {'label': 1, 'movie_review': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ return IterableDatasetDict( { k: dataset.rename_column(original_column_name=original_column_name, new_column_name=new_column_name) for k, dataset in self.items() } ) def rename_columns(self, column_mapping: Dict[str, str]) -> "IterableDatasetDict": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. The renaming is applied to all the datasets of the dataset dictionary. Args: column_mapping (`Dict[str, str]`): A mapping of columns to rename to their new names. Returns: [`IterableDatasetDict`]: A copy of the dataset with renamed columns Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds = ds.rename_columns({"text": "movie_review", "label": "rating"}) >>> next(iter(ds["train"])) {'movie_review': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'rating': 1} ``` """ return IterableDatasetDict( {k: dataset.rename_columns(column_mapping=column_mapping) for k, dataset in self.items()} ) def remove_columns(self, column_names: Union[str, List[str]]) -> "IterableDatasetDict": """ Remove one or several column(s) in the dataset and the features associated to them. The removal is done on-the-fly on the examples when iterating over the dataset. The removal is applied to all the datasets of the dataset dictionary. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to remove. Returns: [`IterableDatasetDict`]: A copy of the dataset object without the columns to remove. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds = ds.remove_columns("label") >>> next(iter(ds["train"])) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ return IterableDatasetDict({k: dataset.remove_columns(column_names) for k, dataset in self.items()}) def select_columns(self, column_names: Union[str, List[str]]) -> "IterableDatasetDict": """Select one or several column(s) in the dataset and the features associated to them. The selection is done on-the-fly on the examples when iterating over the dataset. The selection is applied to all the datasets of the dataset dictionary. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to keep. Returns: [`IterableDatasetDict`]: A copy of the dataset object with only selected columns. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds = ds.select("text") >>> next(iter(ds["train"])) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ return IterableDatasetDict({k: dataset.select_columns(column_names) for k, dataset in self.items()}) def cast_column(self, column: str, feature: FeatureType) -> "IterableDatasetDict": """Cast column to feature for decoding. The type casting is applied to all the datasets of the dataset dictionary. Args: column (`str`): Column name. feature ([`Feature`]): Target feature. Returns: [`IterableDatasetDict`] Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good'])) >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='string', id=None)} ``` """ return IterableDatasetDict( {k: dataset.cast_column(column=column, feature=feature) for k, dataset in self.items()} ) def cast( self, features: Features, ) -> "IterableDatasetDict": """ Cast the dataset to a new set of features. The type casting is applied to all the datasets of the dataset dictionary. Args: features (`Features`): New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `string` <-> `ClassLabel` you should use [`map`] to update the Dataset. Returns: [`IterableDatasetDict`]: A copy of the dataset with casted features. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", streaming=True) >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds["train"].features.copy() >>> new_features['label'] = ClassLabel(names=['bad', 'good']) >>> new_features['text'] = Value('large_string') >>> ds = ds.cast(new_features) >>> ds["train"].features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='large_string', id=None)} ``` """ return IterableDatasetDict({k: dataset.cast(features=features) for k, dataset in self.items()})
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/combine.py
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal logger = logging.get_logger(__name__) DatasetType = TypeVar("DatasetType", Dataset, IterableDataset) def interleave_datasets( datasets: List[DatasetType], probabilities: Optional[List[float]] = None, seed: Optional[int] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "first_exhausted", ) -> DatasetType: """ Interleave several datasets (sources) into a single dataset. The new dataset is constructed by alternating between the sources to get the examples. You can use this function on a list of [`Dataset`] objects, or on a list of [`IterableDataset`] objects. - If `probabilities` is `None` (default) the new dataset is constructed by cycling between each source to get the examples. - If `probabilities` is not `None`, the new dataset is constructed by getting examples from a random source at a time according to the provided probabilities. The resulting dataset ends when one of the source datasets runs out of examples except when `oversampling` is `True`, in which case, the resulting dataset ends when all datasets have ran out of examples at least one time. Note for iterable datasets: In a distributed setup or in PyTorch DataLoader workers, the stopping strategy is applied per process. Therefore the "first_exhausted" strategy on an sharded iterable dataset can generate less samples in total (up to 1 missing sample per subdataset per worker). Args: datasets (`List[Dataset]` or `List[IterableDataset]`): List of datasets to interleave. probabilities (`List[float]`, *optional*, defaults to `None`): If specified, the new dataset is constructed by sampling examples from one source at a time according to these probabilities. seed (`int`, *optional*, defaults to `None`): The random seed used to choose a source for each example. info ([`DatasetInfo`], *optional*): Dataset information, like description, citation, etc. <Added version="2.4.0"/> split ([`NamedSplit`], *optional*): Name of the dataset split. <Added version="2.4.0"/> stopping_strategy (`str`, defaults to `first_exhausted`): Two strategies are proposed right now, `first_exhausted` and `all_exhausted`. By default, `first_exhausted` is an undersampling strategy, i.e the dataset construction is stopped as soon as one dataset has ran out of samples. If the strategy is `all_exhausted`, we use an oversampling strategy, i.e the dataset construction is stopped as soon as every samples of every dataset has been added at least once. Note that if the strategy is `all_exhausted`, the interleaved dataset size can get enormous: - with no probabilities, the resulting dataset will have `max_length_datasets*nb_dataset` samples. - with given probabilities, the resulting dataset will have more samples if some datasets have really low probability of visiting. Returns: [`Dataset`] or [`IterableDataset`]: Return type depends on the input `datasets` parameter. `Dataset` if the input is a list of `Dataset`, `IterableDataset` if the input is a list of `IterableDataset`. Example: For regular datasets (map-style): ```python >>> from datasets import Dataset, interleave_datasets >>> d1 = Dataset.from_dict({"a": [0, 1, 2]}) >>> d2 = Dataset.from_dict({"a": [10, 11, 12]}) >>> d3 = Dataset.from_dict({"a": [20, 21, 22]}) >>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted") >>> dataset["a"] [10, 0, 11, 1, 2, 20, 12, 10, 0, 1, 2, 21, 0, 11, 1, 2, 0, 1, 12, 2, 10, 0, 22] >>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42) >>> dataset["a"] [10, 0, 11, 1, 2] >>> dataset = interleave_datasets([d1, d2, d3]) >>> dataset["a"] [0, 10, 20, 1, 11, 21, 2, 12, 22] >>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted") >>> dataset["a"] [0, 10, 20, 1, 11, 21, 2, 12, 22] >>> d1 = Dataset.from_dict({"a": [0, 1, 2]}) >>> d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) >>> d3 = Dataset.from_dict({"a": [20, 21, 22, 23, 24]}) >>> dataset = interleave_datasets([d1, d2, d3]) >>> dataset["a"] [0, 10, 20, 1, 11, 21, 2, 12, 22] >>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted") >>> dataset["a"] [0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 23, 1, 10, 24] >>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42) >>> dataset["a"] [10, 0, 11, 1, 2] >>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted") >>> dataset["a"] [10, 0, 11, 1, 2, 20, 12, 13, ..., 0, 1, 2, 0, 24] For datasets in streaming mode (iterable): >>> from datasets import load_dataset, interleave_datasets >>> d1 = load_dataset("oscar", "unshuffled_deduplicated_en", split="train", streaming=True) >>> d2 = load_dataset("oscar", "unshuffled_deduplicated_fr", split="train", streaming=True) >>> dataset = interleave_datasets([d1, d2]) >>> iterator = iter(dataset) >>> next(iterator) {'text': 'Mtendere Village was inspired by the vision...} >>> next(iterator) {'text': "Média de débat d'idées, de culture...} ``` """ from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError("Unable to interleave an empty list of datasets.") for i, dataset in enumerate(datasets): if not isinstance(dataset, (Dataset, IterableDataset)): if isinstance(dataset, (DatasetDict, IterableDatasetDict)): if not dataset: raise ValueError( f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " "is an empty dataset dictionary." ) raise ValueError( f"Dataset at position {i} has at least one split: {list(dataset)}\n" f"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(dataset))}']" ) raise ValueError( f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(dataset).__name__}." ) if i == 0: dataset_type, other_type = ( (Dataset, IterableDataset) if isinstance(dataset, Dataset) else (IterableDataset, Dataset) ) elif not isinstance(dataset, dataset_type): raise ValueError( f"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(f"{stopping_strategy} is not supported. Please enter a valid stopping_strategy.") if dataset_type is Dataset: return _interleave_map_style_datasets( datasets, probabilities, seed, info=info, split=split, stopping_strategy=stopping_strategy ) else: return _interleave_iterable_datasets( datasets, probabilities, seed, info=info, split=split, stopping_strategy=stopping_strategy ) def concatenate_datasets( dsets: List[DatasetType], info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, axis: int = 0, ) -> DatasetType: """ Converts a list of [`Dataset`] with the same schema into a single [`Dataset`]. Args: dsets (`List[datasets.Dataset]`): List of Datasets to concatenate. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`NamedSplit`, *optional*): Name of the dataset split. axis (`{0, 1}`, defaults to `0`): Axis to concatenate over, where `0` means over rows (vertically) and `1` means over columns (horizontally). <Added version="1.6.0"/> Example: ```py >>> ds3 = concatenate_datasets([ds1, ds2]) ``` """ if not dsets: raise ValueError("Unable to concatenate an empty list of datasets.") for i, dataset in enumerate(dsets): if not isinstance(dataset, (Dataset, IterableDataset)): if isinstance(dataset, (DatasetDict, IterableDatasetDict)): if not dataset: raise ValueError( f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " "is an empty dataset dictionary." ) raise ValueError( f"Dataset at position {i} has at least one split: {list(dataset)}\n" f"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(dataset))}']" ) raise ValueError( f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(dataset).__name__}." ) if i == 0: dataset_type, other_type = ( (Dataset, IterableDataset) if isinstance(dataset, Dataset) else (IterableDataset, Dataset) ) elif not isinstance(dataset, dataset_type): raise ValueError( f"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if dataset_type is Dataset: return _concatenate_map_style_datasets(dsets, info=info, split=split, axis=axis) else: return _concatenate_iterable_datasets(dsets, info=info, split=split, axis=axis)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/fingerprint.py
import inspect import os import random import shutil import tempfile import weakref from functools import wraps from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import xxhash from . import config from .naming import INVALID_WINDOWS_CHARACTERS_IN_PATH from .utils._dill import dumps from .utils.deprecation_utils import deprecated from .utils.logging import get_logger if TYPE_CHECKING: from .arrow_dataset import Dataset logger = get_logger(__name__) # Fingerprinting allows to have one deterministic fingerprint per dataset state. # A dataset fingerprint is updated after each transform. # Re-running the same transforms on a dataset in a different session results in the same fingerprint. # This is possible thanks to a custom hashing function that works with most python objects. # Fingerprinting is the main mechanism that enables caching. # The caching mechanism allows to reload an existing cache file if it's already been computed. ################# # Caching ################# _CACHING_ENABLED = True _TEMP_DIR_FOR_TEMP_CACHE_FILES: Optional["_TempCacheDir"] = None _DATASETS_WITH_TABLE_IN_TEMP_DIR: Optional[weakref.WeakSet] = None class _TempCacheDir: """ A temporary directory for storing cached Arrow files with a cleanup that frees references to the Arrow files before deleting the directory itself to avoid permission errors on Windows. """ def __init__(self): self.name = tempfile.mkdtemp(prefix=config.TEMP_CACHE_DIR_PREFIX) self._finalizer = weakref.finalize(self, self._cleanup) def _cleanup(self): for dset in get_datasets_with_cache_file_in_temp_dir(): dset.__del__() if os.path.exists(self.name): try: shutil.rmtree(self.name) except Exception as e: raise OSError( f"An error occured while trying to delete temporary cache directory {self.name}. Please delete it manually." ) from e def cleanup(self): if self._finalizer.detach(): self._cleanup() def maybe_register_dataset_for_temp_dir_deletion(dataset): """ This function registers the datasets that have cache files in _TEMP_DIR_FOR_TEMP_CACHE_FILES in order to properly delete them before deleting the temporary directory. The temporary directory _TEMP_DIR_FOR_TEMP_CACHE_FILES is used when caching is disabled. """ if _TEMP_DIR_FOR_TEMP_CACHE_FILES is None: return global _DATASETS_WITH_TABLE_IN_TEMP_DIR if _DATASETS_WITH_TABLE_IN_TEMP_DIR is None: _DATASETS_WITH_TABLE_IN_TEMP_DIR = weakref.WeakSet() if any( Path(_TEMP_DIR_FOR_TEMP_CACHE_FILES.name) in Path(cache_file["filename"]).parents for cache_file in dataset.cache_files ): _DATASETS_WITH_TABLE_IN_TEMP_DIR.add(dataset) def get_datasets_with_cache_file_in_temp_dir(): return list(_DATASETS_WITH_TABLE_IN_TEMP_DIR) if _DATASETS_WITH_TABLE_IN_TEMP_DIR is not None else [] def enable_caching(): """ When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it's already been computed. Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform. If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled: - cache files are always recreated - cache files are written to a temporary directory that is deleted when session closes - cache files are named using a random hash instead of the dataset fingerprint - use [`~datasets.Dataset.save_to_disk`] to save a transformed dataset or it will be deleted when session closes - caching doesn't affect [`~datasets.load_dataset`]. If you want to regenerate a dataset from scratch you should use the `download_mode` parameter in [`~datasets.load_dataset`]. """ global _CACHING_ENABLED _CACHING_ENABLED = True def disable_caching(): """ When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it's already been computed. Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform. If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled: - cache files are always recreated - cache files are written to a temporary directory that is deleted when session closes - cache files are named using a random hash instead of the dataset fingerprint - use [`~datasets.Dataset.save_to_disk`] to save a transformed dataset or it will be deleted when session closes - caching doesn't affect [`~datasets.load_dataset`]. If you want to regenerate a dataset from scratch you should use the `download_mode` parameter in [`~datasets.load_dataset`]. """ global _CACHING_ENABLED _CACHING_ENABLED = False @deprecated( "Use datasets.enable_caching() or datasets.disable_caching() instead. This function will be removed in a future version of datasets." ) def set_caching_enabled(boolean: bool): """ When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it's already been computed. Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform. If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled: - cache files are always recreated - cache files are written to a temporary directory that is deleted when session closes - cache files are named using a random hash instead of the dataset fingerprint - use :func:`datasets.Dataset.save_to_disk` to save a transformed dataset or it will be deleted when session closes - caching doesn't affect :func:`datasets.load_dataset`. If you want to regenerate a dataset from scratch you should use the ``download_mode`` parameter in :func:`datasets.load_dataset`. """ global _CACHING_ENABLED _CACHING_ENABLED = bool(boolean) def is_caching_enabled() -> bool: """ When applying transforms on a dataset, the data are stored in cache files. The caching mechanism allows to reload an existing cache file if it's already been computed. Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated after each transform. If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets. More precisely, if the caching is disabled: - cache files are always recreated - cache files are written to a temporary directory that is deleted when session closes - cache files are named using a random hash instead of the dataset fingerprint - use [`~datasets.Dataset.save_to_disk`]] to save a transformed dataset or it will be deleted when session closes - caching doesn't affect [`~datasets.load_dataset`]. If you want to regenerate a dataset from scratch you should use the `download_mode` parameter in [`~datasets.load_dataset`]. """ global _CACHING_ENABLED return bool(_CACHING_ENABLED) def get_temporary_cache_files_directory() -> str: """Return a directory that is deleted when session closes.""" global _TEMP_DIR_FOR_TEMP_CACHE_FILES if _TEMP_DIR_FOR_TEMP_CACHE_FILES is None: _TEMP_DIR_FOR_TEMP_CACHE_FILES = _TempCacheDir() return _TEMP_DIR_FOR_TEMP_CACHE_FILES.name ################# # Hashing ################# @deprecated("Use `copyreg.pickle` to register a custom reducer.") def hashregister(*types): def proxy(func): for t in types: Hasher.dispatch[t] = func return func return proxy class Hasher: """Hasher that accepts python objects as inputs.""" dispatch: Dict = {} def __init__(self): self.m = xxhash.xxh64() @classmethod def hash_bytes(cls, value: Union[bytes, List[bytes]]) -> str: value = [value] if isinstance(value, bytes) else value m = xxhash.xxh64() for x in value: m.update(x) return m.hexdigest() @classmethod @deprecated("Use `Hasher.hash` instead.") def hash_default(cls, value: Any) -> str: return cls.hash(value) @classmethod def hash(cls, value: Any) -> str: return cls.hash_bytes(dumps(value)) def update(self, value: Any) -> None: header_for_update = f"=={type(value)}==" value_for_update = self.hash(value) self.m.update(header_for_update.encode("utf8")) self.m.update(value_for_update.encode("utf-8")) def hexdigest(self) -> str: return self.m.hexdigest() ################# # Fingerprinting ################# # we show a warning only once when fingerprinting fails to avoid spam fingerprint_warnings: Dict[str, bool] = {} def generate_fingerprint(dataset) -> str: state = dataset.__dict__ hasher = Hasher() for key in sorted(state): if key == "_fingerprint": continue hasher.update(key) hasher.update(state[key]) # hash data files last modification timestamps as well for cache_file in dataset.cache_files: hasher.update(os.path.getmtime(cache_file["filename"])) return hasher.hexdigest() def generate_random_fingerprint(nbits=64) -> str: return f"{random.getrandbits(nbits):0{nbits//4}x}" def update_fingerprint(fingerprint, transform, transform_args): global fingerprint_warnings hasher = Hasher() hasher.update(fingerprint) try: hasher.update(transform) except: # noqa various errors might raise here from pickle or dill if _CACHING_ENABLED: if not fingerprint_warnings.get("update_fingerprint_transform_hash_failed", False): logger.warning( f"Transform {transform} couldn't be hashed properly, a random hash was used instead. " "Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. " "If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. " "This warning is only showed once. Subsequent hashing failures won't be showed." ) fingerprint_warnings["update_fingerprint_transform_hash_failed"] = True else: logger.info(f"Transform {transform} couldn't be hashed properly, a random hash was used instead.") else: logger.info( f"Transform {transform} couldn't be hashed properly, a random hash was used instead. This doesn't affect caching since it's disabled." ) return generate_random_fingerprint() for key in sorted(transform_args): hasher.update(key) try: hasher.update(transform_args[key]) except: # noqa various errors might raise here from pickle or dill if _CACHING_ENABLED: if not fingerprint_warnings.get("update_fingerprint_transform_hash_failed", False): logger.warning( f"Parameter '{key}'={transform_args[key]} of the transform {transform} couldn't be hashed properly, a random hash was used instead. " "Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. " "If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. " "This warning is only showed once. Subsequent hashing failures won't be showed." ) fingerprint_warnings["update_fingerprint_transform_hash_failed"] = True else: logger.info( f"Parameter '{key}'={transform_args[key]} of the transform {transform} couldn't be hashed properly, a random hash was used instead." ) else: logger.info( f"Parameter '{key}'={transform_args[key]} of the transform {transform} couldn't be hashed properly, a random hash was used instead. This doesn't affect caching since it's disabled." ) return generate_random_fingerprint() return hasher.hexdigest() def validate_fingerprint(fingerprint: str, max_length=64): """ Make sure the fingerprint is a non-empty string that is not longer that max_length=64 by default, so that the fingerprint can be used to name cache files without issues. """ if not isinstance(fingerprint, str) or not fingerprint: raise ValueError(f"Invalid fingerprint '{fingerprint}': it should be a non-empty string.") for invalid_char in INVALID_WINDOWS_CHARACTERS_IN_PATH: if invalid_char in fingerprint: raise ValueError( f"Invalid fingerprint. Bad characters from black list '{INVALID_WINDOWS_CHARACTERS_IN_PATH}' found in '{fingerprint}'. " f"They could create issues when creating cache files." ) if len(fingerprint) > max_length: raise ValueError( f"Invalid fingerprint. Maximum lenth is {max_length} but '{fingerprint}' has length {len(fingerprint)}." "It could create issues when creating cache files." ) def format_transform_for_fingerprint(func: Callable, version: Optional[str] = None) -> str: """ Format a transform to the format that will be used to update the fingerprint. """ transform = f"{func.__module__}.{func.__qualname__}" if version is not None: transform += f"@{version}" return transform def format_kwargs_for_fingerprint( func: Callable, args: Tuple, kwargs: Dict[str, Any], use_kwargs: Optional[List[str]] = None, ignore_kwargs: Optional[List[str]] = None, randomized_function: bool = False, ) -> Dict[str, Any]: """ Format the kwargs of a transform to the format that will be used to update the fingerprint. """ kwargs_for_fingerprint = kwargs.copy() if args: params = [p.name for p in inspect.signature(func).parameters.values() if p != p.VAR_KEYWORD] args = args[1:] # assume the first argument is the dataset params = params[1:] kwargs_for_fingerprint.update(zip(params, args)) else: del kwargs_for_fingerprint[ next(iter(inspect.signature(func).parameters)) ] # assume the first key is the dataset # keep the right kwargs to be hashed to generate the fingerprint if use_kwargs: kwargs_for_fingerprint = {k: v for k, v in kwargs_for_fingerprint.items() if k in use_kwargs} if ignore_kwargs: kwargs_for_fingerprint = {k: v for k, v in kwargs_for_fingerprint.items() if k not in ignore_kwargs} if randomized_function: # randomized functions have `seed` and `generator` parameters if kwargs_for_fingerprint.get("seed") is None and kwargs_for_fingerprint.get("generator") is None: _, seed, pos, *_ = np.random.get_state() seed = seed[pos] if pos < 624 else seed[0] kwargs_for_fingerprint["generator"] = np.random.default_rng(seed) # remove kwargs that are the default values default_values = { p.name: p.default for p in inspect.signature(func).parameters.values() if p.default != inspect._empty } for default_varname, default_value in default_values.items(): if default_varname in kwargs_for_fingerprint and kwargs_for_fingerprint[default_varname] == default_value: kwargs_for_fingerprint.pop(default_varname) return kwargs_for_fingerprint def fingerprint_transform( inplace: bool, use_kwargs: Optional[List[str]] = None, ignore_kwargs: Optional[List[str]] = None, fingerprint_names: Optional[List[str]] = None, randomized_function: bool = False, version: Optional[str] = None, ): """ Wrapper for dataset transforms to update the dataset fingerprint using ``update_fingerprint`` Args: inplace (:obj:`bool`): If inplace is True, the fingerprint of the dataset is updated inplace. Otherwise, a parameter "new_fingerprint" is passed to the wrapped method that should take care of setting the fingerprint of the returned Dataset. use_kwargs (:obj:`List[str]`, optional): optional white list of argument names to take into account to update the fingerprint to the wrapped method that should take care of setting the fingerprint of the returned Dataset. By default all the arguments are used. ignore_kwargs (:obj:`List[str]`, optional): optional black list of argument names to take into account to update the fingerprint. Note that ignore_kwargs prevails on use_kwargs. fingerprint_names (:obj:`List[str]`, optional, defaults to ["new_fingerprint"]): If the dataset transforms is not inplace and returns a DatasetDict, then it can require several fingerprints (one per dataset in the DatasetDict). By specifying fingerprint_names, one fingerprint named after each element of fingerprint_names is going to be passed. randomized_function (:obj:`bool`, defaults to False): If the dataset transform is random and has optional parameters "seed" and "generator", then you can set randomized_function to True. This way, even if users set "seed" and "generator" to None, then the fingerprint is going to be randomly generated depending on numpy's current state. In this case, the generator is set to np.random.default_rng(np.random.get_state()[1][0]). version (:obj:`str`, optional): version of the transform. The version is taken into account when computing the fingerprint. If a datase transform changes (or at least if the output data that are cached changes), then one should increase the version. If the version stays the same, then old cached data could be reused that are not compatible with the new transform. It should be in the format "MAJOR.MINOR.PATCH". """ if use_kwargs is not None and not isinstance(use_kwargs, list): raise ValueError(f"use_kwargs is supposed to be a list, not {type(use_kwargs)}") if ignore_kwargs is not None and not isinstance(ignore_kwargs, list): raise ValueError(f"ignore_kwargs is supposed to be a list, not {type(use_kwargs)}") if inplace and fingerprint_names: raise ValueError("fingerprint_names are only used when inplace is False") fingerprint_names = fingerprint_names if fingerprint_names is not None else ["new_fingerprint"] def _fingerprint(func): if not inplace and not all(name in func.__code__.co_varnames for name in fingerprint_names): raise ValueError(f"function {func} is missing parameters {fingerprint_names} in signature") if randomized_function: # randomized function have seed and generator parameters if "seed" not in func.__code__.co_varnames: raise ValueError(f"'seed' must be in {func}'s signature") if "generator" not in func.__code__.co_varnames: raise ValueError(f"'generator' must be in {func}'s signature") # this call has to be outside the wrapper or since __qualname__ changes in multiprocessing transform = format_transform_for_fingerprint(func, version=version) @wraps(func) def wrapper(*args, **kwargs): kwargs_for_fingerprint = format_kwargs_for_fingerprint( func, args, kwargs, use_kwargs=use_kwargs, ignore_kwargs=ignore_kwargs, randomized_function=randomized_function, ) if args: dataset: Dataset = args[0] args = args[1:] else: dataset: Dataset = kwargs.pop(next(iter(inspect.signature(func).parameters))) # compute new_fingerprint and add it to the args of not in-place transforms if inplace: new_fingerprint = update_fingerprint(dataset._fingerprint, transform, kwargs_for_fingerprint) else: for fingerprint_name in fingerprint_names: # transforms like `train_test_split` have several hashes if kwargs.get(fingerprint_name) is None: kwargs_for_fingerprint["fingerprint_name"] = fingerprint_name kwargs[fingerprint_name] = update_fingerprint( dataset._fingerprint, transform, kwargs_for_fingerprint ) else: validate_fingerprint(kwargs[fingerprint_name]) # Call actual function out = func(dataset, *args, **kwargs) # Update fingerprint of in-place transforms + update in-place history of transforms if inplace: # update after calling func so that the fingerprint doesn't change if the function fails dataset._fingerprint = new_fingerprint return out wrapper._decorator_name_ = "fingerprint" return wrapper return _fingerprint
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/data_files.py
import os import re from functools import partial from glob import has_magic from pathlib import Path, PurePath from typing import Callable, Dict, List, Optional, Set, Tuple, Union import huggingface_hub from fsspec import get_fs_token_paths from fsspec.implementations.http import HTTPFileSystem from huggingface_hub import HfFileSystem from packaging import version from tqdm.contrib.concurrent import thread_map from . import config from .download import DownloadConfig from .download.streaming_download_manager import _prepare_path_and_storage_options, xbasename, xjoin from .splits import Split from .utils import logging from .utils import tqdm as hf_tqdm from .utils.file_utils import is_local_path, is_relative_path from .utils.py_utils import glob_pattern_to_regex, string_to_dict SANITIZED_DEFAULT_SPLIT = str(Split.TRAIN) logger = logging.get_logger(__name__) class Url(str): pass class EmptyDatasetError(FileNotFoundError): pass SPLIT_PATTERN_SHARDED = "data/{split}-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*" SPLIT_KEYWORDS = { Split.TRAIN: ["train", "training"], Split.VALIDATION: ["validation", "valid", "dev", "val"], Split.TEST: ["test", "testing", "eval", "evaluation"], } NON_WORDS_CHARS = "-._ 0-9" if config.FSSPEC_VERSION < version.parse("2023.9.0"): KEYWORDS_IN_PATH_NAME_BASE_PATTERNS = ["{keyword}[{sep}/]**", "**[{sep}/]{keyword}[{sep}/]**"] else: KEYWORDS_IN_PATH_NAME_BASE_PATTERNS = ["{keyword}[{sep}/]**", "**/*[{sep}/]{keyword}[{sep}/]**"] DEFAULT_SPLITS = [Split.TRAIN, Split.VALIDATION, Split.TEST] DEFAULT_PATTERNS_SPLIT_IN_PATH_NAME = { split: [ pattern.format(keyword=keyword, sep=NON_WORDS_CHARS) for keyword in SPLIT_KEYWORDS[split] for pattern in KEYWORDS_IN_PATH_NAME_BASE_PATTERNS ] for split in DEFAULT_SPLITS } DEFAULT_PATTERNS_ALL = { Split.TRAIN: ["**"], } ALL_SPLIT_PATTERNS = [SPLIT_PATTERN_SHARDED] ALL_DEFAULT_PATTERNS = [ DEFAULT_PATTERNS_SPLIT_IN_PATH_NAME, DEFAULT_PATTERNS_ALL, ] if config.FSSPEC_VERSION < version.parse("2023.9.0"): METADATA_PATTERNS = [ "metadata.csv", "**/metadata.csv", "metadata.jsonl", "**/metadata.jsonl", ] # metadata file for ImageFolder and AudioFolder else: METADATA_PATTERNS = [ "**/metadata.csv", "**/metadata.jsonl", ] # metadata file for ImageFolder and AudioFolder WILDCARD_CHARACTERS = "*[]" FILES_TO_IGNORE = [ "README.md", "config.json", "dataset_info.json", "dataset_infos.json", "dummy_data.zip", "dataset_dict.json", ] def contains_wildcards(pattern: str) -> bool: return any(wilcard_character in pattern for wilcard_character in WILDCARD_CHARACTERS) def sanitize_patterns(patterns: Union[Dict, List, str]) -> Dict[str, Union[List[str], "DataFilesList"]]: """ Take the data_files patterns from the user, and format them into a dictionary. Each key is the name of the split, and each value is a list of data files patterns (paths or urls). The default split is "train". Returns: patterns: dictionary of split_name -> list of patterns """ if isinstance(patterns, dict): return {str(key): value if isinstance(value, list) else [value] for key, value in patterns.items()} elif isinstance(patterns, str): return {SANITIZED_DEFAULT_SPLIT: [patterns]} elif isinstance(patterns, list): if any(isinstance(pattern, dict) for pattern in patterns): for pattern in patterns: if not ( isinstance(pattern, dict) and len(pattern) == 2 and "split" in pattern and isinstance(pattern.get("path"), (str, list)) ): raise ValueError( f"Expected each split to have a 'path' key which can be a string or a list of strings, but got {pattern}" ) splits = [pattern["split"] for pattern in patterns] if len(set(splits)) != len(splits): raise ValueError(f"Some splits are duplicated in data_files: {splits}") return { str(pattern["split"]): pattern["path"] if isinstance(pattern["path"], list) else [pattern["path"]] for pattern in patterns } else: return {SANITIZED_DEFAULT_SPLIT: patterns} else: return sanitize_patterns(list(patterns)) def _is_inside_unrequested_special_dir(matched_rel_path: str, pattern: str) -> bool: """ When a path matches a pattern, we additionnally check if it's inside a special directory we ignore by default (if it starts with a double underscore). Users can still explicitly request a filepath inside such a directory if "__pycache__" is mentioned explicitly in the requested pattern. Some examples: base directory: ./ └── __pycache__ └── b.txt >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "**") True >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "*/b.txt") True >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "__pycache__/*") False >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "__*/*") False """ # We just need to check if every special directories from the path is present explicly in the pattern. # Since we assume that the path matches the pattern, it's equivalent to counting that both # the parent path and the parent pattern have the same number of special directories. data_dirs_to_ignore_in_path = [part for part in PurePath(matched_rel_path).parent.parts if part.startswith("__")] data_dirs_to_ignore_in_pattern = [part for part in PurePath(pattern).parent.parts if part.startswith("__")] return len(data_dirs_to_ignore_in_path) != len(data_dirs_to_ignore_in_pattern) def _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(matched_rel_path: str, pattern: str) -> bool: """ When a path matches a pattern, we additionnally check if it's a hidden file or if it's inside a hidden directory we ignore by default, i.e. if the file name or a parent directory name starts with a dot. Users can still explicitly request a filepath that is hidden or is inside a hidden directory if the hidden part is mentioned explicitly in the requested pattern. Some examples: base directory: ./ └── .hidden_file.txt >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_file.txt", "**") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_file.txt", ".*") False base directory: ./ └── .hidden_dir └── a.txt >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", "**") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", ".*/*") False >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", ".hidden_dir/*") False base directory: ./ └── .hidden_dir └── .hidden_file.txt >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", "**") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".*/*") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".*/.*") False >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".hidden_dir/*") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".hidden_dir/.*") False """ # We just need to check if every hidden part from the path is present explicly in the pattern. # Since we assume that the path matches the pattern, it's equivalent to counting that both # the path and the pattern have the same number of hidden parts. hidden_directories_in_path = [ part for part in PurePath(matched_rel_path).parts if part.startswith(".") and not set(part) == {"."} ] hidden_directories_in_pattern = [ part for part in PurePath(pattern).parts if part.startswith(".") and not set(part) == {"."} ] return len(hidden_directories_in_path) != len(hidden_directories_in_pattern) def _get_data_files_patterns(pattern_resolver: Callable[[str], List[str]]) -> Dict[str, List[str]]: """ Get the default pattern from a directory or repository by testing all the supported patterns. The first patterns to return a non-empty list of data files is returned. In order, it first tests if SPLIT_PATTERN_SHARDED works, otherwise it tests the patterns in ALL_DEFAULT_PATTERNS. """ # first check the split patterns like data/{split}-00000-of-00001.parquet for split_pattern in ALL_SPLIT_PATTERNS: pattern = split_pattern.replace("{split}", "*") try: data_files = pattern_resolver(pattern) except FileNotFoundError: continue if len(data_files) > 0: splits: Set[str] = { string_to_dict(xbasename(p), glob_pattern_to_regex(xbasename(split_pattern)))["split"] for p in data_files } sorted_splits = [str(split) for split in DEFAULT_SPLITS if split in splits] + sorted( splits - set(DEFAULT_SPLITS) ) return {split: [split_pattern.format(split=split)] for split in sorted_splits} # then check the default patterns based on train/valid/test splits for patterns_dict in ALL_DEFAULT_PATTERNS: non_empty_splits = [] for split, patterns in patterns_dict.items(): for pattern in patterns: try: data_files = pattern_resolver(pattern) except FileNotFoundError: continue if len(data_files) > 0: non_empty_splits.append(split) break if non_empty_splits: return {split: patterns_dict[split] for split in non_empty_splits} raise FileNotFoundError(f"Couldn't resolve pattern {pattern} with resolver {pattern_resolver}") def _get_metadata_files_patterns(pattern_resolver: Callable[[str], List[str]]) -> List[str]: """ Get the supported metadata patterns from a directory or repository. """ non_empty_patterns = [] for pattern in METADATA_PATTERNS: try: metadata_files = pattern_resolver(pattern) if len(metadata_files) > 0: non_empty_patterns.append(pattern) except FileNotFoundError: pass if non_empty_patterns: return non_empty_patterns raise FileNotFoundError(f"Couldn't resolve pattern {pattern} with resolver {pattern_resolver}") def resolve_pattern( pattern: str, base_path: str, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> List[str]: """ Resolve the paths and URLs of the data files from the pattern passed by the user. You can use patterns to resolve multiple local files. Here are a few examples: - *.csv to match all the CSV files at the first level - **.csv to match all the CSV files at any level - data/* to match all the files inside "data" - data/** to match all the files inside "data" and its subdirectories The patterns are resolved using the fsspec glob. glob.glob, Path.glob, Path.match or fnmatch do not support ** with a prefix/suffix other than a forward slash /. For instance, this means **.json is the same as *.json. On the contrary, the fsspec glob has no limits regarding the ** prefix/suffix, resulting in **.json being equivalent to **/*.json. More generally: - '*' matches any character except a forward-slash (to match just the file or directory name) - '**' matches any character including a forward-slash / Hidden files and directories (i.e. whose names start with a dot) are ignored, unless they are explicitly requested. The same applies to special directories that start with a double underscore like "__pycache__". You can still include one if the pattern explicilty mentions it: - to include a hidden file: "*/.hidden.txt" or "*/.*" - to include a hidden directory: ".hidden/*" or ".*/*" - to include a special directory: "__special__/*" or "__*/*" Example:: >>> from datasets.data_files import resolve_pattern >>> base_path = "." >>> resolve_pattern("docs/**/*.py", base_path) [/Users/mariosasko/Desktop/projects/datasets/docs/source/_config.py'] Args: pattern (str): Unix pattern or paths or URLs of the data files to resolve. The paths can be absolute or relative to base_path. Remote filesystems using fsspec are supported, e.g. with the hf:// protocol. base_path (str): Base path to use when resolving relative paths. allowed_extensions (Optional[list], optional): White-list of file extensions to use. Defaults to None (all extensions). For example: allowed_extensions=[".csv", ".json", ".txt", ".parquet"] Returns: List[str]: List of paths or URLs to the local or remote files that match the patterns. """ if is_relative_path(pattern): pattern = xjoin(base_path, pattern) elif is_local_path(pattern): base_path = os.path.splitdrive(pattern)[0] + os.sep else: base_path = "" pattern, storage_options = _prepare_path_and_storage_options(pattern, download_config=download_config) fs, _, _ = get_fs_token_paths(pattern, storage_options=storage_options) fs_base_path = base_path.split("::")[0].split("://")[-1] or fs.root_marker fs_pattern = pattern.split("::")[0].split("://")[-1] files_to_ignore = set(FILES_TO_IGNORE) - {xbasename(pattern)} protocol = fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0] protocol_prefix = protocol + "://" if protocol != "file" else "" glob_kwargs = {} if protocol == "hf" and config.HF_HUB_VERSION >= version.parse("0.20.0"): # 10 times faster glob with detail=True (ignores costly info like lastCommit) glob_kwargs["expand_info"] = False matched_paths = [ filepath if filepath.startswith(protocol_prefix) else protocol_prefix + filepath for filepath, info in fs.glob(pattern, detail=True, **glob_kwargs).items() if info["type"] == "file" and (xbasename(filepath) not in files_to_ignore) and not _is_inside_unrequested_special_dir( os.path.relpath(filepath, fs_base_path), os.path.relpath(fs_pattern, fs_base_path) ) and not _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir( os.path.relpath(filepath, fs_base_path), os.path.relpath(fs_pattern, fs_base_path) ) ] # ignore .ipynb and __pycache__, but keep /../ if allowed_extensions is not None: out = [ filepath for filepath in matched_paths if any("." + suffix in allowed_extensions for suffix in xbasename(filepath).split(".")[1:]) ] if len(out) < len(matched_paths): invalid_matched_files = list(set(matched_paths) - set(out)) logger.info( f"Some files matched the pattern '{pattern}' but don't have valid data file extensions: {invalid_matched_files}" ) else: out = matched_paths if not out: error_msg = f"Unable to find '{pattern}'" if allowed_extensions is not None: error_msg += f" with any supported extension {list(allowed_extensions)}" raise FileNotFoundError(error_msg) return out def get_data_patterns(base_path: str, download_config: Optional[DownloadConfig] = None) -> Dict[str, List[str]]: """ Get the default pattern from a directory testing all the supported patterns. The first patterns to return a non-empty list of data files is returned. Some examples of supported patterns: Input: my_dataset_repository/ ├── README.md └── dataset.csv Output: {"train": ["**"]} Input: my_dataset_repository/ ├── README.md ├── train.csv └── test.csv my_dataset_repository/ ├── README.md └── data/ ├── train.csv └── test.csv my_dataset_repository/ ├── README.md ├── train_0.csv ├── train_1.csv ├── train_2.csv ├── train_3.csv ├── test_0.csv └── test_1.csv Output: {'train': ['train[-._ 0-9/]**', '**/*[-._ 0-9/]train[-._ 0-9/]**', 'training[-._ 0-9/]**', '**/*[-._ 0-9/]training[-._ 0-9/]**'], 'test': ['test[-._ 0-9/]**', '**/*[-._ 0-9/]test[-._ 0-9/]**', 'testing[-._ 0-9/]**', '**/*[-._ 0-9/]testing[-._ 0-9/]**', ...]} Input: my_dataset_repository/ ├── README.md └── data/ ├── train/ │ ├── shard_0.csv │ ├── shard_1.csv │ ├── shard_2.csv │ └── shard_3.csv └── test/ ├── shard_0.csv └── shard_1.csv Output: {'train': ['train[-._ 0-9/]**', '**/*[-._ 0-9/]train[-._ 0-9/]**', 'training[-._ 0-9/]**', '**/*[-._ 0-9/]training[-._ 0-9/]**'], 'test': ['test[-._ 0-9/]**', '**/*[-._ 0-9/]test[-._ 0-9/]**', 'testing[-._ 0-9/]**', '**/*[-._ 0-9/]testing[-._ 0-9/]**', ...]} Input: my_dataset_repository/ ├── README.md └── data/ ├── train-00000-of-00003.csv ├── train-00001-of-00003.csv ├── train-00002-of-00003.csv ├── test-00000-of-00001.csv ├── random-00000-of-00003.csv ├── random-00001-of-00003.csv └── random-00002-of-00003.csv Output: {'train': ['data/train-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*'], 'test': ['data/test-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*'], 'random': ['data/random-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*']} In order, it first tests if SPLIT_PATTERN_SHARDED works, otherwise it tests the patterns in ALL_DEFAULT_PATTERNS. """ resolver = partial(resolve_pattern, base_path=base_path, download_config=download_config) try: return _get_data_files_patterns(resolver) except FileNotFoundError: raise EmptyDatasetError(f"The directory at {base_path} doesn't contain any data files") from None def get_metadata_patterns( base_path: str, download_config: Optional[DownloadConfig] = None, ) -> List[str]: """ Get the supported metadata patterns from a local directory. """ resolver = partial(resolve_pattern, base_path=base_path, download_config=download_config) try: return _get_metadata_files_patterns(resolver) except FileNotFoundError: raise FileNotFoundError(f"The directory at {base_path} doesn't contain any metadata file") from None def _get_single_origin_metadata( data_file: str, download_config: Optional[DownloadConfig] = None, ) -> Tuple[str]: data_file, storage_options = _prepare_path_and_storage_options(data_file, download_config=download_config) fs, _, _ = get_fs_token_paths(data_file, storage_options=storage_options) if isinstance(fs, HfFileSystem): resolved_path = fs.resolve_path(data_file) return (resolved_path.repo_id, resolved_path.revision) elif isinstance(fs, HTTPFileSystem) and data_file.startswith(config.HF_ENDPOINT): hffs = HfFileSystem(endpoint=config.HF_ENDPOINT, token=download_config.token) data_file = "hf://" + data_file[len(config.HF_ENDPOINT) + 1 :].replace("/resolve/", "@", 1) resolved_path = hffs.resolve_path(data_file) return (resolved_path.repo_id, resolved_path.revision) info = fs.info(data_file) # s3fs uses "ETag", gcsfs uses "etag", and for local we simply check mtime for key in ["ETag", "etag", "mtime"]: if key in info: return (str(info[key]),) return () def _get_origin_metadata( data_files: List[str], max_workers=64, download_config: Optional[DownloadConfig] = None, ) -> Tuple[str]: return thread_map( partial(_get_single_origin_metadata, download_config=download_config), data_files, max_workers=max_workers, tqdm_class=hf_tqdm, desc="Resolving data files", disable=len(data_files) <= 16, ) class DataFilesList(List[str]): """ List of data files (absolute local paths or URLs). It has two construction methods given the user's data files patterns : - ``from_hf_repo``: resolve patterns inside a dataset repository - ``from_local_or_remote``: resolve patterns from a local path Moreover DataFilesList has an additional attribute ``origin_metadata``. It can store: - the last modified time of local files - ETag of remote files - commit sha of a dataset repository Thanks to this additional attribute, it is possible to hash the list and get a different hash if and only if at least one file changed. This is useful for caching Dataset objects that are obtained from a list of data files. """ def __init__(self, data_files: List[str], origin_metadata: List[Tuple[str]]): super().__init__(data_files) self.origin_metadata = origin_metadata def __add__(self, other): return DataFilesList([*self, *other], self.origin_metadata + other.origin_metadata) @classmethod def from_hf_repo( cls, patterns: List[str], dataset_info: huggingface_hub.hf_api.DatasetInfo, base_path: Optional[str] = None, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = f"hf://datasets/{dataset_info.id}@{dataset_info.sha}/{base_path or ''}".rstrip("/") return cls.from_patterns( patterns, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config ) @classmethod def from_local_or_remote( cls, patterns: List[str], base_path: Optional[str] = None, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = base_path if base_path is not None else Path().resolve().as_posix() return cls.from_patterns( patterns, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config ) @classmethod def from_patterns( cls, patterns: List[str], base_path: Optional[str] = None, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = base_path if base_path is not None else Path().resolve().as_posix() data_files = [] for pattern in patterns: try: data_files.extend( resolve_pattern( pattern, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) except FileNotFoundError: if not has_magic(pattern): raise origin_metadata = _get_origin_metadata(data_files, download_config=download_config) return cls(data_files, origin_metadata) def filter_extensions(self, extensions: List[str]) -> "DataFilesList": pattern = "|".join("\\" + ext for ext in extensions) pattern = re.compile(f".*({pattern})(\\..+)?$") return DataFilesList( [data_file for data_file in self if pattern.match(data_file)], origin_metadata=self.origin_metadata, ) class DataFilesDict(Dict[str, DataFilesList]): """ Dict of split_name -> list of data files (absolute local paths or URLs). It has two construction methods given the user's data files patterns : - ``from_hf_repo``: resolve patterns inside a dataset repository - ``from_local_or_remote``: resolve patterns from a local path Moreover each list is a DataFilesList. It is possible to hash the dictionary and get a different hash if and only if at least one file changed. For more info, see ``DataFilesList``. This is useful for caching Dataset objects that are obtained from a list of data files. Changing the order of the keys of this dictionary also doesn't change its hash. """ @classmethod def from_local_or_remote( cls, patterns: Dict[str, Union[List[str], DataFilesList]], base_path: Optional[str] = None, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( DataFilesList.from_local_or_remote( patterns_for_key, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) if not isinstance(patterns_for_key, DataFilesList) else patterns_for_key ) return out @classmethod def from_hf_repo( cls, patterns: Dict[str, Union[List[str], DataFilesList]], dataset_info: huggingface_hub.hf_api.DatasetInfo, base_path: Optional[str] = None, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( DataFilesList.from_hf_repo( patterns_for_key, dataset_info=dataset_info, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) if not isinstance(patterns_for_key, DataFilesList) else patterns_for_key ) return out @classmethod def from_patterns( cls, patterns: Dict[str, Union[List[str], DataFilesList]], base_path: Optional[str] = None, allowed_extensions: Optional[List[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( DataFilesList.from_patterns( patterns_for_key, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) if not isinstance(patterns_for_key, DataFilesList) else patterns_for_key ) return out def filter_extensions(self, extensions: List[str]) -> "DataFilesDict": out = type(self)() for key, data_files_list in self.items(): out[key] = data_files_list.filter_extensions(extensions) return out class DataFilesPatternsList(List[str]): """ List of data files patterns (absolute local paths or URLs). For each pattern there should also be a list of allowed extensions to keep, or a None ot keep all the files for the pattern. """ def __init__( self, patterns: List[str], allowed_extensions: List[Optional[List[str]]], ): super().__init__(patterns) self.allowed_extensions = allowed_extensions def __add__(self, other): return DataFilesList([*self, *other], self.allowed_extensions + other.allowed_extensions) @classmethod def from_patterns( cls, patterns: List[str], allowed_extensions: Optional[List[str]] = None ) -> "DataFilesPatternsDict": return cls(patterns, [allowed_extensions] * len(patterns)) def resolve( self, base_path: str, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = base_path if base_path is not None else Path().resolve().as_posix() data_files = [] for pattern, allowed_extensions in zip(self, self.allowed_extensions): try: data_files.extend( resolve_pattern( pattern, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) except FileNotFoundError: if not has_magic(pattern): raise origin_metadata = _get_origin_metadata(data_files, download_config=download_config) return DataFilesList(data_files, origin_metadata) def filter_extensions(self, extensions: List[str]) -> "DataFilesList": return DataFilesPatternsList( self, [allowed_extensions + extensions for allowed_extensions in self.allowed_extensions] ) class DataFilesPatternsDict(Dict[str, DataFilesPatternsList]): """ Dict of split_name -> list of data files patterns (absolute local paths or URLs). """ @classmethod def from_patterns( cls, patterns: Dict[str, List[str]], allowed_extensions: Optional[List[str]] = None ) -> "DataFilesPatternsDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( DataFilesPatternsList.from_patterns( patterns_for_key, allowed_extensions=allowed_extensions, ) if not isinstance(patterns_for_key, DataFilesPatternsList) else patterns_for_key ) return out def resolve( self, base_path: str, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = DataFilesDict() for key, data_files_patterns_list in self.items(): out[key] = data_files_patterns_list.resolve(base_path, download_config) return out def filter_extensions(self, extensions: List[str]) -> "DataFilesPatternsDict": out = type(self)() for key, data_files_patterns_list in self.items(): out[key] = data_files_patterns_list.filter_extensions(extensions) return out
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/search.py
import importlib.util import os import tempfile from pathlib import PurePath from typing import TYPE_CHECKING, Dict, List, NamedTuple, Optional, Union import fsspec import numpy as np from .utils import logging from .utils import tqdm as hf_tqdm if TYPE_CHECKING: from .arrow_dataset import Dataset # noqa: F401 try: from elasticsearch import Elasticsearch # noqa: F401 except ImportError: pass try: import faiss # noqa: F401 except ImportError: pass _has_elasticsearch = importlib.util.find_spec("elasticsearch") is not None _has_faiss = importlib.util.find_spec("faiss") is not None logger = logging.get_logger(__name__) class MissingIndex(Exception): pass class SearchResults(NamedTuple): scores: List[float] indices: List[int] class BatchedSearchResults(NamedTuple): total_scores: List[List[float]] total_indices: List[List[int]] class NearestExamplesResults(NamedTuple): scores: List[float] examples: dict class BatchedNearestExamplesResults(NamedTuple): total_scores: List[List[float]] total_examples: List[dict] class BaseIndex: """Base class for indexing""" def search(self, query, k: int = 10, **kwargs) -> SearchResults: """ To implement. This method has to return the scores and the indices of the retrieved examples given a certain query. """ raise NotImplementedError def search_batch(self, queries, k: int = 10, **kwargs) -> BatchedSearchResults: """Find the nearest examples indices to the query. Args: queries (`Union[List[str], np.ndarray]`): The queries as a list of strings if `column` is a text index or as a numpy array if `column` is a vector index. k (`int`): The number of examples to retrieve per query. Ouput: total_scores (`List[List[float]`): The retrieval scores of the retrieved examples per query. total_indices (`List[List[int]]`): The indices of the retrieved examples per query. """ total_scores, total_indices = [], [] for query in queries: scores, indices = self.search(query, k) total_scores.append(scores) total_indices.append(indices) return BatchedSearchResults(total_scores, total_indices) def save(self, file: Union[str, PurePath]): """Serialize the index on disk""" raise NotImplementedError @classmethod def load(cls, file: Union[str, PurePath]) -> "BaseIndex": """Deserialize the index from disk""" raise NotImplementedError class ElasticSearchIndex(BaseIndex): """ Sparse index using Elasticsearch. It is used to index text and run queries based on BM25 similarity. An Elasticsearch server needs to be accessible, and a python client is declared with ``` es_client = Elasticsearch([{'host': 'localhost', 'port': '9200'}]) ``` for example. """ def __init__( self, host: Optional[str] = None, port: Optional[int] = None, es_client: Optional["Elasticsearch"] = None, es_index_name: Optional[str] = None, es_index_config: Optional[dict] = None, ): if not _has_elasticsearch: raise ImportError( "You must install ElasticSearch to use ElasticSearchIndex. To do so you can run `pip install elasticsearch==7.7.1 for example`" ) if es_client is not None and (host is not None or port is not None): raise ValueError("Please specify either `es_client` or `(host, port)`, but not both.") host = host or "localhost" port = port or 9200 import elasticsearch.helpers # noqa: F401 - need this to properly load all the es features from elasticsearch import Elasticsearch # noqa: F811 self.es_client = es_client if es_client is not None else Elasticsearch([{"host": host, "port": str(port)}]) self.es_index_name = ( es_index_name if es_index_name is not None else "huggingface_datasets_" + os.path.basename(tempfile.NamedTemporaryFile().name) ) self.es_index_config = ( es_index_config if es_index_config is not None else { "settings": { "number_of_shards": 1, "analysis": {"analyzer": {"stop_standard": {"type": "standard", " stopwords": "_english_"}}}, }, "mappings": {"properties": {"text": {"type": "text", "analyzer": "standard", "similarity": "BM25"}}}, } ) def add_documents(self, documents: Union[List[str], "Dataset"], column: Optional[str] = None): """ Add documents to the index. If the documents are inside a certain column, you can specify it using the `column` argument. """ index_name = self.es_index_name index_config = self.es_index_config self.es_client.indices.create(index=index_name, body=index_config) number_of_docs = len(documents) progress = hf_tqdm(unit="docs", total=number_of_docs) successes = 0 def passage_generator(): if column is not None: for i, example in enumerate(documents): yield {"text": example[column], "_id": i} else: for i, example in enumerate(documents): yield {"text": example, "_id": i} # create the ES index import elasticsearch as es for ok, action in es.helpers.streaming_bulk( client=self.es_client, index=index_name, actions=passage_generator(), ): progress.update(1) successes += ok if successes != len(documents): logger.warning( f"Some documents failed to be added to ElasticSearch. Failures: {len(documents)-successes}/{len(documents)}" ) logger.info(f"Indexed {successes:d} documents") def search(self, query: str, k=10, **kwargs) -> SearchResults: """Find the nearest examples indices to the query. Args: query (`str`): The query as a string. k (`int`): The number of examples to retrieve. Ouput: scores (`List[List[float]`): The retrieval scores of the retrieved examples. indices (`List[List[int]]`): The indices of the retrieved examples. """ response = self.es_client.search( index=self.es_index_name, body={"query": {"multi_match": {"query": query, "fields": ["text"], "type": "cross_fields"}}, "size": k}, **kwargs, ) hits = response["hits"]["hits"] return SearchResults([hit["_score"] for hit in hits], [int(hit["_id"]) for hit in hits]) def search_batch(self, queries, k: int = 10, max_workers=10, **kwargs) -> BatchedSearchResults: import concurrent.futures total_scores, total_indices = [None] * len(queries), [None] * len(queries) with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: future_to_index = {executor.submit(self.search, query, k, **kwargs): i for i, query in enumerate(queries)} for future in concurrent.futures.as_completed(future_to_index): index = future_to_index[future] results: SearchResults = future.result() total_scores[index] = results.scores total_indices[index] = results.indices return BatchedSearchResults(total_indices=total_indices, total_scores=total_scores) class FaissIndex(BaseIndex): """ Dense index using Faiss. It is used to index vectors. Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. You can find more information about Faiss here: - For index types and the string factory: https://github.com/facebookresearch/faiss/wiki/The-index-factory - For GPU settings: https://github.com/facebookresearch/faiss/wiki/Faiss-on-the-GPU """ def __init__( self, device: Optional[Union[int, List[int]]] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, ): """ Create a Dense index using Faiss. You can specify `device` if you want to run it on GPU (`device` must be the GPU index). You can find more information about Faiss here: - For `string factory`: https://github.com/facebookresearch/faiss/wiki/The-index-factory """ if string_factory is not None and custom_index is not None: raise ValueError("Please specify either `string_factory` or `custom_index` but not both.") if device is not None and custom_index is not None: raise ValueError( "Cannot pass both 'custom_index' and 'device'. " "Pass 'custom_index' already transferred to the target device instead." ) self.device = device self.string_factory = string_factory self.metric_type = metric_type self.faiss_index = custom_index if not _has_faiss: raise ImportError( "You must install Faiss to use FaissIndex. To do so you can run `conda install -c pytorch faiss-cpu` or `conda install -c pytorch faiss-gpu`. " "A community supported package is also available on pypi: `pip install faiss-cpu` or `pip install faiss-gpu`. " "Note that pip may not have the latest version of FAISS, and thus, some of the latest features and bug fixes may not be available." ) def add_vectors( self, vectors: Union[np.array, "Dataset"], column: Optional[str] = None, batch_size: int = 1000, train_size: Optional[int] = None, faiss_verbose: Optional[bool] = None, ): """ Add vectors to the index. If the arrays are inside a certain column, you can specify it using the `column` argument. """ import faiss # noqa: F811 # Create index if self.faiss_index is None: size = len(vectors[0]) if column is None else len(vectors[0][column]) if self.string_factory is not None: if self.metric_type is None: index = faiss.index_factory(size, self.string_factory) else: index = faiss.index_factory(size, self.string_factory, self.metric_type) else: if self.metric_type is None: index = faiss.IndexFlat(size) else: index = faiss.IndexFlat(size, self.metric_type) self.faiss_index = self._faiss_index_to_device(index, self.device) logger.info(f"Created faiss index of type {type(self.faiss_index)}") # Set verbosity level if faiss_verbose is not None: self.faiss_index.verbose = faiss_verbose if hasattr(self.faiss_index, "index") and self.faiss_index.index is not None: self.faiss_index.index.verbose = faiss_verbose if hasattr(self.faiss_index, "quantizer") and self.faiss_index.quantizer is not None: self.faiss_index.quantizer.verbose = faiss_verbose if hasattr(self.faiss_index, "clustering_index") and self.faiss_index.clustering_index is not None: self.faiss_index.clustering_index.verbose = faiss_verbose # Train if train_size is not None: train_vecs = vectors[:train_size] if column is None else vectors[:train_size][column] logger.info(f"Training the index with the first {len(train_vecs)} vectors") self.faiss_index.train(train_vecs) else: logger.info("Ignored the training step of the faiss index as `train_size` is None.") # Add vectors logger.info(f"Adding {len(vectors)} vectors to the faiss index") for i in hf_tqdm(range(0, len(vectors), batch_size)): vecs = vectors[i : i + batch_size] if column is None else vectors[i : i + batch_size][column] self.faiss_index.add(vecs) @staticmethod def _faiss_index_to_device(index: "faiss.Index", device: Optional[Union[int, List[int]]] = None) -> "faiss.Index": """ Sends a faiss index to a device. A device can either be a positive integer (GPU id), a negative integer (all GPUs), or a list of positive integers (select GPUs to use), or `None` for CPU. """ # If device is not specified, then it runs on CPU. if device is None: return index import faiss # noqa: F811 # If the device id is given as an integer if isinstance(device, int): # Positive integers are directly mapped to GPU ids if device > -1: faiss_res = faiss.StandardGpuResources() index = faiss.index_cpu_to_gpu(faiss_res, device, index) # And negative integers mean using all GPUs else: index = faiss.index_cpu_to_all_gpus(index) # Device ids given as a list mean mapping to those devices specified. elif isinstance(device, (list, tuple)): index = faiss.index_cpu_to_gpus_list(index, gpus=list(device)) else: raise TypeError( f"The argument type: {type(device)} is not expected. " + "Please pass in either nothing, a positive int, a negative int, or a list of positive ints." ) return index def search(self, query: np.array, k=10, **kwargs) -> SearchResults: """Find the nearest examples indices to the query. Args: query (`np.array`): The query as a numpy array. k (`int`): The number of examples to retrieve. Ouput: scores (`List[List[float]`): The retrieval scores of the retrieved examples. indices (`List[List[int]]`): The indices of the retrieved examples. """ if len(query.shape) != 1 and (len(query.shape) != 2 or query.shape[0] != 1): raise ValueError("Shape of query is incorrect, it has to be either a 1D array or 2D (1, N)") queries = query.reshape(1, -1) if not queries.flags.c_contiguous: queries = np.asarray(queries, order="C") scores, indices = self.faiss_index.search(queries, k, **kwargs) return SearchResults(scores[0], indices[0].astype(int)) def search_batch(self, queries: np.array, k=10, **kwargs) -> BatchedSearchResults: """Find the nearest examples indices to the queries. Args: queries (`np.array`): The queries as a numpy array. k (`int`): The number of examples to retrieve. Ouput: total_scores (`List[List[float]`): The retrieval scores of the retrieved examples per query. total_indices (`List[List[int]]`): The indices of the retrieved examples per query. """ if len(queries.shape) != 2: raise ValueError("Shape of query must be 2D") if not queries.flags.c_contiguous: queries = np.asarray(queries, order="C") scores, indices = self.faiss_index.search(queries, k, **kwargs) return BatchedSearchResults(scores, indices.astype(int)) def save(self, file: Union[str, PurePath], storage_options: Optional[Dict] = None): """Serialize the FaissIndex on disk""" import faiss # noqa: F811 if self.device is not None and isinstance(self.device, (int, list, tuple)): index = faiss.index_gpu_to_cpu(self.faiss_index) else: index = self.faiss_index with fsspec.open(str(file), "wb", **(storage_options or {})) as f: faiss.write_index(index, faiss.BufferedIOWriter(faiss.PyCallbackIOWriter(f.write))) @classmethod def load( cls, file: Union[str, PurePath], device: Optional[Union[int, List[int]]] = None, storage_options: Optional[Dict] = None, ) -> "FaissIndex": """Deserialize the FaissIndex from disk""" import faiss # noqa: F811 # Instances of FaissIndex is essentially just a wrapper for faiss indices. faiss_index = cls(device=device) with fsspec.open(str(file), "rb", **(storage_options or {})) as f: index = faiss.read_index(faiss.BufferedIOReader(faiss.PyCallbackIOReader(f.read))) faiss_index.faiss_index = faiss_index._faiss_index_to_device(index, faiss_index.device) return faiss_index class IndexableMixin: """Add indexing features to `datasets.Dataset`""" def __init__(self): self._indexes: Dict[str, BaseIndex] = {} def __len__(self): raise NotImplementedError def __getitem__(self, key): raise NotImplementedError def is_index_initialized(self, index_name: str) -> bool: return index_name in self._indexes def _check_index_is_initialized(self, index_name: str): if not self.is_index_initialized(index_name): raise MissingIndex( f"Index with index_name '{index_name}' not initialized yet. Please make sure that you call `add_faiss_index` or `add_elasticsearch_index` first." ) def list_indexes(self) -> List[str]: """List the `colindex_nameumns`/identifiers of all the attached indexes.""" return list(self._indexes) def get_index(self, index_name: str) -> BaseIndex: """List the `index_name`/identifiers of all the attached indexes. Args: index_name (`str`): Index name. Returns: [`BaseIndex`] """ self._check_index_is_initialized(index_name) return self._indexes[index_name] def add_faiss_index( self, column: str, index_name: Optional[str] = None, device: Optional[Union[int, List[int]]] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, batch_size: int = 1000, train_size: Optional[int] = None, faiss_verbose: bool = False, ): """Add a dense index using Faiss for fast retrieval. The index is created using the vectors of the specified column. You can specify `device` if you want to run it on GPU (`device` must be the GPU index, see more below). You can find more information about Faiss here: - For `string factory`: https://github.com/facebookresearch/faiss/wiki/The-index-factory Args: column (`str`): The column of the vectors to add to the index. index_name (Optional `str`): The index_name/identifier of the index. This is the index_name that is used to call `.get_nearest` or `.search`. By default it corresponds to `column`. device (Optional `Union[int, List[int]]`): If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU. string_factory (Optional `str`): This is passed to the index factory of Faiss to create the index. Default index class is IndexFlatIP. metric_type (Optional `int`): Type of metric. Ex: `faiss.METRIC_INNER_PRODUCT` or `faiss.METRIC_L2`. custom_index (Optional `faiss.Index`): Custom Faiss index that you already have instantiated and configured for your needs. batch_size (Optional `int`): Size of the batch to use while adding vectors to the FaissIndex. Default value is 1000. <Added version="2.4.0"/> train_size (Optional `int`): If the index needs a training step, specifies how many vectors will be used to train the index. faiss_verbose (`bool`, defaults to False): Enable the verbosity of the Faiss index. """ index_name = index_name if index_name is not None else column faiss_index = FaissIndex( device=device, string_factory=string_factory, metric_type=metric_type, custom_index=custom_index ) faiss_index.add_vectors( self, column=column, batch_size=batch_size, train_size=train_size, faiss_verbose=faiss_verbose ) self._indexes[index_name] = faiss_index def add_faiss_index_from_external_arrays( self, external_arrays: np.array, index_name: str, device: Optional[Union[int, List[int]]] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, batch_size: int = 1000, train_size: Optional[int] = None, faiss_verbose: bool = False, ): """Add a dense index using Faiss for fast retrieval. The index is created using the vectors of `external_arrays`. You can specify `device` if you want to run it on GPU (`device` must be the GPU index). You can find more information about Faiss here: - For `string factory`: https://github.com/facebookresearch/faiss/wiki/The-index-factory Args: external_arrays (`np.array`): If you want to use arrays from outside the lib for the index, you can set `external_arrays`. It will use `external_arrays` to create the Faiss index instead of the arrays in the given `column`. index_name (`str`): The index_name/identifier of the index. This is the index_name that is used to call `.get_nearest` or `.search`. device (Optional `Union[int, List[int]]`): If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU. string_factory (Optional `str`): This is passed to the index factory of Faiss to create the index. Default index class is IndexFlatIP. metric_type (Optional `int`): Type of metric. Ex: `faiss.METRIC_INNER_PRODUCT` or `faiss.METRIC_L2`. custom_index (Optional `faiss.Index`): Custom Faiss index that you already have instantiated and configured for your needs. batch_size (Optional `int`): Size of the batch to use while adding vectors to the FaissIndex. Default value is 1000. <Added version="2.4.0"/> train_size (Optional `int`): If the index needs a training step, specifies how many vectors will be used to train the index. faiss_verbose (`bool`, defaults to False): Enable the verbosity of the Faiss index. """ faiss_index = FaissIndex( device=device, string_factory=string_factory, metric_type=metric_type, custom_index=custom_index ) faiss_index.add_vectors( external_arrays, column=None, batch_size=batch_size, train_size=train_size, faiss_verbose=faiss_verbose ) self._indexes[index_name] = faiss_index def save_faiss_index(self, index_name: str, file: Union[str, PurePath], storage_options: Optional[Dict] = None): """Save a FaissIndex on disk. Args: index_name (`str`): The index_name/identifier of the index. This is the index_name that is used to call `.get_nearest` or `.search`. file (`str`): The path to the serialized faiss index on disk or remote URI (e.g. `"s3://my-bucket/index.faiss"`). storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.11.0"/> """ index = self.get_index(index_name) if not isinstance(index, FaissIndex): raise ValueError(f"Index '{index_name}' is not a FaissIndex but a '{type(index)}'") index.save(file, storage_options=storage_options) logger.info(f"Saved FaissIndex {index_name} at {file}") def load_faiss_index( self, index_name: str, file: Union[str, PurePath], device: Optional[Union[int, List[int]]] = None, storage_options: Optional[Dict] = None, ): """Load a FaissIndex from disk. If you want to do additional configurations, you can have access to the faiss index object by doing `.get_index(index_name).faiss_index` to make it fit your needs. Args: index_name (`str`): The index_name/identifier of the index. This is the index_name that is used to call `.get_nearest` or `.search`. file (`str`): The path to the serialized faiss index on disk or remote URI (e.g. `"s3://my-bucket/index.faiss"`). device (Optional `Union[int, List[int]]`): If positive integer, this is the index of the GPU to use. If negative integer, use all GPUs. If a list of positive integers is passed in, run only on those GPUs. By default it uses the CPU. storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.11.0"/> """ index = FaissIndex.load(file, device=device, storage_options=storage_options) if index.faiss_index.ntotal != len(self): raise ValueError( f"Index size should match Dataset size, but Index '{index_name}' at {file} has {index.faiss_index.ntotal} elements while the dataset has {len(self)} examples." ) self._indexes[index_name] = index logger.info(f"Loaded FaissIndex {index_name} from {file}") def add_elasticsearch_index( self, column: str, index_name: Optional[str] = None, host: Optional[str] = None, port: Optional[int] = None, es_client: Optional["Elasticsearch"] = None, es_index_name: Optional[str] = None, es_index_config: Optional[dict] = None, ): """Add a text index using ElasticSearch for fast retrieval. Args: column (`str`): The column of the documents to add to the index. index_name (Optional `str`): The index_name/identifier of the index. This is the index name that is used to call `.get_nearest` or `.search`. By default it corresponds to `column`. host (Optional `str`, defaults to localhost): host of where ElasticSearch is running port (Optional `str`, defaults to 9200): port of where ElasticSearch is running es_client (Optional `elasticsearch.Elasticsearch`): The elasticsearch client used to create the index if host and port are None. es_index_name (Optional `str`): The elasticsearch index name used to create the index. es_index_config (Optional `dict`): The configuration of the elasticsearch index. Default config is: Config:: { "settings": { "number_of_shards": 1, "analysis": {"analyzer": {"stop_standard": {"type": "standard", " stopwords": "_english_"}}}, }, "mappings": { "properties": { "text": { "type": "text", "analyzer": "standard", "similarity": "BM25" }, } }, } """ index_name = index_name if index_name is not None else column es_index = ElasticSearchIndex( host=host, port=port, es_client=es_client, es_index_name=es_index_name, es_index_config=es_index_config ) es_index.add_documents(self, column=column) self._indexes[index_name] = es_index def load_elasticsearch_index( self, index_name: str, es_index_name: str, host: Optional[str] = None, port: Optional[int] = None, es_client: Optional["Elasticsearch"] = None, es_index_config: Optional[dict] = None, ): """Load an existing text index using ElasticSearch for fast retrieval. Args: index_name (`str`): The `index_name`/identifier of the index. This is the index name that is used to call `get_nearest` or `search`. es_index_name (`str`): The name of elasticsearch index to load. host (`str`, *optional*, defaults to `localhost`): Host of where ElasticSearch is running. port (`str`, *optional*, defaults to `9200`): Port of where ElasticSearch is running. es_client (`elasticsearch.Elasticsearch`, *optional*): The elasticsearch client used to create the index if host and port are `None`. es_index_config (`dict`, *optional*): The configuration of the elasticsearch index. Default config is: ``` { "settings": { "number_of_shards": 1, "analysis": {"analyzer": {"stop_standard": {"type": "standard", " stopwords": "_english_"}}}, }, "mappings": { "properties": { "text": { "type": "text", "analyzer": "standard", "similarity": "BM25" }, } }, } ``` """ self._indexes[index_name] = ElasticSearchIndex( host=host, port=port, es_client=es_client, es_index_name=es_index_name, es_index_config=es_index_config ) def drop_index(self, index_name: str): """Drop the index with the specified column. Args: index_name (`str`): The `index_name`/identifier of the index. """ del self._indexes[index_name] def search(self, index_name: str, query: Union[str, np.array], k: int = 10, **kwargs) -> SearchResults: """Find the nearest examples indices in the dataset to the query. Args: index_name (`str`): The name/identifier of the index. query (`Union[str, np.ndarray]`): The query as a string if `index_name` is a text index or as a numpy array if `index_name` is a vector index. k (`int`): The number of examples to retrieve. Returns: `(scores, indices)`: A tuple of `(scores, indices)` where: - **scores** (`List[List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples - **indices** (`List[List[int]]`): the indices of the retrieved examples """ self._check_index_is_initialized(index_name) return self._indexes[index_name].search(query, k, **kwargs) def search_batch( self, index_name: str, queries: Union[List[str], np.array], k: int = 10, **kwargs ) -> BatchedSearchResults: """Find the nearest examples indices in the dataset to the query. Args: index_name (`str`): The `index_name`/identifier of the index. queries (`Union[List[str], np.ndarray]`): The queries as a list of strings if `index_name` is a text index or as a numpy array if `index_name` is a vector index. k (`int`): The number of examples to retrieve per query. Returns: `(total_scores, total_indices)`: A tuple of `(total_scores, total_indices)` where: - **total_scores** (`List[List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples per query - **total_indices** (`List[List[int]]`): the indices of the retrieved examples per query """ self._check_index_is_initialized(index_name) return self._indexes[index_name].search_batch(queries, k, **kwargs) def get_nearest_examples( self, index_name: str, query: Union[str, np.array], k: int = 10, **kwargs ) -> NearestExamplesResults: """Find the nearest examples in the dataset to the query. Args: index_name (`str`): The index_name/identifier of the index. query (`Union[str, np.ndarray]`): The query as a string if `index_name` is a text index or as a numpy array if `index_name` is a vector index. k (`int`): The number of examples to retrieve. Returns: `(scores, examples)`: A tuple of `(scores, examples)` where: - **scores** (`List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples - **examples** (`dict`): the retrieved examples """ self._check_index_is_initialized(index_name) scores, indices = self.search(index_name, query, k, **kwargs) top_indices = [i for i in indices if i >= 0] return NearestExamplesResults(scores[: len(top_indices)], self[top_indices]) def get_nearest_examples_batch( self, index_name: str, queries: Union[List[str], np.array], k: int = 10, **kwargs ) -> BatchedNearestExamplesResults: """Find the nearest examples in the dataset to the query. Args: index_name (`str`): The `index_name`/identifier of the index. queries (`Union[List[str], np.ndarray]`): The queries as a list of strings if `index_name` is a text index or as a numpy array if `index_name` is a vector index. k (`int`): The number of examples to retrieve per query. Returns: `(total_scores, total_examples)`: A tuple of `(total_scores, total_examples)` where: - **total_scores** (`List[List[float]`): the retrieval scores from either FAISS (`IndexFlatL2` by default) or ElasticSearch of the retrieved examples per query - **total_examples** (`List[dict]`): the retrieved examples per query """ self._check_index_is_initialized(index_name) total_scores, total_indices = self.search_batch(index_name, queries, k, **kwargs) total_scores = [ scores_i[: len([i for i in indices_i if i >= 0])] for scores_i, indices_i in zip(total_scores, total_indices) ] total_samples = [self[[i for i in indices if i >= 0]] for indices in total_indices] return BatchedNearestExamplesResults(total_scores, total_samples)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/distributed.py
from typing import TypeVar from .arrow_dataset import Dataset, _split_by_node_map_style_dataset from .iterable_dataset import IterableDataset, _split_by_node_iterable_dataset DatasetType = TypeVar("DatasetType", Dataset, IterableDataset) def split_dataset_by_node(dataset: DatasetType, rank: int, world_size: int) -> DatasetType: """ Split a dataset for the node at rank `rank` in a pool of nodes of size `world_size`. For map-style datasets: Each node is assigned a chunk of data, e.g. rank 0 is given the first chunk of the dataset. To maximize data loading throughput, chunks are made of contiguous data on disk if possible. For iterable datasets: If the dataset has a number of shards that is a factor of `world_size` (i.e. if `dataset.n_shards % world_size == 0`), then the shards are evenly assigned across the nodes, which is the most optimized. Otherwise, each node keeps 1 example out of `world_size`, skipping the other examples. Args: dataset ([`Dataset`] or [`IterableDataset`]): The dataset to split by node. rank (`int`): Rank of the current node. world_size (`int`): Total number of nodes. Returns: [`Dataset`] or [`IterableDataset`]: The dataset to be used on the node at rank `rank`. """ if isinstance(dataset, Dataset): return _split_by_node_map_style_dataset(dataset, rank=rank, world_size=world_size) else: return _split_by_node_iterable_dataset(dataset, rank=rank, world_size=world_size)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/keyhash.py
# Copyright 2020 The HuggingFace Datasets Authors and 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. # Lint as: python3 """ Hashing function for dataset keys using `hashlib.md5` Requirements for the hash function: - Provides a uniformly distributed hash from random space - Adequately fast speed - Working with multiple input types (in this case, `str`, `int` or `bytes`) - Should be platform independent (generates same hash on different OS and systems) The hashing function provides a unique 128-bit integer hash of the key provided. The split name is being used here as the hash salt to avoid having same hashes in different splits due to same keys """ from typing import Union from huggingface_hub.utils import insecure_hashlib def _as_bytes(hash_data: Union[str, int, bytes]) -> bytes: """ Returns the input hash_data in its bytes form Args: hash_data: the hash salt/key to be converted to bytes """ if isinstance(hash_data, bytes): # Data already in bytes, returns as it as return hash_data elif isinstance(hash_data, str): # We keep the data as it as for it ot be later encoded to UTF-8 # However replace `\\` with `/` for Windows compatibility hash_data = hash_data.replace("\\", "/") elif isinstance(hash_data, int): hash_data = str(hash_data) else: # If data is not of the required type, raise error raise InvalidKeyError(hash_data) return hash_data.encode("utf-8") class InvalidKeyError(Exception): """Raises an error when given key is of invalid datatype.""" def __init__(self, hash_data): self.prefix = "\nFAILURE TO GENERATE DATASET: Invalid key type detected" self.err_msg = f"\nFound Key {hash_data} of type {type(hash_data)}" self.suffix = "\nKeys should be either str, int or bytes type" super().__init__(f"{self.prefix}{self.err_msg}{self.suffix}") class DuplicatedKeysError(Exception): """Raise an error when duplicate key found.""" def __init__(self, key, duplicate_key_indices, fix_msg=""): self.key = key self.duplicate_key_indices = duplicate_key_indices self.fix_msg = fix_msg self.prefix = "Found multiple examples generated with the same key" if len(duplicate_key_indices) <= 20: self.err_msg = f"\nThe examples at index {', '.join(duplicate_key_indices)} have the key {key}" else: self.err_msg = f"\nThe examples at index {', '.join(duplicate_key_indices[:20])}... ({len(duplicate_key_indices) - 20} more) have the key {key}" self.suffix = "\n" + fix_msg if fix_msg else "" super().__init__(f"{self.prefix}{self.err_msg}{self.suffix}") class KeyHasher: """KeyHasher class for providing hash using md5""" def __init__(self, hash_salt: str): self._split_md5 = insecure_hashlib.md5(_as_bytes(hash_salt)) def hash(self, key: Union[str, int, bytes]) -> int: """Returns 128-bits unique hash of input key Args: key: the input key to be hashed (should be str, int or bytes) Returns: 128-bit int hash key""" md5 = self._split_md5.copy() byte_key = _as_bytes(key) md5.update(byte_key) # Convert to integer with hexadecimal conversion return int(md5.hexdigest(), 16)
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/arrow_writer.py
# Copyright 2020 The HuggingFace Datasets Authors and 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 # # 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. # Lint as: python3 """To write records into Parquet files.""" import errno import json import os import sys from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple, Union import fsspec import numpy as np import pyarrow as pa import pyarrow.parquet as pq from . import config from .features import Features, Image, Value from .features.features import ( FeatureType, _ArrayXDExtensionType, cast_to_python_objects, generate_from_arrow_type, get_nested_type, list_of_np_array_to_pyarrow_listarray, numpy_to_pyarrow_listarray, to_pyarrow_listarray, ) from .filesystems import is_remote_filesystem from .info import DatasetInfo from .keyhash import DuplicatedKeysError, KeyHasher from .table import array_cast, array_concat, cast_array_to_feature, embed_table_storage, table_cast from .utils import logging from .utils import tqdm as hf_tqdm from .utils.file_utils import hash_url_to_filename from .utils.py_utils import asdict, first_non_null_value logger = logging.get_logger(__name__) type_ = type # keep python's type function class SchemaInferenceError(ValueError): pass class TypedSequence: """ This data container generalizes the typing when instantiating pyarrow arrays, tables or batches. More specifically it adds several features: - Support extension types like ``datasets.features.Array2DExtensionType``: By default pyarrow arrays don't return extension arrays. One has to call ``pa.ExtensionArray.from_storage(type, pa.array(data, type.storage_type))`` in order to get an extension array. - Support for ``try_type`` parameter that can be used instead of ``type``: When an array is transformed, we like to keep the same type as before if possible. For example when calling :func:`datasets.Dataset.map`, we don't want to change the type of each column by default. - Better error message when a pyarrow array overflows. Example:: from datasets.features import Array2D, Array2DExtensionType, Value from datasets.arrow_writer import TypedSequence import pyarrow as pa arr = pa.array(TypedSequence([1, 2, 3], type=Value("int32"))) assert arr.type == pa.int32() arr = pa.array(TypedSequence([1, 2, 3], try_type=Value("int32"))) assert arr.type == pa.int32() arr = pa.array(TypedSequence(["foo", "bar"], try_type=Value("int32"))) assert arr.type == pa.string() arr = pa.array(TypedSequence([[[1, 2, 3]]], type=Array2D((1, 3), "int64"))) assert arr.type == Array2DExtensionType((1, 3), "int64") table = pa.Table.from_pydict({ "image": TypedSequence([[[1, 2, 3]]], type=Array2D((1, 3), "int64")) }) assert table["image"].type == Array2DExtensionType((1, 3), "int64") """ def __init__( self, data: Iterable, type: Optional[FeatureType] = None, try_type: Optional[FeatureType] = None, optimized_int_type: Optional[FeatureType] = None, ): # assert type is None or try_type is None, if type is not None and try_type is not None: raise ValueError("You cannot specify both type and try_type") # set attributes self.data = data self.type = type self.try_type = try_type # is ignored if it doesn't match the data self.optimized_int_type = optimized_int_type # when trying a type (is ignored if data is not compatible) self.trying_type = self.try_type is not None self.trying_int_optimization = optimized_int_type is not None and type is None and try_type is None # used to get back the inferred type after __arrow_array__() is called once self._inferred_type = None def get_inferred_type(self) -> FeatureType: """Return the inferred feature type. This is done by converting the sequence to an Arrow array, and getting the corresponding feature type. Since building the Arrow array can be expensive, the value of the inferred type is cached as soon as pa.array is called on the typed sequence. Returns: FeatureType: inferred feature type of the sequence. """ if self._inferred_type is None: self._inferred_type = generate_from_arrow_type(pa.array(self).type) return self._inferred_type @staticmethod def _infer_custom_type_and_encode(data: Iterable) -> Tuple[Iterable, Optional[FeatureType]]: """Implement type inference for custom objects like PIL.Image.Image -> Image type. This function is only used for custom python objects that can't be direclty passed to build an Arrow array. In such cases is infers the feature type to use, and it encodes the data so that they can be passed to an Arrow array. Args: data (Iterable): array of data to infer the type, e.g. a list of PIL images. Returns: Tuple[Iterable, Optional[FeatureType]]: a tuple with: - the (possibly encoded) array, if the inferred feature type requires encoding - the inferred feature type if the array is made of supported custom objects like PIL images, else None. """ if config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image non_null_idx, non_null_value = first_non_null_value(data) if isinstance(non_null_value, PIL.Image.Image): return [Image().encode_example(value) if value is not None else None for value in data], Image() return data, None def __arrow_array__(self, type: Optional[pa.DataType] = None): """This function is called when calling pa.array(typed_sequence)""" if type is not None: raise ValueError("TypedSequence is supposed to be used with pa.array(typed_sequence, type=None)") del type # make sure we don't use it data = self.data # automatic type inference for custom objects if self.type is None and self.try_type is None: data, self._inferred_type = self._infer_custom_type_and_encode(data) if self._inferred_type is None: type = self.try_type if self.trying_type else self.type else: type = self._inferred_type pa_type = get_nested_type(type) if type is not None else None optimized_int_pa_type = ( get_nested_type(self.optimized_int_type) if self.optimized_int_type is not None else None ) trying_cast_to_python_objects = False try: # custom pyarrow types if isinstance(pa_type, _ArrayXDExtensionType): storage = to_pyarrow_listarray(data, pa_type) return pa.ExtensionArray.from_storage(pa_type, storage) # efficient np array to pyarrow array if isinstance(data, np.ndarray): out = numpy_to_pyarrow_listarray(data) elif isinstance(data, list) and data and isinstance(first_non_null_value(data)[1], np.ndarray): out = list_of_np_array_to_pyarrow_listarray(data) else: trying_cast_to_python_objects = True out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) # use smaller integer precisions if possible if self.trying_int_optimization: if pa.types.is_int64(out.type): out = out.cast(optimized_int_pa_type) elif pa.types.is_list(out.type): if pa.types.is_int64(out.type.value_type): out = array_cast(out, pa.list_(optimized_int_pa_type)) elif pa.types.is_list(out.type.value_type) and pa.types.is_int64(out.type.value_type.value_type): out = array_cast(out, pa.list_(pa.list_(optimized_int_pa_type))) # otherwise we can finally use the user's type elif type is not None: # We use cast_array_to_feature to support casting to custom types like Audio and Image # Also, when trying type "string", we don't want to convert integers or floats to "string". # We only do it if trying_type is False - since this is what the user asks for. out = cast_array_to_feature(out, type, allow_number_to_str=not self.trying_type) return out except ( TypeError, pa.lib.ArrowInvalid, pa.lib.ArrowNotImplementedError, ) as e: # handle type errors and overflows # Ignore ArrowNotImplementedError caused by trying type, otherwise re-raise if not self.trying_type and isinstance(e, pa.lib.ArrowNotImplementedError): raise if self.trying_type: try: # second chance if isinstance(data, np.ndarray): return numpy_to_pyarrow_listarray(data) elif isinstance(data, list) and data and any(isinstance(value, np.ndarray) for value in data): return list_of_np_array_to_pyarrow_listarray(data) else: trying_cast_to_python_objects = True return pa.array(cast_to_python_objects(data, only_1d_for_numpy=True)) except pa.lib.ArrowInvalid as e: if "overflow" in str(e): raise OverflowError( f"There was an overflow with type {type_(data)}. Try to reduce writer_batch_size to have batches smaller than 2GB.\n({e})" ) from None elif self.trying_int_optimization and "not in range" in str(e): optimized_int_pa_type_str = np.dtype(optimized_int_pa_type.to_pandas_dtype()).name logger.info( f"Failed to cast a sequence to {optimized_int_pa_type_str}. Falling back to int64." ) return out elif trying_cast_to_python_objects and "Could not convert" in str(e): out = pa.array( cast_to_python_objects(data, only_1d_for_numpy=True, optimize_list_casting=False) ) if type is not None: out = cast_array_to_feature(out, type, allow_number_to_str=True) return out else: raise elif "overflow" in str(e): raise OverflowError( f"There was an overflow with type {type_(data)}. Try to reduce writer_batch_size to have batches smaller than 2GB.\n({e})" ) from None elif self.trying_int_optimization and "not in range" in str(e): optimized_int_pa_type_str = np.dtype(optimized_int_pa_type.to_pandas_dtype()).name logger.info(f"Failed to cast a sequence to {optimized_int_pa_type_str}. Falling back to int64.") return out elif trying_cast_to_python_objects and "Could not convert" in str(e): out = pa.array(cast_to_python_objects(data, only_1d_for_numpy=True, optimize_list_casting=False)) if type is not None: out = cast_array_to_feature(out, type, allow_number_to_str=True) return out else: raise class OptimizedTypedSequence(TypedSequence): def __init__( self, data, type: Optional[FeatureType] = None, try_type: Optional[FeatureType] = None, col: Optional[str] = None, optimized_int_type: Optional[FeatureType] = None, ): optimized_int_type_by_col = { "attention_mask": Value("int8"), # binary tensor "special_tokens_mask": Value("int8"), "input_ids": Value("int32"), # typical vocab size: 0-50k (max ~500k, never > 1M) "token_type_ids": Value( "int8" ), # binary mask; some (XLNetModel) use an additional token represented by a 2 } if type is None and try_type is None: optimized_int_type = optimized_int_type_by_col.get(col, None) super().__init__(data, type=type, try_type=try_type, optimized_int_type=optimized_int_type) class ArrowWriter: """Shuffles and writes Examples to Arrow files.""" _WRITER_CLASS = pa.RecordBatchStreamWriter def __init__( self, schema: Optional[pa.Schema] = None, features: Optional[Features] = None, path: Optional[str] = None, stream: Optional[pa.NativeFile] = None, fingerprint: Optional[str] = None, writer_batch_size: Optional[int] = None, hash_salt: Optional[str] = None, check_duplicates: Optional[bool] = False, disable_nullable: bool = False, update_features: bool = False, with_metadata: bool = True, unit: str = "examples", embed_local_files: bool = False, storage_options: Optional[dict] = None, ): if path is None and stream is None: raise ValueError("At least one of path and stream must be provided.") if features is not None: self._features = features self._schema = None elif schema is not None: self._schema: pa.Schema = schema self._features = Features.from_arrow_schema(self._schema) else: self._features = None self._schema = None if hash_salt is not None: # Create KeyHasher instance using split name as hash salt self._hasher = KeyHasher(hash_salt) else: self._hasher = KeyHasher("") self._check_duplicates = check_duplicates self._disable_nullable = disable_nullable if stream is None: fs_token_paths = fsspec.get_fs_token_paths(path, storage_options=storage_options) self._fs: fsspec.AbstractFileSystem = fs_token_paths[0] self._path = ( fs_token_paths[2][0] if not is_remote_filesystem(self._fs) else self._fs.unstrip_protocol(fs_token_paths[2][0]) ) self.stream = self._fs.open(fs_token_paths[2][0], "wb") self._closable_stream = True else: self._fs = None self._path = None self.stream = stream self._closable_stream = False self.fingerprint = fingerprint self.disable_nullable = disable_nullable self.writer_batch_size = writer_batch_size or config.DEFAULT_MAX_BATCH_SIZE self.update_features = update_features self.with_metadata = with_metadata self.unit = unit self.embed_local_files = embed_local_files self._num_examples = 0 self._num_bytes = 0 self.current_examples: List[Tuple[Dict[str, Any], str]] = [] self.current_rows: List[pa.Table] = [] self.pa_writer: Optional[pa.RecordBatchStreamWriter] = None self.hkey_record = [] def __len__(self): """Return the number of writed and staged examples""" return self._num_examples + len(self.current_examples) + len(self.current_rows) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): # Try closing if opened; if closed: pyarrow.lib.ArrowInvalid: Invalid operation on closed file if self.pa_writer: # it might be None try: self.pa_writer.close() except Exception: # pyarrow.lib.ArrowInvalid, OSError pass if self._closable_stream and not self.stream.closed: self.stream.close() # This also closes self.pa_writer if it is opened def _build_writer(self, inferred_schema: pa.Schema): schema = self.schema inferred_features = Features.from_arrow_schema(inferred_schema) if self._features is not None: if self.update_features: # keep original features it they match, or update them fields = {field.name: field for field in self._features.type} for inferred_field in inferred_features.type: name = inferred_field.name if name in fields: if inferred_field == fields[name]: inferred_features[name] = self._features[name] self._features = inferred_features schema: pa.Schema = inferred_schema else: self._features = inferred_features schema: pa.Schema = inferred_features.arrow_schema if self.disable_nullable: schema = pa.schema(pa.field(field.name, field.type, nullable=False) for field in schema) if self.with_metadata: schema = schema.with_metadata(self._build_metadata(DatasetInfo(features=self._features), self.fingerprint)) else: schema = schema.with_metadata({}) self._schema = schema self.pa_writer = self._WRITER_CLASS(self.stream, schema) @property def schema(self): _schema = ( self._schema if self._schema is not None else (pa.schema(self._features.type) if self._features is not None else None) ) if self._disable_nullable and _schema is not None: _schema = pa.schema(pa.field(field.name, field.type, nullable=False) for field in _schema) return _schema if _schema is not None else [] @staticmethod def _build_metadata(info: DatasetInfo, fingerprint: Optional[str] = None) -> Dict[str, str]: info_keys = ["features"] # we can add support for more DatasetInfo keys in the future info_as_dict = asdict(info) metadata = {} metadata["info"] = {key: info_as_dict[key] for key in info_keys} if fingerprint is not None: metadata["fingerprint"] = fingerprint return {"huggingface": json.dumps(metadata)} def write_examples_on_file(self): """Write stored examples from the write-pool of examples. It makes a table out of the examples and write it.""" if not self.current_examples: return # order the columns properly cols = ( [col for col in self.schema.names if col in self.current_examples[0][0]] + [col for col in self.current_examples[0][0].keys() if col not in self.schema.names] if self.schema else self.current_examples[0][0].keys() ) batch_examples = {} for col in cols: # We use row[0][col] since current_examples contains (example, key) tuples. # Morever, examples could be Arrow arrays of 1 element. # This can happen in `.map()` when we want to re-write the same Arrow data if all(isinstance(row[0][col], (pa.Array, pa.ChunkedArray)) for row in self.current_examples): arrays = [row[0][col] for row in self.current_examples] batch_examples[col] = array_concat(arrays) else: batch_examples[col] = [ row[0][col].to_pylist()[0] if isinstance(row[0][col], (pa.Array, pa.ChunkedArray)) else row[0][col] for row in self.current_examples ] self.write_batch(batch_examples=batch_examples) self.current_examples = [] def write_rows_on_file(self): """Write stored rows from the write-pool of rows. It concatenates the single-row tables and it writes the resulting table.""" if not self.current_rows: return table = pa.concat_tables(self.current_rows) self.write_table(table) self.current_rows = [] def write( self, example: Dict[str, Any], key: Optional[Union[str, int, bytes]] = None, writer_batch_size: Optional[int] = None, ): """Add a given (Example,Key) pair to the write-pool of examples which is written to file. Args: example: the Example to add. key: Optional, a unique identifier(str, int or bytes) associated with each example """ # Utilize the keys and duplicate checking when `self._check_duplicates` is passed True if self._check_duplicates: # Create unique hash from key and store as (key, example) pairs hash = self._hasher.hash(key) self.current_examples.append((example, hash)) # Maintain record of keys and their respective hashes for checking duplicates self.hkey_record.append((hash, key)) else: # Store example as a tuple so as to keep the structure of `self.current_examples` uniform self.current_examples.append((example, "")) if writer_batch_size is None: writer_batch_size = self.writer_batch_size if writer_batch_size is not None and len(self.current_examples) >= writer_batch_size: if self._check_duplicates: self.check_duplicate_keys() # Re-intializing to empty list for next batch self.hkey_record = [] self.write_examples_on_file() def check_duplicate_keys(self): """Raises error if duplicates found in a batch""" tmp_record = set() for hash, key in self.hkey_record: if hash in tmp_record: duplicate_key_indices = [ str(self._num_examples + index) for index, (duplicate_hash, _) in enumerate(self.hkey_record) if duplicate_hash == hash ] raise DuplicatedKeysError(key, duplicate_key_indices) else: tmp_record.add(hash) def write_row(self, row: pa.Table, writer_batch_size: Optional[int] = None): """Add a given single-row Table to the write-pool of rows which is written to file. Args: row: the row to add. """ if len(row) != 1: raise ValueError(f"Only single-row pyarrow tables are allowed but got table with {len(row)} rows.") self.current_rows.append(row) if writer_batch_size is None: writer_batch_size = self.writer_batch_size if writer_batch_size is not None and len(self.current_rows) >= writer_batch_size: self.write_rows_on_file() def write_batch( self, batch_examples: Dict[str, List], writer_batch_size: Optional[int] = None, ): """Write a batch of Example to file. Ignores the batch if it appears to be empty, preventing a potential schema update of unknown types. Args: batch_examples: the batch of examples to add. """ if batch_examples and len(next(iter(batch_examples.values()))) == 0: return features = None if self.pa_writer is None and self.update_features else self._features try_features = self._features if self.pa_writer is None and self.update_features else None arrays = [] inferred_features = Features() cols = ( [col for col in self.schema.names if col in batch_examples] + [col for col in batch_examples.keys() if col not in self.schema.names] if self.schema else batch_examples.keys() ) for col in cols: col_values = batch_examples[col] col_type = features[col] if features else None if isinstance(col_values, (pa.Array, pa.ChunkedArray)): array = cast_array_to_feature(col_values, col_type) if col_type is not None else col_values arrays.append(array) inferred_features[col] = generate_from_arrow_type(col_values.type) else: col_try_type = try_features[col] if try_features is not None and col in try_features else None typed_sequence = OptimizedTypedSequence(col_values, type=col_type, try_type=col_try_type, col=col) arrays.append(pa.array(typed_sequence)) inferred_features[col] = typed_sequence.get_inferred_type() schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema pa_table = pa.Table.from_arrays(arrays, schema=schema) self.write_table(pa_table, writer_batch_size) def write_table(self, pa_table: pa.Table, writer_batch_size: Optional[int] = None): """Write a Table to file. Args: example: the Table to add. """ if writer_batch_size is None: writer_batch_size = self.writer_batch_size if self.pa_writer is None: self._build_writer(inferred_schema=pa_table.schema) pa_table = pa_table.combine_chunks() pa_table = table_cast(pa_table, self._schema) if self.embed_local_files: pa_table = embed_table_storage(pa_table) self._num_bytes += pa_table.nbytes self._num_examples += pa_table.num_rows self.pa_writer.write_table(pa_table, writer_batch_size) def finalize(self, close_stream=True): self.write_rows_on_file() # In case current_examples < writer_batch_size, but user uses finalize() if self._check_duplicates: self.check_duplicate_keys() # Re-intializing to empty list for next batch self.hkey_record = [] self.write_examples_on_file() # If schema is known, infer features even if no examples were written if self.pa_writer is None and self.schema: self._build_writer(self.schema) if self.pa_writer is not None: self.pa_writer.close() self.pa_writer = None if close_stream: self.stream.close() else: if close_stream: self.stream.close() raise SchemaInferenceError("Please pass `features` or at least one example when writing data") logger.debug( f"Done writing {self._num_examples} {self.unit} in {self._num_bytes} bytes {self._path if self._path else ''}." ) return self._num_examples, self._num_bytes class ParquetWriter(ArrowWriter): _WRITER_CLASS = pq.ParquetWriter class BeamWriter: """ Shuffles and writes Examples to Arrow files. The Arrow files are converted from Parquet files that are the output of Apache Beam pipelines. """ def __init__( self, features: Optional[Features] = None, schema: Optional[pa.Schema] = None, path: Optional[str] = None, namespace: Optional[str] = None, cache_dir: Optional[str] = None, ): if features is None and schema is None: raise ValueError("At least one of features and schema must be provided.") if path is None: raise ValueError("Path must be provided.") if features is not None: self._features: Features = features self._schema: pa.Schema = features.arrow_schema else: self._schema: pa.Schema = schema self._features: Features = Features.from_arrow_schema(schema) self._path = path self._parquet_path = os.path.splitext(path)[0] # remove extension self._namespace = namespace or "default" self._num_examples = None self._cache_dir = cache_dir or config.HF_DATASETS_CACHE def write_from_pcollection(self, pcoll_examples): """Add the final steps of the beam pipeline: write to parquet files.""" import apache_beam as beam def inc_num_examples(example): beam.metrics.Metrics.counter(self._namespace, "num_examples").inc() # count examples _ = pcoll_examples | "Count N. Examples" >> beam.Map(inc_num_examples) # save dataset return ( pcoll_examples | "Get values" >> beam.Values() | "Save to parquet" >> beam.io.parquetio.WriteToParquet( self._parquet_path, self._schema, shard_name_template="-SSSSS-of-NNNNN.parquet" ) ) def finalize(self, metrics_query_result: dict): """ Run after the pipeline has finished. It converts the resulting parquet files to arrow and it completes the info from the pipeline metrics. Args: metrics_query_result: `dict` obtained from pipeline_results.metrics().query(m_filter). Make sure that the filter keeps only the metrics for the considered split, under the namespace `split_name`. """ import apache_beam as beam from .utils import beam_utils # Beam FileSystems require the system's path separator in the older versions fs, _, [parquet_path] = fsspec.get_fs_token_paths(self._parquet_path) parquet_path = str(Path(parquet_path)) if not is_remote_filesystem(fs) else fs.unstrip_protocol(parquet_path) shards_metadata = list(beam.io.filesystems.FileSystems.match([parquet_path + "*.parquet"])[0].metadata_list) shards = [metadata.path for metadata in shards_metadata] num_bytes = sum([metadata.size_in_bytes for metadata in shards_metadata]) shard_lengths = get_parquet_lengths(shards) # Convert to arrow if self._path.endswith(".arrow"): logger.info(f"Converting parquet files {self._parquet_path} to arrow {self._path}") shards = [ metadata.path for metadata in beam.io.filesystems.FileSystems.match([parquet_path + "*.parquet"])[0].metadata_list ] try: # stream conversion num_bytes = 0 for shard in hf_tqdm(shards, unit="shards"): with beam.io.filesystems.FileSystems.open(shard) as source: with beam.io.filesystems.FileSystems.create( shard.replace(".parquet", ".arrow") ) as destination: shard_num_bytes, _ = parquet_to_arrow(source, destination) num_bytes += shard_num_bytes except OSError as e: # broken pipe can happen if the connection is unstable, do local conversion instead if e.errno != errno.EPIPE: # not a broken pipe raise logger.warning( "Broken Pipe during stream conversion from parquet to arrow. Using local convert instead" ) local_convert_dir = os.path.join(self._cache_dir, "beam_convert") os.makedirs(local_convert_dir, exist_ok=True) num_bytes = 0 for shard in hf_tqdm(shards, unit="shards"): local_parquet_path = os.path.join(local_convert_dir, hash_url_to_filename(shard) + ".parquet") beam_utils.download_remote_to_local(shard, local_parquet_path) local_arrow_path = local_parquet_path.replace(".parquet", ".arrow") shard_num_bytes, _ = parquet_to_arrow(local_parquet_path, local_arrow_path) num_bytes += shard_num_bytes remote_arrow_path = shard.replace(".parquet", ".arrow") beam_utils.upload_local_to_remote(local_arrow_path, remote_arrow_path) # Save metrics counters_dict = {metric.key.metric.name: metric.result for metric in metrics_query_result["counters"]} self._num_examples = counters_dict["num_examples"] self._num_bytes = num_bytes self._shard_lengths = shard_lengths return self._num_examples, self._num_bytes def get_parquet_lengths(sources) -> List[int]: shard_lengths = [] for source in hf_tqdm(sources, unit="parquet files"): parquet_file = pa.parquet.ParquetFile(source) shard_lengths.append(parquet_file.metadata.num_rows) return shard_lengths def parquet_to_arrow(source, destination) -> List[int]: """Convert parquet file to arrow file. Inputs can be str paths or file-like objects""" stream = None if isinstance(destination, str) else destination with ArrowWriter(path=destination, stream=stream) as writer: parquet_file = pa.parquet.ParquetFile(source) for record_batch in parquet_file.iter_batches(): pa_table = pa.Table.from_batches([record_batch]) writer.write_table(pa_table) num_bytes, num_examples = writer.finalize() return num_bytes, num_examples
0
hf_public_repos/datasets/src
hf_public_repos/datasets/src/datasets/iterable_dataset.py
import copy import itertools import sys import warnings from collections import Counter from copy import deepcopy from dataclasses import dataclass from functools import partial from itertools import cycle, islice from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union import numpy as np import pyarrow as pa from . import config from .arrow_dataset import Dataset, DatasetInfoMixin from .features import Features from .features.features import FeatureType, _align_features, _check_if_features_can_be_aligned, cast_to_python_objects from .filesystems import _reset_fsspec_lock from .formatting import PythonFormatter, TensorFormatter, get_format_type_from_alias, get_formatter from .info import DatasetInfo from .splits import NamedSplit from .table import cast_table_to_features, read_schema_from_file, table_cast from .utils.logging import get_logger from .utils.py_utils import Literal from .utils.sharding import _merge_gen_kwargs, _number_of_shards_in_gen_kwargs, _shuffle_gen_kwargs, _split_gen_kwargs logger = get_logger(__name__) Key = Union[int, str] def identity_func(x): return x def _rename_columns_fn(example: Dict, column_mapping: Dict[str, str]): if any(col not in example for col in column_mapping): raise ValueError( f"Error when renaming {list(column_mapping)} to {list(column_mapping.values())}: columns {set(column_mapping) - set(example)} are not in the dataset." ) if any(col in example for col in column_mapping.values()): raise ValueError( f"Error when renaming {list(column_mapping)} to {list(column_mapping.values())}: columns {set(example) - set(column_mapping.values())} are already in the dataset." ) return { new_column_name: example[original_column_name] for original_column_name, new_column_name in column_mapping.items() } def add_column_fn(example: Dict, idx: int, name: str, column: List[Dict]): if name in example: raise ValueError(f"Error when adding {name}: column {name} is already in the dataset.") return {name: column[idx]} def _infer_features_from_batch(batch: Dict[str, list], try_features: Optional[Features] = None) -> Features: pa_table = pa.Table.from_pydict(batch) if try_features is not None: try: pa_table = table_cast(pa_table, pa.schema(try_features.type)) except (TypeError, pa.ArrowInvalid, pa.ArrowNotImplementedError): pass return Features.from_arrow_schema(pa_table.schema) def _examples_to_batch(examples: List[Dict[str, Any]]) -> Dict[str, list]: # we order the columns by order of appearance # to do so, we use a dict as an ordered set cols = {col: None for example in examples for col in example} # when an example is missing a column, we set the value to None with .get() arrays = [[example.get(col) for example in examples] for col in cols] return dict(zip(cols, arrays)) def _batch_to_examples(batch: Dict[str, list]) -> List[Dict[str, Any]]: """Convert a batch (dict of examples) to examples list""" n_examples = len(batch[next(iter(batch))]) for i in range(n_examples): yield {col: array[i] for col, array in batch.items()} class _HasNextIterator(Iterator): """Iterator with an hasnext() function. Taken from https://stackoverflow.com/questions/1966591/has-next-in-python-iterators.""" def __init__(self, it): self.it = iter(it) self._hasnext = None def __iter__(self): return self def __next__(self): if self._hasnext: result = self._thenext else: result = next(self.it) self._hasnext = None return result def hasnext(self): if self._hasnext is None: try: self._thenext = next(self.it) except StopIteration: self._hasnext = False else: self._hasnext = True return self._hasnext def _convert_to_arrow( iterable: Iterable[Tuple[Key, dict]], batch_size: int, drop_last_batch: bool = False, ) -> Iterator[Tuple[Key, pa.Table]]: """Convert and group examples in Arrow tables of size `batch_size`. Args: iterable (`Iterable[Tuple[Key, dict]]`): An examples iterable containing tuples (example_key, example) of type (int/str, dict) batch_size (`Optional[int]`): Size of each sub-table to yield. If None or <= 0, yields the full table. drop_last_batch (`bool`, defaults to `False`): Drop the last batch if it is smaller than `batch_size`. """ if batch_size is None or batch_size <= 0: yield ( "all", pa.Table.from_pylist(cast_to_python_objects([example for _, example in iterable], only_1d_for_numpy=True)), ) return iterator = iter(iterable) for key, example in iterator: iterator_batch = islice(iterator, batch_size - 1) key_examples_list = [(key, example)] + list(iterator_batch) if len(key_examples_list) < batch_size and drop_last_batch: return keys, examples = zip(*key_examples_list) new_key = "_".join(str(key) for key in keys) yield new_key, pa.Table.from_pylist(cast_to_python_objects(examples, only_1d_for_numpy=True)) def _batch_arrow_tables( iterable: Iterable[Tuple[Key, pa.Table]], batch_size: Optional[int], drop_last_batch: bool = False, ) -> Iterator[Tuple[Key, pa.Table]]: """Iterate over sub-tables of size `batch_size`. Args: iterable (`Iterable[Tuple[Key, pa.Table]]`): A tables iterable containing tuples (table_key, table) of type (int/str, pa.Table) batch_size (`Optional[int]`): Size of each sub-table to yield. If None or <= 0, yields the full table. drop_last_batch (`bool`, defaults to `False`): Drop the last batch if it is smaller than `batch_size`. """ if batch_size is None or batch_size <= 0: yield "all", pa.concat_tables([pa_table for _, pa_table in iterable]) return keys_buffer = [] chunks_buffer = [] chunks_buffer_size = 0 for key, pa_table in iterable: for chunk in pa_table.to_reader(max_chunksize=batch_size): if len(chunk) == 0: continue elif chunks_buffer_size + len(chunk) < batch_size: keys_buffer.append(key) chunks_buffer.append(chunk) chunks_buffer_size += len(chunk) continue elif chunks_buffer_size + len(chunk) == batch_size: keys_buffer.append(key) chunks_buffer.append(chunk) new_key = "_".join(str(_key) for _key in keys_buffer) yield new_key, pa.Table.from_batches(chunks_buffer) keys_buffer = [] chunks_buffer = [] chunks_buffer_size = 0 else: cropped_chunk_length = batch_size - chunks_buffer_size keys_buffer.append(f"{key}[:{cropped_chunk_length}]") chunks_buffer.append(chunk.slice(0, cropped_chunk_length)) new_key = "_".join(str(_key) for _key in keys_buffer) yield new_key, pa.Table.from_batches(chunks_buffer) keys_buffer = [f"{key}[{cropped_chunk_length}:]"] chunks_buffer = [chunk.slice(cropped_chunk_length, len(chunk) - cropped_chunk_length)] chunks_buffer_size = len(chunk) - cropped_chunk_length if not drop_last_batch and chunks_buffer: new_key = "_".join(str(_key) for _key in keys_buffer) yield new_key, pa.Table.from_batches(chunks_buffer) class _BaseExamplesIterable: """Base class for the examples iterable used by an IterableDataset""" def __init__(self) -> None: self.iter_arrow: Optional[Callable[[], Iterator[Tuple[Key, pa.Table]]]] = None def __iter__(self) -> Iterator[Tuple[Key, dict]]: """An examples iterable should yield tuples (example_key, example) of type (int/str, dict)""" raise NotImplementedError(f"{type(self)} doesn't implement __iter__ yet") def shuffle_data_sources(self, generator: np.random.Generator) -> "_BaseExamplesIterable": """ Either shuffle the shards/sources of the dataset, or propagate the shuffling to the underlying iterable. If the order of the shards must stay fixed (when using .skip or .take for example), then this method returns self. """ raise NotImplementedError(f"{type(self)} doesn't implement shuffle_data_sources yet") def shard_data_sources(self, worker_id: int, num_workers: int) -> "_BaseExamplesIterable": """Either keep only the requested shard, or propagate the request to the underlying iterable.""" raise NotImplementedError(f"{type(self)} doesn't implement shard_data_sources yet") def split_shard_indices_by_worker(self, worker_id: int, num_workers: int) -> List[int]: return list(range(worker_id, self.n_shards, num_workers)) @property def n_shards(self) -> int: raise NotImplementedError(f"{type(self)} doesn't implement n_shards yet") class ExamplesIterable(_BaseExamplesIterable): def __init__(self, generate_examples_fn: Callable[..., Tuple[Key, dict]], kwargs: dict): super().__init__() self.generate_examples_fn = generate_examples_fn self.kwargs = kwargs def __iter__(self): yield from self.generate_examples_fn(**self.kwargs) def shuffle_data_sources(self, generator: np.random.Generator) -> "ExamplesIterable": return ShuffledDataSourcesExamplesIterable(self.generate_examples_fn, self.kwargs, generator) def shard_data_sources(self, worker_id: int, num_workers: int) -> "ExamplesIterable": """Keep only the requested shard.""" gen_kwargs_list = _split_gen_kwargs(self.kwargs, max_num_jobs=self.n_shards) shard_indices = self.split_shard_indices_by_worker(worker_id, num_workers) requested_gen_kwargs = _merge_gen_kwargs([gen_kwargs_list[i] for i in shard_indices]) return ExamplesIterable(self.generate_examples_fn, requested_gen_kwargs) @property def n_shards(self) -> int: return _number_of_shards_in_gen_kwargs(self.kwargs) class ShuffledDataSourcesExamplesIterable(ExamplesIterable): def __init__( self, generate_examples_fn: Callable[..., Tuple[Key, dict]], kwargs: dict, generator: np.random.Generator ): super().__init__(generate_examples_fn, kwargs) self.generator = deepcopy(generator) def __iter__(self): """Shuffle the kwargs order to shuffle shards""" rng = deepcopy(self.generator) kwargs_with_shuffled_shards = _shuffle_gen_kwargs(rng, self.kwargs) yield from self.generate_examples_fn(**kwargs_with_shuffled_shards) def shard_data_sources(self, worker_id: int, num_workers: int) -> "ExamplesIterable": """Keep only the requested shard.""" rng = deepcopy(self.generator) kwargs_with_shuffled_shards = _shuffle_gen_kwargs(rng, self.kwargs) return ExamplesIterable(self.generate_examples_fn, kwargs_with_shuffled_shards).shard_data_sources( worker_id, num_workers ) class ArrowExamplesIterable(_BaseExamplesIterable): def __init__(self, generate_tables_fn: Callable[..., Tuple[Key, pa.Table]], kwargs: dict): super().__init__() self.generate_tables_fn = generate_tables_fn self.kwargs = kwargs self.iter_arrow = self._iter_arrow def __iter__(self): formatter = PythonFormatter() for key, pa_table in self.generate_tables_fn(**self.kwargs): for pa_subtable in pa_table.to_reader(max_chunksize=config.ARROW_READER_BATCH_SIZE_IN_DATASET_ITER): formatted_batch = formatter.format_batch(pa_subtable) for example in _batch_to_examples(formatted_batch): yield key, example def _iter_arrow(self): yield from self.generate_tables_fn(**self.kwargs) def shuffle_data_sources(self, generator: np.random.Generator) -> "ArrowExamplesIterable": return ShuffledDataSourcesArrowExamplesIterable(self.generate_tables_fn, self.kwargs, generator) def shard_data_sources(self, worker_id: int, num_workers: int) -> "ArrowExamplesIterable": """Keep only the requested shard.""" gen_kwargs_list = _split_gen_kwargs(self.kwargs, max_num_jobs=self.n_shards) shard_indices = self.split_shard_indices_by_worker(worker_id, num_workers) requested_gen_kwargs = _merge_gen_kwargs([gen_kwargs_list[i] for i in shard_indices]) return ArrowExamplesIterable(self.generate_tables_fn, requested_gen_kwargs) @property def n_shards(self) -> int: return _number_of_shards_in_gen_kwargs(self.kwargs) class ShuffledDataSourcesArrowExamplesIterable(ArrowExamplesIterable): def __init__( self, generate_tables_fn: Callable[..., Tuple[Key, pa.Table]], kwargs: dict, generator: np.random.Generator, ): super().__init__(generate_tables_fn, kwargs) self.generator = deepcopy(generator) def __iter__(self): """Shuffle the kwargs order to shuffle shards""" rng = deepcopy(self.generator) kwargs_with_shuffled_shards = _shuffle_gen_kwargs(rng, self.kwargs) formatter = PythonFormatter() for key, pa_table in self.generate_tables_fn(**kwargs_with_shuffled_shards): for pa_subtable in pa_table.to_reader(max_chunksize=config.ARROW_READER_BATCH_SIZE_IN_DATASET_ITER): formatted_batch = formatter.format_batch(pa_subtable) for example in _batch_to_examples(formatted_batch): yield key, example def _iter_arrow(self): rng = deepcopy(self.generator) kwargs_with_shuffled_shards = _shuffle_gen_kwargs(rng, self.kwargs) yield from self.generate_tables_fn(**kwargs_with_shuffled_shards) def shard_data_sources(self, worker_id: int, num_workers: int) -> "ArrowExamplesIterable": """Keep only the requested shard.""" rng = deepcopy(self.generator) kwargs_with_shuffled_shards = _shuffle_gen_kwargs(rng, self.kwargs) return ArrowExamplesIterable(self.generate_tables_fn, kwargs_with_shuffled_shards).shard_data_sources( worker_id, num_workers ) class SelectColumnsIterable(_BaseExamplesIterable): def __init__(self, ex_iterable: _BaseExamplesIterable, column_names: List[str]): super().__init__() self.ex_iterable = ex_iterable self.column_names = column_names if self.ex_iterable.iter_arrow: self.iter_arrow = self._iter_arrow def __iter__(self): for idx, row in self.ex_iterable: yield idx, {c: row[c] for c in self.column_names} def _iter_arrow(self) -> Iterator[Tuple[Key, pa.Table]]: for idx, pa_table in self.ex_iterable.iter_arrow(): yield idx, pa_table.select(self.column_names) def shuffle_data_sources(self, generator: np.random.Generator) -> "SelectColumnsIterable": return SelectColumnsIterable(self.ex_iterable.shuffle_data_sources(generator), self.column_names) def shard_data_sources(self, worker_id: int, num_workers: int) -> "SelectColumnsIterable": return SelectColumnsIterable(self.ex_iterable.shard_data_sources(worker_id, num_workers), self.column_names) @property def n_shards(self) -> int: return self.ex_iterable.n_shards class StepExamplesIterable(_BaseExamplesIterable): def __init__(self, ex_iterable: _BaseExamplesIterable, step: int, offset: int): super().__init__() self.ex_iterable = ex_iterable self.step = step self.offset = offset # TODO(QL): implement iter_arrow def __iter__(self): ex_iterator = iter(self.ex_iterable) while True: batch = list(islice(ex_iterator, self.step)) if len(batch) > self.offset: yield batch[self.offset] else: break def shuffle_data_sources(self, generator: np.random.Generator) -> "StepExamplesIterable": return StepExamplesIterable( self.ex_iterable.shuffle_data_sources(generator), step=self.step, offset=self.offset ) def shard_data_sources(self, worker_id: int, num_workers: int) -> "StepExamplesIterable": return StepExamplesIterable( self.ex_iterable.shard_data_sources(worker_id, num_workers), step=self.step, offset=self.offset ) @property def n_shards(self) -> int: return self.ex_iterable.n_shards class CyclingMultiSourcesExamplesIterable(_BaseExamplesIterable): def __init__( self, ex_iterables: List[_BaseExamplesIterable], stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "first_exhausted", ): super().__init__() self.ex_iterables = ex_iterables self.stopping_strategy = stopping_strategy # if undersampling ("first_exhausted"), we stop as soon as one dataset is exhausted # if oversampling ("all_exhausted"), we stop as soons as every dataset is exhausted, i.e as soon as every samples of every dataset has been visited at least once self.bool_strategy_func = np.all if (stopping_strategy == "all_exhausted") else np.any # TODO(QL): implement iter_arrow def _get_indices_iterator(self): # this is an infinite iterator to keep track of which iterator we want to pick examples from return cycle(range(len(self.ex_iterables))) def __iter__(self): iterators = [_HasNextIterator(ex_iterable) for ex_iterable in self.ex_iterables] indices_iterator = self._get_indices_iterator() is_exhausted = np.full(len(self.ex_iterables), False) for i in indices_iterator: try: # let's pick one example from the iterator at index i yield next(iterators[i]) # it will resume from the yield at the next call so that we can directly test if the iterable is exhausted and if we need to break out of the loop if not iterators[i].hasnext(): is_exhausted[i] = True if self.bool_strategy_func(is_exhausted): # if the stopping criteria is met, break the main for loop break # otherwise reinitialise the iterator and yield the first example iterators[i] = _HasNextIterator(self.ex_iterables[i]) except StopIteration: # here it means that the i-th iterabledataset is empty, i.e we never have the occasion to yield an element of the i-th dataset. # we still check if the stopping criteria is met and if we break out of the loop in case of an oversampling strategy is_exhausted[i] = True if self.bool_strategy_func(is_exhausted): # if the stopping criteria is met, break the main for loop break def shuffle_data_sources(self, generator: np.random.Generator) -> "CyclingMultiSourcesExamplesIterable": """Shuffle each underlying examples iterable.""" ex_iterables = [ex_iterable.shuffle_data_sources(generator) for ex_iterable in self.ex_iterables] return CyclingMultiSourcesExamplesIterable(ex_iterables, self.stopping_strategy) @property def n_shards(self) -> int: return min(ex_iterable.n_shards for ex_iterable in self.ex_iterables) def shard_data_sources(self, worker_id: int, num_workers: int) -> "CyclingMultiSourcesExamplesIterable": """Either keep only the requested shard, or propagate the request to the underlying iterable.""" return CyclingMultiSourcesExamplesIterable( [iterable.shard_data_sources(worker_id, num_workers) for iterable in self.ex_iterables], stopping_strategy=self.stopping_strategy, ) class VerticallyConcatenatedMultiSourcesExamplesIterable(_BaseExamplesIterable): """ VerticallyConcatenatedMultiSourcesExamplesIterable simply chains the input iterables. It doesn't require the examples iterables to always yield the same columns. Instead, this is handled by the `IterableDataset` class or `TypedExamplesIterable`. For information, `IterableDataset` merges the features of all the datasets to concatenate into one. We use `IterableDataset._resolve_features` to obtain the features of all the datasets to concatenate. Then for each example, `IterableDataset` and `TypedExamplesIterable` automatically fill missing columns with None. This is done with `_apply_feature_types_on_example`. """ def __init__(self, ex_iterables: List[_BaseExamplesIterable]): super().__init__() self.ex_iterables = ex_iterables if all(ex_iterable.iter_arrow is not None for ex_iterable in ex_iterables): self.iter_arrow = self._iter_arrow def __iter__(self): for ex_iterable in self.ex_iterables: yield from ex_iterable def _iter_arrow(self): for ex_iterable in self.ex_iterables: yield from ex_iterable.iter_arrow() def shuffle_data_sources( self, generator: np.random.Generator ) -> "VerticallyConcatenatedMultiSourcesExamplesIterable": """Shuffle the list of examples iterable, as well as each underlying examples iterable.""" rng = deepcopy(generator) ex_iterables = list(self.ex_iterables) rng.shuffle(ex_iterables) ex_iterables = [ex_iterable.shuffle_data_sources(generator) for ex_iterable in ex_iterables] return VerticallyConcatenatedMultiSourcesExamplesIterable(ex_iterables) @property def n_shards(self) -> int: return min(ex_iterable.n_shards for ex_iterable in self.ex_iterables) def shard_data_sources( self, worker_id: int, num_workers: int ) -> "VerticallyConcatenatedMultiSourcesExamplesIterable": """Either keep only the requested shard, or propagate the request to the underlying iterable.""" return VerticallyConcatenatedMultiSourcesExamplesIterable( [iterable.shard_data_sources(worker_id, num_workers) for iterable in self.ex_iterables] ) def _check_column_names(column_names: List[str]): """Check the column names to make sure they don't contain duplicates.""" counter = Counter(column_names) if not all(count == 1 for count in counter.values()): duplicated_columns = [col for col in counter if counter[col] > 1] raise ValueError( f"The examples iterables can't have duplicated columns but columns {duplicated_columns} are duplicated." ) class HorizontallyConcatenatedMultiSourcesExamplesIterable(_BaseExamplesIterable): """ HorizontallyConcatenatedMultiSourcesExamplesIterable merges examples together for the input list of iterables. It also checks that there are no duplicate columns (otherwise we don't know which one to keep). This check is done once when yielding the first example. However it doesn't fill missing columns with None. Instead, this is handled by the `IterableDataset` class or `TypedExamplesIterable`. For information, `IterableDataset` merges the features of all the datasets to concatenate into one. We use `IterableDataset._resolve_features` to obtain the features of all the datasets to concatenate. Then for each example, `IterableDataset` and `TypedExamplesIterable` automatically fill missing columns with None. This is done with `_apply_feature_types_on_example`. """ def __init__(self, ex_iterables: List[_BaseExamplesIterable]): super().__init__() self.ex_iterables = ex_iterables # TODO(QL): implement iter_arrow def __iter__(self): ex_iterators = [iter(ex_iterable) for ex_iterable in self.ex_iterables] for i in itertools.count(): keys = [] examples = [] for ex_iterator in list(ex_iterators): try: key, example = next(ex_iterator) keys.append(key) examples.append(example) except StopIteration: ex_iterators.remove(ex_iterator) if ex_iterators: if i == 0: _check_column_names([column_name for example in examples for column_name in example]) new_example = {} for example in examples: new_example.update(example) new_key = "_".join(str(key) for key in keys) yield new_key, new_example else: break def shuffle_data_sources( self, generator: np.random.Generator ) -> "HorizontallyConcatenatedMultiSourcesExamplesIterable": """Doesn't shuffle the wrapped examples iterable since it would break the alignment between them.""" return self @property def n_shards(self) -> int: return 1 def shard_data_sources( self, worker_id: int, num_workers: int ) -> "HorizontallyConcatenatedMultiSourcesExamplesIterable": """Either keep only the requested shard, or propagate the request to the underlying iterable.""" return HorizontallyConcatenatedMultiSourcesExamplesIterable( [iterable.shard_data_sources(worker_id, num_workers) for iterable in self.ex_iterables] ) class RandomlyCyclingMultiSourcesExamplesIterable(CyclingMultiSourcesExamplesIterable): def __init__( self, ex_iterables: List[_BaseExamplesIterable], generator: np.random.Generator, probabilities: Optional[List[float]] = None, stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "first_exhausted", ): super().__init__(ex_iterables, stopping_strategy) self.generator = deepcopy(generator) self.probabilities = probabilities # TODO(QL): implement iter_arrow @staticmethod def _iter_random_indices( rng: np.random.Generator, num_sources: int, random_batch_size=1000, p: Optional[List[float]] = None, ) -> Iterator[int]: """Get an infinite iterator that randomly samples the index of the source to pick examples from.""" if p is None: while True: yield from (int(i) for i in rng.integers(0, num_sources, size=random_batch_size)) else: while True: yield from (int(i) for i in rng.choice(num_sources, size=random_batch_size, p=p)) def _get_indices_iterator(self): rng = deepcopy(self.generator) # this is an infinite iterator that randomly samples the index of the source to pick examples from return self._iter_random_indices(rng, len(self.ex_iterables), p=self.probabilities) def shuffle_data_sources(self, generator: np.random.Generator) -> "RandomlyCyclingMultiSourcesExamplesIterable": """Shuffle the data sources of each wrapped examples iterable.""" ex_iterables = [ex_iterable.shuffle_data_sources(generator) for ex_iterable in self.ex_iterables] return RandomlyCyclingMultiSourcesExamplesIterable( ex_iterables, generator=generator, probabilities=self.probabilities, stopping_strategy=self.stopping_strategy, ) def shard_data_sources(self, worker_id: int, num_workers: int) -> "RandomlyCyclingMultiSourcesExamplesIterable": """Either keep only the requested shard, or propagate the request to the underlying iterable.""" return RandomlyCyclingMultiSourcesExamplesIterable( [iterable.shard_data_sources(worker_id, num_workers) for iterable in self.ex_iterables], self.generator, self.probabilities, self.stopping_strategy, ) class MappedExamplesIterable(_BaseExamplesIterable): def __init__( self, ex_iterable: _BaseExamplesIterable, function: Callable, with_indices: bool = False, input_columns: Optional[List[str]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: bool = False, remove_columns: Optional[List[str]] = None, fn_kwargs: Optional[dict] = None, formatting: Optional["FormattingConfig"] = None, format_type="deprecated", ): if format_type != "deprecated": warning_msg = "'format_type' is deprecated and will be removed in the next major version of datasets. " help_message = "Please use 'formatting=FormattingConfig(format_type=format_type)' instead." warnings.warn(warning_msg + help_message, category=FutureWarning, stacklevel=2) formatting = FormattingConfig(format_type=format_type) super().__init__() self.ex_iterable = ex_iterable self.function = function self.batched = batched self.batch_size = batch_size self.drop_last_batch = drop_last_batch self.remove_columns = remove_columns self.with_indices = with_indices self.input_columns = input_columns self.fn_kwargs = fn_kwargs or {} self.formatting = formatting if self.formatting and self.formatting.format_type == "arrow": self.iter_arrow = self._iter_arrow def __iter__(self): if self.formatting and self.formatting.format_type == "arrow": yield from ArrowExamplesIterable(self._iter_arrow, {}) else: yield from self._iter() def _iter(self): iterator = iter(self.ex_iterable) current_idx = 0 if self.formatting: formatter = get_formatter(self.formatting.format_type) format_dict = ( formatter.recursive_tensorize if isinstance(formatter, TensorFormatter) else cast_to_python_objects ) else: format_dict = None if self.batched: for key, example in iterator: # If `batched`, first build the batch, if `batch_size` is None or <=0, then the batch is the whole dataset iterator_batch = ( iterator if self.batch_size is None or self.batch_size <= 0 else islice(iterator, self.batch_size - 1) ) key_examples_list = [(key, example)] + list(iterator_batch) keys, examples = zip(*key_examples_list) if ( self.drop_last_batch and self.batch_size is not None and self.batch_size > 0 and len(examples) < self.batch_size ): # ignore last batch return batch = _examples_to_batch(examples) batch = format_dict(batch) if format_dict else batch # then apply the transform inputs = batch function_args = [inputs] if self.input_columns is None else [inputs[col] for col in self.input_columns] if self.with_indices: function_args.append([current_idx + i for i in range(len(key_examples_list))]) transformed_batch = dict(batch) # this will be updated with the function output transformed_batch.update(self.function(*function_args, **self.fn_kwargs)) # then remove the unwanted columns if self.remove_columns: for c in self.remove_columns: del transformed_batch[c] if transformed_batch: first_col = next(iter(transformed_batch)) bad_cols = [ col for col in transformed_batch if len(transformed_batch[col]) != len(transformed_batch[first_col]) ] if bad_cols: raise ValueError( f"Column lengths mismatch: columns {bad_cols} have length {[len(transformed_batch[col]) for col in bad_cols]} while {first_col} has length {len(transformed_batch[first_col])}." ) # the new key is the concatenation of the examples keys from the batch new_key = "_".join(str(key) for key in keys) # yield one example at a time from the transformed batch for example in _batch_to_examples(transformed_batch): yield new_key, example current_idx += 1 else: for key, example in iterator: # If not batched, we can apply the transform and yield the example directly # first copy the example, since we might drop some keys example = dict(example) example = format_dict(example) if format_dict else example # then apply the transform inputs = example function_args = [inputs] if self.input_columns is None else [inputs[col] for col in self.input_columns] if self.with_indices: function_args.append(current_idx) transformed_example = dict(example) # this will be updated with the function output transformed_example.update(self.function(*function_args, **self.fn_kwargs)) # then we remove the unwanted columns if self.remove_columns: for c in self.remove_columns: del transformed_example[c] yield key, transformed_example current_idx += 1 def _iter_arrow(self) -> Iterator[Tuple[Key, pa.Table]]: if self.ex_iterable.iter_arrow: iterator = _batch_arrow_tables( self.ex_iterable.iter_arrow(), batch_size=self.batch_size if self.batched else 1, drop_last_batch=self.drop_last_batch, ) else: iterator = _convert_to_arrow( self.ex_iterable, batch_size=self.batch_size if self.batched else 1, drop_last_batch=self.drop_last_batch, ) current_idx = 0 for key, pa_table in iterator: # first build the batch function_args = [pa_table] if self.input_columns is None else [pa_table[col] for col in self.input_columns] if self.with_indices: if self.batched: function_args.append([current_idx + i for i in range(len(pa_table))]) else: function_args.append(current_idx) # then apply the transform output_table = self.function(*function_args, **self.fn_kwargs) if not isinstance(output_table, pa.Table): raise TypeError( f"Provided `function` which is applied to pyarrow tables returns a variable of type {type(output_table)}. Make sure provided `function` returns a a pyarrow table to update the dataset." ) # we don't need to merge results for consistency with Dataset.map which merges iif both input and output are dicts # then remove the unwanted columns if self.remove_columns: for column in self.remove_columns: if column in output_table.column_names: output_table = output_table.remove_column(output_table.column_names.index(column)) # return output yield key, output_table current_idx += len(pa_table) def shuffle_data_sources(self, generator: np.random.Generator) -> "MappedExamplesIterable": """Shuffle the wrapped examples iterable.""" return MappedExamplesIterable( self.ex_iterable.shuffle_data_sources(generator), function=self.function, with_indices=self.with_indices, input_columns=self.input_columns, batched=self.batched, batch_size=self.batch_size, drop_last_batch=self.drop_last_batch, remove_columns=self.remove_columns, fn_kwargs=self.fn_kwargs, formatting=self.formatting, ) def shard_data_sources(self, worker_id: int, num_workers: int) -> "MappedExamplesIterable": """Keep only the requested shard.""" return MappedExamplesIterable( self.ex_iterable.shard_data_sources(worker_id, num_workers), function=self.function, with_indices=self.with_indices, input_columns=self.input_columns, batched=self.batched, batch_size=self.batch_size, drop_last_batch=self.drop_last_batch, remove_columns=self.remove_columns, fn_kwargs=self.fn_kwargs, formatting=self.formatting, ) @property def n_shards(self) -> int: return self.ex_iterable.n_shards class FilteredExamplesIterable(_BaseExamplesIterable): def __init__( self, ex_iterable: _BaseExamplesIterable, function: Callable, with_indices: bool = False, input_columns: Optional[List[str]] = None, batched: bool = False, batch_size: Optional[int] = 1000, fn_kwargs: Optional[dict] = None, formatting: Optional["FormattingConfig"] = None, format_type="deprecated", ): if format_type != "deprecated": warning_msg = "'format_type' is deprecated and will be removed in the next major version of datasets. " help_message = "Please use 'formatting=FormattingConfig(format_type=format_type)' instead." warnings.warn(warning_msg + help_message, category=FutureWarning, stacklevel=2) formatting = FormattingConfig(format_type=format_type) super().__init__() self.ex_iterable = ex_iterable self.function = function self.batched = batched self.batch_size = batch_size self.with_indices = with_indices self.input_columns = input_columns self.fn_kwargs = fn_kwargs or {} self.formatting = formatting if self.formatting and self.formatting.format_type == "arrow": self.iter_arrow = self._iter_arrow def __iter__(self): if self.formatting and self.formatting.format_type == "arrow": yield from ArrowExamplesIterable(self._iter_arrow, {}) else: yield from self._iter() def _iter(self): if self.formatting: formatter = get_formatter(self.formatting.format_type) format_dict = ( formatter.recursive_tensorize if isinstance(formatter, TensorFormatter) else cast_to_python_objects ) else: format_dict = None iterator = iter(self.ex_iterable) current_idx = 0 if self.batched: for key, example in iterator: # If `batched`, first build the batch, if `batch_size` is None or <=0, then the batch is the whole dataset iterator_batch = ( iterator if self.batch_size is None or self.batch_size <= 0 else islice(iterator, self.batch_size - 1) ) key_examples_list = [(key, example)] + list(iterator_batch) keys, examples = zip(*key_examples_list) batch = _examples_to_batch(examples) batch = format_dict(batch) if format_dict else batch # then compute the mask for the batch inputs = batch function_args = [inputs] if self.input_columns is None else [inputs[col] for col in self.input_columns] if self.with_indices: function_args.append([current_idx + i for i in range(len(key_examples_list))]) mask = self.function(*function_args, **self.fn_kwargs) # yield one example at a time from the batch for key_example, to_keep in zip(key_examples_list, mask): if to_keep: yield key_example current_idx += 1 else: for key, example in iterator: # If not batched, we can apply the filtering function direcly example = dict(example) inputs = format_dict(example) if format_dict else example function_args = [inputs] if self.input_columns is None else [inputs[col] for col in self.input_columns] if self.with_indices: function_args.append(current_idx) to_keep = self.function(*function_args, **self.fn_kwargs) if to_keep: yield key, example current_idx += 1 def _iter_arrow(self): if self.ex_iterable.iter_arrow: iterator = _batch_arrow_tables( self.ex_iterable.iter_arrow(), batch_size=self.batch_size if self.batched else 1 ) else: iterator = _convert_to_arrow(self.ex_iterable, batch_size=self.batch_size if self.batched else 1) current_idx = 0 for key, pa_table in iterator: # first build the batch function_args = [pa_table] if self.input_columns is None else [pa_table[col] for col in self.input_columns] if self.with_indices: if self.batched: function_args.append([current_idx + i for i in range(len(pa_table))]) else: function_args.append(current_idx) # then apply the transform mask = self.function(*function_args, **self.fn_kwargs) # yield the filtered table if self.batched: yield key, pa_table.filter(mask) elif mask.as_py() if isinstance(mask, pa.BooleanScalar) else mask: yield key, pa_table current_idx += len(pa_table) def shuffle_data_sources(self, seed: Optional[int]) -> "FilteredExamplesIterable": """Shuffle the wrapped examples iterable.""" return FilteredExamplesIterable( self.ex_iterable.shuffle_data_sources(seed), function=self.function, with_indices=self.with_indices, input_columns=self.input_columns, batched=self.batched, batch_size=self.batch_size, ) def shard_data_sources(self, worker_id: int, num_workers: int) -> "FilteredExamplesIterable": """Keep only the requested shard.""" return FilteredExamplesIterable( self.ex_iterable.shard_data_sources(worker_id, num_workers), function=self.function, with_indices=self.with_indices, input_columns=self.input_columns, batched=self.batched, batch_size=self.batch_size, ) @property def n_shards(self) -> int: return self.ex_iterable.n_shards class BufferShuffledExamplesIterable(_BaseExamplesIterable): def __init__(self, ex_iterable: _BaseExamplesIterable, buffer_size: int, generator: np.random.Generator): super().__init__() self.ex_iterable = ex_iterable self.buffer_size = buffer_size self.generator = generator # TODO(QL): implement iter_arrow @staticmethod def _iter_random_indices(rng: np.random.Generator, buffer_size: int, random_batch_size=1000) -> Iterator[int]: while True: yield from (int(i) for i in rng.integers(0, buffer_size, size=random_batch_size)) def __iter__(self): buffer_size = self.buffer_size rng = deepcopy(self.generator) indices_iterator = self._iter_random_indices(rng, buffer_size) # this is the shuffle buffer that we keep in memory mem_buffer = [] for x in self.ex_iterable: if len(mem_buffer) == buffer_size: # if the buffer is full, pick and example from it i = next(indices_iterator) yield mem_buffer[i] mem_buffer[i] = x # replace the picked example by a new one else: # otherwise, keep filling the buffer mem_buffer.append(x) # when we run out of examples, we shuffle the remaining examples in the buffer and yield them rng.shuffle(mem_buffer) yield from mem_buffer def shuffle_data_sources(self, generator: np.random.Generator) -> "BufferShuffledExamplesIterable": """Shuffle the wrapped examples iterable as well as the shuffling buffer.""" return BufferShuffledExamplesIterable( self.ex_iterable.shuffle_data_sources(generator), buffer_size=self.buffer_size, generator=generator ) def shard_data_sources(self, worker_id: int, num_workers: int) -> "BufferShuffledExamplesIterable": """Keep only the requested shard.""" return BufferShuffledExamplesIterable( self.ex_iterable.shard_data_sources(worker_id, num_workers), buffer_size=self.buffer_size, generator=self.generator, ) @property def n_shards(self) -> int: return self.ex_iterable.n_shards class SkipExamplesIterable(_BaseExamplesIterable): def __init__(self, ex_iterable: _BaseExamplesIterable, n: int): super().__init__() self.ex_iterable = ex_iterable self.n = n # TODO(QL): implement iter_arrow def __iter__(self): yield from islice(self.ex_iterable, self.n, None) def shuffle_data_sources(self, generator: np.random.Generator) -> "SkipExamplesIterable": """Doesn't shuffle the wrapped examples iterable since it would skip examples from other shards instead.""" return self @property def n_shards(self) -> int: return self.ex_iterable.n_shards class TakeExamplesIterable(_BaseExamplesIterable): def __init__(self, ex_iterable: _BaseExamplesIterable, n: int): super().__init__() self.ex_iterable = ex_iterable self.n = n # TODO(QL): implement iter_arrow def __iter__(self): yield from islice(self.ex_iterable, self.n) def shuffle_data_sources(self, generator: np.random.Generator) -> "TakeExamplesIterable": """Doesn't shuffle the wrapped examples iterable since it would take examples from other shards instead.""" return self @staticmethod def split_number(num, n): quotient = num // n remainder = num % n result = [quotient] * n for i in range(remainder): result[i] += 1 return result def shard_data_sources(self, worker_id: int, num_workers: int) -> "TakeExamplesIterable": """Keep only the requested shard.""" return TakeExamplesIterable( self.ex_iterable.shard_data_sources(worker_id, num_workers), n=self.split_number(self.n, num_workers)[worker_id], ) @property def n_shards(self) -> int: return self.ex_iterable.n_shards def _apply_feature_types_on_example( example: dict, features: Features, token_per_repo_id: Dict[str, Union[str, bool, None]] ) -> dict: example = dict(example) # add missing columns for column_name in features: if column_name not in example: example[column_name] = None # we encode the example for ClassLabel feature types for example encoded_example = features.encode_example(example) # Decode example for Audio feature, e.g. decoded_example = features.decode_example(encoded_example, token_per_repo_id=token_per_repo_id) return decoded_example def _apply_feature_types_on_batch( batch: dict, features: Features, token_per_repo_id: Dict[str, Union[str, bool, None]] ) -> dict: batch = dict(batch) # add missing columns n_examples = len(batch[next(iter(batch))]) for column_name in features: if column_name not in batch: batch[column_name] = [None] * n_examples # we encode the batch for ClassLabel feature types for example encoded_batch = features.encode_batch(batch) # Decode batch for Audio feature, e.g. decoded_batch = features.decode_batch(encoded_batch, token_per_repo_id=token_per_repo_id) return decoded_batch class TypedExamplesIterable(_BaseExamplesIterable): def __init__( self, ex_iterable: _BaseExamplesIterable, features: Features, token_per_repo_id: Dict[str, Union[str, bool, None]], ): super().__init__() self.ex_iterable = ex_iterable self.features = features self.token_per_repo_id = token_per_repo_id if self.ex_iterable.iter_arrow is not None: self.iter_arrow = self._iter_arrow def __iter__(self): # Then for each example, `TypedExamplesIterable` automatically fills missing columns with None. # This is done with `_apply_feature_types_on_example`. for key, example in self.ex_iterable: yield ( key, _apply_feature_types_on_example(example, self.features, token_per_repo_id=self.token_per_repo_id), ) def _iter_arrow(self) -> Iterator[Tuple[Key, pa.Table]]: schema = self.features.arrow_schema for key, pa_table in self.ex_iterable.iter_arrow(): columns = set(pa_table.column_names) # add missing columns for column_name in self.features: if column_name not in columns: col = pa.NullArray.from_buffers(pa.null(), len(pa_table), [None]) pa_table = pa_table.append_column(column_name, col) if pa_table.schema != schema: pa_table = cast_table_to_features(pa_table, self.features) yield key, pa_table def shuffle_data_sources(self, generator: np.random.Generator) -> "TypedExamplesIterable": """Shuffle the wrapped examples iterable.""" return TypedExamplesIterable( self.ex_iterable.shuffle_data_sources(generator), features=self.features, token_per_repo_id=self.token_per_repo_id, ) def shard_data_sources(self, worker_id: int, num_workers: int) -> "TypedExamplesIterable": """Keep only the requested shard.""" return TypedExamplesIterable( self.ex_iterable.shard_data_sources(worker_id, num_workers), features=self.features, token_per_repo_id=self.token_per_repo_id, ) @property def n_shards(self) -> int: return self.ex_iterable.n_shards @dataclass class FormattingConfig: format_type: Optional[str] def __post_init__(self): if self.format_type == "pandas": raise NotImplementedError( "The 'pandas' formatting is not implemented for iterable datasets. You can use 'numpy' or 'arrow' instead." ) @dataclass class ShufflingConfig: generator: np.random.Generator _original_seed: Optional[int] = None @dataclass class DistributedConfig: rank: int world_size: int def _maybe_add_torch_iterable_dataset_parent_class(cls): """Add torch.utils.data.IterableDataset as a parent class if 'torch' is available""" if config.TORCH_AVAILABLE: import torch.utils.data if torch.utils.data.IterableDataset not in cls.__bases__: cls.__bases__ += (torch.utils.data.IterableDataset,) class IterableDataset(DatasetInfoMixin): """A Dataset backed by an iterable.""" def __init__( self, ex_iterable: _BaseExamplesIterable, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, formatting: Optional[FormattingConfig] = None, shuffling: Optional[ShufflingConfig] = None, distributed: Optional[DistributedConfig] = None, token_per_repo_id: Optional[Dict[str, Union[str, bool, None]]] = None, format_type="deprecated", ): if distributed and distributed.world_size > 1 and shuffling and shuffling._original_seed is None: raise RuntimeError( "The dataset doesn't have a fixed random seed across nodes to shuffle and split the list of dataset shards by node. " "Please pass e.g. `seed=42` in `.shuffle()` to make all the nodes use the same seed. " ) if format_type != "deprecated": warning_msg = "'format_type' is deprecated and will be removed in the next major version of datasets. " help_message = "Please use 'formatting=FormattingConfig(format_type=format_type)' instead." warnings.warn(warning_msg + help_message, category=FutureWarning, stacklevel=2) formatting = FormattingConfig(format_type=format_type) info = info.copy() if info is not None else DatasetInfo() DatasetInfoMixin.__init__(self, info=info, split=split) self._ex_iterable = ex_iterable self._formatting = formatting self._shuffling = shuffling self._distributed = distributed self._epoch = 0 self._token_per_repo_id: Dict[str, Union[str, bool, None]] = token_per_repo_id or {} _maybe_add_torch_iterable_dataset_parent_class(self.__class__) def __repr__(self): return f"IterableDataset({{\n features: {list(self._info.features.keys()) if self._info.features is not None else 'Unknown'},\n n_shards: {self.n_shards}\n}})" def __getstate__(self): return self.__dict__ def __setstate__(self, d): self.__dict__ = d # Re-add torch iterable dataset as a parent class, since dynamically added parent classes are not kept when pickling _maybe_add_torch_iterable_dataset_parent_class(self.__class__) def _head(self, n=5): return _examples_to_batch(list(self.take(n))) def _effective_generator(self): if self._shuffling and self._epoch == 0: return self._shuffling.generator elif self._shuffling: # Create effective seed using self._epoch (we subtract in order to avoir overflow in long_scalars) effective_seed = deepcopy(self._shuffling.generator).integers(0, 1 << 63) - self._epoch effective_seed = (1 << 63) + effective_seed if effective_seed < 0 else effective_seed return np.random.default_rng(effective_seed) else: raise ValueError("This dataset is not shuffled") @property def n_shards(self) -> int: if self._distributed and self._ex_iterable.n_shards % self._distributed.world_size == 0: return self._ex_iterable.n_shards // self._distributed.world_size return self._ex_iterable.n_shards def _iter_pytorch(self): ex_iterable = self._prepare_ex_iterable_for_iteration() # fix for fsspec when using multiprocess _reset_fsspec_lock() # check if there aren't too many workers import torch.utils.data worker_info = torch.utils.data.get_worker_info() if self._is_main_process() and ex_iterable.n_shards < worker_info.num_workers: logger.warning( f"Too many dataloader workers: {worker_info.num_workers} (max is dataset.n_shards={ex_iterable.n_shards}). " f"Stopping {worker_info.num_workers - ex_iterable.n_shards} dataloader workers." ) logger.info( f"To parallelize data loading, we give each process some shards (or data sources) to process. " f"Therefore it's unnecessary to have a number of workers greater than dataset.n_shards={ex_iterable.n_shards}. " f"To enable more parallelism, please split the dataset in more files than {ex_iterable.n_shards}." ) # split workload _log_prefix = f"node#{self._distributed.rank} " if self._distributed else "" shards_indices = self._ex_iterable.split_shard_indices_by_worker(worker_info.id, worker_info.num_workers) if shards_indices: logger.debug( f"{_log_prefix}dataloader worker#{worker_info.id}, ': Starting to iterate over {len(shards_indices)}/{ex_iterable.n_shards} shards." ) ex_iterable = ex_iterable.shard_data_sources(worker_id=worker_info.id, num_workers=worker_info.num_workers) if self._formatting: formatter = get_formatter(self._formatting.format_type, features=self.features) format_dict = ( formatter.recursive_tensorize if isinstance(formatter, TensorFormatter) else cast_to_python_objects ) else: format_dict = None if self._formatting and (ex_iterable.iter_arrow or self._formatting == "arrow"): if ex_iterable.iter_arrow: iterator = _batch_arrow_tables(ex_iterable.iter_arrow(), batch_size=1) else: iterator = _convert_to_arrow(ex_iterable, batch_size=1) for key, pa_table in iterator: yield formatter.format_row(pa_table) return else: for key, example in ex_iterable: if self.features: # `IterableDataset` automatically fills missing columns with None. # This is done with `_apply_feature_types_on_example`. example = _apply_feature_types_on_example( example, self.features, token_per_repo_id=self._token_per_repo_id ) yield format_dict(example) if format_dict else example logger.debug( f"{_log_prefix}dataloader worker#{worker_info.id}, ': Finished iterating over {len(shards_indices)}/{ex_iterable.n_shards} shards." ) else: logger.debug( f"{_log_prefix}dataloader worker#{worker_info.id}, ': Stopping... Number of dataset shards < num_workers ({ex_iterable.n_shards}<{worker_info.num_workers})." ) def _is_main_process(self): if self._distributed and self._distributed.rank > 0: return False if "torch" in sys.modules: import torch.utils.data worker_info = torch.utils.data.get_worker_info() if worker_info is not None and worker_info.id > 0: return False return True def _prepare_ex_iterable_for_iteration(self) -> _BaseExamplesIterable: if self._shuffling: ex_iterable = self._ex_iterable.shuffle_data_sources(self._effective_generator()) else: ex_iterable = self._ex_iterable if self._distributed: rank = self._distributed.rank world_size = self._distributed.world_size if ex_iterable.n_shards % world_size == 0: if self._is_main_process(): n_shards_per_node = ex_iterable.n_shards // world_size plural = "s" if n_shards_per_node > 1 else "" logger.info( f"Assigning {n_shards_per_node} shard{plural} (or data source{plural}) of the dataset to each node." ) ex_iterable = ex_iterable.shard_data_sources(rank, world_size) else: if self._is_main_process(): logger.info( f"Assigning 1 out of {world_size} examples of the dataset to each node. The others are skipped during the iteration." ) logger.info( f"It is more optimized to distribute the dataset shards (or data sources) across nodes. " f"You can do that by using a dataset with number of shards that is a factor of world_size={world_size}. " f"The current dataset has {ex_iterable.n_shards} which is not a factor of {world_size}" ) ex_iterable = StepExamplesIterable(ex_iterable, step=world_size, offset=rank) return ex_iterable def __iter__(self): if "torch" in sys.modules: import torch.utils.data worker_info = torch.utils.data.get_worker_info() if isinstance(self, torch.utils.data.IterableDataset) and worker_info is not None: # We're a torch.utils.data.IterableDataset in a PyTorch worker process yield from self._iter_pytorch() return ex_iterable = self._prepare_ex_iterable_for_iteration() if self._formatting: formatter = get_formatter(self._formatting.format_type, features=self.features) format_dict = ( formatter.recursive_tensorize if isinstance(formatter, TensorFormatter) else cast_to_python_objects ) else: format_dict = None if self._formatting and (ex_iterable.iter_arrow or self._formatting.format_type == "arrow"): if ex_iterable.iter_arrow: iterator = _batch_arrow_tables(ex_iterable.iter_arrow(), batch_size=1) else: iterator = _convert_to_arrow(ex_iterable, batch_size=1) for key, pa_table in iterator: yield formatter.format_row(pa_table) return for key, example in ex_iterable: if self.features: # `IterableDataset` automatically fills missing columns with None. # This is done with `_apply_feature_types_on_example`. example = _apply_feature_types_on_example( example, self.features, token_per_repo_id=self._token_per_repo_id ) yield format_dict(example) if format_dict else example def iter(self, batch_size: int, drop_last_batch: bool = False): """Iterate through the batches of size `batch_size`. Args: batch_size (:obj:`int`): size of each batch to yield. drop_last_batch (:obj:`bool`, default `False`): Whether a last batch smaller than the batch_size should be dropped """ if self._formatting: formatter = get_formatter(self._formatting.format_type, features=self.features) format_dict = ( formatter.recursive_tensorize if isinstance(formatter, TensorFormatter) else cast_to_python_objects ) else: format_dict = None ex_iterable = self._prepare_ex_iterable_for_iteration() if self._formatting and (ex_iterable.iter_arrow or self._formatting == "arrow"): if ex_iterable.iter_arrow: iterator = _batch_arrow_tables( ex_iterable.iter_arrow(), batch_size=batch_size, drop_last_batch=drop_last_batch ) else: iterator = _convert_to_arrow(ex_iterable, batch_size=batch_size, drop_last_batch=drop_last_batch) for key, pa_table in iterator: yield formatter.format_batch(pa_table) return iterator = iter(ex_iterable) for key, example in iterator: # If batched, first build the batch examples = [example] + [example for key, example in islice(iterator, batch_size - 1)] if drop_last_batch and len(examples) < batch_size: # ignore last batch return batch = _examples_to_batch(examples) if self.features: # `IterableDataset` automatically fills missing columns with None. # This is done with `_apply_feature_types_on_batch`. batch = _apply_feature_types_on_batch(batch, self.features, token_per_repo_id=self._token_per_repo_id) yield format_dict(batch) if format_dict else batch @staticmethod def from_generator( generator: Callable, features: Optional[Features] = None, gen_kwargs: Optional[dict] = None, ) -> "IterableDataset": """Create an Iterable Dataset from a generator. Args: generator (`Callable`): A generator function that `yields` examples. features (`Features`, *optional*): Dataset features. gen_kwargs(`dict`, *optional*): Keyword arguments to be passed to the `generator` callable. You can define a sharded iterable dataset by passing the list of shards in `gen_kwargs`. This can be used to improve shuffling and when iterating over the dataset with multiple workers. Returns: `IterableDataset` Example: ```py >>> def gen(): ... yield {"text": "Good", "label": 0} ... yield {"text": "Bad", "label": 1} ... >>> ds = IterableDataset.from_generator(gen) ``` ```py >>> def gen(shards): ... for shard in shards: ... with open(shard) as f: ... for line in f: ... yield {"line": line} ... >>> shards = [f"data{i}.txt" for i in range(32)] >>> ds = IterableDataset.from_generator(gen, gen_kwargs={"shards": shards}) >>> ds = ds.shuffle(seed=42, buffer_size=10_000) # shuffles the shards order + uses a shuffle buffer >>> from torch.utils.data import DataLoader >>> dataloader = DataLoader(ds.with_format("torch"), num_workers=4) # give each worker a subset of 32/4=8 shards ``` """ from .io.generator import GeneratorDatasetInputStream return GeneratorDatasetInputStream( generator=generator, features=features, gen_kwargs=gen_kwargs, streaming=True, ).read() @staticmethod def from_spark( df: "pyspark.sql.DataFrame", split: Optional[NamedSplit] = None, features: Optional[Features] = None, **kwargs, ) -> "IterableDataset": """Create an IterableDataset from Spark DataFrame. The dataset is streamed to the driver in batches. Args: df (`pyspark.sql.DataFrame`): The DataFrame containing the desired data. split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. Returns: [`IterableDataset`] Example: ```py >>> df = spark.createDataFrame( >>> data=[[1, "Elia"], [2, "Teo"], [3, "Fang"]], >>> columns=["id", "name"], >>> ) >>> ds = IterableDataset.from_spark(df) ``` """ from .io.spark import SparkDatasetReader if sys.platform == "win32": raise EnvironmentError("IterableDataset.from_spark is not currently supported on Windows") return SparkDatasetReader( df, split=split, features=features, streaming=True, **kwargs, ).read() @staticmethod def from_file(filename: str) -> "IterableDataset": """Instantiate a IterableDataset from Arrow table at filename. Args: filename (`str`): File name of the dataset. Returns: [`IterableDataset`] """ pa_table_schema = read_schema_from_file(filename) inferred_features = Features.from_arrow_schema(pa_table_schema) ex_iterable = ArrowExamplesIterable(Dataset._generate_tables_from_cache_file, kwargs={"filename": filename}) return IterableDataset(ex_iterable=ex_iterable, info=DatasetInfo(features=inferred_features)) def with_format( self, type: Optional[str] = None, ) -> "IterableDataset": """ Return a dataset with the specified format. Supported formats: "arrow", or None for regular python objects. The other formats are currently not implemented. Args: type (`str`, optional, default None): if set to "torch", the returned dataset will be a subclass of torch.utils.data.IterableDataset to be used in a DataLoader """ type = get_format_type_from_alias(type) # TODO(QL): add format_kwargs # TODO(QL): add format_columns and return_all_columns # TODO(QL): add pandas format return IterableDataset( ex_iterable=self._ex_iterable, info=self._info.copy(), split=self._split, formatting=FormattingConfig(format_type=type), shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def map( self, function: Optional[Callable] = None, with_indices: bool = False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: bool = False, remove_columns: Optional[Union[str, List[str]]] = None, features: Optional[Features] = None, fn_kwargs: Optional[dict] = None, ) -> "IterableDataset": """ Apply a function to all the examples in the iterable dataset (individually or in batches) and update them. If your function returns a column that already exists, then it overwrites it. The function is applied on-the-fly on the examples when iterating over the dataset. You can specify whether the function should be batched or not with the `batched` parameter: - If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`. - If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. A batch is a dictionary, e.g. a batch of 1 example is {"text": ["Hello there !"]}. - If batched is `True` and `batch_size` is `n` > 1, then the function takes a batch of `n` examples as input and can return a batch with `n` examples, or with an arbitrary number of examples. Note that the last batch may have less than `n` examples. A batch is a dictionary, e.g. a batch of `n` examples is `{"text": ["Hello there !"] * n}`. Args: function (`Callable`, *optional*, defaults to `None`): Function applied on-the-fly on the examples when you iterate on the dataset. It must have one of the following signatures: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False` - `function(example: Dict[str, Any], idx: int) -> Dict[str, Any]` if `batched=False` and `with_indices=True` - `function(batch: Dict[str, List]) -> Dict[str, List]` if `batched=True` and `with_indices=False` - `function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List]` if `batched=True` and `with_indices=True` For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx[, rank]): ...`. input_columns (`Optional[Union[str, List[str]]]`, defaults to `None`): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, defaults to `1000`): Number of examples per batch provided to `function` if `batched=True`. `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`. drop_last_batch (`bool`, defaults to `False`): Whether a last batch smaller than the batch_size should be dropped instead of being processed by the function. remove_columns (`[List[str]]`, *optional*, defaults to `None`): Remove a selection of columns while doing the mapping. Columns will be removed before updating the examples with the output of `function`, i.e. if `function` is adding columns with names in `remove_columns`, these columns will be kept. features (`[Features]`, *optional*, defaults to `None`): Feature types of the resulting dataset. fn_kwargs (`Dict`, *optional*, default `None`): Keyword arguments to be passed to `function`. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> def add_prefix(example): ... example["text"] = "Review: " + example["text"] ... return example >>> ds = ds.map(add_prefix) >>> list(ds.take(3)) [{'label': 1, 'text': 'Review: the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}, {'label': 1, 'text': 'Review: the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}, {'label': 1, 'text': 'Review: effective but too-tepid biopic'}] ``` """ if isinstance(input_columns, str): input_columns = [input_columns] if isinstance(remove_columns, str): remove_columns = [remove_columns] if function is None: function = identity_func if fn_kwargs is None: fn_kwargs = {} ex_iterable = MappedExamplesIterable( TypedExamplesIterable(self._ex_iterable, self._info.features, token_per_repo_id=self._token_per_repo_id) if self._info.features is not None else self._ex_iterable, function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, drop_last_batch=drop_last_batch, remove_columns=remove_columns, fn_kwargs=fn_kwargs, formatting=self._formatting, ) info = self.info.copy() info.features = features return IterableDataset( ex_iterable=ex_iterable, info=info, split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def filter( self, function: Optional[Callable] = None, with_indices=False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, fn_kwargs: Optional[dict] = None, ) -> "IterableDataset": """Apply a filter function to all the elements so that the dataset only includes examples according to the filter function. The filtering is done on-the-fly when iterating over the dataset. Args: function (`Callable`): Callable with one of the following signatures: - `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False` - `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False` - `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True` - `function(example: Dict[str, List], indices: List[int]) -> List[bool]` if `with_indices=True, batched=True` If no function is provided, defaults to an always True function: `lambda x: True`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`. input_columns (`str` or `List[str]`, *optional*): The columns to be passed into `function` as positional arguments. If `None`, a dict mapping to all formatted columns is passed as one argument. batched (`bool`, defaults to `False`): Provide batch of examples to `function`. batch_size (`int`, *optional*, default `1000`): Number of examples per batch provided to `function` if `batched=True`. fn_kwargs (`Dict`, *optional*, default `None`): Keyword arguments to be passed to `function`. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> ds = ds.filter(lambda x: x["label"] == 0) >>> list(ds.take(3)) [{'label': 0, 'movie_review': 'simplistic , silly and tedious .'}, {'label': 0, 'movie_review': "it's so laddish and juvenile , only teenage boys could possibly find it funny ."}, {'label': 0, 'movie_review': 'exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}] ``` """ if isinstance(input_columns, str): input_columns = [input_columns] # TODO(QL): keep the features (right now if we keep it it would call decode_example again on an already decoded example) info = copy.deepcopy(self._info) info.features = None # We need the examples to be decoded for certain feature types like Image or Audio, so we use TypedExamplesIterable here ex_iterable = FilteredExamplesIterable( TypedExamplesIterable(self._ex_iterable, self._info.features, token_per_repo_id=self._token_per_repo_id) if self._info.features is not None else self._ex_iterable, function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, fn_kwargs=fn_kwargs, formatting=self._formatting, ) return IterableDataset( ex_iterable=ex_iterable, info=info, split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def shuffle( self, seed=None, generator: Optional[np.random.Generator] = None, buffer_size: int = 1000 ) -> "IterableDataset": """ Randomly shuffles the elements of this dataset. This dataset fills a buffer with `buffer_size` elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required. For instance, if your dataset contains 10,000 elements but `buffer_size` is set to 1000, then `shuffle` will initially select a random element from only the first 1000 elements in the buffer. Once an element is selected, its space in the buffer is replaced by the next (i.e. 1,001-st) element, maintaining the 1000 element buffer. If the dataset is made of several shards, it also does shuffle the order of the shards. However if the order has been fixed by using [`~datasets.IterableDataset.skip`] or [`~datasets.IterableDataset.take`] then the order of the shards is kept unchanged. Args: seed (`int`, *optional*, defaults to `None`): Random seed that will be used to shuffle the dataset. It is used to sample from the shuffle buffer and also to shuffle the data shards. generator (`numpy.random.Generator`, *optional*): Numpy random Generator to use to compute the permutation of the dataset rows. If `generator=None` (default), uses `np.random.default_rng` (the default BitGenerator (PCG64) of NumPy). buffer_size (`int`, defaults to `1000`): Size of the buffer. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> list(ds.take(3)) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}, {'label': 1, 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}, {'label': 1, 'text': 'effective but too-tepid biopic'}] >>> shuffled_ds = ds.shuffle(seed=42) >>> list(shuffled_ds.take(3)) [{'label': 1, 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."}, {'label': 1, 'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'}, {'label': 1, 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}] ``` """ if generator is None: generator = np.random.default_rng(seed) else: generator = deepcopy(generator) shuffling = ShufflingConfig(generator=generator, _original_seed=seed) return IterableDataset( ex_iterable=BufferShuffledExamplesIterable( self._ex_iterable, buffer_size=buffer_size, generator=generator ).shuffle_data_sources(generator), info=self._info.copy(), split=self._split, formatting=self._formatting, shuffling=shuffling, distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def set_epoch(self, epoch: int): self._epoch = epoch def skip(self, n) -> "IterableDataset": """ Create a new [`IterableDataset`] that skips the first `n` elements. Args: n (`int`): Number of elements to skip. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> list(ds.take(3)) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}, {'label': 1, 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}, {'label': 1, 'text': 'effective but too-tepid biopic'}] >>> ds = ds.skip(1) >>> list(ds.take(3)) [{'label': 1, 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}, {'label': 1, 'text': 'effective but too-tepid biopic'}, {'label': 1, 'text': 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'}] ``` """ ex_iterable = SkipExamplesIterable(self._ex_iterable, n) return IterableDataset( ex_iterable=ex_iterable, info=self._info.copy(), split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def take(self, n) -> "IterableDataset": """ Create a new [`IterableDataset`] with only the first `n` elements. Args: n (`int`): Number of elements to take. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> small_ds = ds.take(2) >>> list(small_ds) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}, {'label': 1, 'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}] ``` """ ex_iterable = TakeExamplesIterable(self._ex_iterable, n) return IterableDataset( ex_iterable=ex_iterable, info=self._info.copy(), split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) @property def column_names(self) -> Optional[List[str]]: """Names of the columns in the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation", streaming=True) >>> ds.column_names ['text', 'label'] ``` """ return list(self._info.features.keys()) if self._info.features is not None else None def add_column(self, name: str, column: Union[list, np.array]) -> "IterableDataset": """Add column to Dataset. Args: name (str): Column name. column (list or np.array): Column data to be added. Returns: `IterableDataset` """ return self.map(partial(add_column_fn, name=name, column=column), with_indices=True) def rename_column(self, original_column_name: str, new_column_name: str) -> "IterableDataset": """ Rename a column in the dataset, and move the features associated to the original column under the new column name. Args: original_column_name (`str`): Name of the column to rename. new_column_name (`str`): New name for the column. Returns: `IterableDataset`: A copy of the dataset with a renamed column. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> next(iter(ds)) {'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} >>> ds = ds.rename_column("text", "movie_review") >>> next(iter(ds)) {'label': 1, 'movie_review': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ return self.rename_columns({original_column_name: new_column_name}) def rename_columns(self, column_mapping: Dict[str, str]) -> "IterableDataset": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. Args: column_mapping (`Dict[str, str]`): A mapping of columns to rename to their new names Returns: `IterableDataset`: A copy of the dataset with renamed columns """ original_features = self._info.features.copy() if self._info.features else None ds_iterable = self.map( partial(_rename_columns_fn, column_mapping=column_mapping), remove_columns=list(column_mapping) ) if original_features is not None: ds_iterable._info.features = Features( { column_mapping[col] if col in column_mapping.keys() else col: feature for col, feature in original_features.items() } ) # check that it's still valid, especially with regard to task templates try: ds_iterable._info.copy() except ValueError: ds_iterable._info.task_templates = None return ds_iterable def remove_columns(self, column_names: Union[str, List[str]]) -> "IterableDataset": """ Remove one or several column(s) in the dataset and the features associated to them. The removal is done on-the-fly on the examples when iterating over the dataset. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to remove. Returns: `IterableDataset`: A copy of the dataset object without the columns to remove. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> next(iter(ds)) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1} >>> ds = ds.remove_columns("label") >>> next(iter(ds)) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ original_features = self._info.features.copy() if self._info.features else None ds_iterable = self.map(remove_columns=column_names) if original_features is not None: ds_iterable._info.features = original_features.copy() for col, _ in original_features.items(): if col in column_names: del ds_iterable._info.features[col] # check that it's still valid, especially with regard to task templates try: ds_iterable._info.copy() except ValueError: ds_iterable._info.task_templates = None return ds_iterable def select_columns(self, column_names: Union[str, List[str]]) -> "IterableDataset": """Select one or several column(s) in the dataset and the features associated to them. The selection is done on-the-fly on the examples when iterating over the dataset. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to select. Returns: `IterableDataset`: A copy of the dataset object with selected columns. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> next(iter(ds)) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1} >>> ds = ds.select_columns("text") >>> next(iter(ds)) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'} ``` """ if isinstance(column_names, str): column_names = [column_names] if self._info: info = copy.deepcopy(self._info) if self._info.features is not None: for column_name in column_names: if column_name not in self._info.features: raise ValueError( f"Column name {column_name} not in the " "dataset. Columns in the dataset: " f"{list(self._info.features.keys())}." ) info.features = Features({c: info.features[c] for c in column_names}) # check that it's still valid, especially with regard to task templates try: info.copy() except ValueError: info.task_templates = None ex_iterable = SelectColumnsIterable(self._ex_iterable, column_names) return IterableDataset( ex_iterable=ex_iterable, info=info, split=self._split, formatting=self._formatting, shuffling=self._shuffling, distributed=self._distributed, token_per_repo_id=self._token_per_repo_id, ) def cast_column(self, column: str, feature: FeatureType) -> "IterableDataset": """Cast column to feature for decoding. Args: column (`str`): Column name. feature (`Feature`): Target feature. Returns: `IterableDataset` Example: ```py >>> from datasets import load_dataset, Audio >>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train", streaming=True) >>> ds.features {'audio': Audio(sampling_rate=8000, mono=True, decode=True, id=None), 'english_transcription': Value(dtype='string', id=None), 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan', 'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill'], id=None), 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN'], id=None), 'path': Value(dtype='string', id=None), 'transcription': Value(dtype='string', id=None)} >>> ds = ds.cast_column("audio", Audio(sampling_rate=16000)) >>> ds.features {'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None), 'english_transcription': Value(dtype='string', id=None), 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan', 'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill'], id=None), 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN'], id=None), 'path': Value(dtype='string', id=None), 'transcription': Value(dtype='string', id=None)} ``` """ info = self._info.copy() info.features[column] = feature # check that it's still valid, especially with regard to task templates try: info.copy() except ValueError: info.task_templates = None return IterableDataset( ex_iterable=self._ex_iterable, info=info, split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def cast( self, features: Features, ) -> "IterableDataset": """ Cast the dataset to a new set of features. Args: features ([`Features`]): New features to cast the dataset to. The name of the fields in the features must match the current column names. The type of the data must also be convertible from one type to the other. For non-trivial conversion, e.g. `string` <-> `ClassLabel` you should use [`~Dataset.map`] to update the Dataset. Returns: `IterableDataset`: A copy of the dataset with casted features. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> ds.features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds.features.copy() >>> new_features["label"] = ClassLabel(names=["bad", "good"]) >>> new_features["text"] = Value("large_string") >>> ds = ds.cast(new_features) >>> ds.features {'label': ClassLabel(num_classes=2, names=['bad', 'good'], id=None), 'text': Value(dtype='large_string', id=None)} ``` """ info = self._info.copy() info.features = features # check that it's still valid, especially with regard to task templates try: info.copy() except ValueError: info.task_templates = None return IterableDataset( ex_iterable=self._ex_iterable, info=info, split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def _step(self, step: int, offset: int) -> "IterableDataset": ex_iterable = StepExamplesIterable(self._ex_iterable, step=step, offset=offset) return IterableDataset( ex_iterable=ex_iterable, info=self._info.copy(), split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def _resolve_features(self): if self.features is not None: return self elif isinstance(self._ex_iterable, TypedExamplesIterable): features = self._ex_iterable.features else: features = _infer_features_from_batch(self.with_format(None)._head()) info = self.info.copy() info.features = features return IterableDataset( ex_iterable=self._ex_iterable, info=info, split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, ) def _concatenate_iterable_datasets( dsets: List[IterableDataset], info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, axis: int = 0, ) -> IterableDataset: """ Converts a list of `IterableDataset` with the same schema into a single `IterableDataset`. Missing data are filled with None values. <Added version="2.4.0"/> Args: dsets (`List[datasets.IterableDataset]`): List of Datasets to concatenate. info (`DatasetInfo`, optional): Dataset information, like description, citation, etc. split (`NamedSplit`, optional): Name of the dataset split. axis (``{0, 1}``, default ``0``, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). *New in version 1.6.0* Example: ```py >>> ds3 = _concatenate_iterable_datasets([ds1, ds2]) ``` """ dsets = [d._resolve_features() for d in dsets] # Perform checks (and a potentional cast if axis=0) if axis == 0: _check_if_features_can_be_aligned([dset.features for dset in dsets]) else: _check_column_names([col_name for dset in dsets for col_name in dset.features]) # TODO: improve this to account for a mix of ClassLabel and Value for example # right now it would keep the type of the first dataset in the list features = Features( {k: v for features in _align_features([dset.features for dset in dsets]) for k, v in features.items()} ) ex_iterables = [d._ex_iterable for d in dsets] if axis == 0: ex_iterable = VerticallyConcatenatedMultiSourcesExamplesIterable(ex_iterables) else: ex_iterable = HorizontallyConcatenatedMultiSourcesExamplesIterable(ex_iterables) # Set new info - we update the features # setting the features also ensures to fill missing columns with None if info is None: info = DatasetInfo.from_merge([d.info for d in dsets]) else: info = info.copy() info.features = features # Get all the auth tokens per repository - in case the datasets come from different private repositories token_per_repo_id = {repo_id: token for dataset in dsets for repo_id, token in dataset._token_per_repo_id.items()} # Return new daset return IterableDataset(ex_iterable=ex_iterable, info=info, split=split, token_per_repo_id=token_per_repo_id) def _interleave_iterable_datasets( datasets: List[IterableDataset], probabilities: Optional[List[float]] = None, seed: Optional[int] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "first_exhausted", ) -> IterableDataset: """ Interleave several iterable datasets (sources) into a single iterable dataset. The new iterable dataset alternates between the sources to yield examples. If `probabilities = None` (default) the iterable dataset will cycles through the sources in order for each next example in the iteration. If `probabilities` is not `None, the iterable dataset will sample a random source according to the provided probabilities for each next examples in the iteration. <Added version="2.4.0"/> Args: datasets (`List[IterableDataset]`): list of datasets to interleave probabilities (`List[float]`, optional, default None): If specified, the new iterable dataset samples examples from one source at a time according to these probabilities. seed (`int`, optional, default None): The random seed used to choose a source for each example. stopping_strategy (`str`, defaults to `first_exhausted`): Two strategies are proposed right now. By default, `first_exhausted` is an undersampling strategy, i.e the dataset construction is stopped as soon as one dataset has ran out of samples. If the strategy is `all_exhausted`, we use an oversampling strategy, i.e the dataset construction is stopped as soon as every samples of every dataset has been added at least once. Note that if the strategy is `all_exhausted`, the interleaved dataset size can get enormous: - with no probabilities, the resulting dataset will have max_length_datasets*nb_dataset samples. - with given probabilities, the resulting dataset will have more samples if some datasets have really low probability of visiting. Output: `datasets.IterableDataset` """ datasets = [d._resolve_features() for d in datasets] # Perform checks _check_if_features_can_be_aligned([dset.features for dset in datasets]) # TODO: improve this to account for a mix of ClassLabel and Value for example # right now it would keep the type of the first dataset in the list features = Features( {k: v for features in _align_features([dset.features for dset in datasets]) for k, v in features.items()} ) ex_iterables = [d._ex_iterable for d in datasets] # Use cycling or random cycling of sources if probabilities is None: ex_iterable = CyclingMultiSourcesExamplesIterable(ex_iterables, stopping_strategy=stopping_strategy) else: generator = np.random.default_rng(seed) ex_iterable = RandomlyCyclingMultiSourcesExamplesIterable( ex_iterables, generator=generator, probabilities=probabilities, stopping_strategy=stopping_strategy ) # Set new info - we update the features # setting the features also ensures to fill missing columns with None if info is None: info = DatasetInfo.from_merge([d.info for d in datasets]) else: info = info.copy() info.features = features # Get all the auth tokens per repository - in case the datasets come from different private repositories token_per_repo_id = { repo_id: token for dataset in datasets for repo_id, token in dataset._token_per_repo_id.items() } # Return new daset return IterableDataset(ex_iterable=ex_iterable, info=info, split=split, token_per_repo_id=token_per_repo_id) def _split_by_node_iterable_dataset(dataset: IterableDataset, rank: int, world_size: int) -> IterableDataset: """ Split an iterable dataset for the node at rank `rank` in a pool of nodes of size `world_size`. If the dataset has a number of shards that is a factor of `world_size` (i.e. if `dataset.n_shards % world_size == 0`), then the shards are evenly assigned across the nodes, which is the most optimized. Otherwise, each node keeps 1 example out of `world_size`, skipping the other examples. Args: dataset ([`IterableDataset`]): The iterable dataset to split by node. rank (`int`): Rank of the current node. world_size (`int`): Total number of nodes. Returns: [`IterableDataset`]: The iterable dataset to be used on the node at rank `rank`. """ if dataset._distributed: world_size = world_size * dataset._distributed.world_size rank = world_size * dataset._distributed.rank + rank distributed = DistributedConfig(rank=rank, world_size=world_size) return IterableDataset( ex_iterable=dataset._ex_iterable, info=dataset._info.copy(), split=dataset._split, formatting=dataset._formatting, shuffling=copy.deepcopy(dataset._shuffling), distributed=distributed, token_per_repo_id=dataset._token_per_repo_id, )
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/parallel/__init__.py
from .parallel import parallel_backend, parallel_map, ParallelBackendConfig # noqa F401
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/parallel/parallel.py
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging logger = logging.get_logger(__name__) class ParallelBackendConfig: backend_name = None @experimental def parallel_map(function, iterable, num_proc, types, disable_tqdm, desc, single_map_nested_func): """ **Experimental.** Apply a function to iterable elements in parallel, where the implementation uses either multiprocessing.Pool or joblib for parallelization. Args: function (`Callable[[Any], Any]`): Function to be applied to `iterable`. iterable (`list`, `tuple` or `np.ndarray`): Iterable elements to apply function to. num_proc (`int`): Number of processes (if no backend specified) or jobs (using joblib). types (`tuple`): Additional types (besides `dict` values) to apply `function` recursively to their elements. disable_tqdm (`bool`): Whether to disable the tqdm progressbar. desc (`str`): Prefix for the tqdm progressbar. single_map_nested_func (`Callable`): Map function that applies `function` to an element from `iterable`. Takes a tuple of function, data_struct, types, rank, disable_tqdm, desc as input, where data_struct is an element of `iterable`, and `rank` is used for progress bar. """ if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( function, iterable, num_proc, types, disable_tqdm, desc, single_map_nested_func ) return _map_with_joblib(function, iterable, num_proc, types, disable_tqdm, desc, single_map_nested_func) def _map_with_multiprocessing_pool(function, iterable, num_proc, types, disable_tqdm, desc, single_map_nested_func): num_proc = num_proc if num_proc <= len(iterable) else len(iterable) split_kwds = [] # We organize the splits ourselve (contiguous splits) for index in range(num_proc): div = len(iterable) // num_proc mod = len(iterable) % num_proc start = div * index + min(index, mod) end = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)) if len(iterable) != sum(len(i[1]) for i in split_kwds): raise ValueError( f"Error dividing inputs iterable among processes. " f"Total number of objects {len(iterable)}, " f"length: {sum(len(i[1]) for i in split_kwds)}" ) logger.info( f"Spawning {num_proc} processes for {len(iterable)} objects in slices of {[len(i[1]) for i in split_kwds]}" ) initargs, initializer = None, None if not disable_tqdm: initargs, initializer = (RLock(),), tqdm.set_lock with Pool(num_proc, initargs=initargs, initializer=initializer) as pool: mapped = pool.map(single_map_nested_func, split_kwds) logger.info(f"Finished {num_proc} processes") mapped = [obj for proc_res in mapped for obj in proc_res] logger.info(f"Unpacked {len(mapped)} objects") return mapped def _map_with_joblib(function, iterable, num_proc, types, disable_tqdm, desc, single_map_nested_func): # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib, # and it requires monkey-patching joblib internal classes which is subject to change import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name, n_jobs=num_proc): return joblib.Parallel()( joblib.delayed(single_map_nested_func)((function, obj, types, None, True, None)) for obj in iterable ) @experimental @contextlib.contextmanager def parallel_backend(backend_name: str): """ **Experimental.** Configures the parallel backend for parallelized dataset loading, which uses the parallelization implemented by joblib. Args: backend_name (str): Name of backend for parallelization implementation, has to be supported by joblib. Example usage: ```py with parallel_backend('spark'): dataset = load_dataset(..., num_proc=2) ``` """ ParallelBackendConfig.backend_name = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: ParallelBackendConfig.backend_name = None
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/parquet.py
import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import tqdm as hf_tqdm from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def get_writer_batch_size(features: Features) -> Optional[int]: """ Get the writer_batch_size that defines the maximum row group size in the parquet files. The default in `datasets` is 1,000 but we lower it to 100 for image datasets. This allows to optimize random access to parquet file, since accessing 1 row requires to read its entire row group. This can be improved to get optimized size for querying/iterating but at least it matches the dataset viewer expectations on HF. Args: ds_config_info (`datasets.info.DatasetInfo`): Dataset info from `datasets`. Returns: writer_batch_size (`Optional[int]`): Writer batch size to pass to a dataset builder. If `None`, then it will use the `datasets` default. """ batch_size = np.inf def set_batch_size(feature: FeatureType) -> None: nonlocal batch_size if isinstance(feature, Image): batch_size = min(batch_size, config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS) elif isinstance(feature, Audio): batch_size = min(batch_size, config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS) elif isinstance(feature, Value) and feature.dtype == "binary": batch_size = min(batch_size, config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS) _visit(features, set_batch_size) return None if batch_size is np.inf else batch_size class ParquetDatasetReader(AbstractDatasetReader): def __init__( self, path_or_paths: NestedDataStructureLike[PathLike], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, num_proc: Optional[int] = None, **kwargs, ): super().__init__( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, num_proc=num_proc, **kwargs, ) path_or_paths = path_or_paths if isinstance(path_or_paths, dict) else {self.split: path_or_paths} hash = _PACKAGED_DATASETS_MODULES["parquet"][1] self.builder = Parquet( cache_dir=cache_dir, data_files=path_or_paths, features=features, hash=hash, **kwargs, ) def read(self): # Build iterable dataset if self.streaming: dataset = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, # try_from_hf_gcs=try_from_hf_gcs, base_path=base_path, num_proc=self.num_proc, ) dataset = self.builder.as_dataset( split=self.split, verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset class ParquetDatasetWriter: def __init__( self, dataset: Dataset, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[int] = None, **parquet_writer_kwargs, ): self.dataset = dataset self.path_or_buf = path_or_buf self.batch_size = batch_size or get_writer_batch_size(dataset.features) self.parquet_writer_kwargs = parquet_writer_kwargs def write(self) -> int: batch_size = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf, (str, bytes, os.PathLike)): with open(self.path_or_buf, "wb+") as buffer: written = self._write(file_obj=buffer, batch_size=batch_size, **self.parquet_writer_kwargs) else: written = self._write(file_obj=self.path_or_buf, batch_size=batch_size, **self.parquet_writer_kwargs) return written def _write(self, file_obj: BinaryIO, batch_size: int, **parquet_writer_kwargs) -> int: """Writes the pyarrow table as Parquet to a binary file handle. Caller is responsible for opening and closing the handle. """ written = 0 _ = parquet_writer_kwargs.pop("path_or_buf", None) schema = self.dataset.features.arrow_schema writer = pq.ParquetWriter(file_obj, schema=schema, **parquet_writer_kwargs) for offset in hf_tqdm( range(0, len(self.dataset), batch_size), unit="ba", desc="Creating parquet from Arrow format", ): batch = query_table( table=self.dataset._data, key=slice(offset, offset + batch_size), indices=self.dataset._indices, ) writer.write_table(batch) written += batch.nbytes writer.close() return written
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/abc.py
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class AbstractDatasetReader(ABC): def __init__( self, path_or_paths: Optional[NestedDataStructureLike[PathLike]] = None, split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, num_proc: Optional[int] = None, **kwargs, ): self.path_or_paths = path_or_paths self.split = split if split or isinstance(path_or_paths, dict) else "train" self.features = features self.cache_dir = cache_dir self.keep_in_memory = keep_in_memory self.streaming = streaming self.num_proc = num_proc self.kwargs = kwargs @abstractmethod def read(self) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: pass class AbstractDatasetInputStream(ABC): def __init__( self, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, num_proc: Optional[int] = None, **kwargs, ): self.features = features self.cache_dir = cache_dir self.keep_in_memory = keep_in_memory self.streaming = streaming self.num_proc = num_proc self.kwargs = kwargs @abstractmethod def read(self) -> Union[Dataset, IterableDataset]: pass
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/csv.py
import multiprocessing import os from typing import BinaryIO, Optional, Union from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.csv.csv import Csv from ..utils import tqdm as hf_tqdm from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class CsvDatasetReader(AbstractDatasetReader): def __init__( self, path_or_paths: NestedDataStructureLike[PathLike], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, num_proc: Optional[int] = None, **kwargs, ): super().__init__( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, num_proc=num_proc, **kwargs, ) path_or_paths = path_or_paths if isinstance(path_or_paths, dict) else {self.split: path_or_paths} self.builder = Csv( cache_dir=cache_dir, data_files=path_or_paths, features=features, **kwargs, ) def read(self): # Build iterable dataset if self.streaming: dataset = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, # try_from_hf_gcs=try_from_hf_gcs, base_path=base_path, num_proc=self.num_proc, ) dataset = self.builder.as_dataset( split=self.split, verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset class CsvDatasetWriter: def __init__( self, dataset: Dataset, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[int] = None, num_proc: Optional[int] = None, **to_csv_kwargs, ): if num_proc is not None and num_proc <= 0: raise ValueError(f"num_proc {num_proc} must be an integer > 0.") self.dataset = dataset self.path_or_buf = path_or_buf self.batch_size = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE self.num_proc = num_proc self.encoding = "utf-8" self.to_csv_kwargs = to_csv_kwargs def write(self) -> int: _ = self.to_csv_kwargs.pop("path_or_buf", None) header = self.to_csv_kwargs.pop("header", True) index = self.to_csv_kwargs.pop("index", False) if isinstance(self.path_or_buf, (str, bytes, os.PathLike)): with open(self.path_or_buf, "wb+") as buffer: written = self._write(file_obj=buffer, header=header, index=index, **self.to_csv_kwargs) else: written = self._write(file_obj=self.path_or_buf, header=header, index=index, **self.to_csv_kwargs) return written def _batch_csv(self, args): offset, header, index, to_csv_kwargs = args batch = query_table( table=self.dataset.data, key=slice(offset, offset + self.batch_size), indices=self.dataset._indices, ) csv_str = batch.to_pandas().to_csv( path_or_buf=None, header=header if (offset == 0) else False, index=index, **to_csv_kwargs ) return csv_str.encode(self.encoding) def _write(self, file_obj: BinaryIO, header, index, **to_csv_kwargs) -> int: """Writes the pyarrow table as CSV to a binary file handle. Caller is responsible for opening and closing the handle. """ written = 0 if self.num_proc is None or self.num_proc == 1: for offset in hf_tqdm( range(0, len(self.dataset), self.batch_size), unit="ba", desc="Creating CSV from Arrow format", ): csv_str = self._batch_csv((offset, header, index, to_csv_kwargs)) written += file_obj.write(csv_str) else: num_rows, batch_size = len(self.dataset), self.batch_size with multiprocessing.Pool(self.num_proc) as pool: for csv_str in hf_tqdm( pool.imap( self._batch_csv, [(offset, header, index, to_csv_kwargs) for offset in range(0, num_rows, batch_size)], ), total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size, unit="ba", desc="Creating CSV from Arrow format", ): written += file_obj.write(csv_str) return written
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/generator.py
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class GeneratorDatasetInputStream(AbstractDatasetInputStream): def __init__( self, generator: Callable, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, gen_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, **kwargs, ): super().__init__( features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, num_proc=num_proc, **kwargs, ) self.builder = Generator( cache_dir=cache_dir, features=features, generator=generator, gen_kwargs=gen_kwargs, **kwargs, ) def read(self): # Build iterable dataset if self.streaming: dataset = self.builder.as_streaming_dataset(split="train") # Build regular (map-style) dataset else: download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, try_from_hf_gcs=False, base_path=base_path, num_proc=self.num_proc, ) dataset = self.builder.as_dataset( split="train", verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/sql.py
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import tqdm as hf_tqdm from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlite3 import sqlalchemy class SqlDatasetReader(AbstractDatasetInputStream): def __init__( self, sql: Union[str, "sqlalchemy.sql.Selectable"], con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, **kwargs, ): super().__init__(features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs) self.builder = Sql( cache_dir=cache_dir, features=features, sql=sql, con=con, **kwargs, ) def read(self): download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, # try_from_hf_gcs=try_from_hf_gcs, base_path=base_path, ) # Build dataset for splits dataset = self.builder.as_dataset( split="train", verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset class SqlDatasetWriter: def __init__( self, dataset: Dataset, name: str, con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"], batch_size: Optional[int] = None, num_proc: Optional[int] = None, **to_sql_kwargs, ): if num_proc is not None and num_proc <= 0: raise ValueError(f"num_proc {num_proc} must be an integer > 0.") self.dataset = dataset self.name = name self.con = con self.batch_size = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE self.num_proc = num_proc self.to_sql_kwargs = to_sql_kwargs def write(self) -> int: _ = self.to_sql_kwargs.pop("sql", None) _ = self.to_sql_kwargs.pop("con", None) index = self.to_sql_kwargs.pop("index", False) written = self._write(index=index, **self.to_sql_kwargs) return written def _batch_sql(self, args): offset, index, to_sql_kwargs = args to_sql_kwargs = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs batch = query_table( table=self.dataset.data, key=slice(offset, offset + self.batch_size), indices=self.dataset._indices, ) df = batch.to_pandas() num_rows = df.to_sql(self.name, self.con, index=index, **to_sql_kwargs) return num_rows or len(df) def _write(self, index, **to_sql_kwargs) -> int: """Writes the pyarrow table as SQL to a database. Caller is responsible for opening and closing the SQL connection. """ written = 0 if self.num_proc is None or self.num_proc == 1: for offset in hf_tqdm( range(0, len(self.dataset), self.batch_size), unit="ba", desc="Creating SQL from Arrow format", ): written += self._batch_sql((offset, index, to_sql_kwargs)) else: num_rows, batch_size = len(self.dataset), self.batch_size with multiprocessing.Pool(self.num_proc) as pool: for num_rows in hf_tqdm( pool.imap( self._batch_sql, [(offset, index, to_sql_kwargs) for offset in range(0, num_rows, batch_size)], ), total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size, unit="ba", desc="Creating SQL from Arrow format", ): written += num_rows return written
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/json.py
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import tqdm as hf_tqdm from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class JsonDatasetReader(AbstractDatasetReader): def __init__( self, path_or_paths: NestedDataStructureLike[PathLike], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, field: Optional[str] = None, num_proc: Optional[int] = None, **kwargs, ): super().__init__( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, num_proc=num_proc, **kwargs, ) self.field = field path_or_paths = path_or_paths if isinstance(path_or_paths, dict) else {self.split: path_or_paths} self.builder = Json( cache_dir=cache_dir, data_files=path_or_paths, features=features, field=field, **kwargs, ) def read(self): # Build iterable dataset if self.streaming: dataset = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, # try_from_hf_gcs=try_from_hf_gcs, base_path=base_path, num_proc=self.num_proc, ) dataset = self.builder.as_dataset( split=self.split, verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset class JsonDatasetWriter: def __init__( self, dataset: Dataset, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[int] = None, num_proc: Optional[int] = None, **to_json_kwargs, ): if num_proc is not None and num_proc <= 0: raise ValueError(f"num_proc {num_proc} must be an integer > 0.") self.dataset = dataset self.path_or_buf = path_or_buf self.batch_size = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE self.num_proc = num_proc self.encoding = "utf-8" self.to_json_kwargs = to_json_kwargs def write(self) -> int: _ = self.to_json_kwargs.pop("path_or_buf", None) orient = self.to_json_kwargs.pop("orient", "records") lines = self.to_json_kwargs.pop("lines", True if orient == "records" else False) if "index" not in self.to_json_kwargs and orient in ["split", "table"]: self.to_json_kwargs["index"] = False compression = self.to_json_kwargs.pop("compression", None) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(f"`datasets` currently does not support {compression} compression") if isinstance(self.path_or_buf, (str, bytes, os.PathLike)): with fsspec.open(self.path_or_buf, "wb", compression=compression) as buffer: written = self._write(file_obj=buffer, orient=orient, lines=lines, **self.to_json_kwargs) else: if compression: raise NotImplementedError( f"The compression parameter is not supported when writing to a buffer, but compression={compression}" " was passed. Please provide a local path instead." ) written = self._write(file_obj=self.path_or_buf, orient=orient, lines=lines, **self.to_json_kwargs) return written def _batch_json(self, args): offset, orient, lines, to_json_kwargs = args batch = query_table( table=self.dataset.data, key=slice(offset, offset + self.batch_size), indices=self.dataset._indices, ) json_str = batch.to_pandas().to_json(path_or_buf=None, orient=orient, lines=lines, **to_json_kwargs) if not json_str.endswith("\n"): json_str += "\n" return json_str.encode(self.encoding) def _write( self, file_obj: BinaryIO, orient, lines, **to_json_kwargs, ) -> int: """Writes the pyarrow table as JSON lines to a binary file handle. Caller is responsible for opening and closing the handle. """ written = 0 if self.num_proc is None or self.num_proc == 1: for offset in hf_tqdm( range(0, len(self.dataset), self.batch_size), unit="ba", desc="Creating json from Arrow format", ): json_str = self._batch_json((offset, orient, lines, to_json_kwargs)) written += file_obj.write(json_str) else: num_rows, batch_size = len(self.dataset), self.batch_size with multiprocessing.Pool(self.num_proc) as pool: for json_str in hf_tqdm( pool.imap( self._batch_json, [(offset, orient, lines, to_json_kwargs) for offset in range(0, num_rows, batch_size)], ), total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size, unit="ba", desc="Creating json from Arrow format", ): written += file_obj.write(json_str) return written
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/spark.py
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SparkDatasetReader(AbstractDatasetReader): """A dataset reader that reads from a Spark DataFrame. When caching, cache materialization is parallelized over Spark; an NFS that is accessible to the driver must be provided. Streaming is not currently supported. """ def __init__( self, df: pyspark.sql.DataFrame, split: Optional[NamedSplit] = None, features: Optional[Features] = None, streaming: bool = True, cache_dir: str = None, keep_in_memory: bool = False, working_dir: str = None, load_from_cache_file: bool = True, file_format: str = "arrow", **kwargs, ): super().__init__( split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, **kwargs, ) self._load_from_cache_file = load_from_cache_file self._file_format = file_format self.builder = Spark( df=df, features=features, cache_dir=cache_dir, working_dir=working_dir, **kwargs, ) def read(self): if self.streaming: return self.builder.as_streaming_dataset(split=self.split) download_mode = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=download_mode, file_format=self._file_format, ) return self.builder.as_dataset(split=self.split)
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/io/text.py
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class TextDatasetReader(AbstractDatasetReader): def __init__( self, path_or_paths: NestedDataStructureLike[PathLike], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, num_proc: Optional[int] = None, **kwargs, ): super().__init__( path_or_paths, split=split, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, num_proc=num_proc, **kwargs, ) path_or_paths = path_or_paths if isinstance(path_or_paths, dict) else {self.split: path_or_paths} self.builder = Text( cache_dir=cache_dir, data_files=path_or_paths, features=features, **kwargs, ) def read(self): # Build iterable dataset if self.streaming: dataset = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, # try_from_hf_gcs=try_from_hf_gcs, base_path=base_path, num_proc=self.num_proc, ) dataset = self.builder.as_dataset( split=self.split, verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/packaged_modules/__init__.py
import inspect import re from typing import Dict, List, Tuple from huggingface_hub.utils import insecure_hashlib from .arrow import arrow from .audiofolder import audiofolder from .cache import cache # noqa F401 from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text from .webdataset import webdataset def _hash_python_lines(lines: List[str]) -> str: filtered_lines = [] for line in lines: line = re.sub(r"#.*", "", line) # remove comments if line: filtered_lines.append(line) full_str = "\n".join(filtered_lines) # Make a hash from all this code full_bytes = full_str.encode("utf-8") return insecure_hashlib.sha256(full_bytes).hexdigest() # get importable module names and hash for caching _PACKAGED_DATASETS_MODULES = { "csv": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), "json": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), "pandas": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), "parquet": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), "arrow": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), "text": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), "imagefolder": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), "audiofolder": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), "webdataset": (webdataset.__name__, _hash_python_lines(inspect.getsource(webdataset).splitlines())), } # Used to infer the module to use based on the data files extensions _EXTENSION_TO_MODULE: Dict[str, Tuple[str, dict]] = { ".csv": ("csv", {}), ".tsv": ("csv", {"sep": "\t"}), ".json": ("json", {}), ".jsonl": ("json", {}), ".parquet": ("parquet", {}), ".arrow": ("arrow", {}), ".txt": ("text", {}), ".tar": ("webdataset", {}), } _EXTENSION_TO_MODULE.update({ext: ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _MODULE_SUPPORTS_METADATA = {"imagefolder", "audiofolder"} # Used to filter data files based on extensions given a module name _MODULE_TO_EXTENSIONS: Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) for _module in _MODULE_TO_EXTENSIONS: _MODULE_TO_EXTENSIONS[_module].append(".zip")
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/imagefolder/imagefolder.py
from typing import List import datasets from datasets.tasks import ImageClassification from ..folder_based_builder import folder_based_builder logger = datasets.utils.logging.get_logger(__name__) class ImageFolderConfig(folder_based_builder.FolderBasedBuilderConfig): """BuilderConfig for ImageFolder.""" drop_labels: bool = None drop_metadata: bool = None class ImageFolder(folder_based_builder.FolderBasedBuilder): BASE_FEATURE = datasets.Image BASE_COLUMN_NAME = "image" BUILDER_CONFIG_CLASS = ImageFolderConfig EXTENSIONS: List[str] # definition at the bottom of the script CLASSIFICATION_TASK = ImageClassification(image_column="image", label_column="label") # Obtained with: # ``` # import PIL.Image # IMAGE_EXTENSIONS = [] # PIL.Image.init() # for ext, format in PIL.Image.EXTENSION.items(): # if format in PIL.Image.OPEN: # IMAGE_EXTENSIONS.append(ext[1:]) # ``` # We intentionally do not run this code on launch because: # (1) Pillow is an optional dependency, so importing Pillow in global namespace is not allowed # (2) To ensure the list of supported extensions is deterministic IMAGE_EXTENSIONS = [ ".blp", ".bmp", ".dib", ".bufr", ".cur", ".pcx", ".dcx", ".dds", ".ps", ".eps", ".fit", ".fits", ".fli", ".flc", ".ftc", ".ftu", ".gbr", ".gif", ".grib", ".h5", ".hdf", ".png", ".apng", ".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c", ".icns", ".ico", ".im", ".iim", ".tif", ".tiff", ".jfif", ".jpe", ".jpg", ".jpeg", ".mpg", ".mpeg", ".msp", ".pcd", ".pxr", ".pbm", ".pgm", ".ppm", ".pnm", ".psd", ".bw", ".rgb", ".rgba", ".sgi", ".ras", ".tga", ".icb", ".vda", ".vst", ".webp", ".wmf", ".emf", ".xbm", ".xpm", ] ImageFolder.EXTENSIONS = IMAGE_EXTENSIONS
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/sql/sql.py
import sys from dataclasses import dataclass from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast if TYPE_CHECKING: import sqlite3 import sqlalchemy logger = datasets.utils.logging.get_logger(__name__) @dataclass class SqlConfig(datasets.BuilderConfig): """BuilderConfig for SQL.""" sql: Union[str, "sqlalchemy.sql.Selectable"] = None con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] = None index_col: Optional[Union[str, List[str]]] = None coerce_float: bool = True params: Optional[Union[List, Tuple, Dict]] = None parse_dates: Optional[Union[List, Dict]] = None columns: Optional[List[str]] = None chunksize: Optional[int] = 10_000 features: Optional[datasets.Features] = None def __post_init__(self): if self.sql is None: raise ValueError("sql must be specified") if self.con is None: raise ValueError("con must be specified") def create_config_id( self, config_kwargs: dict, custom_features: Optional[datasets.Features] = None, ) -> str: config_kwargs = config_kwargs.copy() # We need to stringify the Selectable object to make its hash deterministic # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html sql = config_kwargs["sql"] if not isinstance(sql, str): if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules: import sqlalchemy if isinstance(sql, sqlalchemy.sql.Selectable): engine = sqlalchemy.create_engine(config_kwargs["con"].split("://")[0] + "://") sql_str = str(sql.compile(dialect=engine.dialect)) config_kwargs["sql"] = sql_str else: raise TypeError( f"Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(sql)}: {sql}" ) else: raise TypeError( f"Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(sql)}: {sql}" ) con = config_kwargs["con"] if not isinstance(con, str): config_kwargs["con"] = id(con) logger.info( f"SQL connection 'con' of type {type(con)} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead." ) return super().create_config_id(config_kwargs, custom_features=custom_features) @property def pd_read_sql_kwargs(self): pd_read_sql_kwargs = { "index_col": self.index_col, "columns": self.columns, "params": self.params, "coerce_float": self.coerce_float, "parse_dates": self.parse_dates, } return pd_read_sql_kwargs class Sql(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = SqlConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={})] def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.config.features is not None: schema = self.config.features.arrow_schema if all(not require_storage_cast(feature) for feature in self.config.features.values()): # cheaper cast pa_table = pa.Table.from_arrays([pa_table[field.name] for field in schema], schema=schema) else: # more expensive cast; allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, schema) return pa_table def _generate_tables(self): chunksize = self.config.chunksize sql_reader = pd.read_sql( self.config.sql, self.config.con, chunksize=chunksize, **self.config.pd_read_sql_kwargs ) sql_reader = [sql_reader] if chunksize is None else sql_reader for chunk_idx, df in enumerate(sql_reader): pa_table = pa.Table.from_pandas(df) yield chunk_idx, self._cast_table(pa_table)
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/generator/generator.py
from dataclasses import dataclass from typing import Callable, Optional import datasets @dataclass class GeneratorConfig(datasets.BuilderConfig): generator: Optional[Callable] = None gen_kwargs: Optional[dict] = None features: Optional[datasets.Features] = None def __post_init__(self): assert self.generator is not None, "generator must be specified" if self.gen_kwargs is None: self.gen_kwargs = {} class Generator(datasets.GeneratorBasedBuilder): BUILDER_CONFIG_CLASS = GeneratorConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs=self.config.gen_kwargs)] def _generate_examples(self, **gen_kwargs): for idx, ex in enumerate(self.config.generator(**gen_kwargs)): yield idx, ex
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/folder_based_builder/folder_based_builder.py
import collections import itertools import os from dataclasses import dataclass from typing import List, Optional, Tuple, Type import pandas as pd import pyarrow as pa import pyarrow.json as paj import datasets from datasets.features.features import FeatureType from datasets.tasks.base import TaskTemplate logger = datasets.utils.logging.get_logger(__name__) def count_path_segments(path): return path.replace("\\", "/").count("/") @dataclass class FolderBasedBuilderConfig(datasets.BuilderConfig): """BuilderConfig for AutoFolder.""" features: Optional[datasets.Features] = None drop_labels: bool = None drop_metadata: bool = None class FolderBasedBuilder(datasets.GeneratorBasedBuilder): """ Base class for generic data loaders for vision and image data. Abstract class attributes to be overridden by a child class: BASE_FEATURE: feature object to decode data (i.e. datasets.Image, datasets.Audio, ...) BASE_COLUMN_NAME: string key name of a base feature (i.e. "image", "audio", ...) BUILDER_CONFIG_CLASS: builder config inherited from `folder_based_builder.FolderBasedBuilderConfig` EXTENSIONS: list of allowed extensions (only files with these extensions and METADATA_FILENAME files will be included in a dataset) CLASSIFICATION_TASK: classification task to use if labels are obtained from the folder structure """ BASE_FEATURE: Type[FeatureType] BASE_COLUMN_NAME: str BUILDER_CONFIG_CLASS: FolderBasedBuilderConfig EXTENSIONS: List[str] CLASSIFICATION_TASK: TaskTemplate METADATA_FILENAMES: List[str] = ["metadata.csv", "metadata.jsonl"] def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") # Do an early pass if: # * `drop_labels` is None (default) or False, to infer the class labels # * `drop_metadata` is None (default) or False, to find the metadata files do_analyze = not self.config.drop_labels or not self.config.drop_metadata labels, path_depths = set(), set() metadata_files = collections.defaultdict(set) def analyze(files_or_archives, downloaded_files_or_dirs, split): if len(downloaded_files_or_dirs) == 0: return # The files are separated from the archives at this point, so check the first sample # to see if it's a file or a directory and iterate accordingly if os.path.isfile(downloaded_files_or_dirs[0]): original_files, downloaded_files = files_or_archives, downloaded_files_or_dirs for original_file, downloaded_file in zip(original_files, downloaded_files): original_file, downloaded_file = str(original_file), str(downloaded_file) _, original_file_ext = os.path.splitext(original_file) if original_file_ext.lower() in self.EXTENSIONS: if not self.config.drop_labels: labels.add(os.path.basename(os.path.dirname(original_file))) path_depths.add(count_path_segments(original_file)) elif os.path.basename(original_file) in self.METADATA_FILENAMES: metadata_files[split].add((original_file, downloaded_file)) else: original_file_name = os.path.basename(original_file) logger.debug( f"The file '{original_file_name}' was ignored: it is not an image, and is not {self.METADATA_FILENAMES} either." ) else: archives, downloaded_dirs = files_or_archives, downloaded_files_or_dirs for archive, downloaded_dir in zip(archives, downloaded_dirs): archive, downloaded_dir = str(archive), str(downloaded_dir) for downloaded_dir_file in dl_manager.iter_files(downloaded_dir): _, downloaded_dir_file_ext = os.path.splitext(downloaded_dir_file) if downloaded_dir_file_ext in self.EXTENSIONS: if not self.config.drop_labels: labels.add(os.path.basename(os.path.dirname(downloaded_dir_file))) path_depths.add(count_path_segments(downloaded_dir_file)) elif os.path.basename(downloaded_dir_file) in self.METADATA_FILENAMES: metadata_files[split].add((None, downloaded_dir_file)) else: archive_file_name = os.path.basename(archive) original_file_name = os.path.basename(downloaded_dir_file) logger.debug( f"The file '{original_file_name}' from the archive '{archive_file_name}' was ignored: it is not an {self.BASE_COLUMN_NAME}, and is not {self.METADATA_FILENAMES} either." ) data_files = self.config.data_files splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] files, archives = self._split_files_and_archives(files) downloaded_files = dl_manager.download(files) downloaded_dirs = dl_manager.download_and_extract(archives) if do_analyze: # drop_metadata is None or False, drop_labels is None or False logger.info(f"Searching for labels and/or metadata files in {split_name} data files...") analyze(files, downloaded_files, split_name) analyze(archives, downloaded_dirs, split_name) if metadata_files: # add metadata if `metadata_files` are found and `drop_metadata` is None (default) or False add_metadata = not self.config.drop_metadata # if `metadata_files` are found, add labels only if # `drop_labels` is set up to False explicitly (not-default behavior) add_labels = self.config.drop_labels is False else: # if `metadata_files` are not found, don't add metadata add_metadata = False # if `metadata_files` are not found and `drop_labels` is None (default) - # add labels if files are on the same level in directory hierarchy and there is more than one label add_labels = ( (len(labels) > 1 and len(path_depths) == 1) if self.config.drop_labels is None else not self.config.drop_labels ) if add_labels: logger.info("Adding the labels inferred from data directories to the dataset's features...") if add_metadata: logger.info("Adding metadata to the dataset...") else: add_labels, add_metadata, metadata_files = False, False, {} splits.append( datasets.SplitGenerator( name=split_name, gen_kwargs={ "files": list(zip(files, downloaded_files)) + [(None, dl_manager.iter_files(downloaded_dir)) for downloaded_dir in downloaded_dirs], "metadata_files": metadata_files, "split_name": split_name, "add_labels": add_labels, "add_metadata": add_metadata, }, ) ) if add_metadata: # Verify that: # * all metadata files have the same set of features # * the `file_name` key is one of the metadata keys and is of type string features_per_metadata_file: List[Tuple[str, datasets.Features]] = [] # Check that all metadata files share the same format metadata_ext = { os.path.splitext(original_metadata_file)[-1] for original_metadata_file, _ in itertools.chain.from_iterable(metadata_files.values()) } if len(metadata_ext) > 1: raise ValueError(f"Found metadata files with different extensions: {list(metadata_ext)}") metadata_ext = metadata_ext.pop() for _, downloaded_metadata_file in itertools.chain.from_iterable(metadata_files.values()): pa_metadata_table = self._read_metadata(downloaded_metadata_file, metadata_ext=metadata_ext) features_per_metadata_file.append( (downloaded_metadata_file, datasets.Features.from_arrow_schema(pa_metadata_table.schema)) ) for downloaded_metadata_file, metadata_features in features_per_metadata_file: if metadata_features != features_per_metadata_file[0][1]: raise ValueError( f"Metadata files {downloaded_metadata_file} and {features_per_metadata_file[0][0]} have different features: {features_per_metadata_file[0]} != {metadata_features}" ) metadata_features = features_per_metadata_file[0][1] if "file_name" not in metadata_features: raise ValueError("`file_name` must be present as dictionary key in metadata files") if metadata_features["file_name"] != datasets.Value("string"): raise ValueError("`file_name` key must be a string") del metadata_features["file_name"] else: metadata_features = None # Normally, we would do this in _info, but we need to know the labels and/or metadata # before building the features if self.config.features is None: if add_labels: self.info.features = datasets.Features( { self.BASE_COLUMN_NAME: self.BASE_FEATURE(), "label": datasets.ClassLabel(names=sorted(labels)), } ) self.info.task_templates = [self.CLASSIFICATION_TASK.align_with_features(self.info.features)] else: self.info.features = datasets.Features({self.BASE_COLUMN_NAME: self.BASE_FEATURE()}) if add_metadata: # Warn if there are duplicated keys in metadata compared to the existing features # (`BASE_COLUMN_NAME`, optionally "label") duplicated_keys = set(self.info.features) & set(metadata_features) if duplicated_keys: logger.warning( f"Ignoring metadata columns {list(duplicated_keys)} as they are already present in " f"the features dictionary." ) # skip metadata duplicated keys self.info.features.update( { feature: metadata_features[feature] for feature in metadata_features if feature not in duplicated_keys } ) return splits def _split_files_and_archives(self, data_files): files, archives = [], [] for data_file in data_files: _, data_file_ext = os.path.splitext(data_file) if data_file_ext.lower() in self.EXTENSIONS: files.append(data_file) elif os.path.basename(data_file) in self.METADATA_FILENAMES: files.append(data_file) else: archives.append(data_file) return files, archives def _read_metadata(self, metadata_file, metadata_ext: str = ""): if metadata_ext == ".csv": # Use `pd.read_csv` (although slower) instead of `pyarrow.csv.read_csv` for reading CSV files for consistency with the CSV packaged module return pa.Table.from_pandas(pd.read_csv(metadata_file)) else: with open(metadata_file, "rb") as f: return paj.read_json(f) def _generate_examples(self, files, metadata_files, split_name, add_metadata, add_labels): split_metadata_files = metadata_files.get(split_name, []) sample_empty_metadata = ( {k: None for k in self.info.features if k != self.BASE_COLUMN_NAME} if self.info.features else {} ) last_checked_dir = None metadata_dir = None metadata_dict = None downloaded_metadata_file = None metadata_ext = "" if split_metadata_files: metadata_ext = { os.path.splitext(original_metadata_file)[-1] for original_metadata_file, _ in split_metadata_files } metadata_ext = metadata_ext.pop() file_idx = 0 for original_file, downloaded_file_or_dir in files: if original_file is not None: _, original_file_ext = os.path.splitext(original_file) if original_file_ext.lower() in self.EXTENSIONS: if add_metadata: # If the file is a file of a needed type, and we've just entered a new directory, # find the nereast metadata file (by counting path segments) for the directory current_dir = os.path.dirname(original_file) if last_checked_dir is None or last_checked_dir != current_dir: last_checked_dir = current_dir metadata_file_candidates = [ ( os.path.relpath(original_file, os.path.dirname(metadata_file_candidate)), metadata_file_candidate, downloaded_metadata_file, ) for metadata_file_candidate, downloaded_metadata_file in split_metadata_files if metadata_file_candidate is not None # ignore metadata_files that are inside archives and not os.path.relpath( original_file, os.path.dirname(metadata_file_candidate) ).startswith("..") ] if metadata_file_candidates: _, metadata_file, downloaded_metadata_file = min( metadata_file_candidates, key=lambda x: count_path_segments(x[0]) ) pa_metadata_table = self._read_metadata( downloaded_metadata_file, metadata_ext=metadata_ext ) pa_file_name_array = pa_metadata_table["file_name"] pa_metadata_table = pa_metadata_table.drop(["file_name"]) metadata_dir = os.path.dirname(metadata_file) metadata_dict = { os.path.normpath(file_name).replace("\\", "/"): sample_metadata for file_name, sample_metadata in zip( pa_file_name_array.to_pylist(), pa_metadata_table.to_pylist() ) } else: raise ValueError( f"One or several metadata{metadata_ext} were found, but not in the same directory or in a parent directory of {downloaded_file_or_dir}." ) if metadata_dir is not None and downloaded_metadata_file is not None: file_relpath = os.path.relpath(original_file, metadata_dir) file_relpath = file_relpath.replace("\\", "/") if file_relpath not in metadata_dict: raise ValueError( f"{self.BASE_COLUMN_NAME} at {file_relpath} doesn't have metadata in {downloaded_metadata_file}." ) sample_metadata = metadata_dict[file_relpath] else: raise ValueError( f"One or several metadata{metadata_ext} were found, but not in the same directory or in a parent directory of {downloaded_file_or_dir}." ) else: sample_metadata = {} if add_labels: sample_label = {"label": os.path.basename(os.path.dirname(original_file))} else: sample_label = {} yield ( file_idx, { **sample_empty_metadata, self.BASE_COLUMN_NAME: downloaded_file_or_dir, **sample_metadata, **sample_label, }, ) file_idx += 1 else: for downloaded_dir_file in downloaded_file_or_dir: _, downloaded_dir_file_ext = os.path.splitext(downloaded_dir_file) if downloaded_dir_file_ext.lower() in self.EXTENSIONS: if add_metadata: current_dir = os.path.dirname(downloaded_dir_file) if last_checked_dir is None or last_checked_dir != current_dir: last_checked_dir = current_dir metadata_file_candidates = [ ( os.path.relpath( downloaded_dir_file, os.path.dirname(downloaded_metadata_file) ), metadata_file_candidate, downloaded_metadata_file, ) for metadata_file_candidate, downloaded_metadata_file in split_metadata_files if metadata_file_candidate is None # ignore metadata_files that are not inside archives and not os.path.relpath( downloaded_dir_file, os.path.dirname(downloaded_metadata_file) ).startswith("..") ] if metadata_file_candidates: _, metadata_file, downloaded_metadata_file = min( metadata_file_candidates, key=lambda x: count_path_segments(x[0]) ) pa_metadata_table = self._read_metadata( downloaded_metadata_file, metadata_ext=metadata_ext ) pa_file_name_array = pa_metadata_table["file_name"] pa_metadata_table = pa_metadata_table.drop(["file_name"]) metadata_dir = os.path.dirname(downloaded_metadata_file) metadata_dict = { os.path.normpath(file_name).replace("\\", "/"): sample_metadata for file_name, sample_metadata in zip( pa_file_name_array.to_pylist(), pa_metadata_table.to_pylist() ) } else: raise ValueError( f"One or several metadata{metadata_ext} were found, but not in the same directory or in a parent directory of {downloaded_dir_file}." ) if metadata_dir is not None and downloaded_metadata_file is not None: downloaded_dir_file_relpath = os.path.relpath(downloaded_dir_file, metadata_dir) downloaded_dir_file_relpath = downloaded_dir_file_relpath.replace("\\", "/") if downloaded_dir_file_relpath not in metadata_dict: raise ValueError( f"{self.BASE_COLUMN_NAME} at {downloaded_dir_file_relpath} doesn't have metadata in {downloaded_metadata_file}." ) sample_metadata = metadata_dict[downloaded_dir_file_relpath] else: raise ValueError( f"One or several metadata{metadata_ext} were found, but not in the same directory or in a parent directory of {downloaded_dir_file}." ) else: sample_metadata = {} if add_labels: sample_label = {"label": os.path.basename(os.path.dirname(downloaded_dir_file))} else: sample_label = {} yield ( file_idx, { **sample_empty_metadata, self.BASE_COLUMN_NAME: downloaded_dir_file, **sample_metadata, **sample_label, }, ) file_idx += 1
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/parquet/parquet.py
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ParquetConfig(datasets.BuilderConfig): """BuilderConfig for Parquet.""" batch_size: int = 10_000 columns: Optional[List[str]] = None features: Optional[datasets.Features] = None class Parquet(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = ParquetConfig def _info(self): if ( self.config.columns is not None and self.config.features is not None and set(self.config.columns) != set(self.config.features) ): raise ValueError( "The columns and features argument must contain the same columns, but got ", f"{self.config.columns} and {self.config.features}", ) return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] # Infer features if they are stored in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(files): with open(file, "rb") as f: self.info.features = datasets.Features.from_arrow_schema(pq.read_schema(f)) break splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) if self.config.columns is not None and set(self.config.columns) != set(self.info.features): self.info.features = datasets.Features( {col: feat for col, feat in self.info.features.items() if col in self.config.columns} ) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.info.features.arrow_schema) return pa_table def _generate_tables(self, files): if self.config.features is not None and self.config.columns is not None: if sorted(field.name for field in self.info.features.arrow_schema) != sorted(self.config.columns): raise ValueError( f"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) for file_idx, file in enumerate(itertools.chain.from_iterable(files)): with open(file, "rb") as f: parquet_file = pq.ParquetFile(f) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size, columns=self.config.columns) ): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/pandas/pandas.py
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class PandasConfig(datasets.BuilderConfig): """BuilderConfig for Pandas.""" features: Optional[datasets.Features] = None class Pandas(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = PandasConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.config.features.arrow_schema) return pa_table def _generate_tables(self, files): for i, file in enumerate(itertools.chain.from_iterable(files)): with open(file, "rb") as f: pa_table = pa.Table.from_pandas(pd.read_pickle(f)) yield i, self._cast_table(pa_table)
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/audiofolder/audiofolder.py
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder logger = datasets.utils.logging.get_logger(__name__) class AudioFolderConfig(folder_based_builder.FolderBasedBuilderConfig): """Builder Config for AudioFolder.""" drop_labels: bool = None drop_metadata: bool = None class AudioFolder(folder_based_builder.FolderBasedBuilder): BASE_FEATURE = datasets.Audio BASE_COLUMN_NAME = "audio" BUILDER_CONFIG_CLASS = AudioFolderConfig EXTENSIONS: List[str] # definition at the bottom of the script CLASSIFICATION_TASK = AudioClassification(audio_column="audio", label_column="label") # Obtained with: # ``` # import soundfile as sf # # AUDIO_EXTENSIONS = [f".{format.lower()}" for format in sf.available_formats().keys()] # # # .mp3 is currently decoded via `torchaudio`, .opus decoding is supported if version of `libsndfile` >= 1.0.30: # AUDIO_EXTENSIONS.extend([".mp3", ".opus"]) # ``` # We intentionally do not run this code on launch because: # (1) Soundfile is an optional dependency, so importing it in global namespace is not allowed # (2) To ensure the list of supported extensions is deterministic AUDIO_EXTENSIONS = [ ".aiff", ".au", ".avr", ".caf", ".flac", ".htk", ".svx", ".mat4", ".mat5", ".mpc2k", ".ogg", ".paf", ".pvf", ".raw", ".rf64", ".sd2", ".sds", ".ircam", ".voc", ".w64", ".wav", ".nist", ".wavex", ".wve", ".xi", ".mp3", ".opus", ] AudioFolder.EXTENSIONS = AUDIO_EXTENSIONS
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/json/json.py
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline logger = datasets.utils.logging.get_logger(__name__) @dataclass class JsonConfig(datasets.BuilderConfig): """BuilderConfig for JSON.""" features: Optional[datasets.Features] = None encoding: str = "utf-8" encoding_errors: Optional[str] = None field: Optional[str] = None use_threads: bool = True # deprecated block_size: Optional[int] = None # deprecated chunksize: int = 10 << 20 # 10MB newlines_in_values: Optional[bool] = None class Json(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = JsonConfig def _info(self): if self.config.block_size is not None: logger.warning("The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead") self.config.chunksize = self.config.block_size if self.config.use_threads is not True: logger.warning( "The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore." ) if self.config.newlines_in_values is not None: raise ValueError("The JSON loader parameter `newlines_in_values` is no longer supported") return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] files = [dl_manager.iter_files(file) for file in files] splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.config.features is not None: # adding missing columns for column_name in set(self.config.features) - set(pa_table.column_names): type = self.config.features.arrow_schema.field(column_name).type pa_table = pa_table.append_column(column_name, pa.array([None] * len(pa_table), type=type)) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.config.features.arrow_schema) return pa_table def _generate_tables(self, files): for file_idx, file in enumerate(itertools.chain.from_iterable(files)): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(file, encoding=self.config.encoding, errors=self.config.encoding_errors) as f: dataset = json.load(f) # We keep only the field we are interested in dataset = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(dataset, (list, tuple)): keys = set().union(*[row.keys() for row in dataset]) mapping = {col: [row.get(col) for row in dataset] for col in keys} else: mapping = dataset pa_table = pa.Table.from_pydict(mapping) yield file_idx, self._cast_table(pa_table) # If the file has one json object per line else: with open(file, "rb") as f: batch_idx = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small block_size = max(self.config.chunksize // 32, 16 << 10) encoding_errors = ( self.config.encoding_errors if self.config.encoding_errors is not None else "strict" ) while True: batch = f.read(self.config.chunksize) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(f) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": batch = batch.decode(self.config.encoding, errors=encoding_errors).encode("utf-8") try: while True: try: pa_table = paj.read_json( io.BytesIO(batch), read_options=paj.ReadOptions(block_size=block_size) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(e, pa.ArrowInvalid) and "straddling" not in str(e) or block_size > len(batch) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f"Batch of {len(batch)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}." ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( file, encoding=self.config.encoding, errors=self.config.encoding_errors ) as f: dataset = json.load(f) except json.JSONDecodeError: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(dataset, list): # list is the only sequence type supported in JSON try: keys = set().union(*[row.keys() for row in dataset]) mapping = {col: [row.get(col) for row in dataset] for col in keys} pa_table = pa.Table.from_pydict(mapping) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise ValueError(f"Not able to read records in the JSON file at {file}.") from None yield file_idx, self._cast_table(pa_table) break else: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise ValueError( f"Not able to read records in the JSON file at {file}. " f"You should probably indicate the field of the JSON file containing your records. " f"This JSON file contain the following fields: {str(list(dataset.keys()))}. " f"Select the correct one and provide it as `field='XXX'` to the dataset loading method. " ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(pa_table) batch_idx += 1
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/csv/csv.py
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal logger = datasets.utils.logging.get_logger(__name__) _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS = ["names", "prefix"] _PANDAS_READ_CSV_DEPRECATED_PARAMETERS = ["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"] _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS = ["encoding_errors", "on_bad_lines"] _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS = ["date_format"] @dataclass class CsvConfig(datasets.BuilderConfig): """BuilderConfig for CSV.""" sep: str = "," delimiter: Optional[str] = None header: Optional[Union[int, List[int], str]] = "infer" names: Optional[List[str]] = None column_names: Optional[List[str]] = None index_col: Optional[Union[int, str, List[int], List[str]]] = None usecols: Optional[Union[List[int], List[str]]] = None prefix: Optional[str] = None mangle_dupe_cols: bool = True engine: Optional[Literal["c", "python", "pyarrow"]] = None converters: Dict[Union[int, str], Callable[[Any], Any]] = None true_values: Optional[list] = None false_values: Optional[list] = None skipinitialspace: bool = False skiprows: Optional[Union[int, List[int]]] = None nrows: Optional[int] = None na_values: Optional[Union[str, List[str]]] = None keep_default_na: bool = True na_filter: bool = True verbose: bool = False skip_blank_lines: bool = True thousands: Optional[str] = None decimal: str = "." lineterminator: Optional[str] = None quotechar: str = '"' quoting: int = 0 escapechar: Optional[str] = None comment: Optional[str] = None encoding: Optional[str] = None dialect: Optional[str] = None error_bad_lines: bool = True warn_bad_lines: bool = True skipfooter: int = 0 doublequote: bool = True memory_map: bool = False float_precision: Optional[str] = None chunksize: int = 10_000 features: Optional[datasets.Features] = None encoding_errors: Optional[str] = "strict" on_bad_lines: Literal["error", "warn", "skip"] = "error" date_format: Optional[str] = None def __post_init__(self): if self.delimiter is not None: self.sep = self.delimiter if self.column_names is not None: self.names = self.column_names @property def pd_read_csv_kwargs(self): pd_read_csv_kwargs = { "sep": self.sep, "header": self.header, "names": self.names, "index_col": self.index_col, "usecols": self.usecols, "prefix": self.prefix, "mangle_dupe_cols": self.mangle_dupe_cols, "engine": self.engine, "converters": self.converters, "true_values": self.true_values, "false_values": self.false_values, "skipinitialspace": self.skipinitialspace, "skiprows": self.skiprows, "nrows": self.nrows, "na_values": self.na_values, "keep_default_na": self.keep_default_na, "na_filter": self.na_filter, "verbose": self.verbose, "skip_blank_lines": self.skip_blank_lines, "thousands": self.thousands, "decimal": self.decimal, "lineterminator": self.lineterminator, "quotechar": self.quotechar, "quoting": self.quoting, "escapechar": self.escapechar, "comment": self.comment, "encoding": self.encoding, "dialect": self.dialect, "error_bad_lines": self.error_bad_lines, "warn_bad_lines": self.warn_bad_lines, "skipfooter": self.skipfooter, "doublequote": self.doublequote, "memory_map": self.memory_map, "float_precision": self.float_precision, "chunksize": self.chunksize, "encoding_errors": self.encoding_errors, "on_bad_lines": self.on_bad_lines, "date_format": self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig(), pd_read_csv_parameter): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class Csv(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = CsvConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] files = [dl_manager.iter_files(file) for file in files] splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.config.features is not None: schema = self.config.features.arrow_schema if all(not require_storage_cast(feature) for feature in self.config.features.values()): # cheaper cast pa_table = pa.Table.from_arrays([pa_table[field.name] for field in schema], schema=schema) else: # more expensive cast; allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, schema) return pa_table def _generate_tables(self, files): schema = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str dtype = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(feature) else object for name, dtype, feature in zip(schema.names, schema.types, self.config.features.values()) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(files)): csv_file_reader = pd.read_csv(file, iterator=True, dtype=dtype, **self.config.pd_read_csv_kwargs) try: for batch_idx, df in enumerate(csv_file_reader): pa_table = pa.Table.from_pandas(df) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(pa_table) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/text/text.py
import itertools import warnings from dataclasses import InitVar, dataclass from io import StringIO from typing import Optional import pyarrow as pa import datasets from datasets.features.features import require_storage_cast from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class TextConfig(datasets.BuilderConfig): """BuilderConfig for text files.""" features: Optional[datasets.Features] = None encoding: str = "utf-8" errors: InitVar[Optional[str]] = "deprecated" encoding_errors: Optional[str] = None chunksize: int = 10 << 20 # 10MB keep_linebreaks: bool = False sample_by: str = "line" def __post_init__(self, errors): if errors != "deprecated": warnings.warn( "'errors' was deprecated in favor of 'encoding_errors' in version 2.14.0 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'encoding_errors={errors}' instead.", FutureWarning, ) self.encoding_errors = errors class Text(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = TextConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """The `data_files` kwarg in load_dataset() can be a str, List[str], Dict[str,str], or Dict[str,List[str]]. If str or List[str], then the dataset returns only the 'train' split. If dict, then keys should be from the `datasets.Split` enum. """ if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] files = [dl_manager.iter_files(file) for file in files] splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.config.features is not None: schema = self.config.features.arrow_schema if all(not require_storage_cast(feature) for feature in self.config.features.values()): # cheaper cast pa_table = pa_table.cast(schema) else: # more expensive cast; allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, schema) return pa_table else: return pa_table.cast(pa.schema({"text": pa.string()})) def _generate_tables(self, files): pa_table_names = list(self.config.features) if self.config.features is not None else ["text"] for file_idx, file in enumerate(itertools.chain.from_iterable(files)): # open in text mode, by default translates universal newlines ("\n", "\r\n" and "\r") into "\n" with open(file, encoding=self.config.encoding, errors=self.config.encoding_errors) as f: if self.config.sample_by == "line": batch_idx = 0 while True: batch = f.read(self.config.chunksize) if not batch: break batch += f.readline() # finish current line # StringIO.readlines, by default splits only on "\n" (and keeps line breaks) batch = StringIO(batch).readlines() if not self.config.keep_linebreaks: batch = [line.rstrip("\n") for line in batch] pa_table = pa.Table.from_arrays([pa.array(batch)], names=pa_table_names) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(pa_table) batch_idx += 1 elif self.config.sample_by == "paragraph": batch_idx = 0 batch = "" while True: new_batch = f.read(self.config.chunksize) if not new_batch: break batch += new_batch batch += f.readline() # finish current line batch = batch.split("\n\n") pa_table = pa.Table.from_arrays( [pa.array([example for example in batch[:-1] if example])], names=pa_table_names ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(pa_table) batch_idx += 1 batch = batch[-1] if batch: pa_table = pa.Table.from_arrays([pa.array([batch])], names=pa_table_names) yield (file_idx, batch_idx), self._cast_table(pa_table) elif self.config.sample_by == "document": text = f.read() pa_table = pa.Table.from_arrays([pa.array([text])], names=pa_table_names) yield file_idx, self._cast_table(pa_table)
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/cache/cache.py
import glob import os import shutil import time from pathlib import Path from typing import List, Optional, Tuple import pyarrow as pa import datasets import datasets.config from datasets.naming import filenames_for_dataset_split logger = datasets.utils.logging.get_logger(__name__) def _get_modification_time(cached_directory_path): return (Path(cached_directory_path)).stat().st_mtime def _find_hash_in_cache( dataset_name: str, config_name: Optional[str], cache_dir: Optional[str] ) -> Tuple[str, str, str]: cache_dir = os.path.expanduser(str(cache_dir or datasets.config.HF_DATASETS_CACHE)) cached_datasets_directory_path_root = os.path.join(cache_dir, dataset_name.replace("/", "___")) cached_directory_paths = [ cached_directory_path for cached_directory_path in glob.glob( os.path.join(cached_datasets_directory_path_root, config_name or "*", "*", "*") ) if os.path.isdir(cached_directory_path) ] if not cached_directory_paths: if config_name is not None: cached_directory_paths = [ cached_directory_path for cached_directory_path in glob.glob( os.path.join(cached_datasets_directory_path_root, "*", "*", "*") ) if os.path.isdir(cached_directory_path) ] available_configs = sorted( {Path(cached_directory_path).parts[-3] for cached_directory_path in cached_directory_paths} ) raise ValueError( f"Couldn't find cache for {dataset_name}" + (f" for config '{config_name}'" if config_name else "") + (f"\nAvailable configs in the cache: {available_configs}" if available_configs else "") ) # get most recent cached_directory_path = Path(sorted(cached_directory_paths, key=_get_modification_time)[-1]) version, hash = cached_directory_path.parts[-2:] other_configs = [ Path(cached_directory_path).parts[-3] for cached_directory_path in glob.glob(os.path.join(cached_datasets_directory_path_root, "*", version, hash)) if os.path.isdir(cached_directory_path) ] if not config_name and len(other_configs) > 1: raise ValueError( f"There are multiple '{dataset_name}' configurations in the cache: {', '.join(other_configs)}" f"\nPlease specify which configuration to reload from the cache, e.g." f"\n\tload_dataset('{dataset_name}', '{other_configs[0]}')" ) config_name = cached_directory_path.parts[-3] warning_msg = ( f"Found the latest cached dataset configuration '{config_name}' at {cached_directory_path} " f"(last modified on {time.ctime(_get_modification_time(cached_directory_path))})." ) logger.warning(warning_msg) return config_name, version, hash class Cache(datasets.ArrowBasedBuilder): def __init__( self, cache_dir: Optional[str] = None, dataset_name: Optional[str] = None, config_name: Optional[str] = None, version: Optional[str] = "0.0.0", hash: Optional[str] = None, repo_id: Optional[str] = None, **kwargs, ): if repo_id is None and dataset_name is None: raise ValueError("repo_id or dataset_name is required for the Cache dataset builder") if hash == "auto" and version == "auto": config_name, version, hash = _find_hash_in_cache( dataset_name=repo_id or dataset_name, config_name=config_name, cache_dir=cache_dir, ) elif hash == "auto" or version == "auto": raise NotImplementedError("Pass both hash='auto' and version='auto' instead") super().__init__( cache_dir=cache_dir, dataset_name=dataset_name, config_name=config_name, version=version, hash=hash, repo_id=repo_id, **kwargs, ) def _info(self) -> datasets.DatasetInfo: return datasets.DatasetInfo() def download_and_prepare(self, output_dir: Optional[str] = None, *args, **kwargs): if not os.path.exists(self.cache_dir): raise ValueError(f"Cache directory for {self.dataset_name} doesn't exist at {self.cache_dir}") if output_dir is not None and output_dir != self.cache_dir: shutil.copytree(self.cache_dir, output_dir) def _split_generators(self, dl_manager): # used to stream from cache if isinstance(self.info.splits, datasets.SplitDict): split_infos: List[datasets.SplitInfo] = list(self.info.splits.values()) else: raise ValueError(f"Missing splits info for {self.dataset_name} in cache directory {self.cache_dir}") return [ datasets.SplitGenerator( name=split_info.name, gen_kwargs={ "files": filenames_for_dataset_split( self.cache_dir, dataset_name=self.dataset_name, split=split_info.name, filetype_suffix="arrow", shard_lengths=split_info.shard_lengths, ) }, ) for split_info in split_infos ] def _generate_tables(self, files): # used to stream from cache for file_idx, file in enumerate(files): with open(file, "rb") as f: try: for batch_idx, record_batch in enumerate(pa.ipc.open_stream(f)): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", pa_table except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/arrow/arrow.py
import itertools from dataclasses import dataclass from typing import Optional import pyarrow as pa import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ArrowConfig(datasets.BuilderConfig): """BuilderConfig for Arrow.""" features: Optional[datasets.Features] = None class Arrow(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = ArrowConfig def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download_and_extract(self.config.data_files) if isinstance(data_files, (str, list, tuple)): files = data_files if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": files})] splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(files): with open(file, "rb") as f: self.info.features = datasets.Features.from_arrow_schema(pa.ipc.open_stream(f).schema) break splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.info.features.arrow_schema) return pa_table def _generate_tables(self, files): for file_idx, file in enumerate(itertools.chain.from_iterable(files)): with open(file, "rb") as f: try: for batch_idx, record_batch in enumerate(pa.ipc.open_stream(f)): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
0
hf_public_repos/datasets/src/datasets/packaged_modules
hf_public_repos/datasets/src/datasets/packaged_modules/spark/spark.py
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int logger = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class SparkConfig(datasets.BuilderConfig): """BuilderConfig for Spark.""" features: Optional[datasets.Features] = None def _reorder_dataframe_by_partition(df: "pyspark.sql.DataFrame", new_partition_order: List[int]): df_combined = df.select("*").where(f"part_id = {new_partition_order[0]}") for partition_id in new_partition_order[1:]: partition_df = df.select("*").where(f"part_id = {partition_id}") df_combined = df_combined.union(partition_df) return df_combined def _generate_iterable_examples( df: "pyspark.sql.DataFrame", partition_order: List[int], ): import pyspark def generate_fn(): df_with_partition_id = df.select("*", pyspark.sql.functions.spark_partition_id().alias("part_id")) partition_df = _reorder_dataframe_by_partition(df_with_partition_id, partition_order) row_id = 0 # pipeline next partition in parallel to hide latency rows = partition_df.toLocalIterator(prefetchPartitions=True) curr_partition = -1 for row in rows: row_as_dict = row.asDict() part_id = row_as_dict["part_id"] row_as_dict.pop("part_id") if curr_partition != part_id: curr_partition = part_id row_id = 0 yield f"{part_id}_{row_id}", row_as_dict row_id += 1 return generate_fn class SparkExamplesIterable(_BaseExamplesIterable): def __init__( self, df: "pyspark.sql.DataFrame", partition_order=None, ): self.df = df self.partition_order = partition_order or range(self.df.rdd.getNumPartitions()) self.generate_examples_fn = _generate_iterable_examples(self.df, self.partition_order) def __iter__(self): yield from self.generate_examples_fn() def shuffle_data_sources(self, generator: np.random.Generator) -> "SparkExamplesIterable": partition_order = list(range(self.df.rdd.getNumPartitions())) generator.shuffle(partition_order) return SparkExamplesIterable(self.df, partition_order=partition_order) def shard_data_sources(self, worker_id: int, num_workers: int) -> "SparkExamplesIterable": partition_order = self.split_shard_indices_by_worker(worker_id, num_workers) return SparkExamplesIterable(self.df, partition_order=partition_order) @property def n_shards(self) -> int: return len(self.partition_order) class Spark(datasets.DatasetBuilder): BUILDER_CONFIG_CLASS = SparkConfig def __init__( self, df: "pyspark.sql.DataFrame", cache_dir: str = None, working_dir: str = None, **config_kwargs, ): import pyspark self._spark = pyspark.sql.SparkSession.builder.getOrCreate() self.df = df self._working_dir = working_dir super().__init__( cache_dir=cache_dir, config_name=str(self.df.semanticHash()), **config_kwargs, ) def _validate_cache_dir(self): # Define this so that we don't reference self in create_cache_and_write_probe, which will result in a pickling # error due to pickling the SparkContext. cache_dir = self._cache_dir # Returns the path of the created file. def create_cache_and_write_probe(context): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(cache_dir, exist_ok=True) probe_file = os.path.join(cache_dir, "fs_test" + uuid.uuid4().hex) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(probe_file, "a") return [probe_file] if self._spark.conf.get("spark.master", "").startswith("local"): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: probe = ( self._spark.sparkContext.parallelize(range(1), 1).mapPartitions(create_cache_and_write_probe).collect() ) if os.path.isfile(probe[0]): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager: datasets.download.download_manager.DownloadManager): return [datasets.SplitGenerator(name=datasets.Split.TRAIN)] def _repartition_df_if_needed(self, max_shard_size): import pyspark def get_arrow_batch_size(it): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]}) df_num_rows = self.df.count() sample_num_rows = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. approx_bytes_per_row = ( self.df.limit(sample_num_rows) .repartition(1) .mapInArrow(get_arrow_batch_size, "batch_bytes: long") .agg(pyspark.sql.functions.sum("batch_bytes").alias("sample_bytes")) .collect()[0] .sample_bytes / sample_num_rows ) approx_total_size = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. new_num_partitions = min(df_num_rows, int(approx_total_size / max_shard_size)) self.df = self.df.repartition(new_num_partitions) def _prepare_split_single( self, fpath: str, file_format: str, max_shard_size: int, ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark writer_class = ParquetWriter if file_format == "parquet" else ArrowWriter working_fpath = os.path.join(self._working_dir, os.path.basename(fpath)) if self._working_dir else fpath embed_local_files = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. features = self.config.features writer_batch_size = self._writer_batch_size storage_options = self._fs.storage_options def write_arrow(it): # Within the same SparkContext, no two task attempts will share the same attempt ID. task_id = pyspark.TaskContext().taskAttemptId() first_batch = next(it, None) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]], names=["task_id", "num_examples", "num_bytes"], ) shard_id = 0 writer = writer_class( features=features, path=working_fpath.replace("SSSSS", f"{shard_id:05d}").replace("TTTTT", f"{task_id:05d}"), writer_batch_size=writer_batch_size, storage_options=storage_options, embed_local_files=embed_local_files, ) table = pa.Table.from_batches([first_batch]) writer.write_table(table) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: num_examples, num_bytes = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]], names=["task_id", "num_examples", "num_bytes"], ) shard_id += 1 writer = writer_class( features=writer._features, path=working_fpath.replace("SSSSS", f"{shard_id:05d}").replace("TTTTT", f"{task_id:05d}"), writer_batch_size=writer_batch_size, storage_options=storage_options, embed_local_files=embed_local_files, ) table = pa.Table.from_batches([batch]) writer.write_table(table) if writer._num_bytes > 0: num_examples, num_bytes = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]], names=["task_id", "num_examples", "num_bytes"], ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(working_fpath)): dest = os.path.join(os.path.dirname(fpath), os.path.basename(file)) shutil.move(file, dest) stats = ( self.df.mapInArrow(write_arrow, "task_id: long, num_examples: long, num_bytes: long") .groupBy("task_id") .agg( pyspark.sql.functions.sum("num_examples").alias("total_num_examples"), pyspark.sql.functions.sum("num_bytes").alias("total_num_bytes"), pyspark.sql.functions.count("num_bytes").alias("num_shards"), pyspark.sql.functions.collect_list("num_examples").alias("shard_lengths"), ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _prepare_split( self, split_generator: "datasets.SplitGenerator", file_format: str = "arrow", max_shard_size: Optional[Union[str, int]] = None, num_proc: Optional[int] = None, **kwargs, ): self._validate_cache_dir() max_shard_size = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE) self._repartition_df_if_needed(max_shard_size) is_local = not is_remote_filesystem(self._fs) path_join = os.path.join if is_local else posixpath.join SUFFIX = "-TTTTT-SSSSS-of-NNNNN" fname = f"{self.name}-{split_generator.name}{SUFFIX}.{file_format}" fpath = path_join(self._output_dir, fname) total_num_examples = 0 total_num_bytes = 0 total_shards = 0 task_id_and_num_shards = [] all_shard_lengths = [] for task_id, content in self._prepare_split_single(fpath, file_format, max_shard_size): ( num_examples, num_bytes, num_shards, shard_lengths, ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards)) all_shard_lengths.extend(shard_lengths) split_generator.split_info.num_examples = total_num_examples split_generator.split_info.num_bytes = total_num_bytes # should rename everything at the end logger.debug(f"Renaming {total_shards} shards.") if total_shards > 1: split_generator.split_info.shard_lengths = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. fs = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( task_id: int, shard_id: int, global_shard_id: int, ): rename( fs, fpath.replace("SSSSS", f"{shard_id:05d}").replace("TTTTT", f"{task_id:05d}"), fpath.replace("TTTTT-SSSSS", f"{global_shard_id:05d}").replace("NNNNN", f"{total_shards:05d}"), ) args = [] global_shard_id = 0 for i in range(len(task_id_and_num_shards)): task_id, num_shards = task_id_and_num_shards[i] for shard_id in range(num_shards): args.append([task_id, shard_id, global_shard_id]) global_shard_id += 1 self._spark.sparkContext.parallelize(args, len(args)).map(lambda args: _rename_shard(*args)).collect() else: # don't use any pattern shard_id = 0 task_id = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS", f"{shard_id:05d}").replace("TTTTT", f"{task_id:05d}"), fpath.replace(SUFFIX, ""), ) def _get_examples_iterable_for_split( self, split_generator: "datasets.SplitGenerator", ) -> SparkExamplesIterable: return SparkExamplesIterable(self.df)
0