text stringlengths 1 1.02k | class_index int64 0 271 | source stringclasses 76
values |
|---|---|---|
metadata_patterns, download_config=self.download_config, base_path=base_path
)
if metadata_data_files_list:
data_files = DataFilesDict(
{
split: data_files_list + metadata_data_files_list
... | 112 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
module_path, hash = _PACKAGED_DATASETS_MODULES[self.name]
builder_kwargs = {
"data_files": data_files,
"dataset_name": self.name,
}
return DatasetModule(module_path, hash, builder_kwargs) | 112 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class HubDatasetModuleFactoryWithoutScript(_DatasetModuleFactory):
"""
Get the module of a dataset loaded from data files of a dataset repository.
The dataset builder module to use is inferred from the data files extensions.
"""
def __init__(
self,
name: str,
commit_hash: st... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
# Get the Dataset Card and fix the revision in case there are new commits in the meantime
api = HfApi(
endpoint=config.HF_ENDPOINT,
token=self.download_config.token,
library_name="datasets",
library_version=__version_... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
download_config.download_desc = "Downloading standalone yaml"
try:
standalone_yaml_path = cached_path(
hf_dataset_url(self.name, config.REPOYAML_FILENAME, revision=self.commit_hash),
download_config=download_config,
)
with open(standalone_yaml_... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
if config.USE_PARQUET_EXPORT and self.use_exported_dataset_infos:
try:
exported_dataset_infos = _dataset_viewer.get_exported_dataset_infos(
dataset=self.name, commit_hash=self.commit_hash, token=self.download_config.token
)
exported_dataset... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
if self.data_files is not None:
patterns = sanitize_patterns(self.data_files)
elif metadata_configs and not self.data_dir and "data_files" in next(iter(metadata_configs.values())):
patterns = sanitize_patterns(next(iter(metadata_configs.values()))["data_files"])
else:
... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
supports_metadata = module_name in _MODULE_SUPPORTS_METADATA
if self.data_files is None and supports_metadata:
try:
metadata_patterns = get_metadata_patterns(base_path, download_config=self.download_config)
except FileNotFoundError:
metadata_patterns = Non... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
module_path, _ = _PACKAGED_DATASETS_MODULES[module_name]
if metadata_configs:
builder_configs, default_config_name = create_builder_configs_from_metadata_configs(
module_path,
metadata_configs,
base_path=base_path,
supports_metadata=sup... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
if self.data_dir:
builder_kwargs["data_files"] = data_files
download_config = self.download_config.copy()
if download_config.download_desc is None:
download_config.download_desc = "Downloading metadata"
try:
# this file is deprecated and was created automatica... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
# old config e.g. named "username--dataset_name"
legacy_config_name = next(iter(legacy_dataset_infos))
legacy_dataset_infos["default"] = legacy_dataset_infos.pop(legacy_config_name)
legacy_dataset_infos.update(dataset_infos)
dataset_infos = legacy_dataset_... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
return DatasetModule(
module_path,
self.commit_hash,
builder_kwargs,
dataset_infos=dataset_infos,
builder_configs_parameters=BuilderConfigsParameters(
metadata_configs=metadata_configs,
builder_configs=builder_configs,
... | 113 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class HubDatasetModuleFactoryWithParquetExport(_DatasetModuleFactory):
"""
Get the module of a dataset loaded from parquet files of a dataset repository parquet export.
"""
def __init__(
self,
name: str,
commit_hash: str,
download_config: Optional[DownloadConfig] = None,... | 114 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
exported_parquet_files = _dataset_viewer.get_exported_parquet_files(
dataset=self.name, commit_hash=self.commit_hash, token=self.download_config.token
)
exported_dataset_infos = _dataset_viewer.get_exported_dataset_infos(
dataset=sel... | 114 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
revision="refs/convert/parquet",
token=self.download_config.token,
timeout=100.0,
)
.sha
) # fix the revision in case there are new commits in the meantime
metadata_configs = MetadataConfigs._from_exported_parquet_files_and_dataset_infos(
... | 114 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
return DatasetModule(
module_path,
self.commit_hash,
builder_kwargs,
dataset_infos=dataset_infos,
builder_configs_parameters=BuilderConfigsParameters(
metadata_configs=metadata_configs,
builder_configs=builder_configs,
... | 114 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class HubDatasetModuleFactoryWithScript(_DatasetModuleFactory):
"""
Get the module of a dataset from a dataset repository.
The dataset script comes from the script inside the dataset repository.
"""
def __init__(
self,
name: str,
commit_hash: str,
download_config: Op... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def download_loading_script(self) -> str:
file_path = hf_dataset_url(self.name, self.name.split("/")[-1] + ".py", revision=self.commit_hash)
download_config = self.download_config.copy()
if download_config.download_desc is None:
download_config.download_desc = "Downloading builder sc... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def download_dataset_readme_file(self) -> str:
readme_url = hf_dataset_url(self.name, config.REPOCARD_FILENAME, revision=self.commit_hash)
# Download the dataset infos file if available
download_config = self.download_config.copy()
if download_config.download_desc is None:
do... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None:
warnings.warn(
f"The repository for {self.name} contains custom code which must be executed to correctly "
f"load the dataset. You can inspect the reposi... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
name=self.name,
base_path=hf_dataset_url(self.name, "", revision=self.commit_hash),
imports=imports,
download_config=self.download_config,
)
additional_files = []
if dataset_infos_path:
additional_files.append((config.DATASETDICT_INFOS_FILENAME, da... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name)
if trust_remote_code:
_create_importable_file(
local_path=local_path,
local_imports=local_imports,
additional_files=additional_files,
... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
_check_library_imports(name=self.name, library_imports=library_imports)
module_path, hash = _load_importable_file(
dynamic_modules_path=dynamic_modules_path,
module_namespace="datasets",
subdirectory_name=hash,
name=self.name,
)
# make the new modu... | 115 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class CachedDatasetModuleFactory(_DatasetModuleFactory):
"""
Get the module of a dataset that has been loaded once already and cached.
The script that is loaded from the cache is the most recent one with a matching name.
"""
def __init__(
self,
name: str,
cache_dir: Optional... | 116 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules()
importable_directory_path = os.path.join(dynamic_modules_path, "datasets", self.name.replace("/", "--"))
hashes = (
[h for h in os.listdir(... | 116 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
hash = sorted(hashes, key=_get_modification_time)[-1]
warning_msg = (
f"Using the latest cached version of the module from {os.path.join(importable_directory_path, hash)} "
f"(last modified on {time.ctime(_get_modification_time(hash))}) since it "
f"couldn't b... | 116 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
)
# make the new module to be noticed by the import system
importlib.invalidate_caches()
builder_kwargs = {
"repo_id": self.name,
}
return DatasetModule(module_path, hash, builder_kwargs, importable_file_path=importable_file_path)
cache... | 116 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
builder_kwargs = {
"repo_id": self.name,
"dataset_name": self.name.split("/")[-1],
}
warning_msg = f"Using the latest cached version of the dataset since {self.name} couldn't be found on the Hugging Face Hub"
if config.HF_HUB_OFFLINE:
w... | 116 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class SupervisedKeysData:
input: str = ""
output: str = "" | 117 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
class DownloadChecksumsEntryData:
key: str = ""
value: str = "" | 118 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
class MissingCachedSizesConfigError(Exception):
"""The expected cached sizes of the download file are missing.""" | 119 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
class NonMatchingCachedSizesError(Exception):
"""The prepared split doesn't have expected sizes.""" | 120 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
class PostProcessedInfo:
features: Optional[Features] = None
resources_checksums: Optional[dict] = None
def __post_init__(self):
# Convert back to the correct classes when we reload from dict
if self.features is not None and not isinstance(self.features, Features):
self.features... | 121 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
class DatasetInfo:
"""Information about a dataset.
`DatasetInfo` documents datasets, including its name, version, and features.
See the constructor arguments and properties for a full list.
Not all fields are known on construction and may be updated later. | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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 ... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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`].
v... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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 t... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
# 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_proc... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
_INCLUDED_INFO_IN_YAML: ClassVar[List[str]] = [
"config_name",
"download_size",
"dataset_size",
"features",
"splits",
] | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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_processe... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
self.supervised_keys = SupervisedKeysData(*self.supervised_keys)
else:
self.supervised_keys = SupervisedKeysData(**self.supervised_keys) | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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 (`... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("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 {}))
... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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 dat... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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_... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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 t... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
```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_d... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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)
}
... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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
... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
@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... | 122 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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(da... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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_da... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
@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... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
for config_name, dataset_info_dict in json.load(f).items()
}
)
else:
return cls() | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
@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(
{
... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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_c... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
**{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_dic... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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_i... | 123 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/info.py |
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 = "\nKey... | 124 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/keyhash.py |
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 genera... | 125 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/keyhash.py |
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: ... | 126 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/keyhash.py |
class ParallelBackendConfig:
backend_name = None | 127 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/parallel/parallel.py |
class ParquetDatasetReader(AbstractDatasetReader):
def __init__(
self,
path_or_paths: NestedDataStructureLike[PathLike],
split: Optional[NamedSplit] = None,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bo... | 128 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/parquet.py |
) | 128 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/parquet.py |
def read(self):
# Build iterable dataset
if self.streaming:
dataset = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
download_config = None
download_mode = None
verification_mode = None
... | 128 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/parquet.py |
class ParquetDatasetWriter:
def __init__(
self,
dataset: Dataset,
path_or_buf: Union[PathLike, BinaryIO],
batch_size: Optional[int] = None,
storage_options: Optional[dict] = None,
**parquet_writer_kwargs,
):
self.dataset = dataset
self.path_or_buf ... | 129 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/parquet.py |
if isinstance(self.path_or_buf, (str, bytes, os.PathLike)):
with fsspec.open(self.path_or_buf, "wb", **(self.storage_options or {})) as buffer:
written = self._write(file_obj=buffer, batch_size=batch_size, **self.parquet_writer_kwargs)
else:
written = self._write(file_obj... | 129 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/parquet.py |
for offset in hf_tqdm(
range(0, len(self.dataset), batch_size),
unit="ba",
desc="Creating parquet from Arrow format",
):
batch = query_table(
table=self.dataset._data,
key=slice(offset, offset + batch_size),
indices=... | 129 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/parquet.py |
class GeneratorDatasetInputStream(AbstractDatasetInputStream):
def __init__(
self,
generator: Callable,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bool = False,
gen_kwargs: Optional[dict] = None,
... | 130 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/generator.py |
def read(self):
# Build iterable dataset
if self.streaming:
dataset = self.builder.as_streaming_dataset(split=self.builder.config.split)
# Build regular (map-style) dataset
else:
download_config = None
download_mode = None
verification_mode... | 130 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/generator.py |
class CsvDatasetReader(AbstractDatasetReader):
def __init__(
self,
path_or_paths: NestedDataStructureLike[PathLike],
split: Optional[NamedSplit] = None,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bool =... | 131 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/csv.py |
def read(self):
# Build iterable dataset
if self.streaming:
dataset = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
download_config = None
download_mode = None
verification_mode = None
... | 131 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/csv.py |
class CsvDatasetWriter:
def __init__(
self,
dataset: Dataset,
path_or_buf: Union[PathLike, BinaryIO],
batch_size: Optional[int] = None,
num_proc: Optional[int] = None,
storage_options: Optional[dict] = None,
**to_csv_kwargs,
):
if num_proc is not N... | 132 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/csv.py |
if isinstance(self.path_or_buf, (str, bytes, os.PathLike)):
with fsspec.open(self.path_or_buf, "wb", **(self.storage_options or {})) as buffer:
written = self._write(file_obj=buffer, header=header, index=index, **self.to_csv_kwargs)
else:
written = self._write(file_obj=se... | 132 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/csv.py |
def _write(self, file_obj: BinaryIO, header, index, **to_csv_kwargs) -> int:
"""Writes the pyarrow table as CSV to a binary file handle.
Caller is responsible for opening and closing the handle.
"""
written = 0
if self.num_proc is None or self.num_proc == 1:
for off... | 132 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/csv.py |
else:
num_rows, batch_size = len(self.dataset), self.batch_size
with multiprocessing.Pool(self.num_proc) as pool:
for csv_str in hf_tqdm(
pool.imap(
self._batch_csv,
[(offset, header, index, to_csv_kwargs) for of... | 132 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/csv.py |
class TextDatasetReader(AbstractDatasetReader):
def __init__(
self,
path_or_paths: NestedDataStructureLike[PathLike],
split: Optional[NamedSplit] = None,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bool ... | 133 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/text.py |
def read(self):
# Build iterable dataset
if self.streaming:
dataset = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
download_config = None
download_mode = None
verification_mode = None
... | 133 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/text.py |
class SparkDatasetReader(AbstractDatasetReader):
"""A dataset reader that reads from a Spark DataFrame.
When caching, cache materialization is parallelized over Spark; an NFS that is accessible to the driver must be
provided. Streaming is not currently supported.
""" | 134 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/spark.py |
def __init__(
self,
df: pyspark.sql.DataFrame,
split: Optional[NamedSplit] = None,
features: Optional[Features] = None,
streaming: bool = True,
cache_dir: str = None,
keep_in_memory: bool = False,
working_dir: str = None,
load_from_cache_file: bool... | 134 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/spark.py |
def read(self):
if self.streaming:
return self.builder.as_streaming_dataset(split=self.split)
download_mode = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD
self.builder.download_and_prepare(
download_mode=download_mode,
file_format=self... | 134 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/spark.py |
class SqlDatasetReader(AbstractDatasetInputStream):
def __init__(
self,
sql: Union[str, "sqlalchemy.sql.Selectable"],
con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"],
features: Optional[Features] = None,
cache_dir: str = None,... | 135 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/sql.py |
# Build dataset for splits
dataset = self.builder.as_dataset(
split="train", verification_mode=verification_mode, in_memory=self.keep_in_memory
)
return dataset | 135 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/sql.py |
class SqlDatasetWriter:
def __init__(
self,
dataset: Dataset,
name: str,
con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"],
batch_size: Optional[int] = None,
num_proc: Optional[int] = None,
**to_sql_kwargs,
)... | 136 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/sql.py |
def _batch_sql(self, args):
offset, index, to_sql_kwargs = args
to_sql_kwargs = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs
batch = query_table(
table=self.dataset.data,
key=slice(offset, offset + self.batch_size),
indices=self.da... | 136 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/sql.py |
if self.num_proc is None or self.num_proc == 1:
for offset in hf_tqdm(
range(0, len(self.dataset), self.batch_size),
unit="ba",
desc="Creating SQL from Arrow format",
):
written += self._batch_sql((offset, index, to_sql_kwargs))
... | 136 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/sql.py |
class JsonDatasetReader(AbstractDatasetReader):
def __init__(
self,
path_or_paths: NestedDataStructureLike[PathLike],
split: Optional[NamedSplit] = None,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bool ... | 137 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
) | 137 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
def read(self):
# Build iterable dataset
if self.streaming:
dataset = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
download_config = None
download_mode = None
verification_mode = None
... | 137 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
class JsonDatasetWriter:
def __init__(
self,
dataset: Dataset,
path_or_buf: Union[PathLike, BinaryIO],
batch_size: Optional[int] = None,
num_proc: Optional[int] = None,
storage_options: Optional[dict] = None,
**to_json_kwargs,
):
if num_proc is not... | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
def write(self) -> int:
_ = self.to_json_kwargs.pop("path_or_buf", None)
orient = self.to_json_kwargs.pop("orient", "records")
lines = self.to_json_kwargs.pop("lines", True if orient == "records" else False)
if "index" not in self.to_json_kwargs and orient in ["split", "table"]:
... | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
if not lines and self.batch_size < self.dataset.num_rows:
raise NotImplementedError(
"Output JSON will not be formatted correctly when lines = False and batch_size < number of rows in the dataset. Use pandas.DataFrame.to_json() instead."
) | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
if isinstance(self.path_or_buf, (str, bytes, os.PathLike)):
with fsspec.open(
self.path_or_buf, "wb", compression=compression, **(self.storage_options or {})
) as buffer:
written = self._write(file_obj=buffer, orient=orient, lines=lines, **self.to_json_kwargs)
... | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
batch = query_table(
table=self.dataset.data,
key=slice(offset, offset + self.batch_size),
indices=self.dataset._indices,
)
json_str = batch.to_pandas().to_json(path_or_buf=None, orient=orient, lines=lines, **to_json_kwargs)
if not json_str.endswith("\n"):
... | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
if self.num_proc is None or self.num_proc == 1:
for offset in hf_tqdm(
range(0, len(self.dataset), self.batch_size),
unit="ba",
desc="Creating json from Arrow format",
):
json_str = self._batch_json((offset, orient, lines, to_json_k... | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
written += file_obj.write(json_str) | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
return written | 138 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/json.py |
class AbstractDatasetReader(ABC):
def __init__(
self,
path_or_paths: Optional[NestedDataStructureLike[PathLike]] = None,
split: Optional[NamedSplit] = None,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bo... | 139 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/abc.py |
class AbstractDatasetInputStream(ABC):
def __init__(
self,
features: Optional[Features] = None,
cache_dir: str = None,
keep_in_memory: bool = False,
streaming: bool = False,
num_proc: Optional[int] = None,
**kwargs,
):
self.features = features
... | 140 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/io/abc.py |
class Value:
"""
Scalar feature value of a particular data type.
The possible dtypes of `Value` are as follows:
- `null`
- `bool`
- `int8`
- `int16`
- `int32`
- `int64`
- `uint8`
- `uint16`
- `uint32`
- `uint64`
- `float16`
- `float32` (alias float)
- `fl... | 141 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.