'''simple docstring'''





from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

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 TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor

class       snake_case					:




  def __init__(      self     :	Tuple     , a_     :	Optional[Any]     , a_     :	List[str]=13     , a_     :	Union[str, Any]=30     , a_     :	Optional[int]=2     , a_     :	Optional[int]=3     , a_     :	Union[str, Any]=True     , a_     :	List[Any]=True     , a_     :	List[str]=32     , a_     :	Optional[Any]=2     , a_     :	str=4     , a_     :	List[Any]=37     , a_     :	Tuple="gelu"     , a_     :	Tuple=0.1     , a_     :	Optional[Any]=0.1     , a_     :	List[str]=10     , a_     :	List[Any]=0.02     , a_     :	int=3     , a_     :	List[str]=0.6     , a_     :	Union[str, Any]=None     , )->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		parent
       SCREAMING_SNAKE_CASE__				:				str			=		batch_size
       SCREAMING_SNAKE_CASE__				:				Any			=		image_size
       SCREAMING_SNAKE_CASE__				:				List[str]			=		patch_size
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		num_channels
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		is_training
       SCREAMING_SNAKE_CASE__				:				List[str]			=		use_labels
       SCREAMING_SNAKE_CASE__				:				int			=		hidden_size
       SCREAMING_SNAKE_CASE__				:				Any			=		num_hidden_layers
       SCREAMING_SNAKE_CASE__				:				str			=		num_attention_heads
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		intermediate_size
       SCREAMING_SNAKE_CASE__				:				str			=		hidden_act
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		hidden_dropout_prob
       SCREAMING_SNAKE_CASE__				:				int			=		attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__				:				Tuple			=		type_sequence_label_size
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		initializer_range
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		mask_ratio
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		scope

       # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
       # (we add 1 for the [CLS] token)
       SCREAMING_SNAKE_CASE__				:				str			=		(image_size // patch_size) ** 2
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		int(math.ceil((1 - mask_ratio) * (num_patches + 1)				)				)




  def 	__lowercase(      self     :	int				)->       Tuple:




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

       SCREAMING_SNAKE_CASE__				:				List[str]			=		None
       if self.use_labels:
            SCREAMING_SNAKE_CASE__				:				Tuple			=		ids_tensor([self.batch_size]     , self.type_sequence_label_size				)

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.get_config()

       return config, pixel_values, labels




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




       """simple docstring"""
       return ViTMAEConfig(
           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     , decoder_hidden_size=self.hidden_size     , decoder_num_hidden_layers=self.num_hidden_layers     , decoder_num_attention_heads=self.num_attention_heads     , decoder_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=__lowerCamelCase     , initializer_range=self.initializer_range     , mask_ratio=self.mask_ratio     , )




  def 	__lowercase(      self     :	Tuple     , a_     :	Any     , a_     :	str     , a_     :	Any				)->       Tuple:




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




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		TFViTMAEForPreTraining(__lowerCamelCase				)
       SCREAMING_SNAKE_CASE__				:				Any			=		model(__lowerCamelCase     , training=__lowerCamelCase				)
       # expected sequence length = num_patches
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		(self.image_size // self.patch_size) ** 2
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.patch_size**2 * self.num_channels
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, num_patches, expected_num_channels)				)

       # test greyscale images
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		1
       SCREAMING_SNAKE_CASE__				:				Dict			=		TFViTMAEForPreTraining(__lowerCamelCase				)

       SCREAMING_SNAKE_CASE__				:				Tuple			=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
       SCREAMING_SNAKE_CASE__				:				str			=		model(__lowerCamelCase     , training=__lowerCamelCase				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.patch_size**2
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, num_patches, expected_num_channels)				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.prepare_config_and_inputs()
       (SCREAMING_SNAKE_CASE__)				:				Optional[Any]			=		config_and_inputs
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		{"pixel_values": pixel_values}
       return config, inputs_dict




@require_tf
class       snake_case					(      _A   ,						_A   ,						unittest.TestCase						):
  lowercase_			=     (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
  lowercase_			=     {'feature-extraction': TFViTMAEModel} if is_tf_available() else {}

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




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		TFViTMAEModelTester(self				)
       SCREAMING_SNAKE_CASE__				:				Any			=		ConfigTester(self     , config_class=__lowerCamelCase     , has_text_modality=__lowerCamelCase     , hidden_size=37				)




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




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




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




       """simple docstring"""
       pass




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




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

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		model_class(__lowerCamelCase				)
            self.assertIsInstance(model.get_input_embeddings()     , (tf.keras.layers.Layer)				)
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(__lowerCamelCase     , tf.keras.layers.Layer				)				)




  def 	__lowercase(      self     :	str				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.model_tester.prepare_config_and_inputs_for_common()

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

            SCREAMING_SNAKE_CASE__				:				List[str]			=		["pixel_values"]
            self.assertListEqual(arg_names[:1]     , __lowerCamelCase				)




  def 	__lowercase(      self     :	Any				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase				)




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




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




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




       """simple docstring"""
       # make the mask reproducible
       np.random.seed(2				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.model_tester.prepare_config_and_inputs_for_common()

       SCREAMING_SNAKE_CASE__				:				Any			=		int((config.image_size // config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		np.random.uniform(size=(self.model_tester.batch_size, num_patches)				)

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				Any			=		model_class(__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self._prepare_for_class(__lowerCamelCase     , __lowerCamelCase				)

            SCREAMING_SNAKE_CASE__				:				List[str]			=		model(__lowerCamelCase     , noise=__lowerCamelCase				)

            SCREAMING_SNAKE_CASE__				:				Dict			=		copy.deepcopy(self._prepare_for_class(__lowerCamelCase     , __lowerCamelCase				)				)
            SCREAMING_SNAKE_CASE__				:				List[str]			=		model(**__lowerCamelCase     , noise=__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				str			=		outputs_dict[0].numpy()
            SCREAMING_SNAKE_CASE__				:				Dict			=		outputs_keywords[0].numpy()

            self.assertLess(np.sum(np.abs(output_dict - output_keywords				)				)     , 1e-6				)




  def 	__lowercase(      self     :	Any				)->       Dict:




       """simple docstring"""
       # make the mask reproducible
       np.random.seed(2				)

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

       SCREAMING_SNAKE_CASE__				:				int			=		int((config.image_size // config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		np.random.uniform(size=(self.model_tester.batch_size, num_patches)				)

       def prepare_numpy_arrays(a_     :	List[str]				):
            SCREAMING_SNAKE_CASE__				:				Any			=		{}
            for k, v in inputs_dict.items():
                 if tf.is_tensor(__lowerCamelCase				):
                      SCREAMING_SNAKE_CASE__				:				int			=		v.numpy()
                 else:
                      SCREAMING_SNAKE_CASE__				:				Dict			=		np.array(__lowerCamelCase				)

            return inputs_np_dict

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				Any			=		model_class(__lowerCamelCase				)

            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self._prepare_for_class(__lowerCamelCase     , __lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				List[str]			=		prepare_numpy_arrays(__lowerCamelCase				)

            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		model(__lowerCamelCase     , noise=__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				str			=		model(**__lowerCamelCase     , noise=__lowerCamelCase				)
            self.assert_outputs_same(__lowerCamelCase     , __lowerCamelCase				)




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




       """simple docstring"""
       # make masks reproducible
       np.random.seed(2				)

       SCREAMING_SNAKE_CASE__				:				Tuple			=		int((tf_model.config.image_size // tf_model.config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		np.random.uniform(size=(self.model_tester.batch_size, num_patches)				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		tf.constant(__lowerCamelCase				)

       # Add `noise` argument.
       # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		tf_noise

       super().check_pt_tf_models(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase				)




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




       """simple docstring"""
       # make mask reproducible
       np.random.seed(2				)

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

       SCREAMING_SNAKE_CASE__				:				Any			=		{
           module_member
           for model_class in self.all_model_classes
           for module in (import_module(model_class.__module__				),)
           for module_member_name in dir(__lowerCamelCase				)
           if module_member_name.endswith('MainLayer'				)
           # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
           and module_member_name[: -len('MainLayer'				)] == model_class.__name__[: -len('Model'				)]
           for module_member in (getattr(__lowerCamelCase     , __lowerCamelCase				),)
           if isinstance(__lowerCamelCase     , __lowerCamelCase				)
           and tf.keras.layers.Layer in module_member.__bases__
           and getattr(__lowerCamelCase     , '_keras_serializable'     , __lowerCamelCase				)
       }

       SCREAMING_SNAKE_CASE__				:				List[str]			=		int((config.image_size // config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		np.random.uniform(size=(self.model_tester.batch_size, num_patches)				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		tf.convert_to_tensor(__lowerCamelCase				)
       inputs_dict.update({'noise': noise}				)

       for main_layer_class in tf_main_layer_classes:
            SCREAMING_SNAKE_CASE__				:				Dict			=		main_layer_class(__lowerCamelCase				)

            SCREAMING_SNAKE_CASE__				:				int			=		{
                name: tf.keras.Input(tensor.shape[1:]     , dtype=tensor.dtype				) for name, tensor in inputs_dict.items()
            }

            SCREAMING_SNAKE_CASE__				:				Tuple			=		tf.keras.Model(__lowerCamelCase     , outputs=main_layer(__lowerCamelCase				)				)
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		model(__lowerCamelCase				)

            with tempfile.TemporaryDirectory() as tmpdirname:
                 SCREAMING_SNAKE_CASE__				:				str			=		os.path.join(__lowerCamelCase     , 'keras_model.h5'				)
                 model.save(__lowerCamelCase				)
                 SCREAMING_SNAKE_CASE__				:				str			=		tf.keras.models.load_model(
                     __lowerCamelCase     , custom_objects={main_layer_class.__name__: main_layer_class}				)
                 assert isinstance(__lowerCamelCase     , tf.keras.Model				)
                 SCREAMING_SNAKE_CASE__				:				str			=		model(__lowerCamelCase				)
                 self.assert_outputs_same(__lowerCamelCase     , __lowerCamelCase				)




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




       """simple docstring"""
       # make mask reproducible
       np.random.seed(2				)

       SCREAMING_SNAKE_CASE__				:				str			=		self.model_tester.prepare_config_and_inputs_for_common()

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		int((config.image_size // config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		np.random.uniform(size=(self.model_tester.batch_size, num_patches)				)

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				List[str]			=		model_class(__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				str			=		self._prepare_for_class(__lowerCamelCase     , __lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				Tuple			=		model(__lowerCamelCase     , noise=__lowerCamelCase				)

            if model_class.__name__ == "TFViTMAEModel":
                 SCREAMING_SNAKE_CASE__				:				Tuple			=		outputs.last_hidden_state.numpy()
                 SCREAMING_SNAKE_CASE__				:				Optional[int]			=		0
            else:
                 SCREAMING_SNAKE_CASE__				:				Tuple			=		outputs.logits.numpy()
                 SCREAMING_SNAKE_CASE__				:				str			=		0

            with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_pretrained(__lowerCamelCase     , saved_model=__lowerCamelCase				)
                 SCREAMING_SNAKE_CASE__				:				List[str]			=		model_class.from_pretrained(__lowerCamelCase				)
                 SCREAMING_SNAKE_CASE__				:				Tuple			=		model(__lowerCamelCase     , noise=__lowerCamelCase				)

                 if model_class.__name__ == "TFViTMAEModel":
                      SCREAMING_SNAKE_CASE__				:				Dict			=		after_outputs["last_hidden_state"].numpy()
                      SCREAMING_SNAKE_CASE__				:				List[str]			=		0
                 else:
                      SCREAMING_SNAKE_CASE__				:				str			=		after_outputs["logits"].numpy()
                      SCREAMING_SNAKE_CASE__				:				int			=		0

                 SCREAMING_SNAKE_CASE__				:				int			=		np.amax(np.abs(out_a - out_a				)				)
                 self.assertLessEqual(__lowerCamelCase     , 1e-5				)




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




       """simple docstring"""
       # make mask reproducible
       np.random.seed(2				)

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

       SCREAMING_SNAKE_CASE__				:				int			=		int((config.image_size // config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Any			=		np.random.uniform(size=(self.model_tester.batch_size, num_patches)				)

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		model_class(__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				Tuple			=		self._prepare_for_class(__lowerCamelCase     , __lowerCamelCase				)

            SCREAMING_SNAKE_CASE__				:				List[str]			=		model(__lowerCamelCase     , noise=__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				List[str]			=		model.get_config()
            # make sure that returned config is jsonifiable, which is required by keras
            json.dumps(__lowerCamelCase				)
            SCREAMING_SNAKE_CASE__				:				List[Any]			=		model_class.from_config(model.get_config()				)
            # make sure it also accepts a normal config
            SCREAMING_SNAKE_CASE__				:				int			=		model_class.from_config(model.config				)
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		new_model(__lowerCamelCase				)  # Build model
            new_model.set_weights(model.get_weights()				)
            SCREAMING_SNAKE_CASE__				:				str			=		new_model(__lowerCamelCase     , noise=__lowerCamelCase				)

            self.assert_outputs_same(__lowerCamelCase     , __lowerCamelCase				)




  @unittest.skip(
      reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n    to get deterministic results.'				)
  def 	__lowercase(      self     :	int				)->       int:




       """simple docstring"""
       pass




  @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load'				)
  def 	__lowercase(      self     :	Tuple				)->       Any:




       """simple docstring"""
       pass




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		TFViTMAEModel.from_pretrained('google/vit-base-patch16-224'				)
       self.assertIsNotNone(__lowerCamelCase				)







def     _a				(      ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				Dict			=		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]				)->       Union[str, Any]:




       """simple docstring"""
       return ViTImageProcessor.from_pretrained('facebook/vit-mae-base'				) if is_vision_available() else None




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




       """simple docstring"""
       # make random mask reproducible across the PT and TF model
       np.random.seed(2				)

       SCREAMING_SNAKE_CASE__				:				List[Any]			=		TFViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base'				)

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.default_image_processor
       SCREAMING_SNAKE_CASE__				:				Tuple			=		prepare_img()
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image_processor(images=__lowerCamelCase     , return_tensors='tf'				)

       # prepare a noise vector that will be also used for testing the TF model
       # (this way we can ensure that the PT and TF models operate on the same inputs)
       SCREAMING_SNAKE_CASE__				:				Any			=		ViTMAEConfig()
       SCREAMING_SNAKE_CASE__				:				str			=		int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2				)
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		np.random.uniform(size=(1, num_patches)				)

       # forward pass
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		model(**__lowerCamelCase     , noise=__lowerCamelCase				)

       # verify the logits
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		tf.convert_to_tensor([1, 196, 768]				)
       self.assertEqual(outputs.logits.shape     , __lowerCamelCase				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		tf.convert_to_tensor(
           [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]]				)

       tf.debugging.assert_near(outputs.logits[0, :3, :3]     , __lowerCamelCase     , 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



