

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						,							__snake_case						,							__snake_case=13						,							__snake_case=32						,							__snake_case=1						,							__snake_case=3						,							__snake_case=16						,							__snake_case=[1, 2, 1]						,							__snake_case=[2, 2, 4]						,							__snake_case=2						,							__snake_case=2.0						,							__snake_case=True						,							__snake_case=0.0						,							__snake_case=0.0						,							__snake_case=0.1						,							__snake_case="gelu"						,							__snake_case=False						,							__snake_case=True						,							__snake_case=0.0_2						,							__snake_case=1e-5						,							__snake_case=True						,							__snake_case=None						,							__snake_case=False						,							__snake_case=2						,							):
			_UpperCamelCase :		int								=    parent
			_UpperCamelCase :		int								=    batch_size
			_UpperCamelCase :		List[str]								=    image_size
			_UpperCamelCase :		List[str]								=    patch_size
			_UpperCamelCase :		int								=    num_channels
			_UpperCamelCase :		Dict								=    embed_dim
			_UpperCamelCase :		Tuple								=    depths
			_UpperCamelCase :		Any								=    num_heads
			_UpperCamelCase :		List[str]								=    window_size
			_UpperCamelCase :		str								=    mlp_ratio
			_UpperCamelCase :		Union[str, Any]								=    qkv_bias
			_UpperCamelCase :		Union[str, Any]								=    hidden_dropout_prob
			_UpperCamelCase :		Optional[Any]								=    attention_probs_dropout_prob
			_UpperCamelCase :		str								=    drop_path_rate
			_UpperCamelCase :		Dict								=    hidden_act
			_UpperCamelCase :		Tuple								=    use_absolute_embeddings
			_UpperCamelCase :		Optional[int]								=    patch_norm
			_UpperCamelCase :		Optional[Any]								=    layer_norm_eps
			_UpperCamelCase :		List[str]								=    initializer_range
			_UpperCamelCase :		Tuple								=    is_training
			_UpperCamelCase :		Union[str, Any]								=    scope
			_UpperCamelCase :		List[Any]								=    use_labels
			_UpperCamelCase :		int								=    upscale

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


		def 		A__       (					self):
			_UpperCamelCase :		List[str]								=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

			_UpperCamelCase :		str								=    self.get_config()

			return config, pixel_values, labels


		def 		A__       (					self):
			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 		A__       (					self						,							__snake_case						,							__snake_case						,							__snake_case):
			_UpperCamelCase :		Optional[int]								=    SwinaSRModel(config=lowerCamelCase__)
			model.to(lowerCamelCase__)
			model.eval()
			_UpperCamelCase :		Optional[Any]								=    model(lowerCamelCase__)

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


		def 		A__       (					self						,							__snake_case						,							__snake_case						,							__snake_case):
			_UpperCamelCase :		Optional[int]								=    SwinaSRForImageSuperResolution(lowerCamelCase__)
			model.to(lowerCamelCase__)
			model.eval()
			_UpperCamelCase :		List[str]								=    model(lowerCamelCase__)

			_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 		A__       (					self):
			_UpperCamelCase :		Dict								=    self.prepare_config_and_inputs()
			_UpperCamelCase :		str								=    config_and_inputs
			_UpperCamelCase :		List[str]								=    {"pixel_values": pixel_values}
			return config, inputs_dict







@require_torch
class 						lowercase     (					_lowercase     ,				_lowercase     ,				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 		A__       (					self):
			_UpperCamelCase :		Tuple								=    SwinaSRModelTester(self)
			_UpperCamelCase :		Union[str, Any]								=    ConfigTester(self						,							config_class=lowerCamelCase__						,							embed_dim=37)


		def 		A__       (					self):
			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 		A__       (					self):
			_UpperCamelCase :		List[str]								=    self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase__)


		def 		A__       (					self):
			_UpperCamelCase :		Optional[int]								=    self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_super_resolution(*lowerCamelCase__)


		@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.')
		def 		A__       (					self):
			pass


		@unittest.skip(reason='Swin2SR does not use inputs_embeds')
		def 		A__       (					self):
			pass


		@unittest.skip(reason='Swin2SR does not support training yet')
		def 		A__       (					self):
			pass


		@unittest.skip(reason='Swin2SR does not support training yet')
		def 		A__       (					self):
			pass


		def 		A__       (					self):
			_UpperCamelCase :		Tuple								=    self.model_tester.prepare_config_and_inputs_for_common()

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


		def 		A__       (					self):
			_UpperCamelCase :		Optional[Any]								=    self.model_tester.prepare_config_and_inputs_for_common()

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

				_UpperCamelCase :		Dict								=    ["pixel_values"]
				self.assertListEqual(arg_names[:1]						,							lowerCamelCase__)


		@slow
		def 		A__       (					self):




			for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				_UpperCamelCase :		Union[str, Any]								=    SwinaSRModel.from_pretrained(lowerCamelCase__)
				self.assertIsNotNone(lowerCamelCase__)


		def 		A__       (					self):
			_UpperCamelCase :		int								=    self.model_tester.prepare_config_and_inputs_for_common()

			_UpperCamelCase :		List[Any]								=    _config_zero_init(lowerCamelCase__)
			for model_class in self.all_model_classes:
				_UpperCamelCase :		List[Any]								=    model_class(config=lowerCamelCase__)
				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 		A__       (					self):
			_UpperCamelCase :		int								=    self.model_tester.prepare_config_and_inputs_for_common()
			_UpperCamelCase :		int								=    True

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

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

				self.assertListEqual(
				    list(attentions[0].shape[-3:])						,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,							)
				_UpperCamelCase :		int								=    len(lowerCamelCase__)

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

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

				_UpperCamelCase :		Dict								=    outputs.attentions

				self.assertEqual(len(lowerCamelCase__)						,							lowerCamelCase__)

				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 		A__       (					self):
			_UpperCamelCase :		int								=    SwinaSRImageProcessor()
			_UpperCamelCase :		Optional[Any]								=    SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64').to(lowerCamelCase__)

			_UpperCamelCase :		str								=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
			_UpperCamelCase :		int								=    processor(images=lowerCamelCase__						,							return_tensors='pt').to(lowerCamelCase__)

			# forward pass
			with torch.no_grad():
				_UpperCamelCase :		List[str]								=    model(**lowerCamelCase__)

			# verify the logits
			_UpperCamelCase :		List[str]								=    torch.Size([1, 3, 9_76, 12_96])
			self.assertEqual(outputs.reconstruction.shape						,							lowerCamelCase__)
			_UpperCamelCase :		Any								=    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(lowerCamelCase__)
			self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]						,							lowerCamelCase__						,							atol=1e-4))








"""simple docstring"""






import json

import requests

from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info



def 			A__		(					_UpperCAmelCase    :      Optional[int]	)							->	Tuple:

	'''simple docstring'''


	class 			SCREAMING_SNAKE_CASE_  :




								'''simple docstring'''





								def __init__(						self	,					lowerCamelCase__)   ->	None:







									'''simple docstring'''




									assert isinstance(lowerCamelCase__	,					(bytes, str))
									snake_case__  :						int		=      content







								def        UpperCAmelCase (						self)   ->	Union[str, Any]:







									'''simple docstring'''




									return json.loads(self.content)

	def mock_response(*_UpperCAmelCase    :      str				,    **_UpperCAmelCase    :      Optional[int]	):
		assert args[0] == AUTHENTICATED_USER_ENDPOINT
		assert "Authorization" in kwargs["headers"]
		assert kwargs["headers"]["Authorization"].startswith("token "	)
		assert "Accept" in kwargs["headers"]
		return FakeResponse(b"{\"login\":\"test\",\"id\":1}"	)

	monkeypatch.setattr(_UpperCAmelCase				,    "get"				,    _UpperCAmelCase	)
	snake_case__  :						str		=      fetch_github_info("token"	)
	assert result["login"] == "test"
	assert result["id"] == 1





