id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
18,017
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Create a module with name `name` in which you can add dynamic modules such as metrics or datasets. The module can be imported using its name. The module is created in the HF_MODULE_CACHE directory by default (~/.cache/huggingface/modules) but it can be overridden by specifying a path to another directory in `hf_modules...
18,018
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Convert a list of scripts or text files provided in file_paths into a hashed filename in a repeatable way.
18,019
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Update the download count of a dataset or metric.
18,020
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Download additional module for a module <name>.py at URL (or local path) <base_path>/<name>.py The imports must have been parsed first using ``get_imports``. If some modules need to be installed with pip, an error is raised showing how to install them. This function return the list of downloaded modules as tuples (impo...
18,021
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
null
18,022
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
null
18,023
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
null
18,024
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Infer module (and builder kwargs) from data files. Raise if module names for different splits don't match. Args: data_files ([`DataFilesDict`]): Dict of list of data files. path (str, *optional*): Dataset name or path. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters to authe...
18,025
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
null
18,026
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Load a `datasets.Metric`. <Deprecated version="2.5.0"> Use `evaluate.load` instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate </Deprecated> Args: path (``str``): path to the metric processing script with the metric builder. Can be either: - a local path to processing script or the directory...
18,027
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Load a dataset from the Hugging Face Hub, or a local dataset. You can find the list of datasets on the [Hub](https://huggingface.co/datasets) or with [`huggingface_hub.list_datasets`]. A dataset is a directory that contains: - some data files in generic formats (JSON, CSV, Parquet, text, etc.). - and optionally a datas...
18,028
import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Lis...
Loads a dataset that was previously saved using [`~Dataset.save_to_disk`] from a dataset directory, or from a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`. Args: dataset_path (`str`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3://my-bucket/dataset/train"`) of the [`Dataset`] or [`D...
18,029
from typing import TypeVar from .arrow_dataset import Dataset, _split_by_node_map_style_dataset from .iterable_dataset import IterableDataset, _split_by_node_iterable_dataset DatasetType = TypeVar("DatasetType", Dataset, IterableDataset) class Dataset(DatasetInfoMixin, IndexableMixin, TensorflowDatasetMixin): """A...
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 ...
18,030
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
List all the datasets scripts available on the Hugging Face Hub. Args: with_community_datasets (`bool`, *optional*, defaults to `True`): Include the community provided datasets. with_details (`bool`, *optional*, defaults to `False`): Return the full details on the datasets instead of only the short name. Example: ```py...
18,031
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
List all the metrics script available on the Hugging Face Hub. <Deprecated version="2.5.0"> Use `evaluate.list_evaluation_modules` instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate </Deprecated> Args: with_community_metrics (:obj:`bool`, optional, default ``True``): Include the community p...
18,032
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
Allow inspection/modification of a dataset script by copying on local drive at local_path. Args: path (`str`): Path to the dataset processing script with the dataset builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g...
18,033
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
r""" Allow inspection/modification of a metric script by copying it on local drive at local_path. <Deprecated version="2.5.0"> Use `evaluate.inspect_evaluation_module` instead, from the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> Args: path (``str``): path to the dataset processi...
18,034
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
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 direc...
18,035
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
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 scrip...
18,036
import inspect import os import shutil import warnings from pathlib import Path, PurePath from typing import Dict, List, Mapping, Optional, Sequence, Union import huggingface_hub from . import config from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download....
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'`...
18,037
import os import re from functools import partial from glob import has_magic from pathlib import Path, PurePath from typing import Callable, Dict, List, Optional, Set, Tuple, Union import huggingface_hub from fsspec.core import url_to_fs from fsspec.implementations.http import HTTPFileSystem from huggingface_hub import...
null
18,038
import os import re from functools import partial from glob import has_magic from pathlib import Path, PurePath from typing import Callable, Dict, List, Optional, Set, Tuple, Union import huggingface_hub from fsspec.core import url_to_fs from fsspec.implementations.http import HTTPFileSystem from huggingface_hub import...
null
18,039
import os from typing import BinaryIO, Optional, Union import fsspec import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED...
Get the writer_batch_size that defines the maximum row group size in the parquet files. The default in `datasets` is 1,000 but we lower it to 100 for image datasets. This allows to optimize random access to parquet file, since accessing 1 row requires to read its entire row group. This can be improved to get optimized ...
18,040
from collections.abc import Mapping, MutableMapping from functools import partial from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union import numpy as np import pandas as pd import pyarrow as pa from packaging import version from .. import config from ..features import Features from...
null
18,041
from collections.abc import Mapping, MutableMapping from functools import partial from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union import numpy as np import pandas as pd import pyarrow as pa from packaging import version from .. import config from ..features import Features from...
Return the first element of a batch (dict) as a row (dict)
18,042
from collections.abc import Mapping, MutableMapping from functools import partial from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union import numpy as np import pandas as pd import pyarrow as pa from packaging import version from .. import config from ..features import Features from...
Query a Table to extract the subtable that correspond to the given key. Args: table (``datasets.table.Table``): The input Table to query from key (``Union[int, slice, range, str, Iterable]``): The key can be of different types: - an integer i: the subtable containing only the i-th row - a slice [i:j:k]: the subtable co...
18,043
from collections.abc import Mapping, MutableMapping from functools import partial from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union import numpy as np import pandas as pd import pyarrow as pa from packaging import version from .. import config from ..features import Features from...
Format a Table depending on the key that was used and a Formatter object. Args: table (``datasets.table.Table``): The input Table to format key (``Union[int, slice, range, str, Iterable]``): Depending on the key that was used, the formatter formats the table as either a row, a column or a batch. formatter (``datasets.f...
18,044
import itertools import os import re 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}'.") ...
null
18,045
import os import types import uuid from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import pyarrow as pa from filelock import BaseFileLock, Timeout from . import config from .arrow_dataset import Dataset from .arrow_reader import ArrowReader from .arrow_writer import ArrowWriter from .downl...
null
18,046
import errno import json import os import sys from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple, Union import fsspec import numpy as np import pyarrow as pa import pyarrow.parquet as pq from fsspec.core import url_to_fs from . import config from .features import Features, Image, Val...
null
18,047
import errno import json import os import sys from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple, Union import fsspec import numpy as np import pyarrow as pa import pyarrow.parquet as pq from fsspec.core import url_to_fs from . import config from .features import Features, Image, Val...
Convert parquet file to arrow file. Inputs can be str paths or file-like objects
18,048
import enum import io import os import posixpath import tarfile import warnings import zipfile from datetime import datetime from functools import partial from itertools import chain from typing import Callable, Dict, Generator, List, Optional, Tuple, Union from .. import config from ..utils import tqdm as hf_tqdm from...
null
18,049
import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _VERSION_REG = re.compile(r"^(?P<major>\d+)" r"\.(?P<minor>\d+)" r"\.(?P<patch>\d+)$") The provided code snippet includes necessary dependencies for implementing the `_str_to_version_t...
Return the tuple (major, minor, patch) version extracted from the str.
18,050
import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union The provided code snippet includes necessary dependencies for implementing the `_version_tuple_to_str` function. Write a Python function `def _version_tuple_to_str(version_tuple)` to s...
Return the str version from the version tuple (major, minor, patch).
18,051
import os import warnings from functools import partial from math import ceil from uuid import uuid4 import numpy as np import pyarrow as pa from multiprocess import get_context from .. import config def minimal_tf_collate_fn(features): if isinstance(features, dict): # case batch_size=None: nothing to collate ...
null
18,052
import os import warnings from functools import partial from math import ceil from uuid import uuid4 import numpy as np import pyarrow as pa from multiprocess import get_context from .. import config def is_numeric_pa_type(pa_type): if pa.types.is_list(pa_type): return is_numeric_pa_type(pa_type.value_type)...
null
18,053
import os import warnings from functools import partial from math import ceil from uuid import uuid4 import numpy as np import pyarrow as pa from multiprocess import get_context from .. import config def np_get_batch( indices, dataset, cols_to_retain, collate_fn, collate_fn_args, columns_to_np_types, return_dict=Fa...
Create a tf.data.Dataset from the underlying Dataset. This is a single-process method - the multiprocess equivalent is multiprocess_dataset_to_tf. Args: dataset (`Dataset`): Dataset to wrap with tf.data.Dataset. cols_to_retain (`List[str]`): Dataset column(s) to load in the tf.data.Dataset. It is acceptable to include ...
18,054
import os import warnings from functools import partial from math import ceil from uuid import uuid4 import numpy as np import pyarrow as pa from multiprocess import get_context from .. import config class NumpyMultiprocessingGenerator: def __init__( self, dataset, cols_to_retain, co...
Create a tf.data.Dataset from the underlying Dataset. This is a multi-process method - the single-process equivalent is dataset_to_tf. Args: dataset (`Dataset`): Dataset to wrap with tf.data.Dataset. cols_to_retain (`List[str]`): Dataset column(s) to load in the tf.data.Dataset. It is acceptable to include column names...
18,055
import os from apache_beam.io.filesystems import FileSystems from apache_beam.pipeline import Pipeline from .logging import get_logger CHUNK_SIZE = 2 << 20 logger = get_logger(__name__) The provided code snippet includes necessary dependencies for implementing the `upload_local_to_remote` function. Write a Python fun...
Use the Beam Filesystems to upload to a remote directory on gcs/s3/hdfs...
18,056
import os from apache_beam.io.filesystems import FileSystems from apache_beam.pipeline import Pipeline from .logging import get_logger CHUNK_SIZE = 2 << 20 logger = get_logger(__name__) The provided code snippet includes necessary dependencies for implementing the `download_remote_to_local` function. Write a Python f...
Use the Beam Filesystems to download from a remote directory on gcs/s3/hdfs...
18,057
import time from functools import partial from huggingface_hub import HfApi, hf_hub_url from huggingface_hub.hf_api import RepoFile from packaging import version from requests import ConnectionError, HTTPError from .. import config from . import logging logger = logging.get_logger(__name__) def preupload_lfs_files(hf_...
null
18,058
import time from functools import partial from huggingface_hub import HfApi, hf_hub_url from huggingface_hub.hf_api import RepoFile from packaging import version from requests import ConnectionError, HTTPError from .. import config from . import logging def preupload_lfs_files(hf_api: HfApi, **kwargs): hf_api....
null
18,059
import time from functools import partial from huggingface_hub import HfApi, hf_hub_url from huggingface_hub.hf_api import RepoFile from packaging import version from requests import ConnectionError, HTTPError from .. import config from . import logging def list_files_info(hf_api: HfApi, **kwargs): yield from ...
null
18,060
import time from functools import partial from huggingface_hub import HfApi, hf_hub_url from huggingface_hub.hf_api import RepoFile from packaging import version from requests import ConnectionError, HTTPError from .. import config from . import logging def list_files_info(hf_api: HfApi, **kwargs): kwargs = {*...
null
18,061
from typing import Callable The provided code snippet includes necessary dependencies for implementing the `is_documented_by` function. Write a Python function `def is_documented_by(function_with_docstring: Callable)` to solve the following problem: Decorator to share docstrings across common functions. Args: function...
Decorator to share docstrings across common functions. Args: function_with_docstring (`Callable`): Name of the function with the docstring.
18,062
from typing import Any, Dict, List, Optional, Union from .. import config from ..exceptions import DatasetsError from .file_utils import ( get_authentication_headers_for_url, http_get, ) from .logging import get_logger logger = get_logger(__name__) class DatasetsServerError(DatasetsError): """Dataset-server...
Get the dataset exported parquet files Docs: https://huggingface.co/docs/datasets-server/parquet
18,063
from typing import Any, Dict, List, Optional, Union from .. import config from ..exceptions import DatasetsError from .file_utils import ( get_authentication_headers_for_url, http_get, ) from .logging import get_logger logger = get_logger(__name__) class DatasetsServerError(DatasetsError): """Dataset-server...
Get the dataset information, can be useful to get e.g. the dataset features. Docs: https://huggingface.co/docs/datasets-server/info
18,064
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
null
18,065
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
null
18,066
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
Return a logger with the specified name. This function can be used in dataset scripts.
18,067
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
Set the level for the Hugging Face datasets library's root logger to `INFO`. This will display most of the logging information and tqdm bars. Shortcut to `datasets.logging.set_verbosity(datasets.logging.INFO)`.
18,068
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
Set the level for the Hugging Face datasets library's root logger to `DEBUG`. This will display all the logging information and tqdm bars. Shortcut to `datasets.logging.set_verbosity(datasets.logging.DEBUG)`.
18,069
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
Set the level for the Hugging Face datasets library's root logger to `ERROR`. This will display only the errors logging information and tqdm bars. Shortcut to `datasets.logging.set_verbosity(datasets.logging.ERROR)`.
18,070
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
Disable propagation of the library log outputs. Note that log propagation is disabled by default.
18,071
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from .tqdm import ( # noqa: F401 # imported for backward compatibility disable_pro...
Enable propagation of the library log outputs. Please disable the Hugging Face datasets library's default handler to prevent double logging if the root logger has been configured.
18,072
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,073
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,074
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,075
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,076
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,077
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,078
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,079
import copy import io import json import multiprocessing import os import posixpath import re import shutil import sys import time import urllib import warnings from contextlib import closing, contextmanager from functools import partial from pathlib import Path from typing import Optional, TypeVar, Union from unittest...
null
18,080
import enum import inspect import warnings from functools import wraps from typing import Callable, Optional from .logging import get_logger _emitted_deprecation_warnings = set() The provided code snippet includes necessary dependencies for implementing the `deprecated` function. Write a Python function `def deprecate...
Decorator to mark a class or a function as deprecated. Args: help_message (:obj:`str`, optional): An optional message to guide the user on how to switch to non-deprecated usage of the library.
18,081
import numpy as np def approximate_mode(class_counts, n_draws, rng): """Computes approximate mode of multivariate hypergeometric. This is an approximation to the mode of the multivariate hypergeometric given by class_counts and n_draws. It shouldn't be off by more than one. It is the mostly likely o...
Provides train/test indices to split data in train/test sets. It's reference is taken from StratifiedShuffleSplit implementation of scikit-learn library. Args ---------- n_train : int, represents the absolute number of train samples. n_test : int, represents the absolute number of test samples. random_state : int or Ra...
18,082
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config class Pickler(dill.Pickler): dispatch = dill._dill.MetaCatchingDict(dill.Pickler.dispatch.copy()) _legacy_no_dict_keys_sorting = False def save(self, obj, save...
Register a custom reducer for the type.
18,083
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config def dump(obj, file): """Pickle an object to a file.""" Pickler(file, recurse=True).dump(obj) The provided code snippet includes necessary dependencies for impleme...
Pickle an object to a string.
18,084
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): dill._dill.log.info(msg) elif config.DILL_VERSION.release[:3] in [ version.parse("0...
null
18,085
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): dill._dill.log.info(msg) elif config.DILL_VERSION.release[:3] in [ version.parse("0...
null
18,086
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): elif config.DILL_VERSION.release[:3] in [ version.parse("0.3.6").release, version.parse...
null
18,087
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): dill._dill.log.info(msg) elif config.DILL_VERSION.release[:3] in [ version.parse("0...
null
18,088
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): elif config.DILL_VERSION.release[:3] in [ version.parse("0.3.6").release, version.parse...
null
18,089
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): dill._dill.log.info(msg) elif config.DILL_VERSION.release[:3] in [ version.parse("0...
null
18,090
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): dill._dill.log.info(msg) elif config.DILL_VERSION.release[:3] in [ version.parse("0...
null
18,091
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config if config.DILL_VERSION < version.parse("0.3.6"): def log(pickler, msg): dill._dill.log.info(msg) elif config.DILL_VERSION.release[:3] in [ version.parse("0...
From dill._dill.save_code This is a modified version that removes the origin (filename + line no.) of functions created in notebooks or shells for example.
18,092
import os import sys from io import BytesIO from types import CodeType, FunctionType import dill from packaging import version from .. import config def save_code(pickler, obj): dill._dill.logger.trace(pickler, "Co: %s", obj) ############################################################################...
null
18,093
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
Returns a human readable size string. If size_in_bytes is None, then returns "Unknown size". For example `size_str(1.5 * datasets.units.GiB) == "1.50 GiB"`. Args: size_in_bytes: `int` or `None`, the size, in bytes, that we want to format as a human-readable size string.
18,094
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
Converts a size expressed as a string with digits an unit (like `"50MB"`) to an integer (in bytes). Args: size (`int` or `str`): The size to convert. Will be directly returned if an `int`. Example: ```py >>> convert_file_size_to_int("1MiB") 1048576 ```
18,095
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
Temporarily assign obj.attr to value.
18,096
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
Temporarily set the random seed. This works for python numpy, pytorch and tensorflow.
18,097
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
Apply a function recursively to each element of a nested data struct. Use multiprocessing if num_proc > 1 and the length of data_struct is greater than or equal to `parallel_min_length`. <Changed version="2.5.0"> Before version 2.5.0, multiprocessing was not used if `num_proc` was greater than or equal to ``len(iterabl...
18,098
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
null
18,099
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
null
18,100
import copy import functools import itertools import multiprocessing.pool import os import queue import re import types import warnings from contextlib import contextmanager from dataclasses import fields, is_dataclass from multiprocessing import Manager from pathlib import Path from queue import Empty from shutil impo...
null
18,101
import importlib.resources as pkg_resources import logging from pathlib import Path from typing import Any, List, Tuple import yaml from . import resources from .deprecation_utils import deprecated BASE_REF_URL = "https://github.com/huggingface/datasets/tree/main/src/datasets/utils" def load_yaml_resource(resource: st...
null
18,102
import warnings from tqdm.auto import tqdm as old_tqdm from ..config import HF_DATASETS_DISABLE_PROGRESS_BARS _hf_datasets_progress_bars_disabled: bool = HF_DATASETS_DISABLE_PROGRESS_BARS or False HF_DATASETS_DISABLE_PROGRESS_BARS: Optional[bool] = ( __HF_DATASETS_DISABLE_PROGRESS_BARS.upper() in ENV_VARS_TRUE_VAL...
Disable globally progress bars used in `datasets` except if `HF_DATASETS_DISABLE_PROGRESS_BAR` environment variable has been set. Use [`~utils.enable_progress_bars`] to re-enable them.
18,103
import warnings from tqdm.auto import tqdm as old_tqdm from ..config import HF_DATASETS_DISABLE_PROGRESS_BARS _hf_datasets_progress_bars_disabled: bool = HF_DATASETS_DISABLE_PROGRESS_BARS or False HF_DATASETS_DISABLE_PROGRESS_BARS: Optional[bool] = ( __HF_DATASETS_DISABLE_PROGRESS_BARS.upper() in ENV_VARS_TRUE_VAL...
Enable globally progress bars used in `datasets` except if `HF_DATASETS_DISABLE_PROGRESS_BAR` environment variable has been set. Use [`~utils.disable_progress_bars`] to disable them.
18,104
import warnings from tqdm.auto import tqdm as old_tqdm from ..config import HF_DATASETS_DISABLE_PROGRESS_BARS def are_progress_bars_disabled() -> bool: """Return whether progress bars are globally disabled or not. Progress bars used in `datasets` can be enable or disabled globally using [`~utils.enable_progress...
null
18,105
import enum import os from typing import Optional from huggingface_hub.utils import insecure_hashlib from .. import config from .logging import get_logger logger = get_logger(__name__) class UnexpectedDownloadedFile(ChecksumVerificationException): """Some downloaded files were not expected.""" class ExpectedMoreDow...
null
18,106
import enum import os from typing import Optional from huggingface_hub.utils import insecure_hashlib from .. import config from .logging import get_logger logger = get_logger(__name__) class UnexpectedSplits(SplitsVerificationException): """The expected splits of the downloaded file is missing.""" class ExpectedMor...
null
18,107
import enum import os from typing import Optional from huggingface_hub.utils import insecure_hashlib from .. import config from .logging import get_logger The provided code snippet includes necessary dependencies for implementing the `get_size_checksum_dict` function. Write a Python function `def get_size_checksum_dic...
Compute the file size and the sha256 checksum of a file
18,108
from typing import List import numpy as np def _number_of_shards_in_gen_kwargs(gen_kwargs: dict) -> int: """Return the number of possible shards according to the input gen_kwargs""" # Having lists of different sizes makes sharding ambigious, raise an error in this case # until we decide how to define shardi...
Split the gen_kwargs into `max_num_job` gen_kwargs
18,109
from typing import List import numpy as np def _merge_gen_kwargs(gen_kwargs_list: List[dict]) -> dict: return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key], list) else gen_kwargs_list[0][key] for key in gen_kwargs...
null
18,110
from typing import List import numpy as np The provided code snippet includes necessary dependencies for implementing the `_shuffle_gen_kwargs` function. Write a Python function `def _shuffle_gen_kwargs(rng: np.random.Generator, gen_kwargs: dict) -> dict` to solve the following problem: Return a shuffled copy of the i...
Return a shuffled copy of the input gen_kwargs
18,111
import re import textwrap from collections import Counter from itertools import groupby from operator import itemgetter from pathlib import Path from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union import yaml from huggingface_hub import DatasetCardData from ..config import METADATA_CONFIGS_FIELD from ....
null
18,112
import warnings from functools import wraps from typing import Callable The provided code snippet includes necessary dependencies for implementing the `experimental` function. Write a Python function `def experimental(fn: Callable) -> Callable` to solve the following problem: Decorator to flag a feature as experimenta...
Decorator to flag a feature as experimental. An experimental feature trigger a warning when used as it might be subject to breaking changes in the future. Args: fn (`Callable`): The function to flag as experimental. Returns: `Callable`: The decorated function. Example: ```python >>> from datasets.utils import experimen...
18,113
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def get_duration(func): def wrapper(*args, **kwargs): starttime = timeit.default_timer() _ = func(*args, **kwargs) delta = timeit.default_timer() - ...
null
18,114
import json import os import tempfile import datasets from datasets.arrow_writer import ArrowWriter from datasets.features import Array2D from utils import generate_examples, get_duration SPEED_TEST_SHAPE = (100, 100) SPEED_TEST_N_EXAMPLES = 100 RESULTS_FILE_PATH = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILE...
null
18,115
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration SPEED_TEST_N_EXAMPLES = 500_000 RESULTS_FILE_PATH = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) def map(dataset: datasets.Dataset, **kwargs): _ =...
null
18,116
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration SPEED_TEST_N_EXAMPLES = 500_000 RESULTS_FILE_PATH = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) def select(dataset: datasets.Dataset): _ = dataset.select(range(0, le...
null