
"""simple docstring"""




import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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 SwinaSRForImageSuperResolution, SwinaSRModel
    from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
    from PIL import Image

    from transformers import SwinaSRImageProcessor







class 	_lowercase    :


     '''simple docstring'''





     def __init__(   self			,      __UpperCamelCase			,      __UpperCamelCase=13			,      __UpperCamelCase=32			,      __UpperCamelCase=1			,      __UpperCamelCase=3			,      __UpperCamelCase=16			,      __UpperCamelCase=[1, 2, 1]			,      __UpperCamelCase=[2, 2, 4]			,      __UpperCamelCase=2			,      __UpperCamelCase=2.0			,      __UpperCamelCase=True			,      __UpperCamelCase=0.0			,      __UpperCamelCase=0.0			,      __UpperCamelCase=0.1			,      __UpperCamelCase="gelu"			,      __UpperCamelCase=False			,      __UpperCamelCase=True			,      __UpperCamelCase=0.02			,      __UpperCamelCase=1E-5			,      __UpperCamelCase=True			,      __UpperCamelCase=None			,      __UpperCamelCase=False			,      __UpperCamelCase=2			,      )->       int:
          UpperCAmelCase__				:			Any							=    parent
          UpperCAmelCase__				:			List[Any]							=    batch_size
          UpperCAmelCase__				:			List[str]							=    image_size
          UpperCAmelCase__				:			Any							=    patch_size
          UpperCAmelCase__				:			int							=    num_channels
          UpperCAmelCase__				:			List[Any]							=    embed_dim
          UpperCAmelCase__				:			List[Any]							=    depths
          UpperCAmelCase__				:			int							=    num_heads
          UpperCAmelCase__				:			Union[str, Any]							=    window_size
          UpperCAmelCase__				:			Optional[Any]							=    mlp_ratio
          UpperCAmelCase__				:			Tuple							=    qkv_bias
          UpperCAmelCase__				:			List[str]							=    hidden_dropout_prob
          UpperCAmelCase__				:			int							=    attention_probs_dropout_prob
          UpperCAmelCase__				:			int							=    drop_path_rate
          UpperCAmelCase__				:			Union[str, Any]							=    hidden_act
          UpperCAmelCase__				:			int							=    use_absolute_embeddings
          UpperCAmelCase__				:			Tuple							=    patch_norm
          UpperCAmelCase__				:			Any							=    layer_norm_eps
          UpperCAmelCase__				:			Tuple							=    initializer_range
          UpperCAmelCase__				:			Tuple							=    is_training
          UpperCAmelCase__				:			List[str]							=    scope
          UpperCAmelCase__				:			List[Any]							=    use_labels
          UpperCAmelCase__				:			Optional[Any]							=    upscale

          # here we set some attributes to make tests pass
          UpperCAmelCase__				:			Tuple							=    len(__UpperCamelCase	)
          UpperCAmelCase__				:			List[str]							=    embed_dim
          UpperCAmelCase__				:			Any							=    (image_size // patch_size) ** 2



     def 			lowerCAmelCase__							(   self	)->       Tuple:
          UpperCAmelCase__				:			List[Any]							=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

          UpperCAmelCase__				:			Dict							=    self.get_config()

          return config, pixel_values, labels



     def 			lowerCAmelCase__							(   self	)->       int:
          return SwinaSRConfig(
              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			,      window_size=self.window_size			,      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			,      use_absolute_embeddings=self.use_absolute_embeddings			,      path_norm=self.patch_norm			,      layer_norm_eps=self.layer_norm_eps			,      initializer_range=self.initializer_range			,      upscale=self.upscale			,      )



     def 			lowerCAmelCase__							(   self			,      __UpperCamelCase			,      __UpperCamelCase			,      __UpperCamelCase	)->       Dict:
          UpperCAmelCase__				:			Union[str, Any]							=    SwinaSRModel(config=__UpperCamelCase	)
          model.to(__UpperCamelCase	)
          model.eval()
          UpperCAmelCase__				:			Dict							=    model(__UpperCamelCase	)

          self.parent.assertEqual(
              result.last_hidden_state.shape			,      (self.batch_size, self.embed_dim, self.image_size, self.image_size)	)



     def 			lowerCAmelCase__							(   self			,      __UpperCamelCase			,      __UpperCamelCase			,      __UpperCamelCase	)->       Union[str, Any]:
          UpperCAmelCase__				:			Any							=    SwinaSRForImageSuperResolution(__UpperCamelCase	)
          model.to(__UpperCamelCase	)
          model.eval()
          UpperCAmelCase__				:			List[str]							=    model(__UpperCamelCase	)

          UpperCAmelCase__				:			str							=    self.image_size * self.upscale
          self.parent.assertEqual(
              result.reconstruction.shape			,      (self.batch_size, self.num_channels, expected_image_size, expected_image_size)	)



     def 			lowerCAmelCase__							(   self	)->       Dict:
          UpperCAmelCase__				:			Union[str, Any]							=    self.prepare_config_and_inputs()
          UpperCAmelCase__				,						UpperCAmelCase__				,						UpperCAmelCase__				:			Any							=    config_and_inputs
          UpperCAmelCase__				:			Optional[int]							=    {"pixel_values": pixel_values}
          return config, inputs_dict







@require_torch
class 	_lowercase    (							lowerCAmelCase_						, lowerCAmelCase_						, unittest.TestCase					):


     '''simple docstring'''





     _A		    =				(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
     _A		    =				{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

     _A		    =				False
     _A		    =				False
     _A		    =				False
     _A		    =				False
     _A		    =				False



     def 			lowerCAmelCase__							(   self	)->       Optional[int]:
          UpperCAmelCase__				:			Any							=    SwinaSRModelTester(self	)
          UpperCAmelCase__				:			Any							=    ConfigTester(self			,      config_class=__UpperCamelCase			,      embed_dim=37	)



     def 			lowerCAmelCase__							(   self	)->       Any:
          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	)->       Optional[int]:
          UpperCAmelCase__				:			Any							=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__UpperCamelCase	)



     def 			lowerCAmelCase__							(   self	)->       int:
          UpperCAmelCase__				:			List[Any]							=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_super_resolution(*__UpperCamelCase	)



     @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0."	)
     def 			lowerCAmelCase__							(   self	)->       Optional[int]:
          pass



     @unittest.skip(reason="Swin2SR does not use inputs_embeds"	)
     def 			lowerCAmelCase__							(   self	)->       str:
          pass



     @unittest.skip(reason="Swin2SR does not support training yet"	)
     def 			lowerCAmelCase__							(   self	)->       Union[str, Any]:
          pass



     @unittest.skip(reason="Swin2SR does not support training yet"	)
     def 			lowerCAmelCase__							(   self	)->       int:
          pass



     def 			lowerCAmelCase__							(   self	)->       Optional[int]:
          UpperCAmelCase__				,						UpperCAmelCase__				:			List[str]							=    self.model_tester.prepare_config_and_inputs_for_common()

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



     def 			lowerCAmelCase__							(   self	)->       List[Any]:
          UpperCAmelCase__				,						UpperCAmelCase__				:			Union[str, Any]							=    self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase__				:			List[Any]							=    ["pixel_values"]
               self.assertListEqual(arg_names[:1]			,      __UpperCamelCase	)



     @slow
     def 			lowerCAmelCase__							(   self	)->       List[Any]:
          for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__				:			Optional[int]							=    SwinaSRModel.from_pretrained(__UpperCamelCase	)
               self.assertIsNotNone(__UpperCamelCase	)



     def 			lowerCAmelCase__							(   self	)->       Optional[int]:
          UpperCAmelCase__				,						UpperCAmelCase__				:			Union[str, Any]							=    self.model_tester.prepare_config_and_inputs_for_common()

          UpperCAmelCase__				:			List[Any]							=    _config_zero_init(__UpperCamelCase	)
          for model_class in self.all_model_classes:
               UpperCAmelCase__				:			Tuple							=    model_class(config=__UpperCamelCase	)
               for name, param in model.named_parameters():
                    if "logit_scale" in name:
                         continue
                    if 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"			,      )



     def 			lowerCAmelCase__							(   self	)->       Dict:
          UpperCAmelCase__				,						UpperCAmelCase__				:			Dict							=    self.model_tester.prepare_config_and_inputs_for_common()
          UpperCAmelCase__				:			Optional[int]							=    True

          for model_class in self.all_model_classes:
               UpperCAmelCase__				:			Dict							=    True
               UpperCAmelCase__				:			int							=    False
               UpperCAmelCase__				:			Tuple							=    True
               UpperCAmelCase__				:			List[Any]							=    model_class(__UpperCamelCase	)
               model.to(__UpperCamelCase	)
               model.eval()
               with torch.no_grad():
                    UpperCAmelCase__				:			str							=    model(**self._prepare_for_class(__UpperCamelCase			,      __UpperCamelCase	)	)
               UpperCAmelCase__				:			List[str]							=    outputs.attentions
               UpperCAmelCase__				:			str							=    len(self.model_tester.depths	)
               self.assertEqual(len(__UpperCamelCase	)			,      __UpperCamelCase	)

               # check that output_attentions also work using config
               del inputs_dict["output_attentions"]
               UpperCAmelCase__				:			Optional[int]							=    True
               UpperCAmelCase__				:			List[Any]							=    config.window_size**2
               UpperCAmelCase__				:			List[Any]							=    model_class(__UpperCamelCase	)
               model.to(__UpperCamelCase	)
               model.eval()
               with torch.no_grad():
                    UpperCAmelCase__				:			Dict							=    model(**self._prepare_for_class(__UpperCamelCase			,      __UpperCamelCase	)	)
               UpperCAmelCase__				:			str							=    outputs.attentions
               self.assertEqual(len(__UpperCamelCase	)			,      __UpperCamelCase	)

               self.assertListEqual(
                   list(attentions[0].shape[-3:]	)			,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,      )
               UpperCAmelCase__				:			Any							=    len(__UpperCamelCase	)

               # Check attention is always last and order is fine
               UpperCAmelCase__				:			Optional[Any]							=    True
               UpperCAmelCase__				:			List[Any]							=    True
               UpperCAmelCase__				:			Dict							=    model_class(__UpperCamelCase	)
               model.to(__UpperCamelCase	)
               model.eval()
               with torch.no_grad():
                    UpperCAmelCase__				:			List[Any]							=    model(**self._prepare_for_class(__UpperCamelCase			,      __UpperCamelCase	)	)

               self.assertEqual(out_len + 1			,      len(__UpperCamelCase	)	)

               UpperCAmelCase__				:			int							=    outputs.attentions

               self.assertEqual(len(__UpperCamelCase	)			,      __UpperCamelCase	)

               self.assertListEqual(
                   list(self_attentions[0].shape[-3:]	)			,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,      )







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


     '''simple docstring'''





     def 			lowerCAmelCase__							(   self	)->       Any:
          UpperCAmelCase__				:			Optional[Any]							=    SwinaSRImageProcessor()
          UpperCAmelCase__				:			Any							=    SwinaSRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64"	).to(__UpperCamelCase	)

          UpperCAmelCase__				:			Tuple							=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
          UpperCAmelCase__				:			str							=    processor(images=__UpperCamelCase			,      return_tensors="pt"	).to(__UpperCamelCase	)

          # forward pass
          with torch.no_grad():
               UpperCAmelCase__				:			Optional[int]							=    model(**__UpperCamelCase	)

          # verify the logits
          UpperCAmelCase__				:			str							=    torch.Size([1, 3, 9_76, 12_96]	)
          self.assertEqual(outputs.reconstruction.shape			,      __UpperCamelCase	)
          UpperCAmelCase__				:			Dict							=    torch.tensor(
              [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]	).to(__UpperCamelCase	)
          self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]			,      __UpperCamelCase			,      atol=1E-4	)	)





"""simple docstring"""




def 				a__			(					lowerCAmelCase						:							str							,     lowerCAmelCase						:							int = 13		):






     '''simple docstring'''
     UpperCAmelCase__				:			Any							=    ""
     for c in s:
          if "A" <= c <= "Z":
               out += chr(ord("A"		) + (ord(lowerCAmelCase		) - ord("A"		) + n) % 26		)
          elif "a" <= c <= "z":
               out += chr(ord("a"		) + (ord(lowerCAmelCase		) - ord("a"		) + n) % 26		)
          else:
               out += c
     return out



def 				a__			(					):






     '''simple docstring'''
     UpperCAmelCase__				:			Optional[int]							=    input("Enter message: "		)

     UpperCAmelCase__				:			Optional[Any]							=    dencrypt(lowerCAmelCase							,     13		)
     print("Encryption:"							,     lowerCAmelCase		)

     UpperCAmelCase__				:			List[str]							=    dencrypt(lowerCAmelCase							,     13		)
     print("Decryption: "							,     lowerCAmelCase		)


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    main()



