text stringlengths 1 1.02k | class_index int64 0 271 | source stringclasses 76
values |
|---|---|---|
dtype: str
id: Optional[str] = None
# Automatically constructed
pa_type: ClassVar[Any] = None
_type: str = field(default="Value", init=False, repr=False)
def __post_init__(self):
if self.dtype == "double": # fix inferred type
self.dtype = "float64"
if self.dtype == "flo... | 141 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class _ArrayXD:
def __post_init__(self):
self.shape = tuple(self.shape)
def __call__(self):
pa_type = globals()[self.__class__.__name__ + "ExtensionType"](self.shape, self.dtype)
return pa_type
def encode_example(self, value):
return value | 142 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array2D(_ArrayXD):
"""Create a two-dimensional array.
Args:
shape (`tuple`):
Size of each dimension.
dtype (`str`):
Name of the data type.
Example:
```py
>>> from datasets import Features
>>> features = Features({'x': Array2D(shape=(1, 3), dtype='... | 143 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array3D(_ArrayXD):
"""Create a three-dimensional array.
Args:
shape (`tuple`):
Size of each dimension.
dtype (`str`):
Name of the data type.
Example:
```py
>>> from datasets import Features
>>> features = Features({'x': Array3D(shape=(1, 2, 3), dt... | 144 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array4D(_ArrayXD):
"""Create a four-dimensional array.
Args:
shape (`tuple`):
Size of each dimension.
dtype (`str`):
Name of the data type.
Example:
```py
>>> from datasets import Features
>>> features = Features({'x': Array4D(shape=(1, 2, 2, 3), ... | 145 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array5D(_ArrayXD):
"""Create a five-dimensional array.
Args:
shape (`tuple`):
Size of each dimension.
dtype (`str`):
Name of the data type.
Example:
```py
>>> from datasets import Features
>>> features = Features({'x': Array5D(shape=(1, 2, 2, 3, 3... | 146 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class _ArrayXDExtensionType(pa.ExtensionType):
ndims: Optional[int] = None
def __init__(self, shape: tuple, dtype: str):
if self.ndims is None or self.ndims <= 1:
raise ValueError("You must instantiate an array type with a value for dim that is > 1")
if len(shape) != self.ndims:
... | 147 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
@classmethod
def __arrow_ext_deserialize__(cls, storage_type, serialized):
args = json.loads(serialized)
return cls(*args)
# This was added to pa.ExtensionType in pyarrow >= 13.0.0
def __reduce__(self):
return self.__arrow_ext_deserialize__, (self.storage_type, self.__arrow_ext_seri... | 147 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array2DExtensionType(_ArrayXDExtensionType):
ndims = 2 | 148 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array3DExtensionType(_ArrayXDExtensionType):
ndims = 3 | 149 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array4DExtensionType(_ArrayXDExtensionType):
ndims = 4 | 150 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Array5DExtensionType(_ArrayXDExtensionType):
ndims = 5 | 151 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class ArrayExtensionArray(pa.ExtensionArray):
def __array__(self):
zero_copy_only = _is_zero_copy_only(self.storage.type, unnest=True)
return self.to_numpy(zero_copy_only=zero_copy_only)
def __getitem__(self, i):
return self.storage[i]
def to_numpy(self, zero_copy_only=True):
... | 152 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
else:
shape = self.type.shape
ndims = self.type.ndims
arrays = []
first_dim_offsets = np.array([off.as_py() for off in storage.offsets])
for i, is_null in enumerate(null_mask):
if is_null:
arrays.append(np.nan)
... | 152 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
return numpy_arr
def to_pylist(self):
zero_copy_only = _is_zero_copy_only(self.storage.type, unnest=True)
numpy_arr = self.to_numpy(zero_copy_only=zero_copy_only)
if self.type.shape[0] is None and numpy_arr.dtype == object:
return [arr.tolist() for arr in numpy_arr.tolist()]
... | 152 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class PandasArrayExtensionDtype(PandasExtensionDtype):
_metadata = "value_type"
def __init__(self, value_type: Union["PandasArrayExtensionDtype", np.dtype]):
self._value_type = value_type
def __from_arrow__(self, array: Union[pa.Array, pa.ChunkedArray]):
if isinstance(array, pa.ChunkedArra... | 153 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class PandasArrayExtensionArray(PandasExtensionArray):
def __init__(self, data: np.ndarray, copy: bool = False):
self._data = data if not copy else np.array(data)
self._dtype = PandasArrayExtensionDtype(data.dtype)
def __array__(self, dtype=None):
"""
Convert to NumPy Array.
... | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
"""
if dtype == np.dtype(object):
out = np.empty(len(self._data), dtype=object)
for i in range(len(self._data)):
out[i] = self._data[i]
return out
if dtype is None:
return self._data
else:
return self._data.astype(dtype)... | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
@classmethod
def _from_sequence(
cls, scalars, dtype: Optional[PandasArrayExtensionDtype] = None, copy: bool = False
) -> "PandasArrayExtensionArray":
if len(scalars) > 1 and all(
isinstance(x, np.ndarray) and x.shape == scalars[0].shape and x.dtype == scalars[0].dtype for x in scala... | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
@classmethod
def _concat_same_type(cls, to_concat: Sequence_["PandasArrayExtensionArray"]) -> "PandasArrayExtensionArray":
if len(to_concat) > 1 and all(
va._data.shape == to_concat[0]._data.shape and va._data.dtype == to_concat[0]._data.dtype
for va in to_concat
):
... | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def __getitem__(self, item: Union[int, slice, np.ndarray]) -> Union[np.ndarray, "PandasArrayExtensionArray"]:
if isinstance(item, int):
return self._data[item]
return PandasArrayExtensionArray(self._data[item], copy=False) | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def take(
self, indices: Sequence_[int], allow_fill: bool = False, fill_value: bool = None
) -> "PandasArrayExtensionArray":
indices: np.ndarray = np.asarray(indices, dtype=int)
if allow_fill:
fill_value = (
self.dtype.na_value if fill_value is None else np.asarra... | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
took[mask] = [fill_value] * np.sum(mask)
return PandasArrayExtensionArray(took, copy=False) | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def __len__(self) -> int:
return len(self._data)
def __eq__(self, other) -> np.ndarray:
if not isinstance(other, PandasArrayExtensionArray):
raise NotImplementedError(f"Invalid type to compare to: {type(other)}")
return (self._data == other._data).all() | 154 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class ClassLabel:
"""Feature type for integer class labels.
There are 3 ways to define a `ClassLabel`, which correspond to the 3 arguments:
* `num_classes`: Create 0 to (num_classes-1) labels.
* `names`: List of label strings.
* `names_file`: File containing the list of labels.
Under the h... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
```py
>>> from datasets import Features, ClassLabel
>>> features = Features({'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'])})
>>> features
{'label': ClassLabel(names=['bad', 'ok', 'good'], id=None)}
```
"""
num_classes: InitVar[Optional[int]] = None # Pseudo-field: ignored... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def __post_init__(self, num_classes, names_file):
self.num_classes = num_classes
self.names_file = names_file
if self.names_file is not None and self.names is not None:
raise ValueError("Please provide either names or names_file but not both.")
# Set self.names
if sel... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
"ClassLabel number of names do not match the defined num_classes. "
f"Got {len(self.names)} names VS {self.num_classes} num_classes"
)
# Prepare mappings
self._int2str = [str(name) for name in self.names]
self._str2int = {name: i for i, name in enumerate(self._int2str... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def __call__(self):
return self.pa_type
def str2int(self, values: Union[str, Iterable]) -> Union[int, Iterable]:
"""Conversion class name `string` => `integer`.
Example:
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="tra... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def _strval2int(self, value: str) -> int:
failed_parse = False
value = str(value)
# first attempt - raw string value
int_value = self._str2int.get(value)
if int_value is None:
# second attempt - strip whitespace
int_value = self._str2int.get(value.strip())... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Regarding unknown/missing labels: passing negative integers raises `ValueError`.
Example:
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train")
>>> ds.features["label"].int2str(0)
'neg'
```
"""
if not... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def encode_example(self, example_data):
if self.num_classes is None:
raise ValueError(
"Trying to use ClassLabel feature with undefined number of class. "
"Please set ClassLabel.names or num_classes."
)
# If a string is given, convert to associate... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Args:
storage (`Union[pa.StringArray, pa.IntegerArray]`):
PyArrow array to cast.
Returns:
`pa.Int64Array`: Array in the `ClassLabel` arrow storage type.
"""
if isinstance(storage, pa.IntegerArray) and len(storage) > 0:
min_max = pc.min_max(sto... | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
@staticmethod
def _load_names_from_file(names_filepath):
with open(names_filepath, encoding="utf-8") as f:
return [name.strip() for name in f.read().split("\n") if name.strip()] # Filter empty names | 155 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Sequence:
"""Construct a list of feature from a single type or a dict of types.
Mostly here for compatiblity with tfds.
Args:
feature ([`FeatureType`]):
A list of features of a single type or a dictionary of types.
length (`int`):
Length of the sequence.
E... | 156 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
feature: Any
length: int = -1
id: Optional[str] = None
# Automatically constructed
dtype: ClassVar[str] = "list"
pa_type: ClassVar[Any] = None
_type: str = field(default="Sequence", init=False, repr=False) | 156 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class LargeList:
"""Feature type for large list data composed of child feature data type.
It is backed by `pyarrow.LargeListType`, which is like `pyarrow.ListType` but with 64-bit rather than 32-bit offsets.
Args:
feature ([`FeatureType`]):
Child feature data type of each item within t... | 157 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Features(dict):
"""A special dictionary that defines the internal structure of a dataset.
Instantiated with a dictionary of type `dict[str, FieldType]`, where keys are the desired column names,
and values are the type of that column.
`FieldType` can be one of the following:
- [`Value`] f... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
A [`Sequence`] with an internal dictionary feature will be automatically converted into a dictionary of
lists. This behavior is implemented to have a compatibility layer with the TensorFlow Datasets library but may be
un-wanted in some cases. If you don't want this behavior, you can use a Python `... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
- [`Array2D`], [`Array3D`], [`Array4D`] or [`Array5D`] feature for multidimensional arrays.
- [`Audio`] feature to store the absolute path to an audio file or a dictionary with the relative path
to an audio file ("path" key) and its bytes content ("bytes" key). This feature extracts the audio data.
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def __init__(*args, **kwargs):
# self not in the signature to allow passing self as a kwarg
if not args:
raise TypeError("descriptor '__init__' of 'Features' object needs an argument")
self, *args = args
super(Features, self).__init__(*args, **kwargs)
self._column_req... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Returns:
:obj:`pyarrow.DataType`
"""
return get_nested_type(self)
@property
def arrow_schema(self):
"""
Features schema.
Returns:
:obj:`pyarrow.Schema`
"""
hf_metadata = {"info": {"features": self.to_dict()}}
return pa.sch... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Returns:
[`Features`]
"""
# try to load features from the arrow schema metadata
metadata_features = Features()
if pa_schema.metadata is not None and "huggingface".encode("utf-8") in pa_schema.metadata:
metadata = json.loads(pa_schema.metadata["huggingface".encode(... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
@classmethod
def from_dict(cls, dic) -> "Features":
"""
Construct [`Features`] from dict.
Regenerate the nested feature object from a deserialized dict.
We use the `_type` key to infer the dataclass name of the feature `FieldType`.
It allows for a convenient constructor syn... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Example::
>>> Features.from_dict({'_type': {'dtype': 'string', 'id': None, '_type': 'Value'}})
{'_type': Value(dtype='string', id=None)}
"""
obj = generate_from_dict(dic)
return cls(**obj)
def to_dict(self):
return asdict(self)
def _to_yaml_list(self) ->... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
for list_type in ["large_list", "list", "sequence"]:
#
# list_type: -> list_type: int32
# dtype: int32 ->
#
if isinstance(feature.get(list_type), dict) and list(feature[list_type]) == ["dtype"]:
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
#
# class_label: -> class_label:
# names: -> names:
# - negative -> '0': negative
# - positive -> '1': positive
#
if isinsta... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def to_yaml_inner(obj: Union[dict, list]) -> dict:
if isinstance(obj, dict):
_type = obj.pop("_type", None)
if _type == "LargeList":
_feature = obj.pop("feature")
return simplify({"large_list": to_yaml_inner(_feature), **obj})
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
return simplify({"list": simplify(to_yaml_inner(obj[0]))})
elif isinstance(obj, tuple):
return to_yaml_inner(list(obj))
else:
raise TypeError(f"Expected a dict or a list but got {type(obj)}: {obj}") | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def to_yaml_types(obj: dict) -> dict:
if isinstance(obj, dict):
return {k: to_yaml_types(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [to_yaml_types(v) for v in obj]
elif isinstance(obj, tuple):
return to_yaml_types(li... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
for list_type in ["large_list", "list", "sequence"]:
#
# list_type: int32 -> list_type:
# -> dtype: int32
#
if isinstance(feature.get(list_type), str):
featu... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
#
# class_label: -> class_label:
# names: -> names:
# '0': negative -> - negative
# '1': positive -> - positive
#
if isinstanc... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def from_yaml_inner(obj: Union[dict, list]) -> Union[dict, list]:
if isinstance(obj, dict):
if not obj:
return {}
_type = next(iter(obj))
if _type == "large_list":
_feature = unsimplify(obj).pop(_type)
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Value(obj["dtype"])
return {**obj, "_type": "Value"}
except ValueError:
# e.g. Audio, Image, ArrayXD
return {"_type": snakecase_to_camelcase(obj["dtype"])}
else:
return... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
return cls.from_dict(from_yaml_inner(yaml_data))
def encode_example(self, example):
"""
Encode example into a format for Arrow.
Args:
example (`dict[str, Any]`):
Data in a Dataset row.
Returns:
`dict[str, Any]`
"""
example = ... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Args:
batch (`dict[str, list[Any]]`):
Data in a Dataset batch.
Returns:
`dict[str, list[Any]]`
"""
encoded_batch = {}
if set(batch) != set(self):
raise ValueError(f"Column mismatch between batch {set(batch)} and features {set(self)}")
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Args:
example (`dict[str, Any]`):
Dataset row data.
token_per_repo_id (`dict`, *optional*):
To access and decode audio or image files from private repositories on the Hub, you can pass
a dictionary `repo_id (str) -> token (bool or str)`.
R... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Returns:
`list[Any]`
"""
return (
[decode_nested_example(self[column_name], value) if value is not None else None for value in column]
if self._column_requires_decoding[column_name]
else column
)
def decode_batch(self, batch: dict, token_per_r... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
Returns:
`dict[str, list[Any]]`
"""
decoded_batch = {}
for column_name, column in batch.items():
decoded_batch[column_name] = (
[
decode_nested_example(self[column_name], value, token_per_repo_id=token_per_repo_id)
i... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train")
>>> copy_of_features = ds.features.copy()
>>> copy_of_features
{'label': ClassLabel(names=['neg', 'pos'], id=None),
'text': Value(dtype='string', id=None)}
```
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
>>> from datasets import Features, Sequence, Value
>>> # let's say we have two features with a different order of nested fields (for a and b for example)
>>> f1 = Features({"root": Sequence({"a": Value("string"), "b": Value("string")})})
>>> f2 = Features({"root": {"b": Sequence(Valu... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
def recursive_reorder(source, target, stack=""):
stack_position = " at " + stack[1:] if stack else ""
if isinstance(target, Sequence):
target = target.feature
if isinstance(target, dict):
target = {k: [v] for k, v in target.items()}
... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
elif isinstance(source, dict):
if not isinstance(target, dict):
raise ValueError(f"Type mismatch: between {source} and {target}" + stack_position)
if sorted(source) != sorted(target):
message = (
f"Keys mismatch: between {so... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
raise ValueError(f"Length mismatch: between {source} and {target}" + stack_position)
return [recursive_reorder(source[i], target[i], stack + ".<list>") for i in range(len(target))]
elif isinstance(source, LargeList):
if not isinstance(target, LargeList):
r... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
return Features(recursive_reorder(self, other))
def flatten(self, max_depth=16) -> "Features":
"""Flatten the features. Every dictionary column is removed and is replaced by
all the subfields it contains. The new fields are named by concatenating the
name of the original column and the subf... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("squad", split="train")
>>> ds.features.flatten()
{'answers.answer_start': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
'answers.text': Sequence(feature=Value(dtype='string', id=None), leng... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
elif isinstance(subfeature, Sequence) and isinstance(subfeature.feature, dict):
no_change = False
flattened.update(
{
f"{column_name}.{k}": Sequence(v) if not isinstance(v, dict) else [v]
for k, v in ... | 158 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/features.py |
class Translation:
"""`Feature` for translations with fixed languages per example.
Here for compatiblity with tfds.
Args:
languages (`dict`):
A dictionary for each example mapping string language codes to string translations.
Example:
```python
>>> # At construction time:
... | 159 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/translation.py |
def flatten(self) -> Union["FeatureType", Dict[str, "FeatureType"]]:
"""Flatten the Translation feature into a dictionary."""
from .features import Value
return {k: Value("string") for k in sorted(self.languages)} | 159 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/translation.py |
class TranslationVariableLanguages:
"""`Feature` for translations with variable languages per example.
Here for compatiblity with tfds.
Args:
languages (`dict`):
A dictionary for each example mapping string language codes to one or more string translations.
The languages pre... | 160 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/translation.py |
```python
>>> # At construction time:
>>> datasets.features.TranslationVariableLanguages(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
... 'en': 'the cat',
... 'fr': ['le chat', 'la chatte,']
... 'de': 'die katze'
... }
>>> # Tensor r... | 160 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/translation.py |
def __call__(self):
return pa.struct({"language": pa.list_(pa.string()), "translation": pa.list_(pa.string())})
def encode_example(self, translation_dict):
lang_set = set(self.languages)
if set(translation_dict) == {"language", "translation"}:
return translation_dict
eli... | 160 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/translation.py |
# Ensure translations are in ascending order by language code.
languages, translations = zip(*sorted(translation_tuples))
return {"language": languages, "translation": translations}
def flatten(self) -> Union["FeatureType", Dict[str, "FeatureType"]]:
"""Flatten the TranslationVariableLangu... | 160 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/translation.py |
class Audio:
"""Audio [`Feature`] to extract audio data from an audio file.
Input: The Audio feature accepts as input:
- A `str`: Absolute path to the audio file (i.e. random access is allowed).
- A `dict` with the keys:
- `path`: String with relative path of the audio file to the archive file... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
Args:
sampling_rate (`int`, *optional*):
Target sampling rate. If `None`, the native sampling rate is used.
mono (`bool`, defaults to `True`):
Whether to convert the audio signal to mono by averaging samples across
channels.
decode (`bool`, defaults to `True`)... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
```py
>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> ds[0]["audio"]
{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ...,
3.8356509e-05, -7.349... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
def encode_example(self, value: Union[str, bytes, dict]) -> dict:
"""Encode example into a format for Arrow.
Args:
value (`str` or `dict`):
Data passed as input to Audio feature. | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
Returns:
`dict`
"""
try:
import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files.
except ImportError as err:
raise ImportError("To support encoding audio data, please install 'soundfile'.") from err
if isinstance(va... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
if value.get("sampling_rate") is None:
# At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate
raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object")
if value.get("bytes"):
# If ... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
buffer = BytesIO(bytes())
sf.write(buffer, bytes_value, value["sampling_rate"], format="wav")
return {"bytes": buffer.getvalue(), "path": None}
else:
return {"bytes": None, "path": value.get("path")}
elif value.get("bytes") is not None or value.get("pa... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
- `path`: String with relative audio file path.
- `bytes`: Bytes of the audio file.
token_per_repo_id (`dict`, *optional*):
To access and decode
audio files from private repositories on the Hub, you can pass
a dictionary repo_id (`str`) -> toke... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
try:
import librosa
import soundfile as sf
except ImportError as err:
raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'.") from err
audio_format = xsplitext(path)[1][1:].lower() if path is not None else None
if not c... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
if file is None:
token_per_repo_id = token_per_repo_id or {}
source_url = path.split("::")[-1]
pattern = (
config.HUB_DATASETS_URL if source_url.startswith(config.HF_ENDPOINT) else config.HUB_DATASETS_HFFS_URL
)
try:
repo_id = s... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
array = array.T
if self.mono:
array = librosa.to_mono(array)
if self.sampling_rate and self.sampling_rate != sampling_rate:
array = librosa.resample(array, orig_sr=sampling_rate, target_sr=self.sampling_rate)
sampling_rate = self.sampling_rate
return {"path":... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
def cast_storage(self, storage: Union[pa.StringArray, pa.StructArray]) -> pa.StructArray:
"""Cast an Arrow array to the Audio arrow storage type.
The Arrow types that can be converted to the Audio pyarrow storage type are:
- `pa.string()` - it must contain the "path" data
- `pa.binary()... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
Returns:
`pa.StructArray`: Array in the Audio arrow storage type, that is
`pa.struct({"bytes": pa.binary(), "path": pa.string()})`
"""
if pa.types.is_string(storage.type):
bytes_array = pa.array([None] * len(storage), type=pa.binary())
storage = pa.Str... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
else:
bytes_array = pa.array([None] * len(storage), type=pa.binary())
if storage.type.get_field_index("path") >= 0:
path_array = storage.field("path")
else:
path_array = pa.array([None] * len(storage), type=pa.string())
storage = pa.Str... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
def embed_storage(self, storage: pa.StructArray) -> pa.StructArray:
"""Embed audio files into the Arrow array.
Args:
storage (`pa.StructArray`):
PyArrow array to embed.
Returns:
`pa.StructArray`: Array in the Audio arrow storage type, that is
... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
bytes_array = pa.array(
[
(path_to_bytes(x["path"]) if x["bytes"] is None else x["bytes"]) if x is not None else None
for x in storage.to_pylist()
],
type=pa.binary(),
)
path_array = pa.array(
[os.path.basename(path) if path... | 161 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/audio.py |
class Video:
"""
**Experimental.** Video [`Feature`] to read video data from a video file.
Input: The Video feature accepts as input:
- A `str`: Absolute path to the video file (i.e. random access is allowed).
- A `dict` with the keys:
- `path`: String with relative path of the video file ... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
```py
>>> from datasets import Dataset, Video
>>> ds = Dataset.from_dict({"video":["path/to/Screen Recording.mov"]}).cast_column("video", Video())
>>> ds.features["video"]
Video(decode=True, id=None)
>>> ds[0]["video"]
<decord.video_reader.VideoReader at 0x105525c70>
>>> ds = ds.cast_column(... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
Args:
value (`str`, `np.ndarray`, `VideoReader` or `dict`):
Data passed as input to Video feature.
Returns:
`dict` with "path" and "bytes" fields
"""
if config.DECORD_AVAILABLE:
from decord import VideoReader
else:
VideoRe... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
if isinstance(value, str):
return {"path": value, "bytes": None}
elif isinstance(value, bytes):
return {"path": None, "bytes": value}
elif isinstance(value, np.ndarray):
# convert the video array to bytes
return encode_np_array(value)
elif VideoRea... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
f"A video sample should have one of 'path' or 'bytes' but they are missing or None in {value}."
) | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
def decode_example(self, value: dict, token_per_repo_id=None) -> "VideoReader":
"""Decode example video file into video data.
Args:
value (`str` or `dict`):
A string with the absolute video file path, a dictionary with
keys:
- `path`: String ... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
else:
raise ImportError("To support decoding videos, please install 'decord'.")
if token_per_repo_id is None:
token_per_repo_id = {} | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
path, bytes_ = value["path"], value["bytes"]
if bytes_ is None:
if path is None:
raise ValueError(f"A video should have one of 'path' or 'bytes' but both are None in {value}.")
else:
if is_local_path(path):
video = VideoReader(path)
... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
bytes_ = BytesIO(f.read())
video = VideoReader(bytes_)
else:
video = VideoReader(BytesIO(bytes_))
return video | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
def flatten(self) -> Union["FeatureType", Dict[str, "FeatureType"]]:
"""If in the decodable state, return the feature itself, otherwise flatten the feature into a dictionary."""
from .features import Value
return (
self
if self.decode
else {
"... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
- `pa.string()` - it must contain the "path" data
- `pa.binary()` - it must contain the video bytes
- `pa.struct({"bytes": pa.binary()})`
- `pa.struct({"path": pa.string()})`
- `pa.struct({"bytes": pa.binary(), "path": pa.string()})` - order doesn't matter
- `pa.list(*)` - it mu... | 162 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/features/video.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.