


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 lowerCAmelCase_		:

 '''simple docstring'''

 def __init__(			self	,   _UpperCAmelCase	,   _UpperCAmelCase=13	,   _UpperCAmelCase=30	,   _UpperCAmelCase=2	,   _UpperCAmelCase=3	,   _UpperCAmelCase=True	,   _UpperCAmelCase=True	,   _UpperCAmelCase=32	,   _UpperCAmelCase=2	,   _UpperCAmelCase=4	,   _UpperCAmelCase=37	,   _UpperCAmelCase="gelu"	,   _UpperCAmelCase=0.1	,   _UpperCAmelCase=0.1	,   _UpperCAmelCase=10	,   _UpperCAmelCase=0.02	,   _UpperCAmelCase=3	,   _UpperCAmelCase=None	,   ):
       snake_case_ =   parent
       snake_case_ =   batch_size
       snake_case_ =   image_size
       snake_case_ =   patch_size
       snake_case_ =   num_channels
       snake_case_ =   is_training
       snake_case_ =   use_labels
       snake_case_ =   hidden_size
       snake_case_ =   num_hidden_layers
       snake_case_ =   num_attention_heads
       snake_case_ =   intermediate_size
       snake_case_ =   hidden_act
       snake_case_ =   hidden_dropout_prob
       snake_case_ =   attention_probs_dropout_prob
       snake_case_ =   type_sequence_label_size
       snake_case_ =   initializer_range
       snake_case_ =   scope

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



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

       snake_case_ =   self.get_config()

       return config, pixel_values, labels



 def 		UpperCamelCase__  (			self      ):
       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	,   _UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       snake_case_ =   TFViTModel(config=_a      )
       snake_case_ =   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.
       snake_case_ =   self.image_size // 2
       snake_case_ =   pixel_values[:, :, :image_size, :image_size]
       snake_case_ =   model(_a	,   interpolate_pos_encoding=_a	,   training=_a      )
       snake_case_ =   (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	,   _UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       snake_case_ =   self.type_sequence_label_size
       snake_case_ =   TFViTForImageClassification(_a      )
       snake_case_ =   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.
       snake_case_ =   self.image_size // 2
       snake_case_ =   pixel_values[:, :, :image_size, :image_size]
       snake_case_ =   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
       snake_case_ =   1
       snake_case_ =   TFViTForImageClassification(_a      )
       snake_case_ =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
       snake_case_ =   model(_a      )
       self.parent.assertEqual(result.logits.shape	,   (self.batch_size, self.type_sequence_label_size)      )





 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.prepare_config_and_inputs()
       snake_case_ =   config_and_inputs
       snake_case_ =   {"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_tf
class lowerCAmelCase_		(				UpperCamelCase__      ,		UpperCamelCase__      ,		unittest.TestCase ):

 '''simple docstring'''

 __snake_case				=						(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
 __snake_case				=						(
     {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
     if is_tf_available()
     else {}
 )

 __snake_case				=						False
 __snake_case				=						False
 __snake_case				=						False



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   TFViTModelTester(self      )
       snake_case_ =   ConfigTester(self	,   config_class=_a	,   has_text_modality=_a	,   hidden_size=37      )



 def 		UpperCamelCase__  (			self      ):
       self.config_tester.run_common_tests()



 @unittest.skip(reason='''ViT does not use inputs_embeds'''      )
 def 		UpperCamelCase__  (			self      ):
       pass



 @unittest.skip(reason='''ViT does not use inputs_embeds'''      )
 def 		UpperCamelCase__  (			self      ):
       pass



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.model_tester.prepare_config_and_inputs_for_common()

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



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.model_tester.prepare_config_and_inputs_for_common()

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

             snake_case_ =   ["""pixel_values"""]
             self.assertListEqual(arg_names[:1]	,   _a      )



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_a      )



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_a      )





 @slow
 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   TFViTModel.from_pretrained('''google/vit-base-patch16-224'''      )
       self.assertIsNotNone(_a      )






def  __lowerCAmelCase					()->						Optional[Any]:




      """simple docstring"""

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







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

 '''simple docstring'''

 @cached_property
 def 		UpperCamelCase__  (			self      ):
       return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224'''      ) if is_vision_available() else None





 @slow
 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''      )

       snake_case_ =   self.default_image_processor
       snake_case_ =   prepare_img()
       snake_case_ =   image_processor(images=_a	,   return_tensors='''tf'''      )

       # forward pass
       snake_case_ =   model(**_a      )

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

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

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





def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						int:




      """simple docstring"""

      assert column_title.isupper()
      snake_case_ =   0
      snake_case_ =   len(SCREAMING_SNAKE_CASE      ) - 1
      snake_case_ =   0

      while index >= 0:
            snake_case_ =   (ord(column_title[index]      ) - 64) * pow(26      ,      SCREAMING_SNAKE_CASE      )
            answer += value
            power += 1
            index -= 1

      return answer


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

   testmod()