





"""simple docstring"""





import os
from typing import List, Optional, Union

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer




class 							snake_case							(			__UpperCAmelCase ):

      '''simple docstring'''



      _A     :       List[Any]         =       ['image_processor', 'tokenizer']
      _A     :       List[Any]         =       'BlipImageProcessor'
      _A     :       Tuple         =       'AutoTokenizer'

      def __init__(							self       :      Union[str, Any]						,				__lowercase       :      str						,				__lowercase       :      List[Any]						,				__lowercase       :      Optional[int] ):


        '''simple docstring'''




        super().__init__(__lowercase						,				__lowercase )

        # add QFormer tokenizer
        __UpperCAmelCase    :						str       =						qformer_tokenizer

      def __call__(							self       :      Dict						,				__lowercase       :      ImageInput = None						,				__lowercase       :      Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None						,				__lowercase       :      bool = True						,				__lowercase       :      Union[bool, str, PaddingStrategy] = False						,				__lowercase       :      Union[bool, str, TruncationStrategy] = None						,				__lowercase       :      Optional[int] = None						,				__lowercase       :      int = 0						,				__lowercase       :      Optional[int] = None						,				__lowercase       :      Optional[bool] = None						,				__lowercase       :      bool = False						,				__lowercase       :      bool = False						,				__lowercase       :      bool = False						,				__lowercase       :      bool = False						,				__lowercase       :      bool = False						,				__lowercase       :      bool = True						,				__lowercase       :      Optional[Union[str, TensorType]] = None						,				**__lowercase       :      Any						,				):


        '''simple docstring'''




        if images is None and text is None:
          raise ValueError('''You have to specify at least images or text.''' )

        __UpperCAmelCase    :						Union[str, Any]       =						BatchFeature()

        if text is not None:
          __UpperCAmelCase    :						Union[str, Any]       =						self.tokenizer(
              text=__lowercase						,				add_special_tokens=__lowercase						,				padding=__lowercase						,				truncation=__lowercase						,				max_length=__lowercase						,				stride=__lowercase						,				pad_to_multiple_of=__lowercase						,				return_attention_mask=__lowercase						,				return_overflowing_tokens=__lowercase						,				return_special_tokens_mask=__lowercase						,				return_offsets_mapping=__lowercase						,				return_token_type_ids=__lowercase						,				return_length=__lowercase						,				verbose=__lowercase						,				return_tensors=__lowercase						,				**__lowercase						,				)
          encoding.update(__lowercase )
          __UpperCAmelCase    :						Tuple       =						self.qformer_tokenizer(
              text=__lowercase						,				add_special_tokens=__lowercase						,				padding=__lowercase						,				truncation=__lowercase						,				max_length=__lowercase						,				stride=__lowercase						,				pad_to_multiple_of=__lowercase						,				return_attention_mask=__lowercase						,				return_overflowing_tokens=__lowercase						,				return_special_tokens_mask=__lowercase						,				return_offsets_mapping=__lowercase						,				return_token_type_ids=__lowercase						,				return_length=__lowercase						,				verbose=__lowercase						,				return_tensors=__lowercase						,				**__lowercase						,				)
          __UpperCAmelCase    :						Dict       =						qformer_text_encoding.pop('''input_ids''' )
          __UpperCAmelCase    :						str       =						qformer_text_encoding.pop('''attention_mask''' )

        if images is not None:
          __UpperCAmelCase    :						List[Any]       =						self.image_processor(__lowercase						,				return_tensors=__lowercase )
          encoding.update(__lowercase )

        return encoding

      def       A_					(							self       :      List[str]						,				*__lowercase       :      Optional[int]						,				**__lowercase       :      Optional[int] ):


        '''simple docstring'''




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

      def       A_					(							self       :      Optional[int]						,				*__lowercase       :      Optional[Any]						,				**__lowercase       :      Tuple ):


        '''simple docstring'''




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

      @property
      # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
      def       A_					(							self       :      List[Any] ):


        '''simple docstring'''




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

      def       A_					(							self       :      Union[str, Any]						,				__lowercase       :      str						,				**__lowercase       :      Union[str, Any] ):


        '''simple docstring'''




        if os.path.isfile(__lowercase ):
          raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' )
        os.makedirs(__lowercase						,				exist_ok=__lowercase )
        __UpperCAmelCase    :						Union[str, Any]       =						os.path.join(__lowercase						,				'''qformer_tokenizer''' )
        self.qformer_tokenizer.save_pretrained(__lowercase )
        return super().save_pretrained(__lowercase						,				**__lowercase )







      @classmethod
      def       A_					(							cls       :      List[str]						,				__lowercase       :      Optional[Any]						,				**__lowercase       :      Dict ):


        '''simple docstring'''




        __UpperCAmelCase    :						str       =						AutoTokenizer.from_pretrained(__lowercase						,				subfolder='''qformer_tokenizer''' )
        __UpperCAmelCase    :						Dict       =						cls._get_arguments_from_pretrained(__lowercase						,				**__lowercase )
        args.append(__lowercase )
        return cls(*__lowercase )






"""simple docstring"""





from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
  import tensorflow as tf


lowercase__				:Optional[int]				   =       logging.get_logger(__name__)




@dataclass
class 							snake_case							(			__UpperCAmelCase ):

      '''simple docstring'''



      _A     :       Tuple         =       [
          'no_inference',
          'no_cuda',
          'no_tpu',
          'no_speed',
          'no_memory',
          'no_env_print',
          'no_multi_process',
      ]

      def __init__(							self       :      Dict						,				**__lowercase       :      Dict ):


        '''simple docstring'''




        for deprecated_arg in self.deprecated_args:
          if deprecated_arg in kwargs:
            __UpperCAmelCase    :						Optional[Any]       =						deprecated_arg[3:]
            __UpperCAmelCase    :						List[str]       =						not kwargs.pop(__lowercase )
            logger.warning(
                f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or'''
                f''' {positive_arg}={kwargs[positive_arg]}''' )
        __UpperCAmelCase    :						int       =						kwargs.pop('''tpu_name'''						,				self.tpu_name )
        __UpperCAmelCase    :						Any       =						kwargs.pop('''device_idx'''						,				self.device_idx )
        __UpperCAmelCase    :						Tuple       =						kwargs.pop('''eager_mode'''						,				self.eager_mode )
        __UpperCAmelCase    :						Optional[int]       =						kwargs.pop('''use_xla'''						,				self.use_xla )
        super().__init__(**__lowercase )

      _A     :       str         =       field(
          default=__UpperCAmelCase      ,  metadata={'help': 'Name of TPU'}      ,  )
      _A     :       int         =       field(
          default=0      ,  metadata={'help': 'CPU / GPU device index. Defaults to 0.'}      ,  )
      _A     :       bool         =       field(default=__UpperCAmelCase      ,  metadata={'help': 'Benchmark models in eager model.'} )
      _A     :       bool         =       field(
          default=__UpperCAmelCase      ,  metadata={
              'help': 'Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'
          }      ,  )

      @cached_property
      def       A_					(							self       :      int ):


        '''simple docstring'''




        requires_backends(self						,				['''tf'''] )
        __UpperCAmelCase    :						Any       =						None
        if self.tpu:
          try:
            if self.tpu_name:
              __UpperCAmelCase    :						List[str]       =						tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name )
            else:
              __UpperCAmelCase    :						Any       =						tf.distribute.cluster_resolver.TPUClusterResolver()
          except ValueError:
            __UpperCAmelCase    :						int       =						None
        return tpu

      @cached_property
      def       A_					(							self       :      Any ):


        '''simple docstring'''




        requires_backends(self						,				['''tf'''] )
        if self.is_tpu:
          tf.config.experimental_connect_to_cluster(self._setup_tpu )
          tf.tpu.experimental.initialize_tpu_system(self._setup_tpu )

          __UpperCAmelCase    :						Any       =						tf.distribute.TPUStrategy(self._setup_tpu )
        else:
          # currently no multi gpu is allowed
          if self.is_gpu:
            # TODO: Currently only single GPU is supported
            tf.config.set_visible_devices(self.gpu_list[self.device_idx]						,				'''GPU''' )
            __UpperCAmelCase    :						Any       =						tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' )
          else:
            tf.config.set_visible_devices([]						,				'''GPU''' )  # disable GPU
            __UpperCAmelCase    :						str       =						tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' )

        return strategy

      @property
      def       A_					(							self       :      Optional[int] ):


        '''simple docstring'''




        requires_backends(self						,				['''tf'''] )
        return self._setup_tpu is not None

      @property
      def       A_					(							self       :      List[str] ):


        '''simple docstring'''




        requires_backends(self						,				['''tf'''] )
        return self._setup_strategy

      @property
      def       A_					(							self       :      Any ):


        '''simple docstring'''




        requires_backends(self						,				['''tf'''] )
        return tf.config.list_physical_devices('''GPU''' )

      @property
      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




        requires_backends(self						,				['''tf'''] )
        if self.cuda:
          return len(self.gpu_list )
        return 0







      @property
      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




        return self.n_gpu > 0