





'''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_      (		lowercase__						)   ->Optional[int]:
						_snake_case:   int  					=		np.inf

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

						_visit(lowercase__				,  lowercase__						)

						return None if batch_size is np.inf else batch_size







class 			lowerCamelCase					(						__UpperCAmelCase  ):


					def __init__(					self	:  str       ,     __snake_case	:  NestedDataStructureLike[PathLike]       ,     __snake_case	:  Optional[NamedSplit] = None       ,     __snake_case	:  Optional[Features] = None       ,     __snake_case	:  str = None       ,     __snake_case	:  bool = False       ,     __snake_case	:  bool = False       ,     __snake_case	:  Optional[int] = None       ,     **__snake_case	:  List[str]       ,     ):





											'''simple docstring'''





											super().__init__(
											    __snake_case       ,     split=__snake_case       ,     features=__snake_case       ,     cache_dir=__snake_case       ,     keep_in_memory=__snake_case       ,     streaming=__snake_case       ,     num_proc=__snake_case       ,     **__snake_case       ,     )
											_snake_case:   Optional[Any]  					=		path_or_paths if isinstance(__snake_case       ,     __snake_case       ) else {self.split: path_or_paths}
											_snake_case:   List[str]  					=		_PACKAGED_DATASETS_MODULES['parquet'][1]
											_snake_case:   List[str]  					=		Parquet(
											    cache_dir=__snake_case       ,     data_files=__snake_case       ,     features=__snake_case       ,     hash=__snake_case       ,     **__snake_case       ,     )




					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											if self.streaming:
																	_snake_case:   Tuple  					=		self.builder.as_streaming_dataset(split=self.split       )
											# Build regular (map-style) dataset
											else:
																	_snake_case:   Union[str, Any]  					=		None
																	_snake_case:   Tuple  					=		None
																	_snake_case:   Tuple  					=		None
																	_snake_case:   Dict  					=		None

																	self.builder.download_and_prepare(
																	    download_config=__snake_case       ,     download_mode=__snake_case       ,     verification_mode=__snake_case       ,     base_path=__snake_case       ,     num_proc=self.num_proc       ,     )
																	_snake_case:   int  					=		self.builder.as_dataset(
																	    split=self.split       ,     verification_mode=__snake_case       ,     in_memory=self.keep_in_memory       )
											return dataset







class 			lowerCamelCase					:


					def __init__(					self	:  Any       ,     __snake_case	:  Dataset       ,     __snake_case	:  Union[PathLike, BinaryIO]       ,     __snake_case	:  Optional[int] = None       ,     **__snake_case	:  int       ,     ):





											'''simple docstring'''





											_snake_case:   int  					=		dataset
											_snake_case:   Dict  					=		path_or_buf
											_snake_case:   Optional[Any]  					=		batch_size or get_writer_batch_size(dataset.features       )
											_snake_case:   Optional[Any]  					=		parquet_writer_kwargs


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		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:
																							_snake_case:   Dict  					=		self._write(file_obj=__snake_case       ,     batch_size=__snake_case       ,     **self.parquet_writer_kwargs       )
											else:
																	_snake_case:   Union[str, Any]  					=		self._write(file_obj=self.path_or_buf       ,     batch_size=__snake_case       ,     **self.parquet_writer_kwargs       )
											return written




					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  BinaryIO       ,     __snake_case	:  int       ,     **__snake_case	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		0
											_snake_case:   Union[str, Any]  					=		parquet_writer_kwargs.pop('path_or_buf'       ,     __snake_case       )
											_snake_case:   List[Any]  					=		self.dataset.features.arrow_schema

											_snake_case:   Dict  					=		pq.ParquetWriter(__snake_case       ,     schema=__snake_case       ,     **__snake_case       )

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












'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available


A   : Dict             =			{'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		A   : int             =			['SpeechEncoderDecoderModel']

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		A   : Union[str, Any]             =			['FlaxSpeechEncoderDecoderModel']

if TYPE_CHECKING:
		from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel

else:
		import sys

		A   : int             =			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





