



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







       '''simple docstring'''


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


             '''simple docstring'''




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

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



       def 	lowercase__							(				self     :    Dict       )					->		Optional[Any]:


             '''simple docstring'''




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

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

             UpperCAmelCase_     					=				self.get_config()

             return config, pixel_values, labels



       def 	lowercase__							(				self     :    int       )					->		Dict:


             '''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=_UpperCAmelCase						,							initializer_range=self.initializer_range						,							)



       def 	lowercase__							(				self     :    Optional[int]						,							_UpperCAmelCase     :    List[Any]						,							_UpperCAmelCase     :    Any						,							_UpperCAmelCase     :    Optional[int]       )					->		List[str]:


             '''simple docstring'''




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



       def 	lowercase__							(				self     :    Any						,							_UpperCAmelCase     :    Union[str, Any]						,							_UpperCAmelCase     :    Any						,							_UpperCAmelCase     :    str       )					->		List[Any]:


             '''simple docstring'''




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







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


             '''simple docstring'''




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



@require_tf
class  lowercase__  (       SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   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 	lowercase__							(				self     :    Any       )					->		List[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				TFViTModelTester(self       )
             UpperCAmelCase_     					=				ConfigTester(self						,							config_class=_UpperCAmelCase						,							has_text_modality=_UpperCAmelCase						,							hidden_size=37       )



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


             '''simple docstring'''




             self.config_tester.run_common_tests()



       @unittest.skip(reason="ViT does not use inputs_embeds"       )
       def 	lowercase__							(				self     :    Optional[Any]       )					->		List[Any]:


             '''simple docstring'''




             pass



       @unittest.skip(reason="ViT does not use inputs_embeds"       )
       def 	lowercase__							(				self     :    List[str]       )					->		List[Any]:


             '''simple docstring'''




             pass



       def 	lowercase__							(				self     :    str       )					->		str:


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

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



       def 	lowercase__							(				self     :    Tuple       )					->		str:


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

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

                   UpperCAmelCase_     					=				["pixel_values"]
                   self.assertListEqual(arg_names[:1]						,							_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )







       @slow
       def 	lowercase__							(				self     :    int       )					->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_     					=				TFViTModel.from_pretrained("google/vit-base-patch16-224"       )
             self.assertIsNotNone(_UpperCAmelCase       )



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


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







       '''simple docstring'''


       @cached_property
       def 	lowercase__							(				self     :    Union[str, Any]       )					->		List[Any]:


             '''simple docstring'''




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







       @slow
       def 	lowercase__							(				self     :    int       )					->		Any:


             '''simple docstring'''




             UpperCAmelCase_     					=				TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"       )

             UpperCAmelCase_     					=				self.default_image_processor
             UpperCAmelCase_     					=				prepare_img()
             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="tf"       )

             # forward pass
             UpperCAmelCase_     					=				model(**_UpperCAmelCase       )

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

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

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





def 		snake_case__	(		lowercase							,				lowercase					):
   lowerCAmelCase_:							list[list[str]]       =	[[] for _ in range(lowercase					)]
   lowerCAmelCase_:							Optional[Any]       =	key - 1

   if key <= 0:
      raise ValueError("Height of grid can't be 0 or negative"					)
   if key == 1 or len(lowercase					) <= key:
      return input_string

   for position, character in enumerate(lowercase					):
      lowerCAmelCase_:							Optional[Any]       =	position % (lowest * 2)  # puts it in bounds
      lowerCAmelCase_:							Any       =	min(lowercase							,				lowest * 2 - num					)  # creates zigzag pattern
      temp_grid[num].append(lowercase					)
   lowerCAmelCase_:							Optional[int]       =	["".join(lowercase					) for row in temp_grid]
   lowerCAmelCase_:							int       =	"".join(lowercase					)

   return output_string
def 		snake_case__	(		lowercase							,				lowercase					):
   lowerCAmelCase_:							Tuple       =	[]
   lowerCAmelCase_:							str       =	key - 1

   if key <= 0:
      raise ValueError("Height of grid can't be 0 or negative"					)
   if key == 1:
      return input_string

   lowerCAmelCase_:							list[list[str]]       =	[[] for _ in range(lowercase					)]  # generates template
   for position in range(len(lowercase					)					):
      lowerCAmelCase_:							List[str]       =	position % (lowest * 2)  # puts it in bounds
      lowerCAmelCase_:							Optional[int]       =	min(lowercase							,				lowest * 2 - num					)  # creates zigzag pattern
      temp_grid[num].append("*"					)

   lowerCAmelCase_:							Optional[Any]       =	0
   for row in temp_grid:  # fills in the characters
      lowerCAmelCase_:							Tuple       =	input_string[counter : counter + len(lowercase					)]
      grid.append(list(lowercase					)					)
      counter += len(lowercase					)

   lowerCAmelCase_:							int       =	""  # reads as zigzag
   for position in range(len(lowercase					)					):
      lowerCAmelCase_:							str       =	position % (lowest * 2)  # puts it in bounds
      lowerCAmelCase_:							Optional[int]       =	min(lowercase							,				lowest * 2 - num					)  # creates zigzag pattern
      output_string += grid[num][0]
      grid[num].pop(0					)
   return output_string
def 		snake_case__	(		lowercase					):
   lowerCAmelCase_:							Dict       =	{}
   for key_guess in range(1							,				len(lowercase					)					):  # tries every key
      lowerCAmelCase_:							int       =	decrypt(lowercase							,				lowercase					)
   return results


if __name__ == "__main__":
 import doctest

 doctest.testmod()