


import collections
import inspect
import unittest

from transformers import DinatConfig
from transformers.testing_utils import require_natten, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
    import torch
    from torch import nn

    from transformers import DinatBackbone, DinatForImageClassification, DinatModel
    from transformers.models.dinat.modeling_dinat import DINAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor







class       _lowercase			:


       """simple docstring"""




       def __init__(       self							:      Optional[Any] ,				__lowerCamelCase							:      Any ,				__lowerCamelCase							:      int=13 ,				__lowerCamelCase							:      Tuple=64 ,				__lowerCamelCase							:      Tuple=4 ,				__lowerCamelCase							:      Dict=3 ,				__lowerCamelCase							:      Optional[int]=16 ,				__lowerCamelCase							:      Union[str, Any]=[1, 2, 1] ,				__lowerCamelCase							:      str=[2, 4, 8] ,				__lowerCamelCase							:      Optional[int]=3 ,				__lowerCamelCase							:      Optional[int]=[[3], [1, 2], [1]] ,				__lowerCamelCase							:      List[Any]=2.0 ,				__lowerCamelCase							:      str=True ,				__lowerCamelCase							:      Tuple=0.0 ,				__lowerCamelCase							:      List[str]=0.0 ,				__lowerCamelCase							:      Optional[Any]=0.1 ,				__lowerCamelCase							:      Tuple="gelu" ,				__lowerCamelCase							:      Any=True ,				__lowerCamelCase							:      Tuple=0.0_2 ,				__lowerCamelCase							:      Union[str, Any]=1E-5 ,				__lowerCamelCase							:      str=True ,				__lowerCamelCase							:      int=None ,				__lowerCamelCase							:      Tuple=True ,				__lowerCamelCase							:      Tuple=10 ,				__lowerCamelCase							:      List[Any]=["stage1", "stage2"] ,				__lowerCamelCase							:      Dict=[1, 2] ,				):


             '''simple docstring'''



             lowerCamelCase__		:    List[str]   =  parent
             lowerCamelCase__		:    str   =  batch_size
             lowerCamelCase__		:    Any   =  image_size
             lowerCamelCase__		:    Any   =  patch_size
             lowerCamelCase__		:    Union[str, Any]   =  num_channels
             lowerCamelCase__		:    Optional[Any]   =  embed_dim
             lowerCamelCase__		:    Any   =  depths
             lowerCamelCase__		:    List[Any]   =  num_heads
             lowerCamelCase__		:    List[Any]   =  kernel_size
             lowerCamelCase__		:    List[str]   =  dilations
             lowerCamelCase__		:    Optional[int]   =  mlp_ratio
             lowerCamelCase__		:    Optional[int]   =  qkv_bias
             lowerCamelCase__		:    Tuple   =  hidden_dropout_prob
             lowerCamelCase__		:    int   =  attention_probs_dropout_prob
             lowerCamelCase__		:    Tuple   =  drop_path_rate
             lowerCamelCase__		:    str   =  hidden_act
             lowerCamelCase__		:    Any   =  patch_norm
             lowerCamelCase__		:    List[Any]   =  layer_norm_eps
             lowerCamelCase__		:    Tuple   =  initializer_range
             lowerCamelCase__		:    Tuple   =  is_training
             lowerCamelCase__		:    List[str]   =  scope
             lowerCamelCase__		:    Tuple   =  use_labels
             lowerCamelCase__		:    Union[str, Any]   =  num_labels
             lowerCamelCase__		:    Optional[Any]   =  out_features
             lowerCamelCase__		:    Any   =  out_indices





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

             lowerCamelCase__		:    str   =  None
             if self.use_labels:
                   lowerCamelCase__		:    Optional[Any]   =  ids_tensor([self.batch_size] ,				self.num_labels	)

             lowerCamelCase__		:    List[Any]   =  self.get_config()

             return config, pixel_values, labels





       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             return DinatConfig(
                 num_labels=self.num_labels ,				image_size=self.image_size ,				patch_size=self.patch_size ,				num_channels=self.num_channels ,				embed_dim=self.embed_dim ,				depths=self.depths ,				num_heads=self.num_heads ,				kernel_size=self.kernel_size ,				dilations=self.dilations ,				mlp_ratio=self.mlp_ratio ,				qkv_bias=self.qkv_bias ,				hidden_dropout_prob=self.hidden_dropout_prob ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob ,				drop_path_rate=self.drop_path_rate ,				hidden_act=self.hidden_act ,				patch_norm=self.patch_norm ,				layer_norm_eps=self.layer_norm_eps ,				initializer_range=self.initializer_range ,				out_features=self.out_features ,				out_indices=self.out_indices ,				)





       def 						lowerCAmelCase					(       self							:      int ,				__lowerCamelCase							:      Optional[int] ,				__lowerCamelCase							:      List[str] ,				__lowerCamelCase							:      int	):


             '''simple docstring'''



             lowerCamelCase__		:    Any   =  DinatModel(config=__lowerCamelCase	)
             model.to(__lowerCamelCase	)
             model.eval()
             lowerCamelCase__		:    Tuple   =  model(__lowerCamelCase	)

             lowerCamelCase__		:    str   =  (config.image_size // config.patch_size) // (2 ** (len(config.depths	) - 1))
             lowerCamelCase__		:    Optional[Any]   =  int(config.embed_dim * 2 ** (len(config.depths	) - 1)	)

             self.parent.assertEqual(
                 result.last_hidden_state.shape ,				(self.batch_size, expected_height, expected_width, expected_dim)	)





       def 						lowerCAmelCase					(       self							:      List[str] ,				__lowerCamelCase							:      List[str] ,				__lowerCamelCase							:      Union[str, Any] ,				__lowerCamelCase							:      List[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  DinatForImageClassification(__lowerCamelCase	)
             model.to(__lowerCamelCase	)
             model.eval()
             lowerCamelCase__		:    Any   =  model(__lowerCamelCase ,				labels=__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)	)

             # test greyscale images
             lowerCamelCase__		:    str   =  1
             lowerCamelCase__		:    List[Any]   =  DinatForImageClassification(__lowerCamelCase	)
             model.to(__lowerCamelCase	)
             model.eval()

             lowerCamelCase__		:    Optional[int]   =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
             lowerCamelCase__		:    str   =  model(__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)	)





       def 						lowerCAmelCase					(       self							:      List[Any] ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      Dict ,				__lowerCamelCase							:      Optional[int]	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  DinatBackbone(config=__lowerCamelCase	)
             model.to(__lowerCamelCase	)
             model.eval()
             lowerCamelCase__		:    List[Any]   =  model(__lowerCamelCase	)

             # verify hidden states
             self.parent.assertEqual(len(result.feature_maps	) ,				len(config.out_features	)	)
             self.parent.assertListEqual(list(result.feature_maps[0].shape	) ,				[self.batch_size, model.channels[0], 16, 16]	)

             # verify channels
             self.parent.assertEqual(len(model.channels	) ,				len(config.out_features	)	)

             # verify backbone works with out_features=None
             lowerCamelCase__		:    str   =  None
             lowerCamelCase__		:    List[Any]   =  DinatBackbone(config=__lowerCamelCase	)
             model.to(__lowerCamelCase	)
             model.eval()
             lowerCamelCase__		:    str   =  model(__lowerCamelCase	)

             # verify feature maps
             self.parent.assertEqual(len(result.feature_maps	) ,				1	)
             self.parent.assertListEqual(list(result.feature_maps[0].shape	) ,				[self.batch_size, model.channels[-1], 4, 4]	)

             # verify channels
             self.parent.assertEqual(len(model.channels	) ,				1	)





       def 						lowerCAmelCase					(       self							:      Optional[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  self.prepare_config_and_inputs()
             lowerCamelCase__   ,       lowerCamelCase__   ,       lowerCamelCase__		:    Dict   =  config_and_inputs
             lowerCamelCase__		:    Union[str, Any]   =  {"pixel_values": pixel_values}
             return config, inputs_dict







@require_natten
@require_torch
class       _lowercase			(							lowercase__							,  lowercase__							,  unittest.TestCase):


       """simple docstring"""




       A__ 						=      (
           (
               DinatModel,
               DinatForImageClassification,
               DinatBackbone,
           )
           if is_torch_available()
           else ()
       )
       A__ 						=      (
           {"feature-extraction": DinatModel, "image-classification": DinatForImageClassification}
           if is_torch_available()
           else {}
       )
       A__ 						=      False

       A__ 						=      False
       A__ 						=      False
       A__ 						=      False
       A__ 						=      False





       def 						lowerCAmelCase					(       self							:      Dict	):


             '''simple docstring'''



             lowerCamelCase__		:    str   =  DinatModelTester(self	)
             lowerCamelCase__		:    List[str]   =  ConfigTester(self ,				config_class=__lowerCamelCase ,				embed_dim=37	)





       def 						lowerCAmelCase					(       self							:      Optional[Any]	):


             '''simple docstring'''



             self.create_and_test_config_common_properties()
             self.config_tester.create_and_test_config_to_json_string()
             self.config_tester.create_and_test_config_to_json_file()
             self.config_tester.create_and_test_config_from_and_save_pretrained()
             self.config_tester.create_and_test_config_with_num_labels()
             self.config_tester.check_config_can_be_init_without_params()
             self.config_tester.check_config_arguments_init()





       def 						lowerCAmelCase					(       self							:      Dict	):


             '''simple docstring'''



             return





       def 						lowerCAmelCase					(       self							:      Any	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Any   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    str   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_backbone(*__lowerCamelCase	)





       @unittest.skip(reason="Dinat does not use inputs_embeds"	)
       def 						lowerCAmelCase					(       self							:      Optional[int]	):


             '''simple docstring'''



             pass





       @unittest.skip(reason="Dinat does not use feedforward chunking"	)
       def 						lowerCAmelCase					(       self							:      Dict	):


             '''simple docstring'''



             pass





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



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

             for model_class in self.all_model_classes:
                   lowerCamelCase__		:    List[Any]   =  model_class(__lowerCamelCase	)
                   self.assertIsInstance(model.get_input_embeddings() ,				(nn.Module)	)
                   lowerCamelCase__		:    Optional[int]   =  model.get_output_embeddings()
                   self.assertTrue(x is None or isinstance(__lowerCamelCase ,				nn.Linear	)	)





       def 						lowerCAmelCase					(       self							:      Any	):


             '''simple docstring'''



             lowerCamelCase__   ,       lowerCamelCase__		:    List[Any]   =  self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   lowerCamelCase__		:    List[Any]   =  model_class(__lowerCamelCase	)
                   lowerCamelCase__		:    List[str]   =  inspect.signature(model.forward	)
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   lowerCamelCase__		:    Tuple   =  [*signature.parameters.keys()]

                   lowerCamelCase__		:    str   =  ["pixel_values"]
                   self.assertListEqual(arg_names[:1] ,				__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Dict	):


             '''simple docstring'''



             self.skipTest("Dinat's attention operation is handled entirely by NATTEN."	)





       def 						lowerCAmelCase					(       self							:      str ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      Dict	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[Any]   =  model_class(__lowerCamelCase	)
             model.to(__lowerCamelCase	)
             model.eval()

             with torch.no_grad():
                   lowerCamelCase__		:    List[Any]   =  model(**self._prepare_for_class(__lowerCamelCase ,				__lowerCamelCase	)	)

             lowerCamelCase__		:    Optional[int]   =  outputs.hidden_states

             lowerCamelCase__		:    Optional[int]   =  getattr(
                 self.model_tester ,				"expected_num_hidden_layers" ,				len(self.model_tester.depths	) + 1	)
             self.assertEqual(len(__lowerCamelCase	) ,				__lowerCamelCase	)

             # Dinat has a different seq_length
             lowerCamelCase__		:    Union[str, Any]   =  (
                 config.patch_size
                 if isinstance(config.patch_size ,				collections.abc.Iterable	)
                 else (config.patch_size, config.patch_size)
             )

             lowerCamelCase__		:    str   =  image_size[0] // patch_size[0]
             lowerCamelCase__		:    int   =  image_size[1] // patch_size[1]

             self.assertListEqual(
                 list(hidden_states[0].shape[-3:]	) ,				[height, width, self.model_tester.embed_dim] ,				)

             if model_class.__name__ != "DinatBackbone":
                   lowerCamelCase__		:    Any   =  outputs.reshaped_hidden_states
                   self.assertEqual(len(__lowerCamelCase	) ,				__lowerCamelCase	)

                   lowerCamelCase__   ,       lowerCamelCase__   ,       lowerCamelCase__   ,       lowerCamelCase__		:    str   =  reshaped_hidden_states[0].shape
                   lowerCamelCase__		:    Dict   =  (
                       reshaped_hidden_states[0].view(__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase	).permute(0 ,				2 ,				3 ,				1	)
                   )
                   self.assertListEqual(
                       list(reshaped_hidden_states.shape[-3:]	) ,				[height, width, self.model_tester.embed_dim] ,				)





       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             lowerCamelCase__   ,       lowerCamelCase__		:    Dict   =  self.model_tester.prepare_config_and_inputs_for_common()

             lowerCamelCase__		:    Optional[Any]   =  (
                 self.model_tester.image_size
                 if isinstance(self.model_tester.image_size ,				collections.abc.Iterable	)
                 else (self.model_tester.image_size, self.model_tester.image_size)
             )

             for model_class in self.all_model_classes:
                   lowerCamelCase__		:    Optional[int]   =  True
                   self.check_hidden_states_output(__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase	)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   lowerCamelCase__		:    str   =  True

                   self.check_hidden_states_output(__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase	)





       @slow
       def 						lowerCAmelCase					(       self							:      Optional[int]	):


             '''simple docstring'''



             for model_name in DINAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   lowerCamelCase__		:    Optional[Any]   =  DinatModel.from_pretrained(__lowerCamelCase	)
                   self.assertIsNotNone(__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      List[str]	):


             '''simple docstring'''



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

             lowerCamelCase__		:    int   =  _config_zero_init(__lowerCamelCase	)
             for model_class in self.all_model_classes:
                   lowerCamelCase__		:    str   =  model_class(config=__lowerCamelCase	)
                   for name, param in model.named_parameters():
                         if "embeddings" not in name and param.requires_grad:
                               self.assertIn(
                                   ((param.data.mean() * 1E9).round() / 1E9).item() ,				[0.0, 1.0] ,				msg=f"Parameter {name} of model {model_class} seems not properly initialized" ,				)







@require_natten
@require_vision
@require_torch
class       _lowercase			(							unittest.TestCase):


       """simple docstring"""




       @cached_property
       def 						lowerCAmelCase					(       self							:      Dict	):


             '''simple docstring'''



             return AutoImageProcessor.from_pretrained("shi-labs/dinat-mini-in1k-224"	) if is_vision_available() else None





       @slow
       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[Any]   =  DinatForImageClassification.from_pretrained("shi-labs/dinat-mini-in1k-224"	).to(__lowerCamelCase	)
             lowerCamelCase__		:    int   =  self.default_image_processor

             lowerCamelCase__		:    List[Any]   =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
             lowerCamelCase__		:    int   =  image_processor(images=__lowerCamelCase ,				return_tensors="pt"	).to(__lowerCamelCase	)

             # forward pass
             with torch.no_grad():
                   lowerCamelCase__		:    Tuple   =  model(**__lowerCamelCase	)

             # verify the logits
             lowerCamelCase__		:    int   =  torch.Size((1, 1000)	)
             self.assertEqual(outputs.logits.shape ,				__lowerCamelCase	)
             lowerCamelCase__		:    List[str]   =  torch.tensor([-0.1_5_4_5, -0.7_6_6_7, 0.4_6_4_2]	).to(__lowerCamelCase	)
             self.assertTrue(torch.allclose(outputs.logits[0, :3] ,				__lowerCamelCase ,				atol=1E-4	)	)







@require_torch
@require_natten
class       _lowercase			(							unittest.TestCase							,  lowercase__):


       """simple docstring"""




       A__ 						=      (DinatBackbone,) if is_torch_available() else ()
       A__ 						=      DinatConfig





       def 						lowerCAmelCase					(       self							:      Optional[int]	):


             '''simple docstring'''



             lowerCamelCase__		:    Dict   =  DinatModelTester(self	)






A				:   Union[str, Any]		= {
    "A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
    "B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
    "C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
    "D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
    "E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
    "F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
    "G": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"),
    "H": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"),
    "I": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"),
    "J": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"),
    "K": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"),
    "L": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"),
    "M": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"),
    "N": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"),
    "O": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"),
    "P": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"),
    "Q": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"),
    "R": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"),
    "S": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"),
    "T": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"),
    "U": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"),
    "V": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"),
    "W": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"),
    "X": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"),
    "Y": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"),
    "Z": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"),
}

def 				lowercase_		(		_A      :   str						):

      """simple docstring"""




      return [alphabet[char] for char in key.upper()]

def 				lowercase_		(		_A      :   str   , _A      :   str						):

      """simple docstring"""




      lowerCamelCase__		:    List[str]   =  ""
      lowerCamelCase__		:    Union[str, Any]   =  0
      lowerCamelCase__		:    Any   =  generate_table(_A						)
      for char in words.upper():
            cipher += get_opponent(table[count]   , _A						)
            lowerCamelCase__		:    Optional[int]   =  (count + 1) % len(_A						)
      return cipher

def 				lowercase_		(		_A      :   str   , _A      :   str						):

      """simple docstring"""




      return encrypt(_A   , _A						)

def 				lowercase_		(		_A      :   tuple[str, str]   , _A      :   str						):

      """simple docstring"""




      lowerCamelCase__		:    List[Any]   =  0 if char in table[0] else 1
      lowerCamelCase__		:    List[Any]   =  table[row].index(_A						)
      return row, col

def 				lowercase_		(		_A      :   tuple[str, str]   , _A      :   str						):

      """simple docstring"""




      lowerCamelCase__   ,       lowerCamelCase__		:    List[str]   =  get_position(_A   , char.upper()						)
      if row == 1:
            return table[0][col]
      else:
            return table[1][col] if row == 0 else char


if __name__ == "__main__":
    import doctest

    doctest.testmod()  # Fist ensure that all our tests are passing...
    A				:   List[str]		= input("Enter key: ").strip()
    A				:   Tuple		= input("Enter text to encrypt: ").strip()
    A				:   Dict		= encrypt(key, text)

    print(f'Encrypted: {cipher_text}')
    print(f'Decrypted with key: {decrypt(key, cipher_text)}')


