Minimartzz/github-issues huggingface dataset:
Shell completions
State: closed
Labels: description: New feature or request
name: enhancement

### Feature request

Like <https://github.com/huggingface/huggingface_hub/issues/1197>, datasets-cli maybe need it, too.

### Motivation

See above.

### Your contribution

Maybe.

Comments:
I don't think we need completion on the datasets-cli, since we're mainly developing huggingface-cli

I see.
Sharded save_to_disk + multiprocessing
State: closed

Added `num_shards=` and `num_proc=` to `save_to_disk()`

EDIT: also added `max_shard_size=` to `save_to_disk()`, and also `num_shards=` to `push_to_hub`

I also:
- deprecated the fs parameter in favor of storage_options (for consistency with the rest of the lib) in save_to_disk and load_from_disk
- always embed the image/audio data in arrow when doing `save_to_disk`
- added a tqdm bar in `save_to_disk`
- Use the MockFileSystem in tests for `save_to_disk` and `load_from_disk`
- removed the unused integration tests with S3, since we can now test with `mockfs` instead of `s3fs`

TODO:
- [x] implem save_to_disk for dataset dict
- [x] save_to_disk for dataset dict tests
- [x] deprecate fs in dataset dict load_from_disk as well
- [x] update docs

Close #5263 
Close https://github.com/huggingface/datasets/issues/4196
Close https://github.com/huggingface/datasets/issues/4351

Comments:
_The documentation is not available anymore as the PR was closed or merged._

Added both num_shards and max_shard_size in push_to_hub/save_to_disk. Will take care of updating the tests later

It's ready for a final review @mariosasko and @albertvillanova, let me know what you think :)

Took your comments into account, and also changed `iflatmap_unordered` to take an iterable of kwargs to make the code more redable :)
Specify arguments as keywords in librosa.reshape to avoid future errors 
State: closed

Fixes a warning and future deprecation from `librosa.reshape`:
```
FutureWarning: Pass orig_sr=16000, target_sr=48000 as keyword args. From version 0.10 passing these as positional arguments will result in an error

   array = librosa.resample(array, sampling_rate, self.sampling_rate, res_type="kaiser_best")
```

Comments:
_The documentation is not available anymore as the PR was closed or merged._
Get an IterableDataset from a map-style Dataset
State: closed
Labels: description: New feature or request
name: enhancement

name: streaming

This is useful to leverage iterable datasets specific features like:
- fast approximate shuffling
- lazy map, filter etc.

Iterating over the resulting iterable dataset should be at least as fast at iterating over the map-style dataset.

Here are some ideas regarding the API:
```python
# 1. 
# - consistency with load_dataset(..., streaming=True)
# - gives intuition that map/filter/etc. are done on-the-fly
ids = ds.stream()

# 2.
# - more explicit on the output type
# - but maybe sounds like a conversion tool rather than a step in a processing pipeline
ids = ds.as_iterable_dataset()
```

Comments:
I think `stream` could be misleading since the data is not being streamed from remote endpoints (one could think that's the case when they see `load_dataset` followed by `stream`). Hence, I prefer the second option.

PS: When we resolve https://github.com/huggingface/datasets/issues/4542, we could add `as_tf_dataset` to the API for consistency and deprecate `to_tf_dataset`.
AttributeError: 'Value' object has no attribute 'names'
State: closed

Hello

I'm trying to build a model for custom token classification 
I already followed the token classification course on huggingface

while adapting the code to my work, this message occures : 
'Value' object has no attribute 'names'

Here's my code:
`raw_datasets` 
generates
DatasetDict({
    train: Dataset({
        features: ['isDisf', 'pos', 'tokens', 'id'],
        num_rows: 14
    })
})

`raw_datasets["train"][3]["isDisf"]`
generates 
['B_RM', 'I_RM', 'I_RM', 'B_RP', 'I_RP', 'O', 'O']

`dis_feature = raw_datasets["train"].features["isDisf"]
dis_feature`
generates
Sequence(feature=Value(dtype='string', id=None), length=-1, id=None)

and
`label_names = dis_feature.feature.names
label_names`
generates
AttributeError                            Traceback (most recent call last)
[<ipython-input-28-972fd54a869a>](https://localhost:8080/#) in <module>
----> 1 label_names = dis_feature.feature.names
      2 label_names

AttributeError: 'Value' object has
AttributeError: 'Value' object has no attribute 'names'

Thank you for your help

Comments:
Hi ! It looks like your "isDif" column is a Sequence of Value("string"), not a Sequence of ClassLabel.

You can convert your Value("string") feature type to a ClassLabel feature type this way:
```python
from datasets import ClassLabel, Sequence

# provide the label_names yourself
label_names = [...]
# OR get them from the dataset
label_names = sorted(set(label for labels in raw_datasets["train"]["isDif"] for label in labels))

# Cast to ClassLabel
raw_datasets = raw_datasets.cast_column("isDif", Sequence(ClassLabel(names=label_names)))
```


thank you 
it works 💯
Add PubTables-1M
State: open
Labels: description: Requesting to add a new dataset
name: dataset request

### Name

PubTables-1M

### Paper

https://openaccess.thecvf.com/content/CVPR2022/html/Smock_PubTables-1M_Towards_Comprehensive_Table_Extraction_From_Unstructured_Documents_CVPR_2022_paper.html

### Data

https://github.com/microsoft/table-transformer

### Motivation

Table Transformer is now available in 🤗 Transformer, and it was trained on PubTables-1M. It's a large dataset for table extraction and structure recognition in unstructured documents.

Comments:
cc @albertvillanova the author would like to add this dataset to the hub: https://github.com/microsoft/table-transformer/issues/68#issuecomment-1319114621. Could you help him out?
Restore order of split names in dataset_info for canonical datasets
State: closed
Labels: description: Contribution to a dataset script
name: dataset contribution

After a bulk edit of canonical datasets to create the YAML `dataset_info` metadata, the split names were accidentally sorted alphabetically. See for example:
- https://huggingface.co/datasets/bc2gm_corpus/commit/2384629484401ecf4bb77cd808816719c424e57c

Note that this order is the one appearing in the preview of the datasets.

I'm making a bulk edit to align the order of the splits appearing in the metadata info with the order appearing in the loading script.

Related to:
- #5202

Comments:
The bulk edit is running...

See for example: 
- A single config: https://huggingface.co/datasets/acronym_identification/discussions/2
- Multiple configs: https://huggingface.co/datasets/babi_qa/discussions/1

TODO: Add "dataset_info" YAML metadata to:
- [x] "chr_en" has no metadata JSON file, nor "dataset_info" YAML tag in its card
  - Fixing PR: https://huggingface.co/datasets/chr_en/discussions/1 
- [x] "conll2000" has no metadata JSON file, but it has "dataset_info" YAML tag in its card
- [x] "crime_and_punish" has no metadata JSON file, but it has "dataset_info" YAML tag in its card
- [x] "dart" has no metadata JSON file, but it has "dataset_info" YAML tag in its card
- [x] "iwslt2017" has no metadata JSON file, but it has "dataset_info" YAML tag in its card
- [ ] "mc4" has no metadata JSON file, nor "dataset_info" YAML tag in its card
- [ ] "the_pile" has no metadata JSON file, nor "dataset_info" YAML tag in its card
- [ ] "timit_asr" has no metadata JSON file, nor "dataset_info" YAML tag in its card

The bulk edit is finished.
Support for decoding Image/Audio types in map when format type is not default one
State: closed

Add support for decoding the `Image`/`Audio` types in `map` for the formats (Numpy, TF, Jax, PyTorch) other than the default one (Python).

Additional improvements:
* make `Dataset`'s "iter" API  cleaner by removing `_iter` and replacing `_iter_batches` with `iter(batch_size)` (also implemented for `IterableDataset`)
* iterate over arrow tables in `map` to avoid `_getitem` calls, which are much slower than `__iter__`/`iter(batch_size)`, when the `format_type` is not Python
* fix `_iter_batches` (now named `iter`) when `drop_last_batch=True` and `pyarrow<=8.0.0` is installed
* lazily extract and decode arrow data in the default format 

TODO:
* [x] update the `iter` benchmark in the docs (the `BeamBuilder` cannot load the preprocessed datasets from our bucket, so wait for this to be fixed (cc @lhoestq))

Fix https://github.com/huggingface/datasets/issues/3992, fix https://github.com/huggingface/datasets/issues/3756

Comments:
_The documentation is not available anymore as the PR was closed or merged._

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/datasets/pr_5252). All of your documentation changes will be reflected on that endpoint.

Yes, if the image column is the first in the batch keys, it will decode the images because it reads the actual values. We could avoid this by checking the batch type, and if it's `LazyDict`, `num_examples` is equal to `len(batch.pa_table)`, which doesn't lead to decoding.

Good idea. This can be done in a subsequent PR btw, since it's out of scope of the original goal of this PR

Just fixed a small bug where it would show the pyarrow 10 warning about None -> empty lists conversions even with an Array2D with no nulls

Fixed another bug when your map function returns a mix of LazyDict or regular dict and added some tests
Docs are not generated after latest release
State: closed
Labels: description: Maintenance tasks
name: maintenance

After the latest `datasets` release version 0.7.0, the docs were not generated.

As we have changed the release procedure (so that now we do not push directly to main branch), maybe we should also change the corresponding GitHub action:

https://github.com/huggingface/datasets/blob/edf1902f954c5568daadebcd8754bdad44b02a85/.github/workflows/build_documentation.yml#L3-L8

Related to:
- #5250

CC: @mishig25 

Comments:
After a discussion with @mishig25:
- He said that this action should be triggered if we call our release branch according to the regex `v*-release`, as transformers does
- I said that our procedure is different: our release branch is *temporary* and it is deleted just after the release PR is merged to main
  - Indeed the release tag is not yet created when we make the release PR (not event when this is merged to main), but when we make the Release itself.

I was thinking that maybe we could change the triggering event: use `release` instead of `push`.

What do you think, @huggingface/datasets?

Why is it an issue if our branch is temporary ?

He says not; but the branch has no tag yet; does the doc building require the tag? Or just the version number in `__init__.py` or setup.py?

It uses `module.__version__` (i.e. the one defined in `__init__.py`) - no need to have a tag

https://github.com/huggingface/doc-builder/blob/81575cf081964c30ea5fd39450f4820db963f18e/src/doc_builder/commands/build.py#L69

Thanks, @lhoestq.

@mishig25 has manually forced the generation of the docs, that are live for 2.7.0 version: https://huggingface.co/docs/datasets/v2.7.0/en/index 

Cool ! this can be closed then ?

I was waiting for #5250 to be merged to close this.

just to confirm, is there anything I need to do from my side ? Or is everything good here ?
Protect the main branch from inadvertent direct pushes
State: closed
Labels: description: Maintenance tasks
name: maintenance

We have decided to implement a protection mechanism in this repository, so that nobody (not even administrators) can inadvertently push accidentally directly to the main branch.

See context here:
- d7c942228b8dcf4de64b00a3053dce59b335f618

To do:
- [x] Protect main branch
  - Settings > Branches > Branch protection rules > main > Edit
    - [x] Check: Do not allow bypassing the above settings 
      - The above settings will apply to administrators and custom roles with the "bypass branch protections" permission.
    - [x] Additionally, uncheck: Require approvals [under "Require a pull request before merging", which was already checked]
      - Before, we could exceptionally merge a non-approved PR, using Administrator bypass
      - Now that Administrator bypass is no longer possible, we would always need an approval to be able to merge; and pull request authors cannot approve their own pull requests. This could be an inconvenient in some exceptional circumstances when an urgent fix is needed
      - Nevertheless, although it is no longer enforced, it is strongly recommended to merge PRs only if they have at least one approval
- [x] #5250
  - So that direct pushes to main branch are no longer necessary

Comments:
It seems all the tasks have been addressed, meaning this issue can be closed, no?
Complete doc migration
State: closed

Reverts huggingface/datasets#5214

Everything is handled on the doc-builder side now 😊

Comments:
The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/datasets/pr_5248). All of your documentation changes will be reflected on that endpoint.

Thanks for the fix @mishig25.

I guess this is the reason why the docs are not generated for the latest release version 2.7.0? https://huggingface.co/docs/datasets/index
Unable to rename columns in streaming dataset
State: closed

### Describe the bug

Trying to rename column in a streaming datasets, destroys the features object.

### Steps to reproduce the bug

The following code illustrates the error:

```
from datasets import load_dataset
dataset = load_dataset('mc4', 'en', streaming=True, split='train')
dataset.info.features
# {'text': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'url': Value(dtype='string', id=None)}
dataset = dataset.rename_column("text", "content")
dataset.info.features
# This returned object is now None!
```



### Expected behavior

This should just alter the renamed column.

### Environment info

datasets 2.6.1

Comments:
Hi @peregilk this bug is directly related to https://github.com/huggingface/datasets/issues/3888, and still not fixed... But I'll try to have a look!

Thanks @alvarobartt. It is great if you are able to fix it, but when reading the explanation it seems like it is possible to work around it.

We also tried keeping the 'info.features' and then adding a modified version back after the remove/rename. Unforutunately that leads to a dataset that is not possible to iterate over.

So if you iterate over the `IterableDataset` as `next(iter(ds))` and then run `rename_columns` when checking that data it will work, but in the end, it's just renaming the column one example/batch at a time, not renaming the column name for all the entries in the dataset, which is the ideal.

@alvarobartt Thanks. My use case was that I wanted to do multiple things, ie removing all unnecessary columns, renaming some valid columns, and then using cast (in my case checking if the audio is not 16K and casting it). It is just convenient to look into the info.features between each of these operations. Alternatively, I will just plan ahead...;) To me it seems like all the operations are working.

Thanks for the advice. It was very useful.

If we know the features before renaming, then we know the features after renaming, so we can pass the new features to the returned dataset in `rename_column` indeed ! If anyone is interested in contributing, feel free to open a PR and I'd be happy to help / give some pointers :)

Sure @lhoestq thanks! I’ll try to work on that

#self-assign
Failed Data Processing upon upload with zip file full of images
State: open

I went to autotrain and under image classification arrived where it was time to prepare my dataset. Screenshot below
![image](https://user-images.githubusercontent.com/82735473/201814099-3cc5ff8a-88dc-4f5f-8140-f19560641d83.png)


I chose the method 2 option. I have a csv file with two columns. ~23,000 files. 

I uploaded this and chose the image_relpath, and target columns. 

The image uploader said that I could only upload 10,000 singular images at a time so the 2nd option was to zip the images up and upload a zip archive which I did. 

That all uploaded. 

Now I have the message below. It appears the zip archive does just uncompress on the Hugging Face end? 
What am I missing here?



![image](https://user-images.githubusercontent.com/82735473/201813838-b50dbbbc-34e8-4d73-9c07-12f9e41c62eb.png)


Comments:
cc @abhishekkrthakur @SBrandeis
Add num_proc to from_csv/generator/json/parquet/text
State: closed

Allow multiprocessing to from_* methods

Comments:
The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/datasets/pr_5239). All of your documentation changes will be reflected on that endpoint.

I ended up moving `num_proc` to `AbstractDatasetReader.__init__` :)

Let me know if it sounds good to you now
Make `Version` hashable
State: closed

Add `__hash__` to the `Version` class to make it hashable (and remove the unneeded methods), as  `Version("0.0.0")` is the default value of `BuilderConfig.version` and the default fields of a dataclass need to be hashable in Python 3.11.

Fix https://github.com/huggingface/datasets/issues/5230

Comments:
_The documentation is not available anymore as the PR was closed or merged._
Handle ArrowNotImplementedError caused by try_type being Image or Audio in cast
State: closed

Handle the `ArrowNotImplementedError` thrown when `try_type` is `Image` or `Audio` and the input array cannot be converted to their storage formats.

Reproducer:
```python
from datasets import Dataset
from PIL import Image
import requests

ds = Dataset.from_dict({"image": [Image.open(requests.get("https://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", stream=True).raw)]})
ds.map(lambda x: {"image": True}) # ArrowNotImplementedError 
```

PS: This could also be fixed by raising `TypeError` in `{Image, Audio}.cast_storage` for unsupported types instead of passing the array to `array_cast.`

Comments:
_The documentation is not available anymore as the PR was closed or merged._

> Not sure how we can have a test that is relevant for this though - feel free to add one if you have ideas

Yes, this was my reasoning for not adding a test. This change is pretty simple, so I think it's OK not to have a test for it.
Pin `typer` version in tests to <0.5 to fix Windows CI
State: closed

Otherwise `click` fails on Windows: 
```
Traceback (most recent call last):
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\site-packages\spacy\__main__.py", line 4, in <module>
    setup_cli()
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\site-packages\spacy\cli\_util.py", line 71, in setup_cli
    command(prog_name=COMMAND)
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\site-packages\click\core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\site-packages\typer\core.py", line 785, in main
    **extra,
  File "C:\hostedtoolcache\windows\Python\3.7.9\x64\lib\site-packages\typer\core.py", line 190, in _main
    args = click.utils._expand_args(args)
AttributeError: module 'click.utils' has no attribute '_expand_args'
```

See https://github.com/tiangolo/typer/issues/427

Comments:
fix: dataset path should be absolute
State: closed

cache_file_name depends on dataset's path.

A simple way where this could cause a problem:
```
import os
import datasets


def add_prefix(example):
    example["text"] = "Review: " + example["text"]
    return example


ds = datasets.load_from_disk("a/relative/path")
os.chdir("/tmp")

ds_1 = ds.map(add_prefix)
```

while it may feel that the `chdir` is quite constructed, there are many scenarios when the current working dir can/will change...

Comments:
Good catch thanks ! Have you tried to use the absolue path in `MemoryMappedTable.__init__` in `table.py`?

I think it can fix issues with relative paths at more levels than just fixing it `load_from_disk`. If it works I think it would be a more robust fix to this issue

@lhoestq right, that actually fixed it indeed. I've pushed the changes (one-liner). lemme know if there's anything else you need for this fix

_The documentation is not available anymore as the PR was closed or merged._
Incompatible dill versions in datasets 2.6.1
State: closed

### Describe the bug

datasets version 2.6.1 has a dependency on dill<0.3.6. This causes a conflict with dill>=0.3.6 used by multiprocess dependency in datasets 2.6.1

This issue is already fixed in https://github.com/huggingface/datasets/pull/5166/files, but not yet been released. Please release a new version of the datasets library to fix this.

### Steps to reproduce the bug

1. Create requirements.in with only dependency being datasets (or datasets[s3])
2. Run pip-compile
3. The output is as follows:

```
Could not find a version that matches dill<0.3.6,>=0.3.6 (from datasets[s3]==2.6.1->-r requirements.in (line 1))
Tried: 0.2, 0.2, 0.2.1, 0.2.1, 0.2.2, 0.2.2, 0.2.3, 0.2.3, 0.2.4, 0.2.4, 0.2.5, 0.2.5, 0.2.6, 0.2.7, 0.2.7.1, 0.2.8, 0.2.8.1, 0.2.8.2, 0.2.9, 0.3.0, 0.3.1, 0.3.1.1, 0.3.2, 0.3.3, 0.3.3, 0.3.4, 0.3.4, 0.3.5, 0.3.5, 0.3.5.1, 0.3.5.1, 0.3.6, 0.3.6
Skipped pre-versions: 0.1a1, 0.2a1, 0.2a1, 0.2b1, 0.2b1
There are incompatible versions in the resolved dependencies:
  dill<0.3.6 (from datasets[s3]==2.6.1->-r requirements.in (line 1))
  dill>=0.3.6 (from multiprocess==0.70.14->datasets[s3]==2.6.1->-r requirements.in (line 1))
```

### Expected behavior

pip-compile produces requirements.txt without any conflicts

### Environment info

datasets version 2.6.1

Comments:
Thanks for reporting, @vinaykakade.

We are discussing about making a release early this week.

Please note that in the meantime, in your specific case (as we also pointed out here: https://github.com/huggingface/datasets/issues/5162#issuecomment-1291720293), you can circumvent the issue by pinning `multiprocess` to 0.70.13 version (instead of using latest 0.70.14).

Duplicate of:
- https://github.com/huggingface/datasets/issues/5162

You can also make `pip-compile` work by using the backtracking resolver (instead of the legacy one): https://pip-tools.readthedocs.io/en/latest/#a-note-on-resolvers
```
pip-compile --resolver=backtracking requirements.in
```
This resolver will automatically use `multiprocess` 0.70.13 version.
Using `set_format(type='torch', columns=columns)` makes Array2D/3D columns stop formatting correctly
State: closed

I have a Dataset with two Features defined as follows:

```
'image': Array3D(dtype="int64", shape=(3, 224, 224)),
'bbox': Array2D(dtype="int64", shape=(512, 4)),
```

On said dataset, if I `dataset.set_format(type='torch')` and then use the dataset in a dataloader, these columns are correctly cast to Tensors of (batch_size, 3, 224, 244) for example.

However, if I `dataset.set_format(type='torch', columns=['image', 'bbox'])` these columns are cast to Lists of tensors and miss the batch size completely (the 3 dimension is the list length).

I'm currently digging through datasets formatting code to try and find out why, but was curious if someone knew an immediate solution for this.

Comments:
In case others find this, the problem was not with set_format, but my usages of `to_pandas()` and `from_pandas()` which I was using during dataset splitting; somewhere in the chain of converting to and from pandas the `Array2D/Array3D` types get converted to series of `Sequence()` types