






"""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 						lowercase    (				__snake_case				: Features	):
		lowercase_ : List[Any]							       =   np.inf

		def set_batch_size(__snake_case				: FeatureType	) -> None:
				nonlocal batch_size
				if isinstance(_lowerCamelCase		,					_lowerCamelCase	):
						lowercase_ : Any							       =   min(_lowerCamelCase		,					config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS	)
				elif isinstance(_lowerCamelCase		,					_lowerCamelCase	):
						lowercase_ : Union[str, Any]							       =   min(_lowerCamelCase		,					config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS	)
				elif isinstance(_lowerCamelCase		,					_lowerCamelCase	) and feature.dtype == "binary":
						lowercase_ : Dict							       =   min(_lowerCamelCase		,					config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS	)

		_visit(_lowerCamelCase		,					_lowerCamelCase	)

		return None if batch_size is np.inf else batch_size





class 					_UpperCAmelCase       ( __A							):




					def __init__(				self     :						List[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     :						Union[str, Any]    ,						)  ->  Union[str, Any]:
							super().__init__(
							    lowercase_    ,						split=lowercase_    ,						features=lowercase_    ,						cache_dir=lowercase_    ,						keep_in_memory=lowercase_    ,						streaming=lowercase_    ,						num_proc=lowercase_    ,						**lowercase_    ,						)
							lowercase_ : List[str]							       =   path_or_paths if isinstance(lowercase_    ,						lowercase_   ) else {self.split: path_or_paths}
							lowercase_ : Optional[int]							       =   _PACKAGED_DATASETS_MODULES["parquet"][1]
							lowercase_ : Union[str, Any]							       =   Parquet(
							    cache_dir=lowercase_    ,						data_files=lowercase_    ,						features=lowercase_    ,						hash=lowercase_    ,						**lowercase_    ,						)






					def   A  (				self     :						Tuple   )  ->  Dict:
							# Build iterable dataset
							if self.streaming:
									lowercase_ : List[Any]							       =   self.builder.as_streaming_dataset(split=self.split   )
							# Build regular (map-style) dataset
							else:
									lowercase_ : Any							       =   None
									lowercase_ : int							       =   None
									lowercase_ : Dict							       =   None
									lowercase_ : Union[str, Any]							       =   None

									self.builder.download_and_prepare(
									    download_config=lowercase_    ,						download_mode=lowercase_    ,						verification_mode=lowercase_    ,						base_path=lowercase_    ,						num_proc=self.num_proc    ,						)
									lowercase_ : Optional[Any]							       =   self.builder.as_dataset(
									    split=self.split    ,						verification_mode=lowercase_    ,						in_memory=self.keep_in_memory   )
							return dataset





class 					_UpperCAmelCase       :




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




					def   A  (				self     :						List[Any]   )  ->  int:
							lowercase_ : Tuple							       =   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:
											lowercase_ : str							       =   self._write(file_obj=lowercase_    ,						batch_size=lowercase_    ,						**self.parquet_writer_kwargs   )
							else:
									lowercase_ : Tuple							       =   self._write(file_obj=self.path_or_buf    ,						batch_size=lowercase_    ,						**self.parquet_writer_kwargs   )
							return written






					def   A  (				self     :						Union[str, Any]    ,						A     :						BinaryIO    ,						A     :						int    ,						**A     :						Optional[int]   )  ->  int:
							lowercase_ : List[Any]							       =   0
							lowercase_ : List[Any]							       =   parquet_writer_kwargs.pop('''path_or_buf'''    ,						lowercase_   )
							lowercase_ : List[Any]							       =   self.dataset.features.arrow_schema

							lowercase_ : Optional[Any]							       =   pq.ParquetWriter(lowercase_    ,						schema=lowercase_    ,						**lowercase_   )

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




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available


UpperCamelCase  							=						{}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase  							=						['''GPTSw3Tokenizer''']


if TYPE_CHECKING:
      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_gpt_swa import GPTSwaTokenizer

else:
      import sys

      UpperCamelCase  							=						_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



