




"""simple docstring"""

import warnings
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 							lowercase_			(	SCREAMING_SNAKE_CASE__				):



 '''simple docstring'''
 UpperCAmelCase       :	Optional[int]     =      ['''image_processor''', '''tokenizer''']
 UpperCAmelCase       :	Tuple     =      '''FlavaImageProcessor'''
 UpperCAmelCase       :	List[str]     =      ('''BertTokenizer''', '''BertTokenizerFast''')

 def __init__(					self			:			List[Any]       ,				_UpperCAmelCase			:			Union[str, Any]=None       ,				_UpperCAmelCase			:			str=None       ,				**_UpperCAmelCase			:			Any						):
       _A     =  None
       if "feature_extractor" in kwargs:
             warnings.warn(
                 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                 ' instead.'       ,				_UpperCAmelCase       ,				)
             _A     =  kwargs.pop('feature_extractor'						)

       _A     =  image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
             raise ValueError('You need to specify an `image_processor`.'						)
       if tokenizer is None:
             raise ValueError('You need to specify a `tokenizer`.'						)

       super().__init__(_UpperCAmelCase       ,				_UpperCAmelCase						)
       _A     =  self.image_processor

 def __call__(					self			:			Optional[Any]       ,				_UpperCAmelCase			:			int = None       ,				_UpperCAmelCase			:			List[Any] = None       ,				_UpperCAmelCase			:			Optional[Any] = True       ,				_UpperCAmelCase			:			List[str] = False       ,				_UpperCAmelCase			:			Any = False       ,				_UpperCAmelCase			:			Dict = None       ,				_UpperCAmelCase			:			Optional[Any] = 0       ,				_UpperCAmelCase			:			Any = None       ,				_UpperCAmelCase			:			List[str] = None       ,				_UpperCAmelCase			:			Dict = None       ,				_UpperCAmelCase			:			List[Any] = None       ,				_UpperCAmelCase			:			Union[str, Any] = None       ,				_UpperCAmelCase			:			Any = False       ,				_UpperCAmelCase			:			Dict = False       ,				_UpperCAmelCase			:			Optional[Any] = False       ,				_UpperCAmelCase			:			Union[str, Any] = False       ,				_UpperCAmelCase			:			Optional[int] = True       ,				_UpperCAmelCase			:			Union[str, Any] = None       ,				**_UpperCAmelCase			:			Any       ,				):



       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(
                 text=_UpperCAmelCase       ,				add_special_tokens=_UpperCAmelCase       ,				padding=_UpperCAmelCase       ,				truncation=_UpperCAmelCase       ,				max_length=_UpperCAmelCase       ,				stride=_UpperCAmelCase       ,				pad_to_multiple_of=_UpperCAmelCase       ,				return_token_type_ids=_UpperCAmelCase       ,				return_attention_mask=_UpperCAmelCase       ,				return_overflowing_tokens=_UpperCAmelCase       ,				return_special_tokens_mask=_UpperCAmelCase       ,				return_offsets_mapping=_UpperCAmelCase       ,				return_length=_UpperCAmelCase       ,				verbose=_UpperCAmelCase       ,				return_tensors=_UpperCAmelCase       ,				**_UpperCAmelCase       ,				)
       if images is not None:
             _A     =  self.image_processor(
                 _UpperCAmelCase       ,				return_image_mask=_UpperCAmelCase       ,				return_codebook_pixels=_UpperCAmelCase       ,				return_tensors=_UpperCAmelCase       ,				**_UpperCAmelCase       ,				)

       if text is not None and images is not None:
             encoding.update(_UpperCAmelCase						)
             return encoding
       elif text is not None:
             return encoding
       else:
             return BatchEncoding(data=dict(**_UpperCAmelCase						)       ,				tensor_type=_UpperCAmelCase						)

 def      lowerCAmelCase_				(					self			:			List[str]       ,				*_UpperCAmelCase			:			Any       ,				**_UpperCAmelCase			:			List[Any]						):
       return self.tokenizer.batch_decode(*_UpperCAmelCase       ,				**_UpperCAmelCase						)

 def      lowerCAmelCase_				(					self			:			Optional[int]       ,				*_UpperCAmelCase			:			Union[str, Any]       ,				**_UpperCAmelCase			:			int						):
       return self.tokenizer.decode(*_UpperCAmelCase       ,				**_UpperCAmelCase						)

 @property
 def      lowerCAmelCase_				(					self			:			Tuple						):
       _A     =  self.tokenizer.model_input_names
       _A     =  self.image_processor.model_input_names
       return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names						)						)

 @property
 def      lowerCAmelCase_				(					self			:			Dict						):
       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'       ,				_UpperCAmelCase       ,				)
       return self.image_processor_class



 @property
 def      lowerCAmelCase_				(					self			:			Tuple						):
       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'       ,				_UpperCAmelCase       ,				)
       return self.image_processor







from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
				import torch

if is_torch_tpu_available(check_device=False):
				import torch_xla.core.xla_model as xm


SCREAMING_SNAKE_CASE__     :     int		    =       logging.get_logger(__name__)



@dataclass
class       a_       (     SCREAMING_SNAKE_CASE__     ):
	A    							= [
	    '''no_inference''',
	    '''no_cuda''',
	    '''no_tpu''',
	    '''no_speed''',
	    '''no_memory''',
	    '''no_env_print''',
	    '''no_multi_process''',
	]





	def __init__(							self      ,     **SCREAMING_SNAKE_CASE      )  ->					Dict:




				"""simple docstring"""



				for deprecated_arg in self.deprecated_args:
							if deprecated_arg in kwargs:
										SCREAMING_SNAKE_CASE_								=						deprecated_arg[3:]
										setattr(self      ,     SCREAMING_SNAKE_CASE      ,     not kwargs.pop(SCREAMING_SNAKE_CASE      )      )
										logger.warning(
										    f'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or'
										    f' {positive_arg}={kwargs[positive_arg]}'      )

				SCREAMING_SNAKE_CASE_								=						kwargs.pop('torchscript'      ,     self.torchscript      )
				SCREAMING_SNAKE_CASE_								=						kwargs.pop('torch_xla_tpu_print_metrics'      ,     self.torch_xla_tpu_print_metrics      )
				SCREAMING_SNAKE_CASE_								=						kwargs.pop('fp16_opt_level'      ,     self.fpaa_opt_level      )
				super().__init__(**SCREAMING_SNAKE_CASE      )

	A    							= field(default=SCREAMING_SNAKE_CASE__  ,    metadata={'''help''': '''Trace the models using torchscript'''}     )
	A    							= field(default=SCREAMING_SNAKE_CASE__  ,    metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''}     )
	A    							= field(
	    default='''O1'''  ,    metadata={
	        '''help''': (
	            '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. '''
	            '''See details at https://nvidia.github.io/apex/amp.html'''
	        )
	    }  ,    )





	@cached_property
	def 						A_(							self      )  ->					Tuple["torch.device", int]:




				"""simple docstring"""



				requires_backends(self      ,     ['torch']      )
				logger.info('PyTorch: setting up devices'      )
				if not self.cuda:
							SCREAMING_SNAKE_CASE_								=						torch.device('cpu'      )
							SCREAMING_SNAKE_CASE_								=						0
				elif is_torch_tpu_available():
							SCREAMING_SNAKE_CASE_								=						xm.xla_device()
							SCREAMING_SNAKE_CASE_								=						0
				else:
							SCREAMING_SNAKE_CASE_								=						torch.device('cuda' if torch.cuda.is_available() else 'cpu'      )
							SCREAMING_SNAKE_CASE_								=						torch.cuda.device_count()
				return device, n_gpu





	@property
	def 						A_(							self      )  ->					Union[str, Any]:




				"""simple docstring"""



				return is_torch_tpu_available() and self.tpu





	@property
	def 						A_(							self      )  ->					int:




				"""simple docstring"""



				requires_backends(self      ,     ['torch']      )
				# TODO(PVP): currently only single GPU is supported
				return torch.cuda.current_device()





	@property
	def 						A_(							self      )  ->					"torch.device":




				"""simple docstring"""



				requires_backends(self      ,     ['torch']      )
				return self._setup_devices[0]





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




				"""simple docstring"""



				requires_backends(self      ,     ['torch']      )
				return self._setup_devices[1]





	@property
	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				return self.n_gpu > 0
