text stringlengths 1 1.02k | class_index int64 0 271 | source stringclasses 76
values |
|---|---|---|
def rename_column(self, original_column_name: str, new_column_name: str) -> "IterableDatasetDict":
"""
Rename a column in the dataset, and move the features associated to the original column under the new column
name.
The renaming is applied to all the datasets of the dataset dictionary.... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds["train"]))
{'label': 1,
'movie_review': 'the rock is destined to be the 21st century\'s new " conan " a... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def rename_columns(self, column_mapping: Dict[str, str]) -> "IterableDatasetDict":
"""
Rename several columns in the dataset, and move the features associated to the original columns under
the new column names.
The renaming is applied to all the datasets of the dataset dictionary.
... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.rename_columns({"text": "movie_review", "label": "rating"})
>>> next(iter(ds["train"]))
{'movie_review': 'the rock is destined to be the 21st century\'s new " conan " ... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
column_names (`Union[str, List[str]]`):
Name of the column(s) to remove.
Returns:
[`IterableDatasetDict`]: A copy of the dataset object without the columns to remove.
Example:
```py
>>> from datasets import load_dataset
>>> ds = lo... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def select_columns(self, column_names: Union[str, List[str]]) -> "IterableDatasetDict":
"""Select one or several column(s) in the dataset and the features
associated to them. The selection is done on-the-fly on the examples
when iterating over the dataset. The selection is applied to all the
... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.select("text")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater th... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos'], id=None),
'text': Value(dtype='string', id=None)}
>>> ds = ds.cast_column('label', ClassLa... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
features (`Features`):
New features to cast the dataset to.
The name of the fields in the features must match the current column names.
The type of the data must also be convertible from one type to the other.
For non-trivial conversion, ... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos'], id=None),
'text': Value(dtype='string', id=None)}
>>> new_features = ds["train"].features.copy()
... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
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... | 36 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/fingerprint.py |
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.xx... | 37 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/fingerprint.py |
class SchemaInferenceError(ValueError):
pass | 38 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 array... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 == ... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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:
... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 so... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
This function is only used for custom python objects that can't be direclty passed to build
an Arrow array. In such cases is infers the feature type to use, and it encodes the data so
that they can be passed to an Arrow array.
Args:
data (Iterable): array of data to infer the type, ... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
non_null_idx, non_null_value = first_non_null_value(data)
if isinstance(non_null_value, PIL.Image.Image):
return [Image().encode_example(value) if value is not None else None for value in data], Image()
return data, None
def __arrow_array__(self, type: Optional[pa.DataType] = No... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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:
... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
return pa.ExtensionArray.from_storage(pa_type, storage) | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
# efficient np array to pyarrow array
if isinstance(data, np.ndarray):
out = numpy_to_pyarrow_listarray(data)
elif isinstance(data, list) and data and isinstance(first_non_null_value(data)[1], np.ndarray):
out = list_of_np_array_to_pyarrow_listarray(data)
... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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'... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
if not self.trying_type and isinstance(e, pa.lib.ArrowNotImplementedError):
raise | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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):
retur... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 tr... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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())... | 39 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 = {... | 40 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
class ArrowWriter:
"""Shuffles and writes Examples to Arrow files."""
_WRITER_CLASS = pa.RecordBatchStreamWriter | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
self._features = None
self._schema = None | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 i... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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
... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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
i... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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.na... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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) | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
@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(fie... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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.na... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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.curren... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 fro... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
if writer_batch_size is None:
writer_batch_size = self.writer_batch_size
if writer_batch_size is not None and len(self.current_examples) >= writer_batch_size:
if self._check_duplicates:
self.check_duplicate_keys()
# Re-intializing to empty list for next ba... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
Args:
batch_examples: the batch of examples to add.
"""
if batch_examples and len(next(iter(batch_examples.values()))) == 0:
return
features = None if self.pa_writer is None and self.update_features else self._features
try_features = self._features if self.pa_writ... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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:
... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
def finalize(self, close_stream=True):
self.write_rows_on_file()
# In case current_examples < writer_batch_size, but user uses finalize()
if self._check_duplicates:
self.check_duplicate_keys()
# Re-intializing to empty list for next batch
self.hkey_record = []... | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
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 | 41 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
class ParquetWriter(ArrowWriter):
_WRITER_CLASS = pq.ParquetWriter | 42 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_writer.py |
class DatasetNotOnHfGcsError(ConnectionError):
"""When you can't get the dataset from the Hf google cloud storage"""
pass | 43 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
class MissingFilesOnHfGcsError(ConnectionError):
"""When some files are missing on the Hf oogle cloud storage"""
pass | 44 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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.... | 45 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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 datas... | 46 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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-mem... | 46 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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
... | 46 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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
)
f... | 46 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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... | 46 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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 buil... | 46 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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:
... | 47 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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,
... | 47 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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) | 47 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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 tfr... | 48 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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,
filenam... | 48 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
class _AbsoluteInstruction:
"""A machine friendly slice: defined absolute positive boundaries."""
splitname: str
from_: int # uint (starting index).
to: int # uint (ending index). | 49 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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... | 50 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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... | 50 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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('... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
# 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.ReadInstructio... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
@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(rel... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
{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 n... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
@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,
... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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_... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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 = ... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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_instru... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
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 _... | 51 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_reader.py |
class InvalidConfigName(ValueError):
pass | 52 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
class BuilderConfig:
"""Base class for `DatasetBuilder` data configuration.
`DatasetBuilder` subclasses with data configuration options should subclass
`BuilderConfig` and add their own properties.
Attributes:
name (`str`, defaults to `default`):
The name of the configuration.
... | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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_... | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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)) fo... | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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... | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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)... | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
suffix = Hasher.hash(config_kwargs_to_add_to_suffix)
else:
suffix = Hasher.hash(config_kwargs_to_add_to_suffix) | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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_READ... | 53 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
</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/`... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
Used to distinguish builders with the same name but not coming from the same namespace, for example "squad"
and "lhoestq/squad" repo IDs. In the latter, the builder name would be "lhoestq___squad".
data_files (`str` or `Sequence` or `Mapping`, *optional*):
Path(s) to source data file(s).... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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.
... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
# 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... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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 | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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),
... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
# 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.... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
# 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)
)
... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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"
)
wi... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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) | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
# 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 ... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
# 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... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
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_DATASET... | 54 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/builder.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.