import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import (
          TFEfficientFormerForImageClassification,
          TFEfficientFormerForImageClassificationWithTeacher,
          TFEfficientFormerModel,
      )
      from transformers.models.efficientformer.modeling_tf_efficientformer import (
          TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      )


if is_vision_available():
      from PIL import Image

      from transformers import EfficientFormerImageProcessor

class       snake_case					:




  def __init__(      self     :	Tuple     , a_     :	Optional[int]     , a_     :	int = 13     , a_     :	int = 64     , a_     :	int = 2     , a_     :	int = 3     , a_     :	int = 3     , a_     :	bool = True     , a_     :	bool = True     , a_     :	int = 128     , a_     :	Dict=[16, 32, 64, 128]     , a_     :	int = 7     , a_     :	int = 4     , a_     :	int = 37     , a_     :	str = "gelu"     , a_     :	float = 0.1     , a_     :	float = 0.1     , a_     :	int = 10     , a_     :	float = 0.02     , a_     :	int = 2     , a_     :	int = 1     , a_     :	int = 128     , a_     :	List[int] = [2, 2, 2, 2]     , a_     :	int = 2     , a_     :	int = 2     , )->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		parent
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		batch_size
       SCREAMING_SNAKE_CASE__				:				List[str]			=		image_size
       SCREAMING_SNAKE_CASE__				:				Dict			=		patch_size
       SCREAMING_SNAKE_CASE__				:				List[str]			=		num_channels
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		is_training
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		use_labels
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		hidden_size
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		num_hidden_layers
       SCREAMING_SNAKE_CASE__				:				str			=		num_attention_heads
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		intermediate_size
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		hidden_act
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		hidden_dropout_prob
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		type_sequence_label_size
       SCREAMING_SNAKE_CASE__				:				Any			=		initializer_range
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		encoder_stride
       SCREAMING_SNAKE_CASE__				:				Any			=		num_attention_outputs
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		embed_dim
       SCREAMING_SNAKE_CASE__				:				Tuple			=		embed_dim + 1
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		resolution
       SCREAMING_SNAKE_CASE__				:				Any			=		depths
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		hidden_sizes
       SCREAMING_SNAKE_CASE__				:				Dict			=		dim
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		mlp_expansion_ratio




  def 	__lowercase(      self     :	int				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

       SCREAMING_SNAKE_CASE__				:				int			=		None
       if self.use_labels:
            SCREAMING_SNAKE_CASE__				:				Any			=		ids_tensor([self.batch_size]     , self.type_sequence_label_size				)

       SCREAMING_SNAKE_CASE__				:				Any			=		self.get_config()

       return config, pixel_values, labels




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




       """simple docstring"""
       return EfficientFormerConfig(
           image_size=self.image_size     , patch_size=self.patch_size     , num_channels=self.num_channels     , hidden_size=self.hidden_size     , num_hidden_layers=self.num_hidden_layers     , num_attention_heads=self.num_attention_heads     , intermediate_size=self.intermediate_size     , hidden_act=self.hidden_act     , hidden_dropout_prob=self.hidden_dropout_prob     , attention_probs_dropout_prob=self.attention_probs_dropout_prob     , is_decoder=a_     , initializer_range=self.initializer_range     , encoder_stride=self.encoder_stride     , resolution=self.resolution     , depths=self.depths     , hidden_sizes=self.hidden_sizes     , dim=self.dim     , mlp_expansion_ratio=self.mlp_expansion_ratio     , )




  def 	__lowercase(      self     :	Optional[int]     , a_     :	Union[str, Any]     , a_     :	str     , a_     :	Dict				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		TFEfficientFormerModel(config=a_				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		model(a_     , training=a_				)
       self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.seq_length, self.hidden_size)				)




  def 	__lowercase(      self     :	Optional[int]     , a_     :	List[str]     , a_     :	int     , a_     :	Dict				)->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.type_sequence_label_size
       SCREAMING_SNAKE_CASE__				:				Dict			=		TFEfficientFormerForImageClassification(a_				)
       SCREAMING_SNAKE_CASE__				:				str			=		model(a_     , labels=a_     , training=a_				)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.type_sequence_label_size)				)

       # test greyscale images
       SCREAMING_SNAKE_CASE__				:				Tuple			=		1
       SCREAMING_SNAKE_CASE__				:				Tuple			=		TFEfficientFormerForImageClassification(a_				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		model(a_     , labels=a_				)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.type_sequence_label_size)				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__				:				List[str]			=		config_and_inputs
       SCREAMING_SNAKE_CASE__				:				Dict			=		{'pixel_values': pixel_values}
       return config, inputs_dict




@require_tf
class       snake_case					(      UpperCamelCase_   ,						UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     (
      (
          TFEfficientFormerModel,
          TFEfficientFormerForImageClassificationWithTeacher,
          TFEfficientFormerForImageClassification,
      )
      if is_tf_available()
      else ()
  )
  lowercase_			=     (
      {
          'feature-extraction': TFEfficientFormerModel,
          'image-classification': (
              TFEfficientFormerForImageClassification,
              TFEfficientFormerForImageClassificationWithTeacher,
          ),
      }
      if is_tf_available()
      else {}
  )

  lowercase_			=     False

  lowercase_			=     False
  lowercase_			=     False
  lowercase_			=     False
  lowercase_			=     False




  def 	__lowercase(      self     :	Dict				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		TFEfficientFormerModelTester(self				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		ConfigTester(
           self     , config_class=a_     , has_text_modality=a_     , hidden_size=37				)




  def 	__lowercase(      self     :	str				)->       Optional[Any]:




       """simple docstring"""
       self.config_tester.run_common_tests()




  @unittest.skip(reason='EfficientFormer does not use inputs_embeds'				)
  def 	__lowercase(      self     :	int				)->       List[Any]:




       """simple docstring"""
       pass




  @unittest.skip(reason='EfficientFormer does not support input and output embeddings'				)
  def 	__lowercase(      self     :	List[Any]				)->       Union[str, Any]:




       """simple docstring"""
       pass




  def 	__lowercase(      self     :	Optional[int]				)->       int:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		model_class(a_				)
            SCREAMING_SNAKE_CASE__				:				int			=		inspect.signature(model.call				)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            SCREAMING_SNAKE_CASE__				:				Any			=		[*signature.parameters.keys()]

            SCREAMING_SNAKE_CASE__				:				List[Any]			=		['pixel_values']
            self.assertListEqual(arg_names[:1]     , a_				)




  def 	__lowercase(      self     :	int				)->       Optional[Any]:




       """simple docstring"""
       def check_hidden_states_output(a_     :	Union[str, Any]     , a_     :	Dict     , a_     :	Dict				):
            SCREAMING_SNAKE_CASE__				:				List[str]			=		model_class(a_				)

            SCREAMING_SNAKE_CASE__				:				Tuple			=		model(**self._prepare_for_class(a_     , a_				)     , training=a_				)
            SCREAMING_SNAKE_CASE__				:				str			=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		getattr(
                self.model_tester     , 'expected_num_hidden_layers'     , self.model_tester.num_hidden_layers + 1				)
            self.assertEqual(len(a_				)     , a_				)

            if hasattr(self.model_tester     , 'encoder_seq_length'				):
                 SCREAMING_SNAKE_CASE__				:				Any			=		self.model_tester.encoder_seq_length
                 if hasattr(self.model_tester     , 'chunk_length'				) and self.model_tester.chunk_length > 1:
                      SCREAMING_SNAKE_CASE__				:				Tuple			=		seq_length * self.model_tester.chunk_length
            else:
                 SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.model_tester.seq_length

            self.assertListEqual(
                list(hidden_states[-1].shape[-2:]				)     , [seq_length, self.model_tester.hidden_size]     , )

            if config.is_encoder_decoder:
                 SCREAMING_SNAKE_CASE__				:				Any			=		outputs.decoder_hidden_states

                 self.asseretIsInstance(a_     , (list, tuple)				)
                 self.assertEqual(len(a_				)     , a_				)
                 SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		getattr(self.model_tester     , 'seq_length'     , a_				)
                 SCREAMING_SNAKE_CASE__				:				List[Any]			=		getattr(self.model_tester     , 'decoder_seq_length'     , a_				)

                 self.assertListEqual(
                     list(hidden_states[-1].shape[-2:]				)     , [decoder_seq_length, self.model_tester.hidden_size]     , )

       SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				int			=		True
            check_hidden_states_output(a_     , a_     , a_				)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            SCREAMING_SNAKE_CASE__				:				Any			=		True

            check_hidden_states_output(a_     , a_     , a_				)




  def 	__lowercase(      self     :	Dict     , a_     :	Dict     , a_     :	List[Any]     , a_     :	Any=False				)->       List[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[str]			=		super()._prepare_for_class(a_     , a_     , return_labels=a_				)

       if return_labels:
            if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
                 del inputs_dict["labels"]

       return inputs_dict




  def 	__lowercase(      self     :	List[str]				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a_				)




  @unittest.skip(reason='EfficientFormer does not implement masked image modeling yet'				)
  def 	__lowercase(      self     :	Tuple				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*a_				)




  def 	__lowercase(      self     :	Dict				)->       List[str]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a_				)




  @slow
  def 	__lowercase(      self     :	Optional[Any]				)->       Any:




       """simple docstring"""
       for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		TFEfficientFormerModel.from_pretrained(a_				)
            self.assertIsNotNone(a_				)




  def 	__lowercase(      self     :	Dict				)->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__				:				List[str]			=		self.model_tester.prepare_config_and_inputs_for_common()
       SCREAMING_SNAKE_CASE__				:				Any			=		True

       SCREAMING_SNAKE_CASE__				:				List[Any]			=		getattr(self.model_tester     , 'seq_length'     , a_				)
       SCREAMING_SNAKE_CASE__				:				str			=		getattr(self.model_tester     , 'encoder_seq_length'     , a_				)
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		getattr(self.model_tester     , 'key_length'     , a_				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		getattr(self.model_tester     , 'chunk_length'     , a_				)

       if chunk_length is not None and hasattr(self.model_tester     , 'num_hashes'				):
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		encoder_seq_length * self.model_tester.num_hashes

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				List[Any]			=		True
            SCREAMING_SNAKE_CASE__				:				Any			=		False
            SCREAMING_SNAKE_CASE__				:				str			=		True
            SCREAMING_SNAKE_CASE__				:				List[str]			=		model_class(a_				)

            SCREAMING_SNAKE_CASE__				:				Dict			=		model(**self._prepare_for_class(a_     , a_				)     , training=a_				)
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
            self.assertEqual(len(a_				)     , self.model_tester.num_attention_outputs				)

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		True
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		model_class(a_				)
            SCREAMING_SNAKE_CASE__				:				Tuple			=		model(**self._prepare_for_class(a_     , a_				)     , training=a_				)

            SCREAMING_SNAKE_CASE__				:				Dict			=		outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
            self.assertEqual(len(a_				)     , self.model_tester.num_attention_outputs				)

            if chunk_length is not None:
                 self.assertListEqual(
                     list(attentions[0].shape[-4:]				)     , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]     , )
            else:
                 self.assertListEqual(
                     list(attentions[0].shape[-3:]				)     , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]     , )




  def 	__lowercase(      self     :	Union[str, Any]				)->       Optional[Any]:




       """simple docstring"""
       # We use a simplified version of this test for EfficientFormer because it requires training=False
       # and Keras refuses to let us force that during functional construction
       SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            # Prepare our model
            SCREAMING_SNAKE_CASE__				:				List[str]			=		model_class(a_				)
            # These are maximally general inputs for the model, with multiple None dimensions
            # Hopefully this will catch any conditionals that fail for flexible shapes
            SCREAMING_SNAKE_CASE__				:				Any			=		{
                key: tf.keras.Input(shape=val.shape[1:]     , dtype=val.dtype     , name=a_				)
                for key, val in model.input_signature.items()
                if key in model.dummy_inputs
            }
            SCREAMING_SNAKE_CASE__				:				Tuple			=		model(a_				)
            self.assertTrue(outputs_dict is not None				)







def     _a				(      ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				str			=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
     return image







@require_tf
@require_vision
class       snake_case					(      unittest.TestCase						):




  @cached_property
  def 	__lowercase(      self     :	List[Any]				)->       Any:




       """simple docstring"""
       return (
           EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300'				)
           if is_vision_available()
           else None
       )




  @slow
  def 	__lowercase(      self     :	Dict				)->       List[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300'				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.default_image_processor
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		prepare_img()
       SCREAMING_SNAKE_CASE__				:				Tuple			=		image_processor(images=a_     , return_tensors='tf'				)
       # forward pass
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		model(**a_     , training=a_				)
       # verify the logits
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		tf.TensorShape((1, 1000)				)
       self.assertEqual(outputs.logits.shape     , a_				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		tf.constant([-0.0555, 0.4825, -0.0852]				)
       self.assertTrue(np.allclose(outputs.logits[0, :3]     , a_     , atol=1e-4				)				)




  @slow
  def 	__lowercase(      self     :	Any				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
           'snap-research/efficientformer-l1-300'				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.default_image_processor
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		prepare_img()
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		image_processor(images=a_     , return_tensors='tf'				)
       # forward pass
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		model(**a_     , training=a_				)
       # verify the logits
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		tf.TensorShape((1, 1000)				)
       self.assertEqual(outputs.logits.shape     , a_				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		tf.constant([-0.1312, 0.4353, -1.0499]				)
       self.assertTrue(np.allclose(outputs.logits[0, :3]     , a_     , atol=1e-4				)				)




import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available

class       snake_case					(      UpperCamelCase_						):
  lowercase_			=     ['image_processor', 'tokenizer']
  lowercase_			=     'OwlViTImageProcessor'
  lowercase_			=     ('CLIPTokenizer', 'CLIPTokenizerFast')




  def __init__(      self     :	List[str]     , a_     :	List[Any]=None     , a_     :	str=None     , **a_     :	Any				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		None
       if "feature_extractor" in kwargs:
            warnings.warn(
                'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                ' instead.'     , a_     , )
            SCREAMING_SNAKE_CASE__				:				Tuple			=		kwargs.pop('feature_extractor'				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		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__(a_     , a_				)




  def __call__(      self     :	Any     , a_     :	Optional[int]=None     , a_     :	Tuple=None     , a_     :	List[Any]=None     , a_     :	Tuple="max_length"     , a_     :	str="np"     , **a_     :	Any				)->       int:




       """simple docstring"""

       if text is None and query_images is None and images is None:
            raise ValueError(
                'You have to specify at least one text or query image or image. All three cannot be none.'				)

       if text is not None:
            if isinstance(a_     , a_				) or (isinstance(a_     , a_				) and not isinstance(text[0]     , a_				)):
                 SCREAMING_SNAKE_CASE__				:				Tuple			=		[self.tokenizer(a_     , padding=a_     , return_tensors=a_     , **a_				)]

            elif isinstance(a_     , a_				) and isinstance(text[0]     , a_				):
                 SCREAMING_SNAKE_CASE__				:				Any			=		[]

                 # Maximum number of queries across batch
                 SCREAMING_SNAKE_CASE__				:				str			=		max([len(a_				) for t in text]				)

                 # Pad all batch samples to max number of text queries
                 for t in text:
                      if len(a_				) != max_num_queries:
                           SCREAMING_SNAKE_CASE__				:				Tuple			=		t + [' '] * (max_num_queries - len(a_				))

                      SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.tokenizer(a_     , padding=a_     , return_tensors=a_     , **a_				)
                      encodings.append(a_				)
            else:
                 raise TypeError('Input text should be a string, a list of strings or a nested list of strings'				)

            if return_tensors == "np":
                 SCREAMING_SNAKE_CASE__				:				Dict			=		np.concatenate([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				List[Any]			=		np.concatenate([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            elif return_tensors == "jax" and is_flax_available():
                 import jax.numpy as jnp

                 SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		jnp.concatenate([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		jnp.concatenate([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            elif return_tensors == "pt" and is_torch_available():
                 import torch

                 SCREAMING_SNAKE_CASE__				:				int			=		torch.cat([encoding['input_ids'] for encoding in encodings]     , dim=0				)
                 SCREAMING_SNAKE_CASE__				:				Optional[int]			=		torch.cat([encoding['attention_mask'] for encoding in encodings]     , dim=0				)

            elif return_tensors == "tf" and is_tf_available():
                 import tensorflow as tf

                 SCREAMING_SNAKE_CASE__				:				str			=		tf.stack([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				Dict			=		tf.stack([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            else:
                 raise ValueError('Target return tensor type could not be returned'				)

            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		BatchEncoding()
            SCREAMING_SNAKE_CASE__				:				List[str]			=		input_ids
            SCREAMING_SNAKE_CASE__				:				Tuple			=		attention_mask

       if query_images is not None:
            SCREAMING_SNAKE_CASE__				:				Any			=		BatchEncoding()
            SCREAMING_SNAKE_CASE__				:				Dict			=		self.image_processor(
                a_     , return_tensors=a_     , **a_				).pixel_values
            SCREAMING_SNAKE_CASE__				:				Dict			=		query_pixel_values

       if images is not None:
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processor(a_     , return_tensors=a_     , **a_				)

       if text is not None and images is not None:
            SCREAMING_SNAKE_CASE__				:				Dict			=		image_features.pixel_values
            return encoding
       elif query_images is not None and images is not None:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image_features.pixel_values
            return encoding
       elif text is not None or query_images is not None:
            return encoding
       else:
            return BatchEncoding(data=dict(**a_				)     , tensor_type=a_				)




  def 	__lowercase(      self     :	str     , *a_     :	List[str]     , **a_     :	int				)->       List[Any]:




       """simple docstring"""
       return self.image_processor.post_process(*a_     , **a_				)




  def 	__lowercase(      self     :	Tuple     , *a_     :	List[str]     , **a_     :	str				)->       Union[str, Any]:




       """simple docstring"""
       return self.image_processor.post_process_object_detection(*a_     , **a_				)




  def 	__lowercase(      self     :	Optional[Any]     , *a_     :	str     , **a_     :	Dict				)->       Optional[int]:




       """simple docstring"""
       return self.image_processor.post_process_image_guided_detection(*a_     , **a_				)




  def 	__lowercase(      self     :	Optional[int]     , *a_     :	Tuple     , **a_     :	Tuple				)->       Optional[Any]:




       """simple docstring"""
       return self.tokenizer.batch_decode(*a_     , **a_				)




  def 	__lowercase(      self     :	Tuple     , *a_     :	Tuple     , **a_     :	Tuple				)->       List[str]:




       """simple docstring"""
       return self.tokenizer.decode(*a_     , **a_				)




  @property
  def 	__lowercase(      self     :	Tuple				)->       Any:




       """simple docstring"""
       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'     , a_     , )
       return self.image_processor_class




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




       """simple docstring"""
       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'     , a_     , )
       return self.image_processor



