





"""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 					a__    (    _SCREAMING_SNAKE_CASE			):




		"""simple docstring"""


		UpperCamelCase      =		np.inf

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

		_visit(_A     ,		_A			)

		return None if batch_size is np.inf else batch_size





class 				_lowerCamelCase					(				lowerCamelCase__       ):


						def __init__(self      ,							__a      ,							__a = None      ,							__a = None      ,							__a = None      ,							__a = False      ,							__a = False      ,							__a = None      ,							**__a      ,							)       ->      List[Any]:
								super().__init__(
								    lowercase_      ,							split=lowercase_      ,							features=lowercase_      ,							cache_dir=lowercase_      ,							keep_in_memory=lowercase_      ,							streaming=lowercase_      ,							num_proc=lowercase_      ,							**lowercase_      ,							)
								UpperCamelCase      =		path_or_paths if isinstance(lowercase_      ,							lowercase_						) else {self.split: path_or_paths}
								UpperCamelCase      =		_PACKAGED_DATASETS_MODULES["parquet"][1]
								UpperCamelCase      =		Parquet(
								    cache_dir=lowercase_      ,							data_files=lowercase_      ,							features=lowercase_      ,							hash=lowercase_      ,							**lowercase_      ,							)




						def 			snake_case_      (self						)       ->      Dict:






								if self.streaming:
										UpperCamelCase      =		self.builder.as_streaming_dataset(split=self.split						)
								# Build regular (map-style) dataset
								else:
										UpperCamelCase      =		None
										UpperCamelCase      =		None
										UpperCamelCase      =		None
										UpperCamelCase      =		None

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





class 				_lowerCamelCase					:


						def __init__(self      ,							__a      ,							__a      ,							__a = None      ,							**__a      ,							)       ->      Dict:
								UpperCamelCase      =		dataset
								UpperCamelCase      =		path_or_buf
								UpperCamelCase      =		batch_size or get_writer_batch_size(dataset.features						)
								UpperCamelCase      =		parquet_writer_kwargs


						def 			snake_case_      (self						)       ->      int:
								UpperCamelCase      =		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:
												UpperCamelCase      =		self._write(file_obj=lowercase_      ,							batch_size=lowercase_      ,							**self.parquet_writer_kwargs						)
								else:
										UpperCamelCase      =		self._write(file_obj=self.path_or_buf      ,							batch_size=lowercase_      ,							**self.parquet_writer_kwargs						)
								return written




						def 			snake_case_      (self      ,							__a      ,							__a      ,							**__a						)       ->      int:
								UpperCamelCase      =		0
								UpperCamelCase      =		parquet_writer_kwargs.pop("path_or_buf"      ,							lowercase_						)
								UpperCamelCase      =		self.dataset.features.arrow_schema

								UpperCamelCase      =		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"      ,							):
										UpperCamelCase      =		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,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCamelCase           =					{'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']}

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

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					['''XLNetTokenizerFast''']

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					[
           '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''XLNetForMultipleChoice''',
           '''XLNetForQuestionAnswering''',
           '''XLNetForQuestionAnsweringSimple''',
           '''XLNetForSequenceClassification''',
           '''XLNetForTokenClassification''',
           '''XLNetLMHeadModel''',
           '''XLNetModel''',
           '''XLNetPreTrainedModel''',
           '''load_tf_weights_in_xlnet''',
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					[
           '''TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''TFXLNetForMultipleChoice''',
           '''TFXLNetForQuestionAnsweringSimple''',
           '''TFXLNetForSequenceClassification''',
           '''TFXLNetForTokenClassification''',
           '''TFXLNetLMHeadModel''',
           '''TFXLNetMainLayer''',
           '''TFXLNetModel''',
           '''TFXLNetPreTrainedModel''',
       ]


if TYPE_CHECKING:
       from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig

       try:
              if not is_sentencepiece_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_xlnet import XLNetTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_xlnet_fast import XLNetTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_xlnet import (
                  XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  XLNetForMultipleChoice,
                  XLNetForQuestionAnswering,
                  XLNetForQuestionAnsweringSimple,
                  XLNetForSequenceClassification,
                  XLNetForTokenClassification,
                  XLNetLMHeadModel,
                  XLNetModel,
                  XLNetPreTrainedModel,
                  load_tf_weights_in_xlnet,
              )

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_xlnet import (
                  TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  TFXLNetForMultipleChoice,
                  TFXLNetForQuestionAnsweringSimple,
                  TFXLNetForSequenceClassification,
                  TFXLNetForTokenClassification,
                  TFXLNetLMHeadModel,
                  TFXLNetMainLayer,
                  TFXLNetModel,
                  TFXLNetPreTrainedModel,
              )

else:
       import sys

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