


import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
      from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor







class        lowerCamelCase__	:






   """simple docstring"""






   def __init__(							self      ,						snake_case      ,						snake_case=13      ,						snake_case=30      ,						snake_case=2      ,						snake_case=3      ,						snake_case=True      ,						snake_case=True      ,						snake_case=32      ,						snake_case=5      ,						snake_case=4      ,						snake_case=37      ,						snake_case="gelu"      ,						snake_case=0.1      ,						snake_case=0.1      ,						snake_case=10      ,						snake_case=0.02      ,						snake_case=None      ,						snake_case=2      ,						):

      '''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
      UpperCamelCase__					=       encoder_stride

      # 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 				snake_case__				(							self     ):

      '''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 				snake_case__				(							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=UpperCamelCase__      ,						initializer_range=self.initializer_range      ,						encoder_stride=self.encoder_stride      ,						)




   def 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

      '''simple docstring'''


      UpperCamelCase__					=       ViTModel(config=UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()
      UpperCamelCase__					=       model(UpperCamelCase__     )
      self.parent.assertEqual(result.last_hidden_state.shape      ,						(self.batch_size, self.seq_length, self.hidden_size)     )




   def 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

      '''simple docstring'''


      UpperCamelCase__					=       ViTForMaskedImageModeling(config=UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()
      UpperCamelCase__					=       model(UpperCamelCase__     )
      self.parent.assertEqual(
          result.reconstruction.shape      ,						(self.batch_size, self.num_channels, self.image_size, self.image_size)     )

      # test greyscale images
      UpperCamelCase__					=       1
      UpperCamelCase__					=       ViTForMaskedImageModeling(UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()

      UpperCamelCase__					=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
      UpperCamelCase__					=       model(UpperCamelCase__     )
      self.parent.assertEqual(result.reconstruction.shape      ,						(self.batch_size, 1, self.image_size, self.image_size)     )




   def 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

      '''simple docstring'''


      UpperCamelCase__					=       self.type_sequence_label_size
      UpperCamelCase__					=       ViTForImageClassification(UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()
      UpperCamelCase__					=       model(UpperCamelCase__      ,						labels=UpperCamelCase__     )
      self.parent.assertEqual(result.logits.shape      ,						(self.batch_size, self.type_sequence_label_size)     )

      # test greyscale images
      UpperCamelCase__					=       1
      UpperCamelCase__					=       ViTForImageClassification(UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()

      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 				snake_case__				(							self     ):

      '''simple docstring'''


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







@require_torch
class        lowerCamelCase__	(							SCREAMING_SNAKE_CASE_					,	SCREAMING_SNAKE_CASE_					,	unittest.TestCase      ):






   """simple docstring"""






   _UpperCamelCase		:					Union[str, Any]    =		(
       (
           ViTModel,
           ViTForImageClassification,
           ViTForMaskedImageModeling,
       )
       if is_torch_available()
       else ()
   )
   _UpperCamelCase		:					int    =		(
       {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
       if is_torch_available()
       else {}
   )
   _UpperCamelCase		:					List[Any]    =		True

   _UpperCamelCase		:					int    =		False
   _UpperCamelCase		:					Dict    =		False
   _UpperCamelCase		:					str    =		False




   def 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       ViTModelTester(self     )
      UpperCamelCase__					=       ConfigTester(self      ,						config_class=UpperCamelCase__      ,						has_text_modality=UpperCamelCase__      ,						hidden_size=37     )




   def 				snake_case__				(							self     ):

      '''simple docstring'''


      self.config_tester.run_common_tests()




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

      '''simple docstring'''


      pass




   def 				snake_case__				(							self     ):

      '''simple docstring'''


      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()      ,						(nn.Module)     )
         UpperCamelCase__					=       model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(UpperCamelCase__      ,						nn.Linear     )     )




   def 				snake_case__				(							self     ):

      '''simple docstring'''


      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.forward     )
         # 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 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*UpperCamelCase__     )




   def 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__     )




   def 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__     )







   @slow
   def 				snake_case__				(							self     ):

      '''simple docstring'''


      for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         UpperCamelCase__					=       ViTModel.from_pretrained(UpperCamelCase__     )
         self.assertIsNotNone(UpperCamelCase__     )



def        UpperCamelCase_(				)->		Optional[int]:
   UpperCamelCase__					=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
   return image







@require_torch
@require_vision
class        lowerCamelCase__	(							unittest.TestCase      ):






   """simple docstring"""






   @cached_property
   def 				snake_case__				(							self     ):

      '''simple docstring'''


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




   @slow
   def 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       ViTForImageClassification.from_pretrained("google/vit-base-patch16-224"     ).to(UpperCamelCase__     )

      UpperCamelCase__					=       self.default_image_processor
      UpperCamelCase__					=       prepare_img()
      UpperCamelCase__					=       image_processor(images=UpperCamelCase__      ,						return_tensors="pt"     ).to(UpperCamelCase__     )

      # forward pass
      with torch.no_grad():
         UpperCamelCase__					=       model(**UpperCamelCase__     )

      # verify the logits
      UpperCamelCase__					=       torch.Size((1, 1000)     )
      self.assertEqual(outputs.logits.shape      ,						UpperCamelCase__     )

      UpperCamelCase__					=       torch.tensor([-0.2744, 0.8215, -0.0836]     ).to(UpperCamelCase__     )

      self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,						UpperCamelCase__      ,						atol=1E-4     )     )




   @slow
   def 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       ViTModel.from_pretrained("facebook/dino-vits8"     ).to(UpperCamelCase__     )

      UpperCamelCase__					=       ViTImageProcessor.from_pretrained("facebook/dino-vits8"      ,						size=480     )
      UpperCamelCase__					=       prepare_img()
      UpperCamelCase__					=       image_processor(images=UpperCamelCase__      ,						return_tensors="pt"     )
      UpperCamelCase__					=       inputs.pixel_values.to(UpperCamelCase__     )

      # forward pass
      with torch.no_grad():
         UpperCamelCase__					=       model(UpperCamelCase__      ,						interpolate_pos_encoding=UpperCamelCase__     )

      # verify the logits
      UpperCamelCase__					=       torch.Size((1, 3601, 384)     )
      self.assertEqual(outputs.last_hidden_state.shape      ,						UpperCamelCase__     )

      UpperCamelCase__					=       torch.tensor(
          [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]     ).to(UpperCamelCase__     )

      self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]      ,						UpperCamelCase__      ,						atol=1E-4     )     )







   @slow
   @require_accelerate
   @require_torch_gpu
   def 				snake_case__				(							self     ):

      '''simple docstring'''


      UpperCamelCase__					=       ViTModel.from_pretrained("facebook/dino-vits8"      ,						torch_dtype=torch.floataa      ,						device_map="auto"     )
      UpperCamelCase__					=       self.default_image_processor

      UpperCamelCase__					=       prepare_img()
      UpperCamelCase__					=       image_processor(images=UpperCamelCase__      ,						return_tensors="pt"     )
      UpperCamelCase__					=       inputs.pixel_values.to(UpperCamelCase__     )

      # forward pass to make sure inference works in fp16
      with torch.no_grad():
         UpperCamelCase__					=       model(UpperCamelCase__     )






def        UpperCamelCase_(				_A   :str  )->		str:
			UpperCamelCase__					=       ""
			for ch in key:
						if ch == " " or ch not in key_no_dups and ch.isalpha():
									key_no_dups += ch
			return key_no_dups
def        UpperCamelCase_(				_A   :str  )->		dict[str, str]:
			UpperCamelCase__					=       [chr(i + 65  ) for i in range(26  )]
			# Remove duplicate characters from key
			UpperCamelCase__					=       remove_duplicates(key.upper()  )
			UpperCamelCase__					=       len(_A  )
			# First fill cipher with key characters
			UpperCamelCase__					=       {alphabet[i]: char for i, char in enumerate(_A  )}
			# Then map remaining characters in alphabet to
			# the alphabet from the beginning
			for i in range(len(_A  )				,     26  ):
						UpperCamelCase__					=       alphabet[i - offset]
						# Ensure we are not mapping letters to letters previously mapped
						while char in key:
									offset -= 1
									UpperCamelCase__					=       alphabet[i - offset]
						UpperCamelCase__					=       char
			return cipher_alphabet
def        UpperCamelCase_(				_A   :str				,     _A   :dict[str, str]  )->		str:
			return "".join(cipher_map.get(_A				,     _A  ) for ch in message.upper()  )
def        UpperCamelCase_(				_A   :str				,     _A   :dict[str, str]  )->		str:
			UpperCamelCase__					=       {v: k for k, v in cipher_map.items()}
			return "".join(rev_cipher_map.get(_A				,     _A  ) for ch in message.upper()  )
def        UpperCamelCase_(				)->		None:
			UpperCamelCase__					=       input("Enter message to encode or decode: "  ).strip()
			UpperCamelCase__					=       input("Enter keyword: "  ).strip()
			UpperCamelCase__					=       input("Encipher or decipher? E/D:"  ).strip()[0].lower()
			try:
						UpperCamelCase__					=       {"e": encipher, "d": decipher}[option]
			except KeyError:
						raise KeyError("invalid input option"  )
			UpperCamelCase__					=       create_cipher_map(_A  )
			print(func(_A				,     _A  )  )


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						main()


