




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:



 '''simple docstring'''


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

       """simple docstring"""






       lowerCamelCase_	  =					parent
       lowerCamelCase_	  =					batch_size
       lowerCamelCase_	  =					image_size
       lowerCamelCase_	  =					patch_size
       lowerCamelCase_	  =					num_channels
       lowerCamelCase_	  =					is_training
       lowerCamelCase_	  =					use_labels
       lowerCamelCase_	  =					hidden_size
       lowerCamelCase_	  =					num_hidden_layers
       lowerCamelCase_	  =					num_attention_heads
       lowerCamelCase_	  =					intermediate_size
       lowerCamelCase_	  =					hidden_act
       lowerCamelCase_	  =					hidden_dropout_prob
       lowerCamelCase_	  =					attention_probs_dropout_prob
       lowerCamelCase_	  =					type_sequence_label_size
       lowerCamelCase_	  =					initializer_range
       lowerCamelCase_	  =					scope

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

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

       """simple docstring"""






       lowerCamelCase_	  =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

       lowerCamelCase_	  =					self.get_config()

       return config, pixel_values, labels

 def        a__				(       self      :						Dict						)     ->			Any:

       """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        a__				(       self      :						str		,							A_      :						str		,							A_      :						Optional[int]		,							A_      :						Optional[Any]						)     ->			Optional[int]:

       """simple docstring"""






       lowerCamelCase_	  =					TFViTModel(config=_a						)
       lowerCamelCase_	  =					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.
       lowerCamelCase_	  =					self.image_size // 2
       lowerCamelCase_	  =					pixel_values[:, :, :image_size, :image_size]
       lowerCamelCase_	  =					model(_a		,							interpolate_pos_encoding=_a		,							training=_a						)
       lowerCamelCase_	  =					(image_size // self.patch_size) ** 2 + 1
       self.parent.assertEqual(result.last_hidden_state.shape		,							(self.batch_size, seq_length, self.hidden_size)						)

 def        a__				(       self      :						Optional[int]		,							A_      :						Tuple		,							A_      :						List[str]		,							A_      :						Tuple						)     ->			Optional[Any]:

       """simple docstring"""






       lowerCamelCase_	  =					self.type_sequence_label_size
       lowerCamelCase_	  =					TFViTForImageClassification(_a						)
       lowerCamelCase_	  =					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.
       lowerCamelCase_	  =					self.image_size // 2
       lowerCamelCase_	  =					pixel_values[:, :, :image_size, :image_size]
       lowerCamelCase_	  =					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
       lowerCamelCase_	  =					1
       lowerCamelCase_	  =					TFViTForImageClassification(_a						)
       lowerCamelCase_	  =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       lowerCamelCase_	  =					model(_a						)
       self.parent.assertEqual(result.logits.shape		,							(self.batch_size, self.type_sequence_label_size)						)





 def        a__				(       self      :						Optional[Any]						)     ->			Any:

       """simple docstring"""






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







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



 '''simple docstring'''


 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        a__				(       self      :						List[Any]						)     ->			Any:

       """simple docstring"""






       lowerCamelCase_	  =					TFViTModelTester(self						)
       lowerCamelCase_	  =					ConfigTester(self		,							config_class=_a		,							has_text_modality=_a		,							hidden_size=37						)

 def        a__				(       self      :						List[Any]						)     ->			Tuple:

       """simple docstring"""






       self.config_tester.run_common_tests()

 @unittest.skip(reason='ViT does not use inputs_embeds'						)
 def        a__				(       self      :						int						)     ->			Optional[int]:

       """simple docstring"""






       pass

 @unittest.skip(reason='ViT does not use inputs_embeds'						)
 def        a__				(       self      :						Optional[Any]						)     ->			Optional[int]:

       """simple docstring"""






       pass

 def        a__				(       self      :						Dict						)     ->			Any:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs_for_common()

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

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

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs_for_common()

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

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

 def        a__				(       self      :						Dict						)     ->			Any:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_a						)

 def        a__				(       self      :						Any						)     ->			List[Any]:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_a						)





 @slow
 def        a__				(       self      :						str						)     ->			Tuple:

       """simple docstring"""






       lowerCamelCase_	  =					TFViTModel.from_pretrained('google/vit-base-patch16-224'						)
       self.assertIsNotNone(_a						)

def     _SCREAMING_SNAKE_CASE    (							):


      '''simple docstring'''



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







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



 '''simple docstring'''


 @cached_property
 def        a__				(       self      :						int						)     ->			Optional[Any]:

       """simple docstring"""






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





 @slow
 def        a__				(       self      :						Tuple						)     ->			Dict:

       """simple docstring"""






       lowerCamelCase_	  =					TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'						)

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

       # forward pass
       lowerCamelCase_	  =					model(**_a						)

       # verify the logits
       lowerCamelCase_	  =					tf.TensorShape((1, 1000)						)
       self.assertEqual(outputs.logits.shape		,							_a						)

       lowerCamelCase_	  =					tf.constant([-0.2744, 0.8215, -0.0836]						)

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









class 						A:



 '''simple docstring'''


 def __init__(       self      :						Dict						)     ->			Optional[int]:

       """simple docstring"""






       lowerCamelCase_	  =					0
       lowerCamelCase_	  =					0
       lowerCamelCase_	  =					{}

 def        a__				(       self      :						Union[str, Any]		,							A_      :						List[Any]						)     ->			int:

       """simple docstring"""






       if vertex not in self.adjacency:
             lowerCamelCase_	  =					{}
             self.num_vertices += 1

 def        a__				(       self      :						int		,							A_      :						int		,							A_      :						Optional[Any]		,							A_      :						List[str]						)     ->			Tuple:

       """simple docstring"""






       self.add_vertex(A_						)
       self.add_vertex(A_						)

       if head == tail:
             return

       lowerCamelCase_	  =					weight
       lowerCamelCase_	  =					weight

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

       """simple docstring"""






       lowerCamelCase_	  =					self.get_edges()
       for edge in edges:
             lowerCamelCase_  ,       lowerCamelCase_  ,       lowerCamelCase_	  =					edge
             edges.remove((tail, head, weight)						)
       for i in range(len(A_						)						):
             lowerCamelCase_	  =					list(edges[i]						)

       edges.sort(key=lambda A_						: e[2]						)
       for i in range(len(A_						) - 1						):
             if edges[i][2] >= edges[i + 1][2]:
                   lowerCamelCase_	  =					edges[i][2] + 1
       for edge in edges:
             lowerCamelCase_  ,       lowerCamelCase_  ,       lowerCamelCase_	  =					edge
             lowerCamelCase_	  =					weight
             lowerCamelCase_	  =					weight

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

       """simple docstring"""






       lowerCamelCase_	  =					''
       for tail in self.adjacency:
             for head in self.adjacency[tail]:
                   lowerCamelCase_	  =					self.adjacency[head][tail]
                   string += f"""{head} -> {tail} == {weight}\n"""
       return string.rstrip('\n'						)

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

       """simple docstring"""






       lowerCamelCase_	  =					[]
       for tail in self.adjacency:
             for head in self.adjacency[tail]:
                   output.append((tail, head, self.adjacency[head][tail])						)
       return output

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

       """simple docstring"""






       return self.adjacency.keys()

 @staticmethod
 def        a__				(       A_      :						Optional[Any]=None		,							A_      :						List[str]=None						)     ->			List[str]:

       """simple docstring"""






       lowerCamelCase_	  =					Graph()
       if vertices is None:
             lowerCamelCase_	  =					[]
       if edges is None:
             lowerCamelCase_	  =					[]
       for vertex in vertices:
             g.add_vertex(A_						)
       for edge in edges:
             g.add_edge(*A_						)
       return g







 class 						A:



  '''simple docstring'''


  def __init__(       self      :						Optional[int]						)     ->			int:

        """simple docstring"""






        lowerCamelCase_	  =					{}
        lowerCamelCase_	  =					{}

  def __len__(       self      :						Any						)     ->			List[str]:

        """simple docstring"""






        return len(self.parent						)

  def        a__				(       self      :						List[str]		,							A_      :						Any						)     ->			Dict:

        """simple docstring"""






        if item in self.parent:
              return self.find(A_						)

        lowerCamelCase_	  =					item
        lowerCamelCase_	  =					0
        return item

  def        a__				(       self      :						List[str]		,							A_      :						Tuple						)     ->			Optional[int]:

        """simple docstring"""






        if item not in self.parent:
              return self.make_set(A_						)
        if item != self.parent[item]:
              lowerCamelCase_	  =					self.find(self.parent[item]						)
        return self.parent[item]





  def        a__				(       self      :						Any		,							A_      :						int		,							A_      :						Tuple						)     ->			Union[str, Any]:

        """simple docstring"""






        lowerCamelCase_	  =					self.find(A_						)
        lowerCamelCase_	  =					self.find(A_						)

        if roota == roota:
              return roota

        if self.rank[roota] > self.rank[roota]:
              lowerCamelCase_	  =					roota
              return roota

        if self.rank[roota] < self.rank[roota]:
              lowerCamelCase_	  =					roota
              return roota

        if self.rank[roota] == self.rank[roota]:
              self.rank[roota] += 1
              lowerCamelCase_	  =					roota
              return roota
        return None

 @staticmethod
 def        a__				(       A_      :						int						)     ->			Tuple:

       """simple docstring"""






       lowerCamelCase_	  =					graph.num_vertices

       lowerCamelCase_	  =					Graph.UnionFind()
       lowerCamelCase_	  =					[]
       while num_components > 1:
             lowerCamelCase_	  =					{}
             for vertex in graph.get_vertices():
                   lowerCamelCase_	  =					-1

             lowerCamelCase_	  =					graph.get_edges()
             for edge in edges:
                   lowerCamelCase_  ,       lowerCamelCase_  ,       lowerCamelCase_	  =					edge
                   edges.remove((tail, head, weight)						)
             for edge in edges:
                   lowerCamelCase_  ,       lowerCamelCase_  ,       lowerCamelCase_	  =					edge
                   lowerCamelCase_	  =					union_find.find(A_						)
                   lowerCamelCase_	  =					union_find.find(A_						)
                   if seta != seta:
                         if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
                               lowerCamelCase_	  =					[head, tail, weight]

                         if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
                               lowerCamelCase_	  =					[head, tail, weight]
             for vertex in cheap_edge:
                   if cheap_edge[vertex] != -1:
                         lowerCamelCase_  ,       lowerCamelCase_  ,       lowerCamelCase_	  =					cheap_edge[vertex]
                         if union_find.find(A_						) != union_find.find(A_						):
                               union_find.union(A_		,							A_						)
                               mst_edges.append(cheap_edge[vertex]						)
                               lowerCamelCase_	  =					num_components - 1
       lowerCamelCase_	  =					Graph.build(edges=A_						)
       return mst



