





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



      '''simple docstring'''

      def __init__(     self					,      snake_case_					,      snake_case_=1_3					,      snake_case_=3_0					,      snake_case_=2					,      snake_case_=3					,      snake_case_=True					,      snake_case_=True					,      snake_case_=3_2					,      snake_case_=2					,      snake_case_=4					,      snake_case_=3_7					,      snake_case_="gelu"					,      snake_case_=0.1					,      snake_case_=0.1					,      snake_case_=1_0					,      snake_case_=0.02					,      snake_case_=3					,      snake_case_=None					,      ):

        """simple docstring"""

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

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

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

        A_  :       Tuple										=  None
        if self.use_labels:
          A_  :       Dict										=  ids_tensor([self.batch_size]					,      self.type_sequence_label_size  )

        A_  :       List[str]										=  self.get_config()

        return config, pixel_values, labels

      def 					lowerCamelCase_			(     self  ):

        """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=snake_case_					,      initializer_range=self.initializer_range					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       Optional[int]										=  TFViTModel(config=snake_case_  )
        A_  :       List[str]										=  model(snake_case_					,      training=snake_case_  )
        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_  :       str										=  self.image_size // 2
        A_  :       List[str]										=  pixel_values[:, :, :image_size, :image_size]
        A_  :       Optional[Any]										=  model(snake_case_					,      interpolate_pos_encoding=snake_case_					,      training=snake_case_  )
        A_  :       Tuple										=  (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					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       Tuple										=  self.type_sequence_label_size
        A_  :       int										=  TFViTForImageClassification(snake_case_  )
        A_  :       Any										=  model(snake_case_					,      labels=snake_case_					,      training=snake_case_  )
        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_  :       Optional[Any]										=  self.image_size // 2
        A_  :       Tuple										=  pixel_values[:, :, :image_size, :image_size]
        A_  :       Any										=  model(snake_case_					,      interpolate_pos_encoding=snake_case_					,      training=snake_case_  )
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.type_sequence_label_size)  )

        # test greyscale images
        A_  :       Tuple										=  1
        A_  :       int										=  TFViTForImageClassification(snake_case_  )
        A_  :       Optional[int]										=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
        A_  :       Dict										=  model(snake_case_  )
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.type_sequence_label_size)  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       str										=  self.prepare_config_and_inputs()
        A_						,       A_						,       A_  :       Any										=  config_and_inputs
        A_  :       Optional[Any]										=  {'pixel_values': pixel_values}
        return config, inputs_dict


@require_tf
class  _UpperCAmelCase  (   UpperCAmelCase__			,   UpperCAmelCase__			,   unittest.TestCase		):



      '''simple docstring'''
      lowercase_      : str	    =   (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
      lowercase_      : Dict	    =   (
          {"""feature-extraction""": TFViTModel, """image-classification""": TFViTForImageClassification}
          if is_tf_available()
          else {}
      )

      lowercase_      : List[Any]	    =   False
      lowercase_      : Any	    =   False
      lowercase_      : int	    =   False

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       str										=  TFViTModelTester(self  )
        A_  :       Optional[Any]										=  ConfigTester(self					,      config_class=snake_case_					,      has_text_modality=snake_case_					,      hidden_size=3_7  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        self.config_tester.run_common_tests()

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

        """simple docstring"""

        pass

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

        """simple docstring"""

        pass

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

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

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

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_						,       A_  :       str										=  self.model_tester.prepare_config_and_inputs_for_common()

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

          A_  :       Any										=  ['pixel_values']
          self.assertListEqual(arg_names[:1]					,      snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       int										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Dict										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*snake_case_  )

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       str										=  TFViTModel.from_pretrained('google/vit-base-patch16-224'  )
        self.assertIsNotNone(snake_case_  )





def 						UpperCAmelCase__		(     ):






  """simple docstring"""





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





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



      '''simple docstring'''

      @cached_property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

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

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       int										=  TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'  )

        A_  :       Tuple										=  self.default_image_processor
        A_  :       Optional[Any]										=  prepare_img()
        A_  :       List[Any]										=  image_processor(images=snake_case_					,      return_tensors='tf'  )

        # forward pass
        A_  :       str										=  model(**snake_case_  )

        # verify the logits
        A_  :       int										=  tf.TensorShape((1, 1_0_0_0)  )
        self.assertEqual(outputs.logits.shape					,      snake_case_  )

        A_  :       Tuple										=  tf.constant([-0.27_44, 0.82_15, -0.08_36]  )

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






"""simple docstring"""




from transformers import BertTokenizerFast

from .custom_tokenization import CustomTokenizer

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : List[str]	    =   CustomTokenizer
      pass