


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 		_snake_case    :






						'''simple docstring'''







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

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







						def lowerCAmelCase__ (  self:	Any     )							->	Optional[Any]:
										__magic_name__				:					Optional[int]						       =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

										__magic_name__				:					Union[str, Any]						       =       self.get_config()

										return config, pixel_values, labels







						def lowerCAmelCase__ (  self:	List[str]     )							->	Tuple:
										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:	Optional[int]      ,							__UpperCamelCase:	List[str]      ,							__UpperCamelCase:	Dict      ,							__UpperCamelCase:	int     )							->	Tuple:
										__magic_name__				:					Union[str, Any]						       =       SwinaSRModel(config=__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					List[Any]						       =       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:	Any      ,							__UpperCamelCase:	Any      ,							__UpperCamelCase:	Union[str, Any]      ,							__UpperCamelCase:	Dict     )							->	str:
										__magic_name__				:					List[str]						       =       SwinaSRForImageSuperResolution(__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					Dict						       =       model(__UpperCamelCase     )

										__magic_name__				:					Tuple						       =       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:	Tuple     )							->	Optional[int]:
										__magic_name__				:					Optional[Any]						       =       self.prepare_config_and_inputs()
										__magic_name__				:					Any						       =       config_and_inputs
										__magic_name__				:					str						       =       {"pixel_values": pixel_values}
										return config, inputs_dict






@require_torch
class 		_snake_case    (				snake_case_  ,  snake_case_  ,  unittest.TestCase		):






						'''simple docstring'''







						__snake_case   =      (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
						__snake_case   =      {"feature-extraction": SwinaSRModel} if is_torch_available() else {}

						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False







						def lowerCAmelCase__ (  self:	Dict     )							->	Dict:
										__magic_name__				:					Tuple						       =       SwinaSRModelTester(self     )
										__magic_name__				:					List[Any]						       =       ConfigTester(self      ,							config_class=__UpperCamelCase      ,							embed_dim=37     )







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







						def lowerCAmelCase__ (  self:	Any     )							->	List[str]:
										__magic_name__				:					Tuple						       =       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:	Tuple     )							->	List[Any]:
										pass







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







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







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







						def lowerCAmelCase__ (  self:	Dict     )							->	Dict:
										__magic_name__				:					Optional[Any]						       =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														__magic_name__				:					Union[str, Any]						       =       model_class(__UpperCamelCase     )
														self.assertIsInstance(model.get_input_embeddings()      ,							(nn.Module)     )
														__magic_name__				:					List[Any]						       =       model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(__UpperCamelCase      ,							nn.Linear     )     )







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

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

														__magic_name__				:					Tuple						       =       ["pixel_values"]
														self.assertListEqual(arg_names[:1]      ,							__UpperCamelCase     )







						@slow
						def lowerCAmelCase__ (  self:	Dict     )							->	str:
										for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__magic_name__				:					Dict						       =       SwinaSRModel.from_pretrained(__UpperCamelCase     )
														self.assertIsNotNone(__UpperCamelCase     )







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

										__magic_name__				:					Optional[Any]						       =       _config_zero_init(__UpperCamelCase     )
										for model_class in self.all_model_classes:
														__magic_name__				:					Any						       =       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:	Optional[Any]     )							->	int:
										__magic_name__				:					List[Any]						       =       self.model_tester.prepare_config_and_inputs_for_common()
										__magic_name__				:					Any						       =       True

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

														# check that output_attentions also work using config
														del inputs_dict["output_attentions"]
														__magic_name__				:					str						       =       True
														__magic_name__				:					str						       =       config.window_size**2
														__magic_name__				:					Any						       =       model_class(__UpperCamelCase     )
														model.to(__UpperCamelCase     )
														model.eval()
														with torch.no_grad():
																		__magic_name__				:					Union[str, Any]						       =       model(**self._prepare_for_class(__UpperCamelCase      ,							__UpperCamelCase     )     )
														__magic_name__				:					Tuple						       =       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]      ,							)
														__magic_name__				:					str						       =       len(__UpperCamelCase     )

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

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

														__magic_name__				:					Tuple						       =       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 		_snake_case    (				unittest.TestCase		):






						'''simple docstring'''







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

										__magic_name__				:					Optional[Any]						       =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
										__magic_name__				:					Dict						       =       processor(images=__UpperCamelCase      ,							return_tensors="pt"     ).to(__UpperCamelCase     )

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

										# verify the logits
										__magic_name__				:					List[str]						       =       torch.Size([1, 3, 976, 1296]     )
										self.assertEqual(outputs.reconstruction.shape      ,							__UpperCamelCase     )
										__magic_name__				:					List[str]						       =       torch.tensor(
										    [[0.5_4_5_8, 0.5_5_4_6, 0.5_6_3_8], [0.5_5_2_6, 0.5_5_6_5, 0.5_6_5_1], [0.5_3_9_6, 0.5_4_2_6, 0.5_6_2_1]]     ).to(__UpperCamelCase     )
										self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]      ,							__UpperCamelCase      ,							atol=1E-4     )     )



'''simple docstring'''







def 						_UpperCamelCase							( UpperCamelCase__     ,   UpperCamelCase__		):






				"""simple docstring"""



				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("plaintext must be a string"		)
				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("key must be a string"		)

				if not plaintext:
								raise ValueError("plaintext is empty"		)
				if not key:
								raise ValueError("key is empty"		)

				key += plaintext
				__magic_name__				:					List[str]						       =       plaintext.lower()
				__magic_name__				:					Tuple						       =       key.lower()
				__magic_name__				:					Dict						       =       0
				__magic_name__				:					Optional[int]						       =       0
				__magic_name__				:					List[str]						       =       ""
				while plaintext_iterator < len(UpperCamelCase__		):
								if (
								    ord(plaintext[plaintext_iterator]		) < 97
								    or ord(plaintext[plaintext_iterator]		) > 122
								):
												ciphertext += plaintext[plaintext_iterator]
												plaintext_iterator += 1
								elif ord(key[key_iterator]		) < 97 or ord(key[key_iterator]		) > 122:
												key_iterator += 1
								else:
												ciphertext += chr(
												    (
												        (ord(plaintext[plaintext_iterator]		) - 97 + ord(key[key_iterator]		))
												        - 97
												    )
												    % 26
												    + 97		)
												key_iterator += 1
												plaintext_iterator += 1
				return ciphertext



def 						_UpperCamelCase							( UpperCamelCase__     ,   UpperCamelCase__		):






				"""simple docstring"""



				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("ciphertext must be a string"		)
				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("key must be a string"		)

				if not ciphertext:
								raise ValueError("ciphertext is empty"		)
				if not key:
								raise ValueError("key is empty"		)

				__magic_name__				:					List[str]						       =       key.lower()
				__magic_name__				:					str						       =       0
				__magic_name__				:					Optional[Any]						       =       0
				__magic_name__				:					Tuple						       =       ""
				while ciphertext_iterator < len(UpperCamelCase__		):
								if (
								    ord(ciphertext[ciphertext_iterator]		) < 97
								    or ord(ciphertext[ciphertext_iterator]		) > 122
								):
												plaintext += ciphertext[ciphertext_iterator]
								else:
												plaintext += chr(
												    (ord(ciphertext[ciphertext_iterator]		) - ord(key[key_iterator]		)) % 26
												    + 97		)
												key += chr(
												    (ord(ciphertext[ciphertext_iterator]		) - ord(key[key_iterator]		)) % 26
												    + 97		)
												key_iterator += 1
								ciphertext_iterator += 1
				return plaintext


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		_SCREAMING_SNAKE_CASE       :   Tuple        = int(input("Type 1 to encrypt or 2 to decrypt:"))
		if operation == 1:
				_SCREAMING_SNAKE_CASE       :   Optional[Any]        = input("Typeplaintext to be encrypted:\n")
				_SCREAMING_SNAKE_CASE       :   Tuple        = input("Type the key:\n")
				print(encrypt(plaintext, key))
		elif operation == 2:
				_SCREAMING_SNAKE_CASE       :   Optional[Any]        = input("Type the ciphertext to be decrypted:\n")
				_SCREAMING_SNAKE_CASE       :   List[str]        = input("Type the key:\n")
				print(decrypt(ciphertext, key))
		decrypt("jsqqs avvwo", "coffee")