from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor






class 		a__						:

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







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    parent
							SCREAMING_SNAKE_CASE_  :		str				      =    batch_size
							SCREAMING_SNAKE_CASE_  :		Any				      =    image_size
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    patch_size
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    num_channels
							SCREAMING_SNAKE_CASE_  :		Any				      =    is_training
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    use_labels
							SCREAMING_SNAKE_CASE_  :		str				      =    hidden_size
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    num_hidden_layers
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    num_attention_heads
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    intermediate_size
							SCREAMING_SNAKE_CASE_  :		Dict				      =    hidden_act
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    hidden_dropout_prob
							SCREAMING_SNAKE_CASE_  :		str				      =    attention_probs_dropout_prob
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    type_sequence_label_size
							SCREAMING_SNAKE_CASE_  :		str				      =    initializer_range
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    scope

							# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
							SCREAMING_SNAKE_CASE_  :		str				      =    (image_size // patch_size) ** 2
							SCREAMING_SNAKE_CASE_  :		int				      =    num_patches + 1

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

							SCREAMING_SNAKE_CASE_  :		Tuple				      =    None
							if self.use_labels:
									SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    ids_tensor([self.batch_size],self.type_sequence_label_size    )

							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.get_config()

							return config, pixel_values, labels

					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							return ViTConfig(
							    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,)

					def 				__UpperCamelCase   (    self      :       Union[str, Any],_A      :       Optional[int],_A      :       List[Any],_A      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    TFViTModel(config=_A    )
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    model(_A,training=_A    )
							self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)    )

							# Test with an image with different size than the one specified in config.
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.image_size // 2
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    pixel_values[:, :, :image_size, :image_size]
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    model(_A,interpolate_pos_encoding=_A,training=_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    (image_size // self.patch_size) ** 2 + 1
							self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, seq_length, self.hidden_size)    )

					def 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       str,_A      :       Optional[int],_A      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.type_sequence_label_size
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    TFViTForImageClassification(_A    )
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(_A,labels=_A,training=_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)    )

							# Test with an image with different size than the one specified in config.
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.image_size // 2
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    pixel_values[:, :, :image_size, :image_size]
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    model(_A,interpolate_pos_encoding=_A,training=_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)    )

							# test greyscale images
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    1
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TFViTForImageClassification(_A    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)    )






					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		List[str]				      =    config_and_inputs
							SCREAMING_SNAKE_CASE_  :		int				      =    {"pixel_values": pixel_values}
							return config, inputs_dict







@require_tf
class 		a__						(					A__    ,		A__    ,		unittest.TestCase					):
					A	       =							(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
					A	       =							(
					    {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
					    if is_tf_available()
					    else {}
					)

					A	       =							False
					A	       =							False
					A	       =							False

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    TFViTModelTester(self    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    ConfigTester(self,config_class=_A,has_text_modality=_A,hidden_size=37    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							self.config_tester.run_common_tests()

					@unittest.skip(reason="ViT does not use inputs_embeds"    )
					def 				__UpperCamelCase   (    self      :       Dict    ):







							"""simple docstring"""






							pass

					@unittest.skip(reason="ViT does not use inputs_embeds"    )
					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							pass

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






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

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

					def 				__UpperCamelCase   (    self      :       Any    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Dict				      =    self.model_tester.prepare_config_and_inputs_for_common()

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

									SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    ["pixel_values"]
									self.assertListEqual(arg_names[:1],_A    )

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A    )






					@slow
					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TFViTModel.from_pretrained("google/vit-base-patch16-224"    )
							self.assertIsNotNone(_A    )







def       _snake_case	(   ):
		"""simple docstring"""







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







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

					@cached_property
					def 				__UpperCamelCase   (    self      :       Union[str, Any]    ):







							"""simple docstring"""






							return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"    ) if is_vision_available() else None






					@slow
					def 				__UpperCamelCase   (    self      :       Any    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"    )

							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.default_image_processor
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    prepare_img()
							SCREAMING_SNAKE_CASE_  :		Dict				      =    image_processor(images=_A,return_tensors="tf"    )

							# forward pass
							SCREAMING_SNAKE_CASE_  :		Dict				      =    model(**_A    )

							# verify the logits
							SCREAMING_SNAKE_CASE_  :		int				      =    tf.TensorShape((1, 1000)    )
							self.assertEqual(outputs.logits.shape,_A    )

							SCREAMING_SNAKE_CASE_  :		int				      =    tf.constant([-0.2744, 0.8215, -0.0836]    )

							tf.debugging.assert_near(outputs.logits[0, :3],_A,atol=1E-4    )

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


__lowerCamelCase					:	Dict       =  {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__lowerCamelCase					:	Any       =  [
		    '''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''ViTMAEForPreTraining''',
		    '''ViTMAELayer''',
		    '''ViTMAEModel''',
		    '''ViTMAEPreTrainedModel''',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__lowerCamelCase					:	Optional[Any]       =  [
		    '''TFViTMAEForPreTraining''',
		    '''TFViTMAEModel''',
		    '''TFViTMAEPreTrainedModel''',
		]

if TYPE_CHECKING:
		from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_vit_mae import (
				    VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST,
				    ViTMAEForPreTraining,
				    ViTMAELayer,
				    ViTMAEModel,
				    ViTMAEPreTrainedModel,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel


else:
		import sys

		__lowerCamelCase					:	Any       =  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
