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






			'''simple docstring'''

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

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

			def 					lowerCAmelCase__		(				self       :				Dict					):
							UpperCamelCase_:							List[Any]		=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

							UpperCamelCase_:							Union[str, Any]		=  None
							if self.use_labels:
											UpperCamelCase_:							List[str]		=  ids_tensor([self.batch_size]  ,		self.type_sequence_label_size					)

							UpperCamelCase_:							Dict		=  self.get_config()

							return config, pixel_values, labels

			def 					lowerCAmelCase__		(				self       :				Optional[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       :				Any  ,		snake_case_       :				Any  ,		snake_case_       :				Union[str, Any]  ,		snake_case_       :				Optional[Any]					):
							UpperCamelCase_:							Optional[Any]		=  SwinaSRModel(config=snake_case_					)
							model.to(snake_case_					)
							model.eval()
							UpperCamelCase_:							Dict		=  model(snake_case_					)

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

			def 					lowerCAmelCase__		(				self       :				Union[str, Any]  ,		snake_case_       :				Dict  ,		snake_case_       :				Optional[int]  ,		snake_case_       :				List[Any]					):
							UpperCamelCase_:							Tuple		=  SwinaSRForImageSuperResolution(snake_case_					)
							model.to(snake_case_					)
							model.eval()
							UpperCamelCase_:							Union[str, Any]		=  model(snake_case_					)

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




@require_torch
class 				_UpperCamelCase (    _A   ,				_A   ,				unittest.TestCase     ):






			'''simple docstring'''

			__UpperCamelCase					:  Optional[Any]    					=       (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
			__UpperCamelCase					:  Any    					=       {"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

			__UpperCamelCase					:  str    					=       False
			__UpperCamelCase					:  Tuple    					=       False
			__UpperCamelCase					:  List[Any]    					=       False
			__UpperCamelCase					:  Union[str, Any]    					=       False
			__UpperCamelCase					:  str    					=       False

			def 					lowerCAmelCase__		(				self       :				int					):
							UpperCamelCase_:							Tuple		=  SwinaSRModelTester(self					)
							UpperCamelCase_:							str		=  ConfigTester(self  ,		config_class=snake_case_  ,		embed_dim=37					)

			def 					lowerCAmelCase__		(				self       :				str					):
							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       :				Union[str, Any]					):
							UpperCamelCase_:							Dict		=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*snake_case_					)

			def 					lowerCAmelCase__		(				self       :				Union[str, Any]					):
							UpperCamelCase_:							Optional[Any]		=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_super_resolution(*snake_case_					)

			@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       :				List[Any]					):
							pass

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

			@unittest.skip(reason="""Swin2SR does not support training yet"""					)
			def 					lowerCAmelCase__		(				self       :				List[Any]					):
							pass

			def 					lowerCAmelCase__		(				self       :				List[str]					):
							UpperCamelCase_,      UpperCamelCase_:							int		=  self.model_tester.prepare_config_and_inputs_for_common()

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

			def 					lowerCAmelCase__		(				self       :				int					):
							UpperCamelCase_,      UpperCamelCase_:							str		=  self.model_tester.prepare_config_and_inputs_for_common()

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

											UpperCamelCase_:							int		=  ["""pixel_values"""]
											self.assertListEqual(arg_names[:1]  ,		snake_case_					)

			@slow
			def 					lowerCAmelCase__		(				self       :				Optional[int]					):
							for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCamelCase_:							Any		=  SwinaSRModel.from_pretrained(snake_case_					)
											self.assertIsNotNone(snake_case_					)

			def 					lowerCAmelCase__		(				self       :				str					):
							UpperCamelCase_,      UpperCamelCase_:							int		=  self.model_tester.prepare_config_and_inputs_for_common()

							UpperCamelCase_:							Tuple		=  _config_zero_init(snake_case_					)
							for model_class in self.all_model_classes:
											UpperCamelCase_:							Tuple		=  model_class(config=snake_case_					)
											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       :				List[str]					):
							UpperCamelCase_,      UpperCamelCase_:							Optional[int]		=  self.model_tester.prepare_config_and_inputs_for_common()
							UpperCamelCase_:							Union[str, Any]		=  True

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

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

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

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

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

											UpperCamelCase_:							Optional[int]		=  outputs.attentions

											self.assertEqual(len(snake_case_					)  ,		snake_case_					)

											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 				_UpperCamelCase (    unittest.TestCase     ):






			'''simple docstring'''

			def 					lowerCAmelCase__		(				self       :				Dict					):
							UpperCamelCase_:							Dict		=  SwinaSRImageProcessor()
							UpperCamelCase_:							List[Any]		=  SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""					).to(snake_case_					)

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

							# forward pass
							with torch.no_grad():
											UpperCamelCase_:							List[Any]		=  model(**snake_case_					)

							# verify the logits
							UpperCamelCase_:							Optional[int]		=  torch.Size([1, 3, 976, 1296]					)
							self.assertEqual(outputs.reconstruction.shape  ,		snake_case_					)
							UpperCamelCase_:							str		=  torch.tensor(
							    [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]					).to(snake_case_					)
							self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]  ,		snake_case_  ,		atol=1e-4					)					)








from math import cos, sin







def 				A__    (  lowerCamelCase  )     ->		list[list[float]]:
				UpperCamelCase_:							int		=  float(lowerCamelCase  )
				return [[scaling_factor * int(x == y  ) for x in range(2  )] for y in range(2  )]







def 				A__    (  lowerCamelCase  )     ->		list[list[float]]:
				UpperCamelCase_,      UpperCamelCase_:							Union[str, Any]		=  cos(lowerCamelCase  ), sin(lowerCamelCase  )
				return [[c, -s], [s, c]]







def 				A__    (  lowerCamelCase  )     ->		list[list[float]]:
				UpperCamelCase_,      UpperCamelCase_:							Any		=  cos(lowerCamelCase  ), sin(lowerCamelCase  )
				UpperCamelCase_:							List[Any]		=  c * s
				return [[c * c, cs], [cs, s * s]]







def 				A__    (  lowerCamelCase  )     ->		list[list[float]]:
				UpperCamelCase_,      UpperCamelCase_:							List[str]		=  cos(lowerCamelCase  ), sin(lowerCamelCase  )
				UpperCamelCase_:							int		=  c * s
				return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]


print(F"""    {scaling(5) = }""")
print(F"""  {rotation(45) = }""")
print(F"""{projection(45) = }""")





print(F"""{reflection(45) = }""")






