





"""simple docstring"""
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 					_UpperCAmelCase   :


					def __init__(					self			:Optional[int]     ,       __UpperCamelCase			:List[str]     ,       __UpperCamelCase			:Union[str, Any]=13     ,       __UpperCamelCase			:List[Any]=30     ,       __UpperCamelCase			:List[str]=2     ,       __UpperCamelCase			:int=3     ,       __UpperCamelCase			:Dict=True     ,       __UpperCamelCase			:Optional[Any]=True     ,       __UpperCamelCase			:Any=32     ,       __UpperCamelCase			:Dict=2     ,       __UpperCamelCase			:Tuple=4     ,       __UpperCamelCase			:Union[str, Any]=37     ,       __UpperCamelCase			:List[str]="gelu"     ,       __UpperCamelCase			:Optional[int]=0.1     ,       __UpperCamelCase			:Optional[int]=0.1     ,       __UpperCamelCase			:Any=10     ,       __UpperCamelCase			:Optional[int]=0.02     ,       __UpperCamelCase			:str=3     ,       __UpperCamelCase			:Optional[int]=None     ,       ):
												A		=  parent
												A		=  batch_size
												A		=  image_size
												A		=  patch_size
												A		=  num_channels
												A		=  is_training
												A		=  use_labels
												A		=  hidden_size
												A		=  num_hidden_layers
												A		=  num_attention_heads
												A		=  intermediate_size
												A		=  hidden_act
												A		=  hidden_dropout_prob
												A		=  attention_probs_dropout_prob
												A		=  type_sequence_label_size
												A		=  initializer_range
												A		=  scope

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


					def 	lowerCamelCase       (					self			:int		):
												A		=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

												A		=  None
												if self.use_labels:
																			A		=  ids_tensor([self.batch_size]     ,       self.type_sequence_label_size		)

												A		=  self.get_config()

												return config, pixel_values, labels


					def 	lowerCamelCase       (					self			:List[str]		):
												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=__UpperCamelCase     ,       initializer_range=self.initializer_range     ,       )


					def 	lowerCamelCase       (					self			:Dict     ,       __UpperCamelCase			:Optional[Any]     ,       __UpperCamelCase			:int     ,       __UpperCamelCase			:Union[str, Any]		):
												A		=  TFViTModel(config=__UpperCamelCase		)
												A		=  model(__UpperCamelCase     ,       training=__UpperCamelCase		)
												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.
												A		=  self.image_size // 2
												A		=  pixel_values[:, :, :image_size, :image_size]
												A		=  model(__UpperCamelCase     ,       interpolate_pos_encoding=__UpperCamelCase     ,       training=__UpperCamelCase		)
												A		=  (image_size // self.patch_size) ** 2 + 1
												self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, seq_length, self.hidden_size)		)


					def 	lowerCamelCase       (					self			:str     ,       __UpperCamelCase			:Optional[Any]     ,       __UpperCamelCase			:int     ,       __UpperCamelCase			:List[str]		):
												A		=  self.type_sequence_label_size
												A		=  TFViTForImageClassification(__UpperCamelCase		)
												A		=  model(__UpperCamelCase     ,       labels=__UpperCamelCase     ,       training=__UpperCamelCase		)
												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.
												A		=  self.image_size // 2
												A		=  pixel_values[:, :, :image_size, :image_size]
												A		=  model(__UpperCamelCase     ,       interpolate_pos_encoding=__UpperCamelCase     ,       training=__UpperCamelCase		)
												self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.type_sequence_label_size)		)

												# test greyscale images
												A		=  1
												A		=  TFViTForImageClassification(__UpperCamelCase		)
												A		=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
												A		=  model(__UpperCamelCase		)
												self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.type_sequence_label_size)		)


					def 	lowerCamelCase       (					self			:Dict		):
												A		=  self.prepare_config_and_inputs()
												A,	A,	A		=  config_and_inputs
												A		=  {"pixel_values": pixel_values}
												return config, inputs_dict







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

					UpperCamelCase      =							False
					UpperCamelCase      =							False
					UpperCamelCase      =							False


					def 	lowerCamelCase       (					self			:Union[str, Any]		):
												A		=  TFViTModelTester(self		)
												A		=  ConfigTester(self     ,       config_class=__UpperCamelCase     ,       has_text_modality=__UpperCamelCase     ,       hidden_size=37		)


					def 	lowerCamelCase       (					self			:Optional[int]		):
												self.config_tester.run_common_tests()


					@unittest.skip(reason="ViT does not use inputs_embeds"		)
					def 	lowerCamelCase       (					self			:Any		):
												pass


					@unittest.skip(reason="ViT does not use inputs_embeds"		)
					def 	lowerCamelCase       (					self			:Optional[int]		):
												pass


					def 	lowerCamelCase       (					self			:List[str]		):
												A,	A		=  self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			A		=  model_class(__UpperCamelCase		)
																			self.assertIsInstance(model.get_input_embeddings()     ,       (tf.keras.layers.Layer)		)
																			A		=  model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(__UpperCamelCase     ,       tf.keras.layers.Layer		)		)


					def 	lowerCamelCase       (					self			:Union[str, Any]		):
												A,	A		=  self.model_tester.prepare_config_and_inputs_for_common()

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

																			A		=  ["pixel_values"]
																			self.assertListEqual(arg_names[:1]     ,       __UpperCamelCase		)


					def 	lowerCamelCase       (					self			:List[str]		):
												A		=  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__UpperCamelCase		)


					def 	lowerCamelCase       (					self			:Tuple		):
												A		=  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase		)


					@slow
					def 	lowerCamelCase       (					self			:Any		):
												A		=  TFViTModel.from_pretrained("google/vit-base-patch16-224"		)
												self.assertIsNotNone(__UpperCamelCase		)







def 					A__				(			):
							A		=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
							return image






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


					@cached_property
					def 	lowerCamelCase       (					self			:Union[str, Any]		):
												return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"		) if is_vision_available() else None


					@slow
					def 	lowerCamelCase       (					self			:str		):
												A		=  TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"		)

												A		=  self.default_image_processor
												A		=  prepare_img()
												A		=  image_processor(images=__UpperCamelCase     ,       return_tensors="tf"		)

												# forward pass
												A		=  model(**__UpperCamelCase		)

												# verify the logits
												A		=  tf.TensorShape((1, 10_00)		)
												self.assertEqual(outputs.logits.shape     ,       __UpperCamelCase		)

												A		=  tf.constant([-0.2_744, 0.8_215, -0.0_836]		)

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









"""simple docstring"""
def 					A__				(			UpperCamelCase					,  UpperCamelCase = False       ):

							if not isinstance(UpperCamelCase					,  UpperCamelCase       ):
														A		=  F"Expected string as input, found {type(UpperCamelCase       )}"
														raise ValueError(UpperCamelCase       )
							if not isinstance(UpperCamelCase					,  UpperCamelCase       ):
														A		=  F"Expected boolean as use_pascal parameter, found {type(UpperCamelCase       )}"
														raise ValueError(UpperCamelCase       )

							A		=  input_str.split("_"       )

							A		=  0 if use_pascal else 1

							A		=  words[start_index:]

							A		=  [word[0].upper() + word[1:] for word in words_to_capitalize]

							A		=  "" if use_pascal else words[0]

							return "".join([initial_word, *capitalized_words]       )


if __name__ == "__main__":
		from doctest import testmod

		testmod()


