Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/datasets/__init__.pyAdded+47
- lib/python3.12/site-packages/datasets/arrow_dataset.pyAdded
- lib/python3.12/site-packages/datasets/arrow_reader.pyAdded+620
- lib/python3.12/site-packages/datasets/arrow_writer.pyAdded+677
- lib/python3.12/site-packages/datasets/builder.pyAdded+1903
- lib/python3.12/site-packages/datasets/combine.pyAdded+215
- lib/python3.12/site-packages/datasets/commands/__init__.pyAdded+13
- lib/python3.12/site-packages/datasets/commands/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/__pycache__/convert.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/__pycache__/convert_to_parquet.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/__pycache__/datasets_cli.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/__pycache__/delete_from_hub.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/__pycache__/env.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/__pycache__/test.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/commands/convert.pyAdded+195
- lib/python3.12/site-packages/datasets/commands/convert_to_parquet.pyAdded+46
- lib/python3.12/site-packages/datasets/commands/datasets_cli.pyAdded+43
- lib/python3.12/site-packages/datasets/commands/delete_from_hub.pyAdded+42
- lib/python3.12/site-packages/datasets/commands/env.pyAdded+41
- lib/python3.12/site-packages/datasets/commands/test.pyAdded+207
- lib/python3.12/site-packages/datasets/config.pyAdded+269
- lib/python3.12/site-packages/datasets/data_files.pyAdded+795
- lib/python3.12/site-packages/datasets/dataset_dict.pyAdded
- lib/python3.12/site-packages/datasets/distributed.pyAdded+39
- lib/python3.12/site-packages/datasets/exceptions.pyAdded+119
- lib/python3.12/site-packages/datasets/fingerprint.pyAdded+454
- lib/python3.12/site-packages/datasets/hub.pyAdded+230
- lib/python3.12/site-packages/datasets/info.pyAdded+430
- lib/python3.12/site-packages/datasets/inspect.pyAdded+363
- lib/python3.12/site-packages/datasets/iterable_dataset.pyAdded
- lib/python3.12/site-packages/datasets/keyhash.pyAdded+104
- lib/python3.12/site-packages/datasets/load.pyAdded
- lib/python3.12/site-packages/datasets/naming.pyAdded+84
- lib/python3.12/site-packages/datasets/packaged_modules/__init__.pyAdded+104
- lib/python3.12/site-packages/datasets/packaged_modules/csv/__init__.pyAdded
- lib/python3.12/site-packages/datasets/packaged_modules/csv/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/csv/__pycache__/csv.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/csv/csv.pyAdded+198
- lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/__init__.pyAdded
- lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/__pycache__/folder_based_builder.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/folder_based_builder.pyAdded+417
- lib/python3.12/site-packages/datasets/packaged_modules/generator/__init__.pyAdded
- lib/python3.12/site-packages/datasets/packaged_modules/generator/__pycache__/generator.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/generator/generator.pyAdded+33
- lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/__init__.pyAdded
- lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/__pycache__/imagefolder.cpython-312.pycAdded
- lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/imagefolder.pyAdded+103
- lib/python3.12/site-packages/datasets/packaged_modules/sql/__init__.pyAdded
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# 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.
__version__ = "3.6.0"
from .arrow_dataset import Datasetfrom .arrow_reader import ReadInstructionfrom .builder import ArrowBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilderfrom .combine import concatenate_datasets, interleave_datasetsfrom .dataset_dict import DatasetDict, IterableDatasetDictfrom .download import *from .features import *from .fingerprint import disable_caching, enable_caching, is_caching_enabledfrom .info import DatasetInfofrom .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_default_config_name, get_dataset_infos, get_dataset_split_names,)from .iterable_dataset import IterableDatasetfrom .load import load_dataset, load_dataset_builder, load_from_diskfrom .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent,)from .utils import *from .utils import logging123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620# 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 copyimport mathimport osimport refrom dataclasses import dataclassfrom functools import partialfrom typing import TYPE_CHECKING, Optional, Union
import pyarrow as paimport pyarrow.parquet as pqfrom tqdm.contrib.concurrent import thread_map
from .download.download_config import DownloadConfig # noqa: F401from .naming import _split_re, filenames_for_dataset_splitfrom .table import InMemoryTable, MemoryMappedTable, Table, concat_tablesfrom .utils import loggingfrom .utils import tqdm as hf_tqdm
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: take = to - from_ if take == 0: continue num_examples += take file_instructions.append({"filename": filename, "skip": from_, "take": take}) 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") files = copy.deepcopy(files) for f in files: f["filename"] = os.path.join(self._path, f["filename"])
pa_tables = thread_map( partial(self._get_table_from_filename, in_memory=in_memory), files, tqdm_class=hf_tqdm, desc="Loading dataset shards", # set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached disable=len(files) <= 16 or None, ) 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
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 from_ < 0: from_ = max(num_examples + from_, 0) if to < 0: to = max(num_examples + to, 0) from_ = min(from_, num_examples) to = min(to, num_examples) 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]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677# 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 jsonimport sysfrom collections.abc import Iterablefrom typing import Any, Optional, Union
import fsspecimport numpy as npimport pyarrow as paimport pyarrow.parquet as pqfrom fsspec.core import url_to_fs
from . import configfrom .features import Audio, Features, Image, Pdf, Value, Videofrom .features.features import ( FeatureType, _ArrayXDExtensionType, _visit, 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_filesystemfrom .info import DatasetInfofrom .keyhash import DuplicatedKeysError, KeyHasherfrom .table import array_cast, cast_array_to_feature, embed_table_storage, table_castfrom .utils import loggingfrom .utils.py_utils import asdict, first_non_null_non_empty_value
logger = logging.get_logger(__name__)
type_ = type # keep python's type function
def get_writer_batch_size(features: Optional[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/audio datasets and 10 for videos. 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: features (`datasets.Features` or `None`): Dataset Features 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. """ if not features: return None
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, Video): batch_size = min(batch_size, config.PARQUET_ROW_GROUP_SIZE_FOR_VIDEO_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 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 directly 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_non_empty_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() if isinstance(non_null_value, list) and isinstance(non_null_value[0], PIL.Image.Image): return [[Image().encode_example(x) for x in value] if value is not None else None for value in data], [ Image() ] if config.PDFPLUMBER_AVAILABLE and "pdfplumber" in sys.modules: import pdfplumber
non_null_idx, non_null_value = first_non_null_non_empty_value(data) if isinstance(non_null_value, pdfplumber.pdf.PDF): return [Pdf().encode_example(value) if value is not None else None for value in data], Pdf() if isinstance(non_null_value, list) and isinstance(non_null_value[0], pdfplumber.pdf.PDF): return [[Pdf().encode_example(x) for x in value] if value is not None else None for value in data], [ Pdf() ] 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_non_empty_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_primitive_to_str=not self.trying_type, allow_decimal_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_primitive_to_str=True, allow_decimal_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_primitive_to_str=True, allow_decimal_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, path = url_to_fs(path, **(storage_options or {})) self._fs: fsspec.AbstractFileSystem = fs self._path = path if not is_remote_filesystem(self._fs) else self._fs.unstrip_protocol(path) self.stream = self._fs.open(path, "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 get_writer_batch_size(self._features) 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 # preserve the order the columns if self.schema: schema_cols = set(self.schema.names) examples_cols = self.current_examples[0][0].keys() # .keys() preserves the order (unlike set) common_cols = [col for col in self.schema.names if col in examples_cols] extra_cols = [col for col in examples_cols if col not in schema_cols] cols = common_cols + extra_cols else: cols = list(self.current_examples[0][0]) batch_examples = {} for col in cols: # We use row[0][col] since current_examples contains (example, key) tuples. # Moreover, 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] arrays = [ chunk for array in arrays for chunk in (array.chunks if isinstance(array, pa.ChunkedArray) else [array]) ] batch_examples[col] = pa.concat_arrays(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-initializing 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, try_original_type: Optional[bool] = True, ): """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. try_original_type: use `try_type` when instantiating OptimizedTypedSequence if `True`, otherwise `try_type = None`. """ 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() # preserve the order the columns if self.schema: schema_cols = set(self.schema.names) batch_cols = batch_examples.keys() # .keys() preserves the order (unlike set) common_cols = [col for col in self.schema.names if col in batch_cols] extra_cols = [col for col in batch_cols if col not in schema_cols] cols = common_cols + extra_cols else: cols = list(batch_examples) 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 and try_original_type 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-initializing 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.ParquetWriter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903# 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 abcimport contextlibimport copyimport inspectimport osimport posixpathimport shutilimport textwrapimport timeimport urllibfrom collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING, Optional, Unionfrom unittest.mock import patch
import fsspecfrom fsspec.core import url_to_fsfrom multiprocess import Poolfrom tqdm.contrib.concurrent import thread_map
from . import config, utilsfrom .arrow_dataset import Datasetfrom .arrow_reader import ( ArrowReader, ReadInstruction,)from .arrow_writer import ArrowWriter, ParquetWriter, SchemaInferenceErrorfrom .data_files import DataFilesDict, DataFilesPatternsDict, sanitize_patternsfrom .dataset_dict import DatasetDict, IterableDatasetDictfrom .download.download_config import DownloadConfigfrom .download.download_manager import DownloadManager, DownloadModefrom .download.streaming_download_manager import StreamingDownloadManager, xjoinfrom .exceptions import DatasetGenerationCastError, DatasetGenerationError, FileFormatError, ManualDownloadErrorfrom .features import Featuresfrom .filesystems import ( is_remote_filesystem, rename,)from .fingerprint import Hasherfrom .info import DatasetInfo, DatasetInfosDict, PostProcessedInfofrom .iterable_dataset import ArrowExamplesIterable, ExamplesIterable, IterableDatasetfrom .keyhash import DuplicatedKeysErrorfrom .naming import INVALID_WINDOWS_CHARACTERS_IN_PATH, camelcase_to_snakecasefrom .splits import Split, SplitDict, SplitGenerator, SplitInfofrom .streaming import extend_dataset_builder_for_streamingfrom .table import CastErrorfrom .utils import loggingfrom .utils import tqdm as hf_tqdmfrom .utils._filelock import FileLockfrom .utils.file_utils import is_remote_urlfrom .utils.info_utils import VerificationMode, get_size_checksum_dict, verify_checksums, verify_splitsfrom .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_kwargsfrom .utils.track import tracked_list
if TYPE_CHECKING: from .load import DatasetModule
logger = logging.get_logger(__name__)
class InvalidConfigName(ValueError): pass
@dataclassclass 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 "rajpurkar/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. **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, 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, **config_kwargs, ): # 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 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_kwargs = config_kwargs 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 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) and not (set(self.config_kwargs) - {"data_files", "data_dir"}) ): from .packaged_modules import _PACKAGED_DATASETS_MODULES_2_15_HASHES 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_2_15_HASHES.get(self.name, "missing") 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('vivos') >>> ds_builder.get_all_exported_dataset_infos() {'default': DatasetInfo(description='', citation='', homepage='', license='', features={'speaker_id': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None), 'sentence': Value(dtype='string', id=None)}, post_processed=None, supervised_keys=None, builder_name=None, dataset_name=None, config_name='default', version=None, splits={'train': SplitInfo(name='train', num_bytes=1722002133, num_examples=11660, shard_lengths=None, dataset_name=None), 'test': SplitInfo(name='test', num_bytes=86120227, num_examples=760, shard_lengths=None, dataset_name=None)}, download_checksums=None, download_size=1475540500, post_processing_size=None, dataset_size=1808122360, size_in_bytes=None)} ``` """ 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('cornell-movie-review-data/rotten_tomatoes') >>> ds_builder.get_exported_dataset_info() DatasetInfo(description='', citation='', homepage='', license='', features={'speaker_id': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None), 'sentence': Value(dtype='string', id=None)}, post_processed=None, supervised_keys=None, builder_name=None, dataset_name=None, config_name='default', version=None, splits={'train': SplitInfo(name='train', num_bytes=1722002133, num_examples=11660, shard_lengths=None, dataset_name=None), 'test': SplitInfo(name='test', num_bytes=86120227, num_examples=760, shard_lengths=None, dataset_name=None)}, download_checksums=None, download_size=1475540500, post_processing_size=None, dataset_size=1808122360, size_in_bytes=None) ``` """ 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.repo_id or 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, dl_manager: Optional[DownloadManager] = None, base_path: Optional[str] = None, 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"/> 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. 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("cornell-movie-review-data/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("cornell-movie-review-data/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("cornell-movie-review-data/rotten_tomatoes") >>> builder.download_and_prepare("s3://my-bucket/my_rotten_tomatoes", storage_options=storage_options, file_format="parquet") ``` """ 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 fs, output_dir = url_to_fs(output_dir, **(storage_options or {})) 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=self.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) 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): 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() if self.info.download_size is not None: 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.repo_id or self.dataset_name}", data_dir="<path/to/manual/data>")""" ) )
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, 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"/> 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('cornell-movie-review-data/rotten_tomatoes') >>> builder.download_and_prepare() >>> ds = builder.as_dataset(split='train') >>> ds Dataset({ features: ['text', 'label'], num_rows: 8530 }) ``` """ 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: Union[DownloadManager, StreamingDownloadManager]): """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 (`Union[DownloadManager, StreamingDownloadManager]`): 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 """ 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215from typing import Optional, TypeVar
from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasetsfrom .dataset_dict import DatasetDict, IterableDatasetDictfrom .info import DatasetInfofrom .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasetsfrom .splits import NamedSplitfrom .utils import loggingfrom .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 interleave_datasets >>> d1 = load_dataset('allenai/c4', 'es', split='train', streaming=True) >>> d2 = load_dataset('allenai/c4', 'fr', split='train', streaming=True) >>> dataset = interleave_datasets([d1, d2]) >>> iterator = iter(dataset) >>> next(iterator) {'text': 'Comprar Zapatillas para niña en chancla con goma por...'} >>> next(iterator) {'text': 'Le sacre de philippe ier, 23 mai 1059 - Compte Rendu...' ``` """ 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)12345678910111213from abc import ABC, abstractmethodfrom argparse import ArgumentParser
class BaseDatasetsCLICommand(ABC): @staticmethod @abstractmethod def register_subcommand(parser: ArgumentParser): raise NotImplementedError()
@abstractmethod def run(self): raise NotImplementedError()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import osimport reimport shutilfrom argparse import ArgumentParser, Namespace
from datasets.commands import BaseDatasetsCLICommandfrom datasets.utils.logging import get_logger
HIGHLIGHT_MESSAGE_PRE = """<<<<<<< This should probably be modified because it mentions: """
HIGHLIGHT_MESSAGE_POST = """=======>>>>>>>"""
TO_HIGHLIGHT = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir",]
TO_CONVERT = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"),]
def convert_command_factory(args: Namespace): """ Factory function used to convert a model TF 1.0 checkpoint in a PyTorch checkpoint.
Returns: ConvertCommand """ return ConvertCommand(args.tfds_path, args.datasets_directory)
class ConvertCommand(BaseDatasetsCLICommand): @staticmethod def register_subcommand(parser: ArgumentParser): """ Register this command to argparse so it's available for the datasets-cli
Args: parser: Root parser to register command-specific arguments """ train_parser = parser.add_parser( "convert", help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.", ) train_parser.add_argument( "--tfds_path", type=str, required=True, help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.", ) train_parser.add_argument( "--datasets_directory", type=str, required=True, help="Path to the HuggingFace Datasets folder." ) train_parser.set_defaults(func=convert_command_factory)
def __init__(self, tfds_path: str, datasets_directory: str, *args): self._logger = get_logger("datasets-cli/converting")
self._tfds_path = tfds_path self._datasets_directory = datasets_directory
def run(self): if os.path.isdir(self._tfds_path): abs_tfds_path = os.path.abspath(self._tfds_path) elif os.path.isfile(self._tfds_path): abs_tfds_path = os.path.dirname(self._tfds_path) else: raise ValueError("--tfds_path is neither a directory nor a file. Please check path.")
abs_datasets_path = os.path.abspath(self._datasets_directory)
self._logger.info(f"Converting datasets from {abs_tfds_path} to {abs_datasets_path}")
utils_files = [] with_manual_update = [] imports_to_builder_map = {}
if os.path.isdir(self._tfds_path): file_names = os.listdir(abs_tfds_path) else: file_names = [os.path.basename(self._tfds_path)]
for f_name in file_names: self._logger.info(f"Looking at file {f_name}") input_file = os.path.join(abs_tfds_path, f_name) output_file = os.path.join(abs_datasets_path, f_name)
if not os.path.isfile(input_file) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("Skipping file") continue
with open(input_file, encoding="utf-8") as f: lines = f.readlines()
out_lines = [] is_builder = False needs_manual_update = False tfds_imports = [] for line in lines: out_line = line
# Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: out_line = "import datasets\n" elif "import tensorflow" in out_line: # order is important here out_line = "" continue elif "from absl import logging" in out_line: out_line = "from datasets import logging\n" elif "getLogger" in out_line: out_line = out_line.replace("getLogger", "get_logger") elif any(expression in out_line for expression in TO_HIGHLIGHT): needs_manual_update = True to_remove = list(filter(lambda e: e in out_line, TO_HIGHLIGHT)) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(to_remove) + "\n") out_lines.append(out_line) out_lines.append(HIGHLIGHT_MESSAGE_POST) continue else: for pattern, replacement in TO_CONVERT: out_line = re.sub(pattern, replacement, out_line)
# Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: match = re.match(r"from\stensorflow_datasets.*import\s([^\.\r\n]+)", out_line) tfds_imports.extend(imp.strip() for imp in match.group(1).split(",")) out_line = "from . import " + match.group(1)
# Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f"Error converting {out_line.strip()}")
if "GeneratorBasedBuilder" in out_line: is_builder = True out_lines.append(out_line)
if is_builder or "wmt" in f_name: # We create a new directory for each dataset dir_name = f_name.replace(".py", "") output_dir = os.path.join(abs_datasets_path, dir_name) output_file = os.path.join(output_dir, f_name) os.makedirs(output_dir, exist_ok=True) self._logger.info(f"Adding directory {output_dir}") imports_to_builder_map.update(dict.fromkeys(tfds_imports, output_dir)) else: # Utilities will be moved at the end utils_files.append(output_file)
if needs_manual_update: with_manual_update.append(output_file)
with open(output_file, "w", encoding="utf-8") as f: f.writelines(out_lines) self._logger.info(f"Converted in {output_file}")
for utils_file in utils_files: try: f_name = os.path.basename(utils_file) dest_folder = imports_to_builder_map[f_name.replace(".py", "")] self._logger.info(f"Moving {dest_folder} to {utils_file}") shutil.copy(utils_file, dest_folder) except KeyError: self._logger.error(f"Cannot find destination folder for {utils_file}. Please copy manually.")
if with_manual_update: for file_path in with_manual_update: self._logger.warning( f"You need to manually update file {file_path} to remove configurations using 'TextEncoderConfig'." )12345678910111213141516171819202122232425262728293031323334353637383940414243444546from argparse import ArgumentParserfrom typing import Optional
from datasets.commands import BaseDatasetsCLICommandfrom datasets.hub import convert_to_parquet
def _command_factory(args): return ConvertToParquetCommand( args.dataset_id, args.token, args.revision, args.trust_remote_code, )
class ConvertToParquetCommand(BaseDatasetsCLICommand): @staticmethod def register_subcommand(parser): parser: ArgumentParser = parser.add_parser("convert_to_parquet", help="Convert dataset to Parquet") parser.add_argument( "dataset_id", help="source dataset ID, e.g. USERNAME/DATASET_NAME or ORGANIZATION/DATASET_NAME" ) parser.add_argument("--token", help="access token to the Hugging Face Hub (defaults to logged-in user's one)") parser.add_argument("--revision", help="source revision") parser.add_argument( "--trust_remote_code", action="store_true", help="whether to trust the code execution of the load script" ) parser.set_defaults(func=_command_factory)
def __init__( self, dataset_id: str, token: Optional[str], revision: Optional[str], trust_remote_code: bool, ): self._dataset_id = dataset_id self._token = token self._revision = revision self._trust_remote_code = trust_remote_code
def run(self) -> None: _ = convert_to_parquet( self._dataset_id, revision=self._revision, token=self._token, trust_remote_code=self._trust_remote_code )12345678910111213141516171819202122232425262728293031323334353637383940414243#!/usr/bin/env pythonfrom argparse import ArgumentParser
from datasets.commands.convert import ConvertCommandfrom datasets.commands.convert_to_parquet import ConvertToParquetCommandfrom datasets.commands.delete_from_hub import DeleteFromHubCommandfrom datasets.commands.env import EnvironmentCommandfrom datasets.commands.test import TestCommandfrom datasets.utils.logging import set_verbosity_info
def parse_unknown_args(unknown_args): return {key.lstrip("-"): value for key, value in zip(unknown_args[::2], unknown_args[1::2])}
def main(): parser = ArgumentParser( "HuggingFace Datasets CLI tool", usage="datasets-cli <command> [<args>]", allow_abbrev=False ) commands_parser = parser.add_subparsers(help="datasets-cli command helpers") set_verbosity_info()
# Register commands ConvertCommand.register_subcommand(commands_parser) EnvironmentCommand.register_subcommand(commands_parser) TestCommand.register_subcommand(commands_parser) ConvertToParquetCommand.register_subcommand(commands_parser) DeleteFromHubCommand.register_subcommand(commands_parser)
# Parse args args, unknown_args = parser.parse_known_args() if not hasattr(args, "func"): parser.print_help() exit(1) kwargs = parse_unknown_args(unknown_args)
# Run service = args.func(args, **kwargs) service.run()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142from argparse import ArgumentParserfrom typing import Optional
from datasets.commands import BaseDatasetsCLICommandfrom datasets.hub import delete_from_hub
def _command_factory(args): return DeleteFromHubCommand( args.dataset_id, args.config_name, args.token, args.revision, )
class DeleteFromHubCommand(BaseDatasetsCLICommand): @staticmethod def register_subcommand(parser): parser: ArgumentParser = parser.add_parser("delete_from_hub", help="Delete dataset config from the Hub") parser.add_argument( "dataset_id", help="source dataset ID, e.g. USERNAME/DATASET_NAME or ORGANIZATION/DATASET_NAME" ) parser.add_argument("config_name", help="config name to delete") parser.add_argument("--token", help="access token to the Hugging Face Hub") parser.add_argument("--revision", help="source revision") parser.set_defaults(func=_command_factory)
def __init__( self, dataset_id: str, config_name: str, token: Optional[str], revision: Optional[str], ): self._dataset_id = dataset_id self._config_name = config_name self._token = token self._revision = revision
def run(self) -> None: _ = delete_from_hub(self._dataset_id, self._config_name, revision=self._revision, token=self._token)1234567891011121314151617181920212223242526272829303132333435363738394041import platformfrom argparse import ArgumentParser
import fsspecimport huggingface_hubimport pandasimport pyarrow
from datasets import __version__ as versionfrom datasets.commands import BaseDatasetsCLICommand
def info_command_factory(_): return EnvironmentCommand()
class EnvironmentCommand(BaseDatasetsCLICommand): @staticmethod def register_subcommand(parser: ArgumentParser): download_parser = parser.add_parser("env", help="Print relevant system environment info.") download_parser.set_defaults(func=info_command_factory)
def run(self): info = { "`datasets` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "`huggingface_hub` version": huggingface_hub.__version__, "PyArrow version": pyarrow.__version__, "Pandas version": pandas.__version__, "`fsspec` version": fsspec.__version__, }
print("\nCopy-and-paste the text below in your GitHub issue.\n") print(self.format_dict(info))
return info
@staticmethod def format_dict(d): return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import loggingimport osfrom argparse import ArgumentParserfrom collections.abc import Generatorfrom pathlib import Pathfrom shutil import copyfile, rmtreefrom typing import Optional
import datasets.configfrom datasets.builder import DatasetBuilderfrom datasets.commands import BaseDatasetsCLICommandfrom datasets.download.download_manager import DownloadModefrom datasets.load import dataset_module_factory, import_main_classfrom datasets.utils.info_utils import VerificationModefrom datasets.utils.logging import ERROR, get_logger
logger = get_logger(__name__)
def _test_command_factory(args): return TestCommand( args.dataset, args.name, args.cache_dir, args.data_dir, args.all_configs, args.save_info or args.save_infos, args.ignore_verifications, args.force_redownload, args.clear_cache, args.num_proc, args.trust_remote_code, )
class TestCommand(BaseDatasetsCLICommand): __test__ = False # to tell pytest it's not a test class
@staticmethod def register_subcommand(parser: ArgumentParser): test_parser = parser.add_parser("test", help="Test dataset implementation.") test_parser.add_argument("--name", type=str, default=None, help="Dataset processing name") test_parser.add_argument( "--cache_dir", type=str, default=None, help="Cache directory where the datasets are stored.", ) test_parser.add_argument( "--data_dir", type=str, default=None, help="Can be used to specify a manual directory to get the files from.", ) test_parser.add_argument("--all_configs", action="store_true", help="Test all dataset configurations") test_parser.add_argument( "--save_info", action="store_true", help="Save the dataset infos in the dataset card (README.md)" ) test_parser.add_argument( "--ignore_verifications", action="store_true", help="Run the test without checksums and splits checks.", ) test_parser.add_argument("--force_redownload", action="store_true", help="Force dataset redownload") test_parser.add_argument( "--clear_cache", action="store_true", help="Remove downloaded files and cached datasets after each config test", ) test_parser.add_argument("--num_proc", type=int, default=None, help="Number of processes") test_parser.add_argument( "--trust_remote_code", action="store_true", help="whether to trust the code execution of the load script" ) # aliases test_parser.add_argument("--save_infos", action="store_true", help="alias to save_info") test_parser.add_argument("dataset", type=str, help="Name of the dataset to download") test_parser.set_defaults(func=_test_command_factory)
def __init__( self, dataset: str, name: str, cache_dir: str, data_dir: str, all_configs: bool, save_infos: bool, ignore_verifications: bool, force_redownload: bool, clear_cache: bool, num_proc: int, trust_remote_code: Optional[bool], ): self._dataset = dataset self._name = name self._cache_dir = cache_dir self._data_dir = data_dir self._all_configs = all_configs self._save_infos = save_infos self._ignore_verifications = ignore_verifications self._force_redownload = force_redownload self._clear_cache = clear_cache self._num_proc = num_proc self._trust_remote_code = trust_remote_code if clear_cache and not cache_dir: print( "When --clear_cache is used, specifying a cache directory is mandatory.\n" "The 'download' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n" "Please provide a --cache_dir that will be used to test the dataset script." ) exit(1) if save_infos: self._ignore_verifications = True
def run(self): logging.getLogger("filelock").setLevel(ERROR) if self._name is not None and self._all_configs: print("Both parameters `config` and `all_configs` can't be used at once.") exit(1) path, config_name = self._dataset, self._name module = dataset_module_factory(path, trust_remote_code=self._trust_remote_code) builder_cls = import_main_class(module.module_path) n_builders = len(builder_cls.BUILDER_CONFIGS) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1
def get_builders() -> Generator[DatasetBuilder, None, None]: if self._all_configs and builder_cls.BUILDER_CONFIGS: for i, config in enumerate(builder_cls.BUILDER_CONFIGS): if "config_name" in module.builder_kwargs: yield builder_cls( cache_dir=self._cache_dir, data_dir=self._data_dir, **module.builder_kwargs, ) else: yield builder_cls( config_name=config.name, cache_dir=self._cache_dir, data_dir=self._data_dir, **module.builder_kwargs, ) else: if "config_name" in module.builder_kwargs: yield builder_cls(cache_dir=self._cache_dir, data_dir=self._data_dir, **module.builder_kwargs) else: yield builder_cls( config_name=config_name, cache_dir=self._cache_dir, data_dir=self._data_dir, **module.builder_kwargs, )
for j, builder in enumerate(get_builders()): print(f"Testing builder '{builder.config.name}' ({j + 1}/{n_builders})") builder._record_infos = os.path.exists( os.path.join(builder.get_imported_module_dir(), datasets.config.DATASETDICT_INFOS_FILENAME) ) # record checksums only if we need to update a (deprecated) dataset_infos.json builder.download_and_prepare( download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS if not self._force_redownload else DownloadMode.FORCE_REDOWNLOAD, verification_mode=VerificationMode.NO_CHECKS if self._ignore_verifications else VerificationMode.ALL_CHECKS, num_proc=self._num_proc, ) builder.as_dataset() if self._save_infos: builder._save_infos()
# If save_infos=True, the dataset card (README.md) is created next to the loaded module file. # The dataset_infos are saved in the YAML part of the README.md
# Let's move it to the original directory of the dataset script, to allow the user to # upload them on S3 at the same time afterwards. if self._save_infos: dataset_readme_path = os.path.join( builder_cls.get_imported_module_dir(), datasets.config.REPOCARD_FILENAME ) name = Path(path).name + ".py" combined_path = os.path.join(path, name) if os.path.isfile(path): dataset_dir = os.path.dirname(path) elif os.path.isfile(combined_path): dataset_dir = path elif os.path.isdir(path): # for local directories containing only data files dataset_dir = path else: # in case of a remote dataset dataset_dir = None print(f"Dataset card saved at {dataset_readme_path}")
# Move dataset_info back to the user if dataset_dir is not None: user_dataset_readme_path = os.path.join(dataset_dir, datasets.config.REPOCARD_FILENAME) copyfile(dataset_readme_path, user_dataset_readme_path) print(f"Dataset card saved at {user_dataset_readme_path}")
# If clear_cache=True, the download folder and the dataset builder cache directory are deleted if self._clear_cache: if os.path.isdir(builder._cache_dir): logger.warning(f"Clearing cache at {builder._cache_dir}") rmtree(builder._cache_dir) download_dir = os.path.join(self._cache_dir, datasets.config.DOWNLOADED_DATASETS_DIR) if os.path.isdir(download_dir): logger.warning(f"Clearing cache at {download_dir}") rmtree(download_dir)
print("Test successful.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269import importlibimport importlib.metadataimport loggingimport osimport platformfrom pathlib import Pathfrom typing import Optional
from huggingface_hub import constantsfrom packaging import version
logger = logging.getLogger(__name__.split(".", 1)[0]) # to avoid circular import from .utils.logging
# DatasetsS3_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}"
# HubHF_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 booleansENV_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"})
# ImportsDILL_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: passelse: logger.info("Disabling PyTorch because USE_TF is set")
POLARS_VERSION = "N/A"POLARS_AVAILABLE = importlib.util.find_spec("polars") is not None
if POLARS_AVAILABLE: try: POLARS_VERSION = version.parse(importlib.metadata.version("polars")) logger.info(f"Polars version {POLARS_VERSION} available.") except importlib.metadata.PackageNotFoundError: pass
DUCKDB_VERSION = "N/A"DUCKDB_AVAILABLE = importlib.util.find_spec("duckdb") is not None
if DUCKDB_AVAILABLE: try: DUCKDB_VERSION = version.parse(importlib.metadata.version("duckdb")) logger.info(f"Duckdb version {DUCKDB_VERSION} available.") except importlib.metadata.PackageNotFoundError: pass
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: passelse: logger.info("Disabling JAX because USE_JAX is set to False")
# Optional tools for data loadingSQLALCHEMY_AVAILABLE = importlib.util.find_spec("sqlalchemy") is not None
# Optional tools for feature decodingPIL_AVAILABLE = importlib.util.find_spec("PIL") is not NoneIS_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")TORCHVISION_AVAILABLE = importlib.util.find_spec("torchvision") is not NonePDFPLUMBER_AVAILABLE = importlib.util.find_spec("pdfplumber") is not None
# Optional compression toolsRARFILE_AVAILABLE = importlib.util.find_spec("rarfile") is not NoneZSTANDARD_AVAILABLE = importlib.util.find_spec("zstandard") is not NoneLZ4_AVAILABLE = importlib.util.find_spec("lz4") is not NonePY7ZR_AVAILABLE = importlib.util.find_spec("py7zr") is not None
# Cache locationDEFAULT_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_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 websiteHF_UPDATE_DOWNLOAD_COUNTS = ( os.environ.get("HF_UPDATE_DOWNLOAD_COUNTS", "AUTO").upper() in ENV_VARS_TRUE_AND_AUTO_VALUES)
# For downloads and to check remote files metadataHF_DATASETS_MULTITHREADING_MAX_WORKERS = 16
# Remote dataset scripts support__HF_DATASETS_TRUST_REMOTE_CODE = os.environ.get("HF_DATASETS_TRUST_REMOTE_CODE", "ask")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
# Dataset viewer APIUSE_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 configurationPARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS = 100PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS = 100PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS = 100PARQUET_ROW_GROUP_SIZE_FOR_VIDEO_DATASETS = 10
# Offline mode_offline = os.environ.get("HF_DATASETS_OFFLINE")HF_HUB_OFFLINE = constants.HF_HUB_OFFLINE if _offline is None else _offline.upper() in ENV_VARS_TRUE_VALUESHF_DATASETS_OFFLINE = HF_HUB_OFFLINE # kept for backward-compatibility
# 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-memoryDEFAULT_IN_MEMORY_MAX_SIZE = 0 # DisabledIN_MEMORY_MAX_SIZE = float(os.environ.get("HF_DATASETS_IN_MEMORY_MAX_SIZE", DEFAULT_IN_MEMORY_MAX_SIZE))
# File namesDATASET_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"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 prefixTEMP_CACHE_DIR_PREFIX = "hf_datasets-"
# StreamingSTREAMING_READ_MAX_RETRIES = 20STREAMING_READ_RETRY_INTERVAL = 5
# Datasets without scriptDATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE = 200GLOBBED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE = 10ARCHIVED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE = 200
# Async map functionsMAX_NUM_RUNNING_ASYNC_MAP_FUNCTIONS_IN_PARALLEL = 1000
# Progress barsPBAR_REFRESH_TIME_INTERVAL = 0.05 # 20 progress updates per sec
# Maximum number of uploaded files per commitUPLOADS_MAX_NUMBER_PER_COMMIT = 50
# Backward compatibilityMAX_TABLE_NBYTES_FOR_PICKLING = 4 << 30123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795import osimport refrom functools import partialfrom glob import has_magicfrom pathlib import Path, PurePathfrom typing import Callable, Optional, Union
import huggingface_hubfrom fsspec.core import url_to_fsfrom huggingface_hub import HfFileSystemfrom packaging import versionfrom tqdm.contrib.concurrent import thread_map
from . import configfrom .download import DownloadConfigfrom .naming import _split_refrom .splits import Splitfrom .utils import loggingfrom .utils import tqdm as hf_tqdmfrom .utils.file_utils import _prepare_path_and_storage_options, is_local_path, is_relative_path, xbasename, xjoinfrom .utils.py_utils import glob_pattern_to_regex, string_to_dict
SingleOriginMetadata = Union[tuple[str, str], tuple[str], tuple[()]]
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_FILENAME_BASE_PATTERNS = ["**[{sep}/]{keyword}[{sep}]*", "{keyword}[{sep}]*"] KEYWORDS_IN_DIR_NAME_BASE_PATTERNS = [ "{keyword}/**", "{keyword}[{sep}]*/**", "**[{sep}/]{keyword}/**", "**[{sep}/]{keyword}[{sep}]*/**", ]elif config.FSSPEC_VERSION < version.parse("2023.12.0"): KEYWORDS_IN_FILENAME_BASE_PATTERNS = ["**/*[{sep}/]{keyword}[{sep}]*", "{keyword}[{sep}]*"] KEYWORDS_IN_DIR_NAME_BASE_PATTERNS = [ "{keyword}/**/*", "{keyword}[{sep}]*/**/*", "**/*[{sep}/]{keyword}/**/*", "**/*[{sep}/]{keyword}[{sep}]*/**/*", ]else: KEYWORDS_IN_FILENAME_BASE_PATTERNS = ["**/{keyword}[{sep}]*", "**/*[{sep}]{keyword}[{sep}]*"] KEYWORDS_IN_DIR_NAME_BASE_PATTERNS = [ "**/{keyword}/**", "**/{keyword}[{sep}]*/**", "**/*[{sep}]{keyword}/**", "**/*[{sep}]{keyword}[{sep}]*/**", ]
DEFAULT_SPLITS = [Split.TRAIN, Split.VALIDATION, Split.TEST]DEFAULT_PATTERNS_SPLIT_IN_FILENAME = { split: [ pattern.format(keyword=keyword, sep=NON_WORDS_CHARS) for keyword in SPLIT_KEYWORDS[split] for pattern in KEYWORDS_IN_FILENAME_BASE_PATTERNS ] for split in DEFAULT_SPLITS}DEFAULT_PATTERNS_SPLIT_IN_DIR_NAME = { split: [ pattern.format(keyword=keyword, sep=NON_WORDS_CHARS) for keyword in SPLIT_KEYWORDS[split] for pattern in KEYWORDS_IN_DIR_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_DIR_NAME, DEFAULT_PATTERNS_SPLIT_IN_FILENAME, DEFAULT_PATTERNS_ALL,]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(wildcard_character in pattern for wildcard_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 additionally 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 explicitly 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 additionally 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 explicitly 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] = set() for p in data_files: p_parts = string_to_dict(xbasename(p), glob_pattern_to_regex(xbasename(split_pattern))) assert p_parts is not None splits.add(p_parts["split"])
if any(not re.match(_split_re, split) for split in splits): raise ValueError(f"Split name should match '{_split_re}'' but got '{splits}'.") sorted_splits = [str(split) for split in DEFAULT_SPLITS if split in splits] + sorted( splits - {str(split) for split in 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 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. In fsspec>=2023.12.0 this is equivalent to Python's glob.glob, Path.glob, Path.match and fnmatch where ** is unsupported with a prefix/suffix other than a forward slash /.
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 explicitly 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"] download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. 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, fs_pattern = url_to_fs(pattern, **storage_options) 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" or (info.get("islink") and os.path.isfile(os.path.realpath(filepath)))) and (xbasename(filepath) not in files_to_ignore) and not _is_inside_unrequested_special_dir(filepath, fs_pattern) and not _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(filepath, fs_pattern) ] # 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/**', '**/train[-._ 0-9]*/**', '**/*[-._ 0-9]train/**', '**/*[-._ 0-9]train[-._ 0-9]*/**', ...], 'test': ['**/test/**', '**/test[-._ 0-9]*/**', '**/*[-._ 0-9]test/**', '**/*[-._ 0-9]test[-._ 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_single_origin_metadata( data_file: str, download_config: Optional[DownloadConfig] = None,) -> SingleOriginMetadata: data_file, storage_options = _prepare_path_and_storage_options(data_file, download_config=download_config) fs, *_ = url_to_fs(data_file, **storage_options) if isinstance(fs, HfFileSystem): resolved_path = fs.resolve_path(data_file) return resolved_path.repo_id, resolved_path.revision elif 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], download_config: Optional[DownloadConfig] = None, max_workers: Optional[int] = None,) -> list[SingleOriginMetadata]: max_workers = max_workers if max_workers is not None else config.HF_DATASETS_MULTITHREADING_MAX_WORKERS 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", # set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached disable=len(data_files) <= 16 or None, )
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[SingleOriginMetadata]) -> None: super().__init__(data_files) self.origin_metadata = origin_metadata
def __add__(self, other: "DataFilesList") -> "DataFilesList": 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( self, *, extensions: Optional[list[str]] = None, file_names: Optional[list[str]] = None ) -> "DataFilesList": patterns = [] if extensions: ext_pattern = "|".join(re.escape(ext) for ext in extensions) patterns.append(re.compile(f".*({ext_pattern})(\\..+)?$")) if file_names: fn_pattern = "|".join(re.escape(fn) for fn in file_names) patterns.append(re.compile(rf".*[\/]?({fn_pattern})$")) if patterns: return DataFilesList( [data_file for data_file in self if any(pattern.match(data_file) for pattern in patterns)], origin_metadata=self.origin_metadata, ) else: return DataFilesList(list(self), 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] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesList) else DataFilesList.from_local_or_remote( patterns_for_key, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) 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] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesList) else DataFilesList.from_hf_repo( patterns_for_key, dataset_info=dataset_info, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) 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] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesList) else DataFilesList.from_patterns( patterns_for_key, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) return out
def filter( self, *, extensions: Optional[list[str]] = None, file_names: Optional[list[str]] = None ) -> "DataFilesDict": out = type(self)() for key, data_files_list in self.items(): out[key] = data_files_list.filter(extensions=extensions, file_names=file_names) 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 ) -> "DataFilesPatternsList": 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]) -> "DataFilesPatternsList": 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] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesPatternsList) else DataFilesPatternsList.from_patterns( patterns_for_key, allowed_extensions=allowed_extensions, ) ) 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 out123456789101112131415161718192021222324252627282930313233343536373839from typing import TypeVar
from .arrow_dataset import Dataset, _split_by_node_map_style_datasetfrom .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.num_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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119# SPDX-License-Identifier: Apache-2.0# Copyright 2023 The HuggingFace Authors.from typing import Any, Optional, Union
from huggingface_hub import HfFileSystem
from . import configfrom .table import CastErrorfrom .utils.track import TrackedIterableFromGenerator, 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, TrackedIterableFromGenerator)): continue while ( isinstance(gen_kwarg, (tracked_list, TrackedIterableFromGenerator)) 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)
class ChecksumVerificationError(DatasetsError): """Error raised during checksums verifications of downloaded files."""
class UnexpectedDownloadedFileError(ChecksumVerificationError): """Some downloaded files were not expected."""
class ExpectedMoreDownloadedFilesError(ChecksumVerificationError): """Some files were supposed to be downloaded but were not."""
class NonMatchingChecksumError(ChecksumVerificationError): """The downloaded file checksum don't match the expected checksum."""
class SplitsVerificationError(DatasetsError): """Error raised during splits verifications."""
class UnexpectedSplitsError(SplitsVerificationError): """The expected splits of the downloaded file is missing."""
class ExpectedMoreSplitsError(SplitsVerificationError): """Some recorded splits are missing."""
class NonMatchingSplitsSizesError(SplitsVerificationError): """The splits sizes don't match the expected splits sizes."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454import inspectimport osimport randomimport shutilimport tempfileimport weakreffrom functools import wrapsfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Optional, Union
import numpy as npimport xxhash
from . import configfrom .naming import INVALID_WINDOWS_CHARACTERS_IN_PATHfrom .utils._dill import dumpsfrom .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
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#################
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 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#################
fingerprint_rng = random.Random()# we show a warning only once when fingerprinting fails to avoid spamfingerprint_warnings: dict[str, bool] = {}
def generate_fingerprint(dataset: "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: int = 64) -> str: return f"{fingerprint_rng.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 _fingerprint123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230import timefrom itertools import chainfrom typing import Optional, Union
from huggingface_hub import ( CommitInfo, CommitOperationAdd, CommitOperationDelete, DatasetCard, DatasetCardData, HfApi, HfFileSystem,)from huggingface_hub.utils import HfHubHTTPError
import datasets.configfrom datasets.info import DatasetInfosDictfrom datasets.inspect import get_dataset_config_names, get_dataset_default_config_namefrom datasets.load import load_dataset, load_dataset_builderfrom datasets.utils.metadata import MetadataConfigs
def convert_to_parquet( repo_id: str, revision: Optional[str] = None, token: Optional[Union[bool, str]] = None, trust_remote_code: Optional[bool] = None,) -> CommitInfo: """Convert Hub [script-based dataset](dataset_script) to Parquet [data-only dataset](repository_structure), so that the dataset viewer will be supported.
This function: - makes a copy of the script on the "main" branch into a dedicated branch called "script" (if it does not already exist) - creates a pull request to the Hub dataset to convert it to Parquet files (and deletes the script from the main branch)
If in the future you need to recreate the Parquet files from the "script" branch, pass the `revision="script"` argument.
Note that you should pass the `trust_remote_code=True` argument only if you trust the remote code to be executed locally on your machine.
Args: repo_id (`str`): ID of the source Hub dataset repository, in the following format: `<user>/<dataset_name>` or `<org>/<dataset_name>`. revision (`str`, *optional*): Branch of the source Hub dataset repository. Defaults to the `"main"` branch. token (`bool` or `str`, *optional*): Authentication token for the Hugging Face Hub. trust_remote_code (`bool`, defaults to `False`): Whether you trust the remote code of the Hub script-based dataset to be executed locally on your machine. This option should only be set to `True` for repositories where you have read the code and which you trust.
<Changed version="2.20.0">
`trust_remote_code` defaults to `False` if not specified.
</Changed>
Returns: `huggingface_hub.CommitInfo` """ print(f"{repo_id}") configs = get_dataset_config_names(repo_id, token=token, revision=revision, trust_remote_code=trust_remote_code) print(f"{configs = }") default_config = get_dataset_default_config_name( repo_id, token=token, revision=revision, trust_remote_code=trust_remote_code ) print(f"{default_config = }") if default_config: config = default_config configs.remove(default_config) else: config = configs.pop(0) print(f"{config = }") dataset = load_dataset(repo_id, config, revision=revision, trust_remote_code=trust_remote_code) commit_info = dataset.push_to_hub( repo_id, config_name=config, commit_message="Convert dataset to Parquet", commit_description="Convert dataset to Parquet.", create_pr=True, token=token, set_default=default_config is not None, ) time.sleep(5) pr_revision, pr_url = commit_info.pr_revision, commit_info.pr_url for config in configs: print(f"{config = }") dataset = load_dataset(repo_id, config, revision=revision, trust_remote_code=trust_remote_code) dataset.push_to_hub( repo_id, config_name=config, commit_message=f"Add '{config}' config data files", revision=pr_revision, token=token, ) time.sleep(5) _delete_files(repo_id, revision=pr_revision, token=token) if not revision: api = HfApi(endpoint=datasets.config.HF_ENDPOINT, token=token) try: api.create_branch(repo_id, branch="script", repo_type="dataset", token=token, exist_ok=True) except HfHubHTTPError: pass print(f"You can find your PR to convert the dataset to Parquet at: {pr_url}") return commit_info
def delete_from_hub( repo_id: str, config_name: str, revision: Optional[str] = None, token: Optional[Union[bool, str]] = None,) -> CommitInfo: """Delete a dataset configuration from a [data-only dataset](repository_structure) on the Hub.
Args: repo_id (`str`): ID of the Hub dataset repository, in the following format: `<user>/<dataset_name>` or `<org>/<dataset_name>`. config_name (`str`): Name of the dataset configuration. revision (`str`, *optional*): Branch to delete the configuration from. Defaults to the `"main"` branch. token (`bool` or `str`, *optional*): Authentication token for the Hugging Face Hub.
Returns: `huggingface_hub.CommitInfo` """ operations = [] # data_files fs = HfFileSystem(endpoint=datasets.config.HF_ENDPOINT, token=token) builder = load_dataset_builder(repo_id, config_name, revision=revision, token=token, trust_remote_code=False) for data_file in chain(*builder.config.data_files.values()): data_file_resolved_path = fs.resolve_path(data_file) if data_file_resolved_path.repo_id == repo_id: operations.append(CommitOperationDelete(path_in_repo=data_file_resolved_path.path_in_repo)) # README.md dataset_card = DatasetCard.load(repo_id) # config_names if dataset_card.data.get("config_names", None) and config_name in dataset_card.data["config_names"]: dataset_card.data["config_names"].remove(config_name) # metadata_configs metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card.data) if metadata_configs: _ = metadata_configs.pop(config_name, None) dataset_card_data = DatasetCardData() metadata_configs.to_dataset_card_data(dataset_card_data) if datasets.config.METADATA_CONFIGS_FIELD in dataset_card_data: dataset_card.data[datasets.config.METADATA_CONFIGS_FIELD] = dataset_card_data[ datasets.config.METADATA_CONFIGS_FIELD ] else: _ = dataset_card.data.pop(datasets.config.METADATA_CONFIGS_FIELD, None) # dataset_info dataset_infos: DatasetInfosDict = DatasetInfosDict.from_dataset_card_data(dataset_card.data) if dataset_infos: _ = dataset_infos.pop(config_name, None) dataset_card_data = DatasetCardData() dataset_infos.to_dataset_card_data(dataset_card_data) if "dataset_info" in dataset_card_data: dataset_card.data["dataset_info"] = dataset_card_data["dataset_info"] else: _ = dataset_card.data.pop("dataset_info", None) # Commit operations.append( CommitOperationAdd(path_in_repo=datasets.config.REPOCARD_FILENAME, path_or_fileobj=str(dataset_card).encode()) ) api = HfApi(endpoint=datasets.config.HF_ENDPOINT, token=token) commit_info = api.create_commit( repo_id, operations=operations, commit_message=f"Delete '{config_name}' config", commit_description=f"Delete '{config_name}' config.", token=token, repo_type="dataset", revision=revision, create_pr=True, ) print(f"You can find your PR to delete the dataset config at: {commit_info.pr_url}") return commit_info
def _delete_files(dataset_id, revision=None, token=None): dataset_name = dataset_id.split("/")[-1] hf_api = HfApi(endpoint=datasets.config.HF_ENDPOINT, token=token) repo_files = hf_api.list_repo_files( dataset_id, repo_type="dataset", ) if repo_files: legacy_json_file = [] python_files = [] data_files = [] for filename in repo_files: if filename in {".gitattributes", "README.md"}: continue elif filename == f"{dataset_name}.py": hf_api.delete_file( filename, dataset_id, repo_type="dataset", revision=revision, commit_message="Delete loading script", ) elif filename == "dataset_infos.json": legacy_json_file.append(filename) elif filename.endswith(".py"): python_files.append(filename) else: data_files.append(filename) if legacy_json_file: hf_api.delete_file( "dataset_infos.json", dataset_id, repo_type="dataset", revision=revision, commit_message="Delete legacy dataset_infos.json", ) if python_files: for filename in python_files: hf_api.delete_file( filename, dataset_id, repo_type="dataset", revision=revision, commit_message="Delete loading script auxiliary file", ) if data_files: for filename in data_files: hf_api.delete_file( filename, dataset_id, repo_type="dataset", revision=revision, commit_message="Delete data file", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430# 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 record information we know about a dataset.
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'veprocessed the dataset as well: - number of examples (in each split) - etc."""
import copyimport dataclassesimport jsonimport osimport posixpathfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import ClassVar, Optional, Union
import fsspecfrom fsspec.core import url_to_fsfrom huggingface_hub import DatasetCard, DatasetCardData
from . import configfrom .features import Featuresfrom .splits import SplitDictfrom .utils import Versionfrom .utils.logging import get_loggerfrom .utils.py_utils import asdict, unique_values
logger = get_logger(__name__)
@dataclassclass SupervisedKeysData: input: str = "" output: str = ""
@dataclassclass 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."""
@dataclassclass 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})
@dataclassclass 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). **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
# 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)
def write_to_directory(self, dataset_info_dir, pretty_print=False, 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. 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("cornell-movie-review-data/rotten_tomatoes", split="validation") >>> ds.info.write_to_directory("/path/to/directory/") ``` """ fs: fsspec.AbstractFileSystem fs, *_ = url_to_fs(dataset_info_dir, **(storage_options or {})) 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]
if len(dataset_infos) > 0 and all(dataset_infos[0] == dset_info for dset_info in dataset_infos): # if all dataset_infos are equal we don't need to merge. Just return the first. return dataset_infos[0]
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
return cls( description=description, citation=citation, homepage=homepage, license=license, features=features, supervised_keys=supervised_keys, )
@classmethod def from_directory(cls, dataset_info_dir: str, 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. 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/") ``` """ fs: fsspec.AbstractFileSystem fs, *_ = url_to_fs(dataset_info_dir, **(storage_options or {})) 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363# 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 osfrom collections.abc import Mapping, Sequencefrom typing import Optional, Union
from .download.download_config import DownloadConfigfrom .download.download_manager import DownloadModefrom .download.streaming_download_manager import StreamingDownloadManagerfrom .info import DatasetInfofrom .load import ( dataset_module_factory, get_dataset_builder_class, load_dataset_builder,)from .utils.logging import get_loggerfrom .utils.version import Version
logger = get_logger(__name__)
class SplitsNotFoundError(ValueError): pass
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, **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 [`huggingface_hub.list_datasets`]), e.g. `'rajpurkar/squad'`, `'nyu-mll/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"`. **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('cornell-movie-review-data/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...), ...} ``` """ 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 [`huggingface_hub.list_datasets`]), e.g. `'rajpurkar/squad'`, `'nyu-mll/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 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("nyu-mll/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. Can return None only if the dataset has multiple configurations and no default configuration.
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 [`huggingface_hub.list_datasets`]), e.g. `'rajpurkar/squad'`, `'nyu-mll/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 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]: the default config name if there is one
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, **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 [`huggingface_hub.list_datasets`]), e.g. ``'rajpurkar/squad'``, ``'nyu-mll/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"`. **config_kwargs (additional keyword arguments): optional attributes for builder class which will override the attributes if supplied.
""" 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, **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 [`huggingface_hub.list_datasets`]), e.g. `'rajpurkar/squad'`, `'nyu-mll/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"`. **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('cornell-movie-review-data/rotten_tomatoes') ['train', 'validation', 'test'] ``` """ 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())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# 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 hashesin 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, bytearray]) -> 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, bytearray)): # 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# 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 itertoolsimport osimport 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]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import inspectimport refrom typing import Dict, List, Tuple
from huggingface_hub.utils import insecure_hashlib
from .arrow import arrowfrom .audiofolder import audiofolderfrom .cache import cachefrom .csv import csvfrom .imagefolder import imagefolderfrom .json import jsonfrom .pandas import pandasfrom .parquet import parquetfrom .pdffolder import pdffolderfrom .sql import sqlfrom .text import textfrom .videofolder import videofolderfrom .webdataset import webdatasetfrom .xml import xml
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())), "videofolder": (videofolder.__name__, _hash_python_lines(inspect.getsource(videofolder).splitlines())), "pdffolder": (pdffolder.__name__, _hash_python_lines(inspect.getsource(pdffolder).splitlines())), "webdataset": (webdataset.__name__, _hash_python_lines(inspect.getsource(webdataset).splitlines())), "xml": (xml.__name__, _hash_python_lines(inspect.getsource(xml).splitlines())),}
# get importable module names and hash for caching_PACKAGED_DATASETS_MODULES_2_15_HASHES = { "csv": "eea64c71ca8b46dd3f537ed218fc9bf495d5707789152eb2764f5c78fa66d59d", "json": "8bb11242116d547c741b2e8a1f18598ffdd40a1d4f2a2872c7a28b697434bc96", "pandas": "3ac4ffc4563c796122ef66899b9485a3f1a977553e2d2a8a318c72b8cc6f2202", "parquet": "ca31c69184d9832faed373922c2acccec0b13a0bb5bbbe19371385c3ff26f1d1", "arrow": "74f69db2c14c2860059d39860b1f400a03d11bf7fb5a8258ca38c501c878c137", "text": "c4a140d10f020282918b5dd1b8a49f0104729c6177f60a6b49ec2a365ec69f34", "imagefolder": "7b7ce5247a942be131d49ad4f3de5866083399a0f250901bd8dc202f8c5f7ce5", "audiofolder": "d3c1655c66c8f72e4efb5c79e952975fa6e2ce538473a6890241ddbddee9071c",}
# 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", {}), # ndjson is no longer maintained (see: https://github.com/ndjson/ndjson-spec/issues/35#issuecomment-1285673417) ".ndjson": ("json", {}), ".parquet": ("parquet", {}), ".geoparquet": ("parquet", {}), ".gpq": ("parquet", {}), ".arrow": ("arrow", {}), ".txt": ("text", {}), ".tar": ("webdataset", {}), ".xml": ("xml", {}),}_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})_EXTENSION_TO_MODULE.update({ext: ("videofolder", {}) for ext in videofolder.VideoFolder.EXTENSIONS})_EXTENSION_TO_MODULE.update({ext.upper(): ("videofolder", {}) for ext in videofolder.VideoFolder.EXTENSIONS})_EXTENSION_TO_MODULE.update({ext: ("pdffolder", {}) for ext in pdffolder.PdfFolder.EXTENSIONS})_EXTENSION_TO_MODULE.update({ext.upper(): ("pdffolder", {}) for ext in pdffolder.PdfFolder.EXTENSIONS})
# 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")
# Used to filter data files based on file names_MODULE_TO_METADATA_FILE_NAMES: Dict[str, List[str]] = {}for _module in _MODULE_TO_EXTENSIONS: _MODULE_TO_METADATA_FILE_NAMES[_module] = []_MODULE_TO_METADATA_FILE_NAMES["imagefolder"] = imagefolder.ImageFolder.METADATA_FILENAMES_MODULE_TO_METADATA_FILE_NAMES["audiofolder"] = imagefolder.ImageFolder.METADATA_FILENAMES_MODULE_TO_METADATA_FILE_NAMES["videofolder"] = imagefolder.ImageFolder.METADATA_FILENAMES_MODULE_TO_METADATA_FILE_NAMES["pdffolder"] = imagefolder.ImageFolder.METADATA_FILENAMES123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198import itertoolsfrom dataclasses import dataclassfrom typing import Any, Callable, Optional, Union
import pandas as pdimport pyarrow as pa
import datasetsimport datasets.configfrom datasets.features.features import require_storage_castfrom datasets.table import table_castfrom 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"]_PANDAS_READ_CSV_DEPRECATED_2_2_0_PARAMETERS = ["verbose"]
@dataclassclass 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): super().__post_init__() 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 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]
# 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 2.2 deprecated arguments if datasets.config.PANDAS_VERSION.release >= (2, 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_DEPRECATED_2_2_0_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]
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}") dl_manager.download_config.extract_on_the_fly = True data_files = dl_manager.download_and_extract(self.config.data_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}") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417import collectionsimport ioimport itertoolsimport osfrom dataclasses import dataclassfrom typing import Any, Callable, Iterator, Optional, Union
import pandas as pdimport pyarrow as paimport pyarrow.dataset as dsimport pyarrow.json as pajimport pyarrow.parquet as pq
import datasetsfrom datasets import configfrom datasets.features.features import FeatureType, _visit, _visit_with_path, _VisitPath, require_storage_castfrom datasets.utils.file_utils import readline
logger = datasets.utils.logging.get_logger(__name__)
def count_path_segments(path): return path.replace("\\", "/").count("/")
@dataclassclass FolderBasedBuilderConfig(datasets.BuilderConfig): """BuilderConfig for AutoFolder."""
features: Optional[datasets.Features] = None drop_labels: bool = None drop_metadata: bool = None filters: Optional[Union[ds.Expression, list[tuple], list[list[tuple]]]] = None
def __post_init__(self): super().__post_init__()
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) """
BASE_FEATURE: type[FeatureType] BASE_COLUMN_NAME: str BUILDER_CONFIG_CLASS: FolderBasedBuilderConfig EXTENSIONS: list[str]
METADATA_FILENAMES: list[str] = ["metadata.csv", "metadata.jsonl", "metadata.parquet"]
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}") dl_manager.download_config.extract_on_the_fly = True # 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 a {self.BASE_COLUMN_NAME}, 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 a {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, don't add labels add_labels = 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": tuple(zip(files, downloaded_files)) + tuple((None, dl_manager.iter_files(downloaded_dir)) for downloaded_dir in downloaded_dirs), "metadata_files": metadata_files.get(split_name, []), "add_labels": add_labels, "add_metadata": add_metadata, }, ) )
if add_metadata: # Verify that: # * all metadata files have the same set of features in each split # * 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 or downloaded_metadata_file)[-1] for original_metadata_file, downloaded_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 split_metadata_files in metadata_files.values(): pa_metadata_table = None for _, downloaded_metadata_file in split_metadata_files: for pa_metadata_table in self._read_metadata(downloaded_metadata_file, metadata_ext=metadata_ext): break # just fetch the first rows if pa_metadata_table is not None: features_per_metadata_file.append( (downloaded_metadata_file, datasets.Features.from_arrow_schema(pa_metadata_table.schema)) ) break # no need to fetch all the files 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] feature_not_found = True
def _set_feature(feature): nonlocal feature_not_found if isinstance(feature, dict): out = type(feature)() for key in feature: if (key == "file_name" or key.endswith("_file_name")) and feature[key] == datasets.Value( "string" ): key = key[: -len("_file_name")] or self.BASE_COLUMN_NAME out[key] = self.BASE_FEATURE() feature_not_found = False elif (key == "file_names" or key.endswith("_file_names")) and feature[ key ] == datasets.Sequence(datasets.Value("string")): key = key[: -len("_file_names")] or (self.BASE_COLUMN_NAME + "s") out[key] = datasets.Sequence(self.BASE_FEATURE()) feature_not_found = False elif (key == "file_names" or key.endswith("_file_names")) and feature[key] == [ datasets.Value("string") ]: key = key[: -len("_file_names")] or (self.BASE_COLUMN_NAME + "s") out[key] = [self.BASE_FEATURE()] feature_not_found = False else: out[key] = feature[key] return out return feature
metadata_features = _visit(metadata_features, _set_feature)
if feature_not_found: raise ValueError( "`file_name` or `*_file_name` must be present as dictionary key (with type string) in metadata files" ) 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_metadata: self.info.features = metadata_features elif add_labels: self.info.features = datasets.Features( { self.BASE_COLUMN_NAME: self.BASE_FEATURE(), "label": datasets.ClassLabel(names=sorted(labels)), } ) else: self.info.features = datasets.Features({self.BASE_COLUMN_NAME: self.BASE_FEATURE()})
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: str, metadata_ext: str = "") -> Iterator[pa.Table]: """using the same logic as the Csv, Json and Parquet dataset builders to stream the data""" if self.config.filters is not None: filter_expr = ( pq.filters_to_expression(self.config.filters) if isinstance(self.config.filters, list) else self.config.filters ) else: filter_expr = None if metadata_ext == ".csv": chunksize = 10_000 # 10k lines 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 ) csv_file_reader = pd.read_csv(metadata_file, iterator=True, dtype=dtype, chunksize=chunksize) for df in csv_file_reader: pa_table = pa.Table.from_pandas(df) if self.config.filters is not None: pa_table = pa_table.filter(filter_expr) if len(pa_table) > 0: yield pa_table elif metadata_ext == ".jsonl": with open(metadata_file, "rb") as f: chunksize: int = 10 << 20 # 10MB # 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(chunksize // 32, 16 << 10) while True: batch = f.read(chunksize) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(f) 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 if self.config.filters is not None: pa_table = pa_table.filter(filter_expr) if len(pa_table) > 0: yield pa_table else: with open(metadata_file, "rb") as f: parquet_fragment = ds.ParquetFileFormat().make_fragment(f) if parquet_fragment.row_groups: batch_size = parquet_fragment.row_groups[0].num_rows else: batch_size = config.DEFAULT_MAX_BATCH_SIZE for record_batch in parquet_fragment.to_batches( batch_size=batch_size, filter=filter_expr, batch_readahead=0, fragment_readahead=0, ): yield pa.Table.from_batches([record_batch])
def _generate_examples(self, files, metadata_files, add_metadata, add_labels): sample_idx = 0 if add_metadata: feature_paths = []
def find_feature_path(feature, feature_path): nonlocal feature_paths if feature_path and isinstance(feature, self.BASE_FEATURE): feature_paths.append(feature_path)
_visit_with_path(self.info.features, find_feature_path)
for original_metadata_file, downloaded_metadata_file in metadata_files: metadata_ext = os.path.splitext(original_metadata_file or downloaded_metadata_file)[-1] downloaded_metadata_dir = os.path.dirname(downloaded_metadata_file)
def set_feature(item, feature_path: _VisitPath): if len(feature_path) == 2 and isinstance(feature_path[0], str) and feature_path[1] == 0: item[feature_path[0]] = item.pop("file_names", None) or item.pop( feature_path[0] + "_file_names", None ) elif len(feature_path) == 1 and isinstance(feature_path[0], str): item[feature_path[0]] = item.pop("file_name", None) or item.pop( feature_path[0] + "_file_name", None ) elif len(feature_path) == 0: file_relpath = os.path.normpath(item).replace("\\", "/") item = os.path.join(downloaded_metadata_dir, file_relpath) return item
for pa_metadata_table in self._read_metadata(downloaded_metadata_file, metadata_ext=metadata_ext): for sample in pa_metadata_table.to_pylist(): for feature_path in feature_paths: _nested_apply(sample, feature_path, set_feature) yield sample_idx, sample sample_idx += 1 else: if self.config.filters is not None: filter_expr = ( pq.filters_to_expression(self.config.filters) if isinstance(self.config.filters, list) else self.config.filters ) for original_file, downloaded_file_or_dir in files: downloaded_files = [downloaded_file_or_dir] if original_file else downloaded_file_or_dir for downloaded_file in downloaded_files: original_file_ext = os.path.splitext(original_file or downloaded_file)[-1] if original_file_ext.lower() not in self.EXTENSIONS: continue sample = {self.BASE_COLUMN_NAME: downloaded_file} if add_labels: sample["label"] = os.path.basename(os.path.dirname(original_file or downloaded_file)) if self.config.filters is not None: pa_table = pa.Table.from_pylist([sample]).filter(filter_expr) if len(pa_table) == 0: continue yield sample_idx, sample sample_idx += 1
def _nested_apply(item: Any, feature_path: _VisitPath, func: Callable[[Any, _VisitPath], Any]): # see _visit_with_path() to see how feature paths are constructed item = func(item, feature_path) if feature_path: key = feature_path[0] if key == 0: for i in range(len(item)): item[i] = _nested_apply(item[i], feature_path[1:], func) else: item[key] = _nested_apply(item[key], feature_path[1:], func) return item123456789101112131415161718192021222324252627282930313233from dataclasses import dataclassfrom typing import Callable, Optional
import datasets
@dataclassclass GeneratorConfig(datasets.BuilderConfig): generator: Optional[Callable] = None gen_kwargs: Optional[dict] = None features: Optional[datasets.Features] = None split: datasets.NamedSplit = datasets.Split.TRAIN
def __post_init__(self): super().__post_init__() if self.generator is None: raise ValueError("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=self.config.split, gen_kwargs=self.config.gen_kwargs)]
def _generate_examples(self, **gen_kwargs): yield from enumerate(self.config.generator(**gen_kwargs))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import datasets
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
def __post_init__(self): super().__post_init__()
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
# 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 deterministicIMAGE_EXTENSIONS = [ ".blp", ".bmp", ".dib", ".bufr", ".cur", ".pcx", ".dcx", ".dds", ".ps", ".eps", ".fit", ".fits", ".fli", ".flc", ".ftc", ".ftu", ".gbr", ".gif", ".grib", # ".h5", # may contain zero or several images # ".hdf", # may contain zero or several images ".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_EXTENSIONSlib/python3.12/site-packages/datasets/__init__.pyAdded+47
lib/python3.12/site-packages/datasets/arrow_dataset.pyAdded
lib/python3.12/site-packages/datasets/arrow_reader.pyAdded+620
lib/python3.12/site-packages/datasets/arrow_writer.pyAdded+677
lib/python3.12/site-packages/datasets/builder.pyAdded+1903
lib/python3.12/site-packages/datasets/combine.pyAdded+215
lib/python3.12/site-packages/datasets/commands/__init__.pyAdded+13
lib/python3.12/site-packages/datasets/commands/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/__pycache__/convert.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/__pycache__/convert_to_parquet.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/__pycache__/datasets_cli.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/__pycache__/delete_from_hub.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/__pycache__/env.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/__pycache__/test.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/commands/convert.pyAdded+195
lib/python3.12/site-packages/datasets/commands/convert_to_parquet.pyAdded+46
lib/python3.12/site-packages/datasets/commands/datasets_cli.pyAdded+43
lib/python3.12/site-packages/datasets/commands/delete_from_hub.pyAdded+42
lib/python3.12/site-packages/datasets/commands/env.pyAdded+41
lib/python3.12/site-packages/datasets/commands/test.pyAdded+207
lib/python3.12/site-packages/datasets/config.pyAdded+269
lib/python3.12/site-packages/datasets/data_files.pyAdded+795
lib/python3.12/site-packages/datasets/dataset_dict.pyAdded
lib/python3.12/site-packages/datasets/distributed.pyAdded+39
lib/python3.12/site-packages/datasets/exceptions.pyAdded+119
lib/python3.12/site-packages/datasets/fingerprint.pyAdded+454
lib/python3.12/site-packages/datasets/hub.pyAdded+230
lib/python3.12/site-packages/datasets/info.pyAdded+430
lib/python3.12/site-packages/datasets/inspect.pyAdded+363
lib/python3.12/site-packages/datasets/iterable_dataset.pyAdded
lib/python3.12/site-packages/datasets/keyhash.pyAdded+104
lib/python3.12/site-packages/datasets/load.pyAdded
lib/python3.12/site-packages/datasets/naming.pyAdded+84
lib/python3.12/site-packages/datasets/packaged_modules/__init__.pyAdded+104
lib/python3.12/site-packages/datasets/packaged_modules/csv/__init__.pyAdded
lib/python3.12/site-packages/datasets/packaged_modules/csv/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/csv/__pycache__/csv.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/csv/csv.pyAdded+198
lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/__init__.pyAdded
lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/__pycache__/folder_based_builder.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/folder_based_builder/folder_based_builder.pyAdded+417
lib/python3.12/site-packages/datasets/packaged_modules/generator/__init__.pyAdded
lib/python3.12/site-packages/datasets/packaged_modules/generator/__pycache__/generator.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/generator/generator.pyAdded+33
lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/__init__.pyAdded
lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/__pycache__/imagefolder.cpython-312.pycAdded
lib/python3.12/site-packages/datasets/packaged_modules/imagefolder/imagefolder.pyAdded+103
lib/python3.12/site-packages/datasets/packaged_modules/sql/__init__.pyAdded