






'''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 		__SCREAMING_SNAKE_CASE       (	_UpperCamelCase				):


   """simple docstring"""




   lowercase_						:     int							     =  np.inf

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

   _visit(_UpperCamelCase    ,		_UpperCamelCase				)

   return None if batch_size is np.inf else batch_size


class 							_UpperCAmelCase    (		snake_case      ):




    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	:							Union[str, Any]	,  ):






       '''simple docstring'''






       super().__init__(
           a	,  split=a	,  features=a	,  cache_dir=a	,  keep_in_memory=a	,  streaming=a	,  num_proc=a	,  **a	,  )
       lowercase_						:     Tuple							     =  path_or_paths if isinstance(a	,  a      ) else {self.split: path_or_paths}
       lowercase_						:     Optional[int]							     =  _PACKAGED_DATASETS_MODULES["parquet"][1]
       lowercase_						:     Optional[Any]							     =  Parquet(
           cache_dir=a	,  data_files=a	,  features=a	,  hash=a	,  **a	,  )





    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       if self.streaming:
          lowercase_						:     Dict							     =  self.builder.as_streaming_dataset(split=self.split      )
       # Build regular (map-style) dataset
       else:
          lowercase_						:     List[str]							     =  None
          lowercase_						:     Optional[int]							     =  None
          lowercase_						:     Optional[Any]							     =  None
          lowercase_						:     Optional[Any]							     =  None

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


class 							_UpperCAmelCase    :




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






       '''simple docstring'''






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




    def 					lowerCAmelCase__					(      self	:							Dict      ):






       '''simple docstring'''






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





    def 					lowerCAmelCase__					(      self	:							Optional[Any]	,  a	:							BinaryIO	,  a	:							int	,  **a	:							List[str]      ):






       '''simple docstring'''






       lowercase_						:     Union[str, Any]							     =  0
       lowercase_						:     Dict							     =  parquet_writer_kwargs.pop("path_or_buf"	,  a      )
       lowercase_						:     Optional[Any]							     =  self.dataset.features.arrow_schema

       lowercase_						:     int							     =  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"	,  ):
          lowercase_						:     int							     =  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












'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


UpperCamelCase__			=      {
    'configuration_layoutlmv3': [
        'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'LayoutLMv3Config',
        'LayoutLMv3OnnxConfig',
    ],
    'processing_layoutlmv3': ['LayoutLMv3Processor'],
    'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'],
}

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

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      [
     'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST',
     'LayoutLMv3ForQuestionAnswering',
     'LayoutLMv3ForSequenceClassification',
     'LayoutLMv3ForTokenClassification',
     'LayoutLMv3Model',
     'LayoutLMv3PreTrainedModel',
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      [
     'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TFLayoutLMv3ForQuestionAnswering',
     'TFLayoutLMv3ForSequenceClassification',
     'TFLayoutLMv3ForTokenClassification',
     'TFLayoutLMv3Model',
     'TFLayoutLMv3PreTrainedModel',
 ]

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      ['LayoutLMv3FeatureExtractor']
 UpperCamelCase__			=      ['LayoutLMv3ImageProcessor']


if TYPE_CHECKING:
 from .configuration_layoutlmva import (
     LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
     LayoutLMvaConfig,
     LayoutLMvaOnnxConfig,
 )
 from .processing_layoutlmva import LayoutLMvaProcessor
 from .tokenization_layoutlmva import LayoutLMvaTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_layoutlmva import (
      LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      LayoutLMvaForQuestionAnswering,
      LayoutLMvaForSequenceClassification,
      LayoutLMvaForTokenClassification,
      LayoutLMvaModel,
      LayoutLMvaPreTrainedModel,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_layoutlmva import (
      TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFLayoutLMvaForQuestionAnswering,
      TFLayoutLMvaForSequenceClassification,
      TFLayoutLMvaForTokenClassification,
      TFLayoutLMvaModel,
      TFLayoutLMvaPreTrainedModel,
  )

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
  from .image_processing_layoutlmva import LayoutLMvaImageProcessor

else:
 import sys

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




