text stringlengths 1 1.02k | class_index int64 0 271 | source stringclasses 76
values |
|---|---|---|
class GzipExtractor(MagicNumberBaseExtractor):
magic_numbers = [b"\x1f\x8b"]
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
with gzip.open(input_path, "rb") as gzip_file:
with open(output_path, "wb") as extracted_file:
shu... | 219 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class ZipExtractor(MagicNumberBaseExtractor):
magic_numbers = [
b"PK\x03\x04",
b"PK\x05\x06", # empty archive
b"PK\x07\x08", # spanned archive
]
@classmethod
def is_extractable(cls, path: Union[Path, str], magic_number: bytes = b"") -> bool:
if super().is_extractable(p... | 220 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
with open(path, "rb") as fp:
endrec = _EndRecData(fp)
if endrec:
if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
return True # Empty zipfiles are still zipfiles
elif endrec[_ECD_D... | 220 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
return False
except Exception: # catch all errors in case future python versions change the zipfile internals
return False | 220 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
os.makedirs(output_path, exist_ok=True)
with zipfile.ZipFile(input_path, "r") as zip_file:
zip_file.extractall(output_path)
zip_file.close() | 220 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class XzExtractor(MagicNumberBaseExtractor):
magic_numbers = [b"\xfd\x37\x7a\x58\x5a\x00"]
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
with lzma.open(input_path) as compressed_file:
with open(output_path, "wb") as extracted_file:
... | 221 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class RarExtractor(MagicNumberBaseExtractor):
magic_numbers = [b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"] # RAR_ID # RAR5_ID
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
if not config.RARFILE_AVAILABLE:
raise ImportError("Please pi... | 222 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class ZstdExtractor(MagicNumberBaseExtractor):
magic_numbers = [b"\x28\xb5\x2f\xfd"]
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
if not config.ZSTANDARD_AVAILABLE:
raise ImportError("Please pip install zstandard")
import zstand... | 223 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class Bzip2Extractor(MagicNumberBaseExtractor):
magic_numbers = [b"\x42\x5a\x68"]
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
with bz2.open(input_path, "rb") as compressed_file:
with open(output_path, "wb") as extracted_file:
... | 224 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class SevenZipExtractor(MagicNumberBaseExtractor):
magic_numbers = [b"\x37\x7a\xbc\xaf\x27\x1c"]
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
if not config.PY7ZR_AVAILABLE:
raise ImportError("Please pip install py7zr")
import py... | 225 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class Lz4Extractor(MagicNumberBaseExtractor):
magic_numbers = [b"\x04\x22\x4d\x18"]
@staticmethod
def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
if not config.LZ4_AVAILABLE:
raise ImportError("Please pip install lz4")
import lz4.frame
... | 226 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class Extractor:
# Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
extractors: Dict[str, Type[BaseExtractor]] = {
"tar": TarExtractor,
"gzip": GzipExtractor,
"zip": ZipExtractor,
"xz": XzExtractor,
"rar": RarExtract... | 227 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
@staticmethod
def _read_magic_number(path: Union[Path, str], magic_number_length: int):
try:
return MagicNumberBaseExtractor.read_magic_number(path, magic_number_length=magic_number_length)
except OSError:
return b""
@classmethod
def is_extractable(cls, path: Union[P... | 227 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
@classmethod
def infer_extractor_format(cls, path: Union[Path, str]) -> Optional[str]: # <Added version="2.4.0"/>
magic_number_max_length = cls._get_magic_number_max_length()
magic_number = cls._read_magic_number(path, magic_number_max_length)
for extractor_format, extractor in cls.extracto... | 227 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/extract.py |
class SharedMemoryContext:
# This is a context manager for creating shared memory that ensures cleanup happens even if a process is interrupted
# The process that creates shared memory is always the one responsible for unlinking it in the end
def __init__(self):
self.created_shms = []
self.o... | 228 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
def __exit__(self, exc_type, exc_value, traceback):
for shm in self.created_shms:
shm.close()
shm.unlink()
for shm in self.opened_shms:
shm.close() | 228 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
class NumpyMultiprocessingGenerator:
def __init__(
self,
dataset,
cols_to_retain,
collate_fn,
collate_fn_args,
columns_to_np_types,
output_signature,
shuffle,
batch_size,
drop_remainder,
num_workers,
):
self.dataset ... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
self.num_workers = num_workers
# Because strings are converted to characters, we need to add one extra dimension to the shape
self.columns_to_ranks = {
col: int(spec.shape.rank) if col not in self.string_columns else int(spec.shape.rank) + 1
for col, spec in output_signature.item... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
def __iter__(self):
# Make sure we only spawn workers if they have work to do
num_workers = min(self.num_workers, int(ceil(len(self.dataset) / self.batch_size)))
# Do the shuffling in iter so that it's done at the start of each epoch
per_worker_batches, final_batch, final_batch_worker = ... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
base_args = {
"dataset": self.dataset,
"cols_to_retain": self.cols_to_retain,
"collate_fn": self.collate_fn,
"collate_fn_args": self.collate_fn_args,
"columns_to_np_types": self.columns_to_np_types,
"columns_to_ranks": self.columns_to_ranks,
... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
worker_indices = per_worker_batches[i]
if i == final_batch_worker and final_batch is not None:
final_batch_arg = final_batch
else:
final_batch_arg = None
worker_kwargs = {
"worker_name": worker_name,
... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
end_signal_received = False
while not end_signal_received:
for i in range(num_workers):
if not array_ready_events[i].wait(timeout=60):
raise TimeoutError("Data loading worker timed out!")
array_ready_events[i].clear()
... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
# A future optimization, at the cost of some code complexity, could be to reuse shared memory
# between iterations, but this would require knowing in advance the maximum size, or having
# a system to only create a new memory block when a new maximum size is seen... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
create=False,
)
for col, shape in array_shapes.items()
}
# Copy everything out of shm because the memory
# will be unlinked by the child process at some point
arrays = ... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
def __call__(self):
return self
@staticmethod
def worker_loop(
dataset,
cols_to_retain,
collate_fn,
collate_fn_args,
columns_to_np_types,
columns_to_ranks,
string_columns,
indices,
extra_batch,
worker_name,
array_re... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
def send_batch_to_parent(indices):
batch = np_get_batch(
indices=indices,
dataset=dataset,
cols_to_retain=cols_to_retain,
collate_fn=collate_fn,
collate_fn_args=collate_fn_args,
columns_to_np_types=columns_to_np_... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
# Now begins the fun part where we start shovelling shared memory at the parent process
out_arrays = {}
with SharedMemoryContext() as batch_shm_ctx:
# The batch shared memory context exists only as long as it takes for the parent process
# to read everything, afte... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
out_arrays[col] = batch_shm_ctx.get_array(
f"{worker_name}_{col}", shape=array.shape, dtype=cast_dtype, create=True
)
out_arrays[col][:] = array | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
array_ready_event.set()
array_loaded_event.wait()
array_loaded_event.clear()
with SharedMemoryContext() as shm_ctx:
shape_arrays = {
col: shm_ctx.get_array(f"{worker_name}_{col}_shape", shape=(rank,), dtype=np.int64, create=False)
for ... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
@staticmethod
def distribute_batches(dataset, batch_size, drop_remainder, num_workers, shuffle):
indices = np.arange(len(dataset))
if shuffle:
np.random.shuffle(indices)
num_samples = len(indices)
# We distribute the batches so that reading from the workers in round-robin... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
per_worker_indices = np.split(indices, indices.shape[1], axis=1)
per_worker_indices = [np.squeeze(worker_indices, 1) for worker_indices in per_worker_indices]
# Distribute the final batches to the first workers
for i in range(len(final_batches)):
# len(final_batches) can be zero, and... | 229 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/tf_utils.py |
class VerificationMode(enum.Enum):
"""`Enum` that specifies which verification checks to run.
The default mode is `BASIC_CHECKS`, which will perform only rudimentary checks to avoid slowdowns
when generating/downloading a dataset for the first time.
The verification modes:
| ... | 230 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/info_utils.py |
ALL_CHECKS = "all_checks"
BASIC_CHECKS = "basic_checks"
NO_CHECKS = "no_checks" | 230 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/info_utils.py |
class OnAccess(enum.EnumMeta):
"""
Enum metaclass that calls a user-specified function whenever a member is accessed.
"""
def __getattribute__(cls, name):
obj = super().__getattribute__(name)
if isinstance(obj, enum.Enum) and obj._on_access:
obj._on_access()
return o... | 231 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/deprecation_utils.py |
class DeprecatedEnum(enum.Enum, metaclass=OnAccess):
"""
Enum class that calls `deprecate` method whenever a member is accessed.
"""
def __new__(cls, value):
member = object.__new__(cls)
member._value_ = value
member._on_access = member.deprecate
return member
@prop... | 232 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/utils/deprecation_utils.py |
class DownloadConfig:
"""Configuration for our cached path manager. | 233 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_config.py |
Attributes:
cache_dir (`str` or `Path`, *optional*):
Specify a cache directory to save the file to (overwrite the
default cache dir).
force_download (`bool`, defaults to `False`):
If `True`, re-dowload the file even if it's already cached in
the cache dir.... | 233 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_config.py |
was already extracted, re-extract the archive and override the folder where it was extracted.
delete_extracted (`bool`, defaults to `False`):
Whether to delete (or keep) the extracted files.
extract_on_the_fly (`bool`, defaults to `False`):
If `True`, extract compressed files whi... | 233 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_config.py |
Key/value pairs to be passed on to the dataset file-system backend, if any.
download_desc (`str`, *optional*):
A description to be displayed alongside with the progress bar while downloading the files.
disable_tqdm (`bool`, defaults to `False`):
Whether to disable the individual ... | 233 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_config.py |
cache_dir: Optional[Union[str, Path]] = None
force_download: bool = False
resume_download: bool = False
local_files_only: bool = False
proxies: Optional[Dict] = None
user_agent: Optional[str] = None
extract_compressed_file: bool = False
force_extract: bool = False
delete_extracted: bool ... | 233 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_config.py |
def __setattr__(self, name, value):
if name == "token" and getattr(self, "storage_options", None) is not None:
if "hf" not in self.storage_options:
self.storage_options["hf"] = {"token": value, "endpoint": config.HF_ENDPOINT}
elif getattr(self.storage_options["hf"], "toke... | 233 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_config.py |
class DownloadMode(enum.Enum):
"""`Enum` for how to treat pre-existing downloads and data.
The default mode is `REUSE_DATASET_IF_EXISTS`, which will reuse both
raw downloads and the prepared dataset if they exist.
The generations modes:
| | Downloads | Dataset ... | 234 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
class DownloadManager:
is_streaming = False
def __init__(
self,
dataset_name: Optional[str] = None,
data_dir: Optional[str] = None,
download_config: Optional[DownloadConfig] = None,
base_path: Optional[str] = None,
record_checksums=True,
):
"""Downloa... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
Args:
data_dir:
can be used to specify a manual directory to get the files from.
dataset_name (`str`):
name of dataset this instance will be used for. If
provided, downloads will contain which datasets they were used for.
download_confi... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
self._recorded_sizes_checksums: Dict[str, Dict[str, Optional[Union[int, str]]]] = {}
self.record_checksums = record_checksums
self.download_config = download_config or DownloadConfig()
self.downloaded_paths = {}
self.extracted_paths = {} | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
@property
def manual_dir(self):
return self._data_dir
@property
def downloaded_size(self):
"""Returns the total size of downloaded files."""
return sum(checksums_dict["num_bytes"] for checksums_dict in self._recorded_sizes_checksums.values())
def _record_sizes_checksums(self, u... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
By default, only one process is used for download. Pass customized `download_config.num_proc` to change this behavior.
Args:
url_or_urls (`str` or `list` or `dict`):
URL or `list` or `dict` of URLs to download. Each URL is a `str`.
Returns:
`str` or `list` or `d... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
start_time = datetime.now()
with stack_multiprocessing_download_progress_bars():
downloaded_path_or_paths = map_nested(
download_func,
url_or_urls,
map_tuple=True,
num_proc=download_config.num_proc,
desc="Downloading dat... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
start_time = datetime.now()
self._record_sizes_checksums(url_or_urls, downloaded_path_or_paths)
duration = datetime.now() - start_time
logger.info(f"Checksum Computation took {duration.total_seconds() // 60} min")
return downloaded_path_or_paths.data
def _download_batched(
... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
fs: fsspec.AbstractFileSystem
path = str(url_or_filenames[0])
if is_relative_path(path):
# append the relative path to the base_path
path = url_or_path_join(self._base_path, path)
fs, path = url_to_fs(path, **download_config.storage_options)
... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
return thread_map(
download_func,
url_or_filenames,
desc=download_config.download_desc or "Downloading",
unit="files",
position=multiprocessing.current_process()._identity[-1] # contains the ranks of subprocesses
if os.envi... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
def _download_single(self, url_or_filename: str, download_config: DownloadConfig) -> str:
url_or_filename = str(url_or_filename)
if is_relative_path(url_or_filename):
# append the relative path to the base_path
url_or_filename = url_or_path_join(self._base_path, url_or_filename)
... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
```py
>>> archive = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> files = dl_manager.iter_archive(archive)
```
"""
if hasattr(path_or_buf, "read"):
return ArchiveIterable.from_buf(path_or_buf)
... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
Args:
path_or_paths (path or `list` or `dict`):
Path of file to extract. Each path is a `str`.
Returns:
extracted_path(s): `str`, The extracted paths matching the given input
path_or_paths.
Example: | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
```py
>>> downloaded_files = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> extracted_files = dl_manager.extract(downloaded_files)
```
"""
download_config = self.download_config.copy()
download_config.... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
Is roughly equivalent to:
```
extracted_paths = dl_manager.extract(dl_manager.download(url_or_urls))
```
Args:
url_or_urls (`str` or `list` or `dict`):
URL or `list` or `dict` of URLs to download and extract. Each URL is a `str`.
Returns:
... | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
def manage_extracted_files(self):
if self.download_config.delete_extracted:
self.delete_extracted_files() | 235 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/download_manager.py |
class StreamingDownloadManager:
"""
Download manager that uses the "::" separator to navigate through (possibly remote) compressed archives.
Contrary to the regular `DownloadManager`, the `download` and `extract` methods don't actually download nor extract
data, but they rather return the path or url th... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
@property
def manual_dir(self):
return self._data_dir
def download(self, url_or_urls):
"""Normalize URL(s) of files to stream data from.
This is the lazy version of `DownloadManager.download` for streaming.
Args:
url_or_urls (`str` or `list` or `dict`):
... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
def _download_single(self, urlpath: str) -> str:
urlpath = str(urlpath)
if is_relative_path(urlpath):
# append the relative path to the base_path
urlpath = url_or_path_join(self._base_path, urlpath)
return urlpath
def extract(self, url_or_urls):
"""Add extrac... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
```py
>>> downloaded_files = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polaritydata.tar.gz')
>>> extracted_files = dl_manager.extract(downloaded_files)
```
"""
urlpaths = map_nested(self._extract, url_or_urls, map_tuple=True)
... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
def _extract(self, urlpath: str) -> str:
urlpath = str(urlpath)
protocol = _get_extraction_protocol(urlpath, download_config=self.download_config)
# get inner file: zip://train-00000.json.gz::https://foo.bar/data.zip -> zip://train-00000.json.gz
path = urlpath.split("::")[0]
exte... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
return urlpath
elif protocol in SINGLE_FILE_COMPRESSION_PROTOCOLS:
# there is one single file which is the uncompressed file
inner_file = os.path.basename(urlpath.split("::")[0])
inner_file = inner_file[: inner_file.rindex(".")] if "." in inner_file else inner_file
... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
def download_and_extract(self, url_or_urls):
"""Prepare given `url_or_urls` for streaming (add extraction protocol).
This is the lazy version of `DownloadManager.download_and_extract` for streaming.
Is equivalent to:
```
urls = dl_manager.extract(dl_manager.download(url_or_url... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
Yields:
`tuple[str, io.BufferedReader]`:
2-tuple (path_within_archive, file_object).
File object is opened in binary mode.
Example:
```py
>>> archive = dl_manager.download('https://storage.googleapis.com/seldon-datasets/sentence_polarity_v1/rt-polari... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
```py
>>> files = dl_manager.download_and_extract('https://huggingface.co/datasets/beans/resolve/main/data/train.zip')
>>> files = dl_manager.iter_files(files)
```
"""
return FilesIterable.from_urlpaths(urlpaths, download_config=self.download_config)
def manage_extracted_fil... | 236 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/download/streaming_download_manager.py |
class PolarsArrowExtractor(BaseArrowExtractor["pl.DataFrame", "pl.Series", "pl.DataFrame"]):
def extract_row(self, pa_table: pa.Table) -> "pl.DataFrame":
if config.POLARS_AVAILABLE:
if "polars" not in sys.modules:
import polars
else:
polars = sys.modul... | 237 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/polars_formatter.py |
def extract_batch(self, pa_table: pa.Table) -> "pl.DataFrame":
if config.POLARS_AVAILABLE:
if "polars" not in sys.modules:
import polars
else:
polars = sys.modules["polars"]
return polars.from_arrow(pa_table)
else:
raise Va... | 237 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/polars_formatter.py |
class PolarsFeaturesDecoder:
def __init__(self, features: Optional[Features]):
self.features = features
import polars as pl # noqa: F401 - import pl at initialization
def decode_row(self, row: "pl.DataFrame") -> "pl.DataFrame":
decode = (
{
column_name: no_o... | 238 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/polars_formatter.py |
def decode_column(self, column: "pl.Series", column_name: str) -> "pl.Series":
decode = (
no_op_if_value_is_null(partial(decode_nested_example, self.features[column_name]))
if self.features and column_name in self.features and self.features._column_requires_decoding[column_name]
... | 238 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/polars_formatter.py |
class PolarsFormatter(TensorFormatter[Mapping, "pl.DataFrame", Mapping]):
def __init__(self, features=None, **np_array_kwargs):
super().__init__(features=features)
self.np_array_kwargs = np_array_kwargs
self.polars_arrow_extractor = PolarsArrowExtractor
self.polars_features_decoder =... | 239 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/polars_formatter.py |
def format_batch(self, pa_table: pa.Table) -> "pl.DataFrame":
row = self.polars_arrow_extractor().extract_batch(pa_table)
row = self.polars_features_decoder.decode_batch(row)
return row | 239 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/polars_formatter.py |
class BaseArrowExtractor(Generic[RowFormat, ColumnFormat, BatchFormat]):
"""
Arrow extractor are used to extract data from pyarrow tables.
It makes it possible to extract rows, columns and batches.
These three extractions types have to be implemented.
"""
def extract_row(self, pa_table: pa.Tabl... | 240 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class SimpleArrowExtractor(BaseArrowExtractor[pa.Table, pa.Array, pa.Table]):
def extract_row(self, pa_table: pa.Table) -> pa.Table:
return pa_table
def extract_column(self, pa_table: pa.Table) -> pa.Array:
return pa_table.column(0)
def extract_batch(self, pa_table: pa.Table) -> pa.Table:
... | 241 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class PythonArrowExtractor(BaseArrowExtractor[dict, list, dict]):
def extract_row(self, pa_table: pa.Table) -> dict:
return _unnest(pa_table.to_pydict())
def extract_column(self, pa_table: pa.Table) -> list:
return pa_table.column(0).to_pylist()
def extract_batch(self, pa_table: pa.Table) ... | 242 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class NumpyArrowExtractor(BaseArrowExtractor[dict, np.ndarray, dict]):
def __init__(self, **np_array_kwargs):
self.np_array_kwargs = np_array_kwargs
def extract_row(self, pa_table: pa.Table) -> dict:
return _unnest(self.extract_batch(pa_table))
def extract_column(self, pa_table: pa.Table) ... | 243 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def _arrow_array_to_numpy(self, pa_array: pa.Array) -> np.ndarray:
if isinstance(pa_array, pa.ChunkedArray):
if isinstance(pa_array.type, _ArrayXDExtensionType):
# don't call to_pylist() to preserve dtype of the fixed-size array
zero_copy_only = _is_zero_copy_only(pa_... | 243 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
# don't call to_pylist() to preserve dtype of the fixed-size array
zero_copy_only = _is_zero_copy_only(pa_array.type.storage_dtype, unnest=True)
array: List = pa_array.to_numpy(zero_copy_only=zero_copy_only)
else:
zero_copy_only = _is_zero_copy_only(pa_array.t... | 243 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
if len(array) > 0:
if any(
(isinstance(x, np.ndarray) and (x.dtype == object or x.shape != array[0].shape))
or (isinstance(x, float) and np.isnan(x))
for x in array
):
if np.lib.NumpyVersion(np.__version__) >= "2.0.0b1":
... | 243 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class PandasArrowExtractor(BaseArrowExtractor[pd.DataFrame, pd.Series, pd.DataFrame]):
def extract_row(self, pa_table: pa.Table) -> pd.DataFrame:
return pa_table.slice(length=1).to_pandas(types_mapper=pandas_types_mapper)
def extract_column(self, pa_table: pa.Table) -> pd.Series:
return pa_tabl... | 244 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class PythonFeaturesDecoder:
def __init__(
self, features: Optional[Features], token_per_repo_id: Optional[Dict[str, Union[str, bool, None]]] = None
):
self.features = features
self.token_per_repo_id = token_per_repo_id
def decode_row(self, row: dict) -> dict:
return self.fe... | 245 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class PandasFeaturesDecoder:
def __init__(self, features: Optional[Features]):
self.features = features
def decode_row(self, row: pd.DataFrame) -> pd.DataFrame:
decode = (
{
column_name: no_op_if_value_is_null(partial(decode_nested_example, feature))
... | 246 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def decode_column(self, column: pd.Series, column_name: str) -> pd.Series:
decode = (
no_op_if_value_is_null(partial(decode_nested_example, self.features[column_name]))
if self.features and column_name in self.features and self.features._column_requires_decoding[column_name]
... | 246 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class LazyDict(MutableMapping):
"""A dictionary backed by Arrow data. The values are formatted on-the-fly when accessing the dictionary."""
def __init__(self, pa_table: pa.Table, formatter: "Formatter"):
self.pa_table = pa_table
self.formatter = formatter
self.data = {key: None for key... | 247 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def __iter__(self):
return iter(self.data)
def __contains__(self, key):
return key in self.data
def __repr__(self):
self._format_all()
return repr(self.data)
if config.PY_VERSION >= version.parse("3.9"):
# merging with the union ("|") operator is supported in Pytho... | 247 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def __ror__(self, other):
if isinstance(other, LazyDict):
inst = self.copy()
other = other.copy()
other._format_all()
inst.keys_to_format -= other.data.keys()
inst.data = other.data | inst.data
return inst
... | 247 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def __copy__(self):
# Identical to `UserDict.__copy__`
inst = self.__class__.__new__(self.__class__)
inst.__dict__.update(self.__dict__)
# Create a copy and avoid triggering descriptors
inst.__dict__["data"] = self.__dict__["data"].copy()
inst.__dict__["keys_to_format"] =... | 247 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class LazyRow(LazyDict):
def format(self, key):
return self.formatter.format_column(self.pa_table.select([key]))[0] | 248 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class LazyBatch(LazyDict):
def format(self, key):
return self.formatter.format_column(self.pa_table.select([key])) | 249 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class Formatter(Generic[RowFormat, ColumnFormat, BatchFormat]):
"""
A formatter is an object that extracts and formats data from pyarrow tables.
It defines the formatting for rows, columns and batches.
"""
simple_arrow_extractor = SimpleArrowExtractor
python_arrow_extractor = PythonArrowExtract... | 250 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def __call__(self, pa_table: pa.Table, query_type: str) -> Union[RowFormat, ColumnFormat, BatchFormat]:
if query_type == "row":
return self.format_row(pa_table)
elif query_type == "column":
return self.format_column(pa_table)
elif query_type == "batch":
return... | 250 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class TensorFormatter(Formatter[RowFormat, ColumnFormat, BatchFormat]):
def recursive_tensorize(self, data_struct: dict):
raise NotImplementedError | 251 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class ArrowFormatter(Formatter[pa.Table, pa.Array, pa.Table]):
def format_row(self, pa_table: pa.Table) -> pa.Table:
return self.simple_arrow_extractor().extract_row(pa_table)
def format_column(self, pa_table: pa.Table) -> pa.Array:
return self.simple_arrow_extractor().extract_column(pa_table)
... | 252 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class PythonFormatter(Formatter[Mapping, list, Mapping]):
def __init__(self, features=None, lazy=False, token_per_repo_id=None):
super().__init__(features, token_per_repo_id)
self.lazy = lazy
def format_row(self, pa_table: pa.Table) -> Mapping:
if self.lazy:
return LazyRow(p... | 253 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class PandasFormatter(Formatter[pd.DataFrame, pd.Series, pd.DataFrame]):
def format_row(self, pa_table: pa.Table) -> pd.DataFrame:
row = self.pandas_arrow_extractor().extract_row(pa_table)
row = self.pandas_features_decoder.decode_row(row)
return row
def format_column(self, pa_table: pa... | 254 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class CustomFormatter(Formatter[dict, ColumnFormat, dict]):
"""
A user-defined custom formatter function defined by a ``transform``.
The transform must take as input a batch of data extracted for an arrow table using the python extractor,
and return a batch.
If the output batch is not a dict, then o... | 255 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def format_row(self, pa_table: pa.Table) -> dict:
formatted_batch = self.format_batch(pa_table)
try:
return _unnest(formatted_batch)
except Exception as exc:
raise TypeError(
f"Custom formatting function must return a dict of sequences to be able to pick a... | 255 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def format_column(self, pa_table: pa.Table) -> ColumnFormat:
formatted_batch = self.format_batch(pa_table)
if hasattr(formatted_batch, "keys"):
if len(formatted_batch.keys()) > 1:
raise TypeError(
"Tried to query a column but the custom formatting function... | 255 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
def format_batch(self, pa_table: pa.Table) -> dict:
batch = self.python_arrow_extractor().extract_batch(pa_table)
batch = self.python_features_decoder.decode_batch(batch)
return self.transform(batch) | 255 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/formatting.py |
class TorchFormatter(TensorFormatter[Mapping, "torch.Tensor", Mapping]):
def __init__(self, features=None, token_per_repo_id=None, **torch_tensor_kwargs):
super().__init__(features=features, token_per_repo_id=token_per_repo_id)
self.torch_tensor_kwargs = torch_tensor_kwargs
import torch # n... | 256 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/formatting/torch_formatter.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.