



"""simple docstring"""
from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType



class       SCREAMING_SNAKE_CASE__  (					__lowerCamelCase ):
   __lowerCAmelCase  :   Any						=						["image_processor", "tokenizer"]
   __lowerCAmelCase  :   List[Any]						=						"BlipImageProcessor"
   __lowerCAmelCase  :   Optional[int]						=						("BertTokenizer", "BertTokenizerFast")

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      List[Any]:





    '''simple docstring'''




    UpperCAmelCase	:					Optional[Any]	=	False
    super().__init__(__A      ,     __A						)
    UpperCAmelCase	:					int	=	self.image_processor

   def __call__(   self      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = True      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = 0      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = True      ,     _SCREAMING_SNAKE_CASE = None      ,     **_SCREAMING_SNAKE_CASE      ,     )  ->      Tuple:





    '''simple docstring'''




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

    # Get only text
    if images is None:
     UpperCAmelCase	:					Any	=	self.tokenizer
     UpperCAmelCase	:					Optional[Any]	=	self.tokenizer(
         text=__A      ,     add_special_tokens=__A      ,     padding=__A      ,     truncation=__A      ,     max_length=__A      ,     stride=__A      ,     pad_to_multiple_of=__A      ,     return_attention_mask=__A      ,     return_overflowing_tokens=__A      ,     return_special_tokens_mask=__A      ,     return_offsets_mapping=__A      ,     return_token_type_ids=__A      ,     return_length=__A      ,     verbose=__A      ,     return_tensors=__A      ,     **__A      ,     )
     return text_encoding

    # add pixel_values
    UpperCAmelCase	:					List[Any]	=	self.image_processor(__A      ,     return_tensors=__A						)

    if text is not None:
     UpperCAmelCase	:					Dict	=	self.tokenizer(
         text=__A      ,     add_special_tokens=__A      ,     padding=__A      ,     truncation=__A      ,     max_length=__A      ,     stride=__A      ,     pad_to_multiple_of=__A      ,     return_attention_mask=__A      ,     return_overflowing_tokens=__A      ,     return_special_tokens_mask=__A      ,     return_offsets_mapping=__A      ,     return_token_type_ids=__A      ,     return_length=__A      ,     verbose=__A      ,     return_tensors=__A      ,     **__A      ,     )
    else:
     UpperCAmelCase	:					Dict	=	None

    if text_encoding is not None:
     encoding_image_processor.update(__A						)

    return encoding_image_processor

   def 	SCREAMING_SNAKE_CASE     (   self      ,     *_SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      List[str]:





    '''simple docstring'''




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

   def 	SCREAMING_SNAKE_CASE     (   self      ,     *_SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      List[str]:





    '''simple docstring'''




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




   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	self.tokenizer.model_input_names
    UpperCAmelCase	:					Optional[int]	=	self.image_processor.model_input_names
    return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names						)						)







'''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						:  Features     ) ->      Optional[int]:



       """simple docstring"""






       __UpperCamelCase       =  np.inf

       def set_batch_size(__lowercase						:  FeatureType     ) -> None:
              nonlocal batch_size
              if isinstance(__lowercase				,  __lowercase     ):
                     __UpperCamelCase       =  min(__lowercase				,  config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS     )
              elif isinstance(__lowercase				,  __lowercase     ):
                     __UpperCamelCase       =  min(__lowercase				,  config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS     )
              elif isinstance(__lowercase				,  __lowercase     ) and feature.dtype == "binary":
                     __UpperCamelCase       =  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      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 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       :							Dict							,	):
        super().__init__(
            __A							,	split=__A							,	features=__A							,	cache_dir=__A							,	keep_in_memory=__A							,	streaming=__A							,	num_proc=__A							,	**__A							,	)
        __UpperCamelCase       =  path_or_paths if isinstance(__A							,	__A	) else {self.split: path_or_paths}
        __UpperCamelCase       =  _PACKAGED_DATASETS_MODULES['parquet'][1]
        __UpperCamelCase       =  Parquet(
            cache_dir=__A							,	data_files=__A							,	features=__A							,	hash=__A							,	**__A							,	)






 def        _lowerCamelCase					(       self       :							Optional[int]	):
        # Build iterable dataset
        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=__A							,	download_mode=__A							,	verification_mode=__A							,	base_path=__A							,	num_proc=self.num_proc							,	)
               __UpperCamelCase       =  self.builder.as_dataset(
                   split=self.split							,	verification_mode=__A							,	in_memory=self.keep_in_memory	)
        return dataset






class      snake_case     :




 """simple docstring"""



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






 def        _lowerCamelCase					(       self       :							Optional[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=__A							,	batch_size=__A							,	**self.parquet_writer_kwargs	)
        else:
               __UpperCamelCase       =  self._write(file_obj=self.path_or_buf							,	batch_size=__A							,	**self.parquet_writer_kwargs	)
        return written






 def        _lowerCamelCase					(       self       :							List[str]							,	__A       :							BinaryIO							,	__A       :							int							,	**__A       :							List[str]	):
        __UpperCamelCase       =  0
        __UpperCamelCase       =  parquet_writer_kwargs.pop('path_or_buf'							,	__A	)
        __UpperCamelCase       =  self.dataset.features.arrow_schema

        __UpperCamelCase       =  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'							,	):
               __UpperCamelCase       =  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
