




'''simple docstring'''





import os
from typing import BinaryIO, Optional, Union

import numpy as np
import pyarrow.parquet as pq

from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			SCREAMING_SNAKE_CASE           =					np.inf

			def set_batch_size(SCREAMING_SNAKE_CASE   ) -> None:
						nonlocal batch_size
						if isinstance(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
									SCREAMING_SNAKE_CASE           =					min(SCREAMING_SNAKE_CASE					,	config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS   )
						elif isinstance(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
									SCREAMING_SNAKE_CASE           =					min(SCREAMING_SNAKE_CASE					,	config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS   )
						elif isinstance(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ) and feature.dtype == "binary":
									SCREAMING_SNAKE_CASE           =					min(SCREAMING_SNAKE_CASE					,	config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS   )

			_visit(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   )

			return None if batch_size is np.inf else batch_size




class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							def __init__(					self       :	str       ,     a       :	NestedDataStructureLike[PathLike]       ,     a       :	Optional[NamedSplit] = None       ,     a       :	Optional[Features] = None       ,     a       :	str = None       ,     a       :	bool = False       ,     a       :	bool = False       ,     a       :	Optional[int] = None       ,     **a       :	Any       ,     )			->					Union[str, Any]:
										super().__init__(
										    a       ,     split=a       ,     features=a       ,     cache_dir=a       ,     keep_in_memory=a       ,     streaming=a       ,     num_proc=a       ,     **a       ,     )
										SCREAMING_SNAKE_CASE           =					path_or_paths if isinstance(a       ,     a			) else {self.split: path_or_paths}
										SCREAMING_SNAKE_CASE           =					_PACKAGED_DATASETS_MODULES["""parquet"""][1]
										SCREAMING_SNAKE_CASE           =					Parquet(
										    cache_dir=a       ,     data_files=a       ,     features=a       ,     hash=a       ,     **a       ,     )







							def    _UpperCAmelCase     (					self       :	List[Any]			)			->					List[Any]:
										# Build iterable dataset
										if self.streaming:
													SCREAMING_SNAKE_CASE           =					self.builder.as_streaming_dataset(split=self.split			)
										# Build regular (map-style) dataset
										else:
													SCREAMING_SNAKE_CASE           =					None
													SCREAMING_SNAKE_CASE           =					None
													SCREAMING_SNAKE_CASE           =					None
													SCREAMING_SNAKE_CASE           =					None

													self.builder.download_and_prepare(
													    download_config=a       ,     download_mode=a       ,     verification_mode=a       ,     base_path=a       ,     num_proc=self.num_proc       ,     )
													SCREAMING_SNAKE_CASE           =					self.builder.as_dataset(
													    split=self.split       ,     verification_mode=a       ,     in_memory=self.keep_in_memory			)
										return dataset





class 			UpperCAmelCase_      :




							'''simple docstring'''



							def __init__(					self       :	Optional[Any]       ,     a       :	Dataset       ,     a       :	Union[PathLike, BinaryIO]       ,     a       :	Optional[int] = None       ,     **a       :	str       ,     )			->					Optional[int]:
										SCREAMING_SNAKE_CASE           =					dataset
										SCREAMING_SNAKE_CASE           =					path_or_buf
										SCREAMING_SNAKE_CASE           =					batch_size or get_writer_batch_size(dataset.features			)
										SCREAMING_SNAKE_CASE           =					parquet_writer_kwargs





							def    _UpperCAmelCase     (					self       :	List[Any]			)			->					int:
										SCREAMING_SNAKE_CASE           =					self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE

										if isinstance(self.path_or_buf       ,     (str, bytes, os.PathLike)			):
													with open(self.path_or_buf       ,     """wb+"""			) as buffer:
																SCREAMING_SNAKE_CASE           =					self._write(file_obj=a       ,     batch_size=a       ,     **self.parquet_writer_kwargs			)
										else:
													SCREAMING_SNAKE_CASE           =					self._write(file_obj=self.path_or_buf       ,     batch_size=a       ,     **self.parquet_writer_kwargs			)
										return written







							def    _UpperCAmelCase     (					self       :	Tuple       ,     a       :	BinaryIO       ,     a       :	int       ,     **a       :	Optional[int]			)			->					int:
										SCREAMING_SNAKE_CASE           =					0
										SCREAMING_SNAKE_CASE           =					parquet_writer_kwargs.pop("""path_or_buf"""       ,     a			)
										SCREAMING_SNAKE_CASE           =					self.dataset.features.arrow_schema

										SCREAMING_SNAKE_CASE           =					pq.ParquetWriter(a       ,     schema=a       ,     **a			)

										for offset in logging.tqdm(
										    range(0       ,     len(self.dataset			)       ,     a			)       ,     unit="""ba"""       ,     disable=not logging.is_progress_bar_enabled()       ,     desc="""Creating parquet from Arrow format"""       ,     ):
													SCREAMING_SNAKE_CASE           =					query_table(
													    table=self.dataset._data       ,     key=slice(a       ,     offset + batch_size			)       ,     indices=self.dataset._indices if self.dataset._indices is not None else None       ,     )
													writer.write_table(a			)
													written += batch.nbytes
										writer.close()
										return written












import importlib
import shutil
import threading
import warnings
from typing import List

import fsspec
import fsspec.asyn

from . import compression
from .hffilesystem import HfFileSystem


__A						:							Tuple							=  importlib.util.find_spec("""s3fs""") is not None

if _has_safs:
		from .safilesystem import SaFileSystem  # noqa: F401

__A						:							List[compression.BaseCompressedFileFileSystem]							=  [
    compression.BzaFileSystem,
    compression.GzipFileSystem,
    compression.LzaFileSystem,
    compression.XzFileSystem,
    compression.ZstdFileSystem,
]

# Register custom filesystems
for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]:
		if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class:
				warnings.warn(f'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''')
		fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True)
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if "://" in dataset_path:
						SCREAMING_SNAKE_CASE           =					dataset_path.split("""://"""   )[1]
			return dataset_path
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			if fs is not None and fs.protocol != "file":
						return True
			else:
						return False
def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''
			SCREAMING_SNAKE_CASE           =					not is_remote_filesystem(SCREAMING_SNAKE_CASE   )
			if is_local:
						# LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory
						shutil.move(fs._strip_protocol(SCREAMING_SNAKE_CASE   )					,	fs._strip_protocol(SCREAMING_SNAKE_CASE   )   )
			else:
						fs.mv(SCREAMING_SNAKE_CASE					,	SCREAMING_SNAKE_CASE					,	recursive=SCREAMING_SNAKE_CASE   )




def 					lowerCamelCase_    (    ):
			'''simple docstring'''
			if hasattr(fsspec.asyn					,	"""reset_lock"""   ):
						# for future fsspec>2022.05.0
						fsspec.asyn.reset_lock()
			else:
						SCREAMING_SNAKE_CASE           =					None
						SCREAMING_SNAKE_CASE           =					None
						SCREAMING_SNAKE_CASE           =					threading.Lock()






