




'''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        SCREAMING_SNAKE_CASE:

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=13					,		lowerCamelCase__=32					,		lowerCamelCase__=1					,		lowerCamelCase__=3					,		lowerCamelCase__=16					,		lowerCamelCase__=[1, 2, 1]					,		lowerCamelCase__=[2, 2, 4]					,		lowerCamelCase__=2					,		lowerCamelCase__=2.0					,		lowerCamelCase__=True					,		lowerCamelCase__=0.0					,		lowerCamelCase__=0.0					,		lowerCamelCase__=0.1					,		lowerCamelCase__="gelu"					,		lowerCamelCase__=False					,		lowerCamelCase__=True					,		lowerCamelCase__=0.02					,		lowerCamelCase__=1E-5					,		lowerCamelCase__=True					,		lowerCamelCase__=None					,		lowerCamelCase__=False					,		lowerCamelCase__=2					,		)    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						image_size
           __lowercase							=						patch_size
           __lowercase							=						num_channels
           __lowercase							=						embed_dim
           __lowercase							=						depths
           __lowercase							=						num_heads
           __lowercase							=						window_size
           __lowercase							=						mlp_ratio
           __lowercase							=						qkv_bias
           __lowercase							=						hidden_dropout_prob
           __lowercase							=						attention_probs_dropout_prob
           __lowercase							=						drop_path_rate
           __lowercase							=						hidden_act
           __lowercase							=						use_absolute_embeddings
           __lowercase							=						patch_norm
           __lowercase							=						layer_norm_eps
           __lowercase							=						initializer_range
           __lowercase							=						is_training
           __lowercase							=						scope
           __lowercase							=						use_labels
           __lowercase							=						upscale

           # here we set some attributes to make tests pass
           __lowercase							=						len(lowerCamelCase__     )
           __lowercase							=						embed_dim
           __lowercase							=						(image_size // patch_size) ** 2

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

           __lowercase							=						None
           if self.use_labels:
               __lowercase							=						ids_tensor([self.batch_size]					,		self.type_sequence_label_size     )

           __lowercase							=						self.get_config()

           return config, pixel_values, labels

       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           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     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						SwinaSRModel(config=lowerCamelCase__     )
           model.to(lowerCamelCase__     )
           model.eval()
           __lowercase							=						model(lowerCamelCase__     )

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

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					Dict:

           """simple docstring"""



           __lowercase							=						SwinaSRForImageSuperResolution(lowerCamelCase__     )
           model.to(lowerCamelCase__     )
           model.eval()
           __lowercase							=						model(lowerCamelCase__     )

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




       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           __lowercase							=						self.prepare_config_and_inputs()
           __lowercase				,__lowercase				,__lowercase							=						config_and_inputs
           __lowercase							=						{"""pixel_values""": pixel_values}
           return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE(				__A   ,      __A   ,      unittest.TestCase     ):
       snake_case_ :     List[Any]    =					(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
       snake_case_ :     Any    =					{"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

       snake_case_ :     Optional[int]    =					False
       snake_case_ :     Any    =					False
       snake_case_ :     Any    =					False
       snake_case_ :     List[Any]    =					False
       snake_case_ :     Optional[int]    =					False

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

           """simple docstring"""



           __lowercase							=						SwinaSRModelTester(self     )
           __lowercase							=						ConfigTester(self					,		config_class=lowerCamelCase__					,		embed_dim=37     )

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           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     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           __lowercase							=						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     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass

       @unittest.skip(reason="""Swin2SR does not use inputs_embeds"""     )
       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           pass

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

           """simple docstring"""



           pass

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

           """simple docstring"""



           pass

       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __lowercase							=						model_class(lowerCamelCase__     )
               self.assertIsInstance(model.get_input_embeddings()					,		(nn.Module)     )
               __lowercase							=						model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(lowerCamelCase__					,		nn.Linear     )     )

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

       @slow
       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __lowercase							=						SwinaSRModel.from_pretrained(lowerCamelCase__     )
               self.assertIsNotNone(lowerCamelCase__     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           __lowercase							=						_config_zero_init(lowerCamelCase__     )
           for model_class in self.all_model_classes:
               __lowercase							=						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     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()
           __lowercase							=						True

           for model_class in self.all_model_classes:
               __lowercase							=						True
               __lowercase							=						False
               __lowercase							=						True
               __lowercase							=						model_class(lowerCamelCase__     )
               model.to(lowerCamelCase__     )
               model.eval()
               with torch.no_grad():
                   __lowercase							=						model(**self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )     )
               __lowercase							=						outputs.attentions
               __lowercase							=						len(self.model_tester.depths     )
               self.assertEqual(len(lowerCamelCase__     )					,		lowerCamelCase__     )

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

               # Check attention is always last and order is fine
               __lowercase							=						True
               __lowercase							=						True
               __lowercase							=						model_class(lowerCamelCase__     )
               model.to(lowerCamelCase__     )
               model.eval()
               with torch.no_grad():
                   __lowercase							=						model(**self._prepare_for_class(lowerCamelCase__					,		lowerCamelCase__     )     )

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

               __lowercase							=						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        SCREAMING_SNAKE_CASE(				unittest.TestCase     ):

       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						SwinaSRImageProcessor()
           __lowercase							=						SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""     ).to(lowerCamelCase__     )

           __lowercase							=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
           __lowercase							=						processor(images=lowerCamelCase__					,		return_tensors="""pt"""     ).to(lowerCamelCase__     )

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

           # verify the logits
           __lowercase							=						torch.Size([1, 3, 976, 1296]     )
           self.assertEqual(outputs.reconstruction.shape					,		lowerCamelCase__     )
           __lowercase							=						torch.tensor(
               [[0.54_58, 0.55_46, 0.56_38], [0.55_26, 0.55_65, 0.56_51], [0.53_96, 0.54_26, 0.56_21]]     ).to(lowerCamelCase__     )
           self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]					,		lowerCamelCase__					,		atol=1E-4     )     )










'''simple docstring'''
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import BlipImageProcessor






class        SCREAMING_SNAKE_CASE(				unittest.TestCase     ):

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=7					,		lowerCamelCase__=3					,		lowerCamelCase__=18					,		lowerCamelCase__=30					,		lowerCamelCase__=400					,		lowerCamelCase__=True					,		lowerCamelCase__=None					,		lowerCamelCase__=True					,		lowerCamelCase__=False					,		lowerCamelCase__=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]					,		lowerCamelCase__=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]					,		lowerCamelCase__=True					,		)    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						size if size is not None else {"""height""": 20, """width""": 20}
           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						num_channels
           __lowercase							=						image_size
           __lowercase							=						min_resolution
           __lowercase							=						max_resolution
           __lowercase							=						do_resize
           __lowercase							=						size
           __lowercase							=						do_normalize
           __lowercase							=						image_mean
           __lowercase							=						image_std
           __lowercase							=						do_pad
           __lowercase							=						do_convert_rgb

       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           return {
               "do_resize": self.do_resize,
               "size": self.size,
               "do_normalize": self.do_normalize,
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_convert_rgb": self.do_convert_rgb,
               "do_pad": self.do_pad,
           }




       def     snake_case__			(    self					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False     )    ->					Tuple:

           """simple docstring"""



           assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

           if equal_resolution:
               __lowercase							=						[]
               for i in range(self.batch_size     ):
                   image_inputs.append(
                       np.random.randint(
                           255					,		size=(self.num_channels, self.max_resolution, self.max_resolution)					,		dtype=np.uinta     )     )
           else:
               __lowercase							=						[]
               for i in range(self.batch_size     ):
                   __lowercase				,__lowercase							=						np.random.choice(np.arange(self.min_resolution					,		self.max_resolution     )					,		2     )
                   image_inputs.append(np.random.randint(255					,		size=(self.num_channels, width, height)					,		dtype=np.uinta     )     )

           if not numpify and not torchify:
               # PIL expects the channel dimension as last dimension
               __lowercase							=						[Image.fromarray(np.moveaxis(lowerCamelCase__					,		0					,		-1     )     ) for x in image_inputs]

           if torchify:
               __lowercase							=						[torch.from_numpy(lowerCamelCase__     ) for x in image_inputs]

           return image_inputs






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Optional[int]    =					BlipImageProcessor if is_vision_available() else None

       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						BlipImageProcessingTester(self     )

       @property
       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           return self.image_processor_tester.prepare_image_processor_dict()

       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_resize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""size"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_normalize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_mean"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_std"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_convert_rgb"""     )     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PIL images
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		Image.Image     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random numpy tensors
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__					,		numpify=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		np.ndarray     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)




       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PyTorch tensors
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__					,		torchify=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		torch.Tensor     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Union[str, Any]    =					BlipImageProcessor if is_vision_available() else None

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						BlipImageProcessingTester(self					,		num_channels=4     )
           __lowercase							=						3

       @property
       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           return self.image_processor_tester.prepare_image_processor_dict()

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_resize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""size"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_normalize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_mean"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_std"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_convert_rgb"""     )     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass




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

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PIL images
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		Image.Image     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)




