




"""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       (							lowercase_						)						->		int:
 A__	=    np.inf

 def set_batch_size(lowercase_						) -> None:
  nonlocal batch_size
  if isinstance(lowercase_      ,			lowercase_						):
   A__	=    min(lowercase_      ,			config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS						)
  elif isinstance(lowercase_      ,			lowercase_						):
   A__	=    min(lowercase_      ,			config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS						)
  elif isinstance(lowercase_      ,			lowercase_						) and feature.dtype == "binary":
   A__	=    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      UpperCAmelCase_  (						UpperCAmelCase_							):




    def __init__(   self						:	Union[str, Any]     ,			snake_case_						:	Union[str, Any]     ,			snake_case_						:	List[str] = None     ,			snake_case_						:	Optional[Any] = None     ,			snake_case_						:	List[Any] = None     ,			snake_case_						:	Dict = False     ,			snake_case_						:	Tuple = False     ,			snake_case_						:	Optional[int] = None     ,			**snake_case_						:	Tuple     ,			)				->							int:




     '''simple docstring'''

     super().__init__(
         __lowercase     ,			split=__lowercase     ,			features=__lowercase     ,			cache_dir=__lowercase     ,			keep_in_memory=__lowercase     ,			streaming=__lowercase     ,			num_proc=__lowercase     ,			**__lowercase     ,			)
     A__	=    path_or_paths if isinstance(__lowercase     ,			__lowercase				) else {self.split: path_or_paths}
     A__	=    _PACKAGED_DATASETS_MODULES['''parquet'''][1]
     A__	=    Parquet(
         cache_dir=__lowercase     ,			data_files=__lowercase     ,			features=__lowercase     ,			hash=__lowercase     ,			**__lowercase     ,			)




    def 							__magic_name__							(   self						:	Dict				)				->							Union[str, Any]:




     '''simple docstring'''

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

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






class      UpperCAmelCase_  :




    def __init__(   self						:	Tuple     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	Dict = None     ,			**snake_case_						:	List[Any]     ,			)				->							Any:




     '''simple docstring'''

     A__	=    dataset
     A__	=    path_or_buf
     A__	=    batch_size or get_writer_batch_size(dataset.features				)
     A__	=    parquet_writer_kwargs




    def 							__magic_name__							(   self						:	List[Any]				)				->							int:




     '''simple docstring'''

     A__	=    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:
       A__	=    self._write(file_obj=__lowercase     ,			batch_size=__lowercase     ,			**self.parquet_writer_kwargs				)
     else:
      A__	=    self._write(file_obj=self.path_or_buf     ,			batch_size=__lowercase     ,			**self.parquet_writer_kwargs				)
     return written




    def 							__magic_name__							(   self						:	Any     ,			snake_case_						:	Tuple     ,			snake_case_						:	Tuple     ,			**snake_case_						:	Any				)				->							int:




     '''simple docstring'''

     A__	=    0
     A__	=    parquet_writer_kwargs.pop("path_or_buf"     ,			__lowercase				)
     A__	=    self.dataset.features.arrow_schema

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











"""simple docstring"""



from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class      UpperCAmelCase_  (						A_							):
    lowercase__						 =				['''image_processor''', '''tokenizer''']
    lowercase__						 =				'''AutoImageProcessor'''
    lowercase__						 =				'''AutoTokenizer'''




    def __init__(   self						:	str     ,			snake_case_						:	Dict     ,			snake_case_						:	List[str]				)				->							str:




     '''simple docstring'''

     super().__init__(snake_case_     ,			snake_case_				)
     A__	=    self.image_processor




    def __call__(   self						:	int     ,			snake_case_						:	Any=None     ,			snake_case_						:	Any=None     ,			snake_case_						:	Union[str, Any]=None     ,			**snake_case_						:	Optional[int]				)				->							Optional[int]:




     '''simple docstring'''

     if text is None and images is None:
      raise ValueError("You have to specify either text or images. Both cannot be none."				)

     if text is not None:
      A__	=    self.tokenizer(snake_case_     ,			return_tensors=snake_case_     ,			**snake_case_				)

     if images is not None:
      A__	=    self.image_processor(snake_case_     ,			return_tensors=snake_case_     ,			**snake_case_				)

     if text is not None and images is not None:
      A__	=    image_features.pixel_values
      return encoding
     elif text is not None:
      return encoding
     else:
      return BatchEncoding(data=dict(**snake_case_				)     ,			tensor_type=snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]     ,			*snake_case_						:	Union[str, Any]     ,			**snake_case_						:	List[Any]				)				->							int:




     '''simple docstring'''

     return self.tokenizer.batch_decode(*snake_case_     ,			**snake_case_				)




    def 							__magic_name__							(   self						:	List[str]     ,			*snake_case_						:	List[str]     ,			**snake_case_						:	Optional[int]				)				->							Tuple:




     '''simple docstring'''

     return self.tokenizer.decode(*snake_case_     ,			**snake_case_				)




    @property
    def 							__magic_name__							(   self						:	List[Any]				)				->							List[Any]:




     '''simple docstring'''

     return ["input_ids", "attention_mask", "pixel_values"]





