






"""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 __a :



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

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



  def     A_					(self	:		Any )		->				Dict:
   __A						:							Tuple      =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

   __A						:							List[Any]      =						None
   if self.use_labels:
    __A						:							int      =						ids_tensor([self.batch_size]					,      self.type_sequence_label_size )

   __A						:							Optional[int]      =						self.get_config()

   return config, pixel_values, labels



  def     A_					(self	:		Dict )		->				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     A_					(self	:		Any					,      lowercase_	:		List[Any]					,      lowercase_	:		int					,      lowercase_	:		int )		->				Optional[int]:
   __A						:							Optional[Any]      =						SwinaSRModel(config=lowercase_ )
   model.to(lowercase_ )
   model.eval()
   __A						:							List[Any]      =						model(lowercase_ )

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



  def     A_					(self	:		Dict					,      lowercase_	:		Any					,      lowercase_	:		int					,      lowercase_	:		Union[str, Any] )		->				Dict:
   __A						:							Tuple      =						SwinaSRForImageSuperResolution(lowercase_ )
   model.to(lowercase_ )
   model.eval()
   __A						:							Any      =						model(lowercase_ )

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






@require_torch
class __a ( snake_case_			,snake_case_			,unittest.TestCase					):
  __lowercase     :     List[str]       						=       (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
  __lowercase     :     Any       						=       {'feature-extraction': SwinaSRModel} if is_torch_available() else {}

  __lowercase     :     Union[str, Any]       						=       False
  __lowercase     :     int       						=       False
  __lowercase     :     str       						=       False
  __lowercase     :     str       						=       False
  __lowercase     :     Tuple       						=       False



  def     A_					(self	:		int )		->				List[str]:
   __A						:							Optional[Any]      =						SwinaSRModelTester(self )
   __A						:							Union[str, Any]      =						ConfigTester(self					,      config_class=lowercase_					,      embed_dim=37 )



  def     A_					(self	:		List[str] )		->				Dict:
   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	:		Any )		->				List[str]:
   __A						:							Optional[int]      =						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowercase_ )



  def     A_					(self	:		Optional[int] )		->				str:
   __A						:							int      =						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_super_resolution(*lowercase_ )



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



  @unittest.skip(reason='Swin2SR does not use inputs_embeds' )
  def     A_					(self	:		Optional[Any] )		->				Any:
   pass



  @unittest.skip(reason='Swin2SR does not support training yet' )
  def     A_					(self	:		Any )		->				Optional[int]:
   pass



  @unittest.skip(reason='Swin2SR does not support training yet' )
  def     A_					(self	:		Any )		->				Dict:
   pass



  def     A_					(self	:		Union[str, Any] )		->				str:
   __A     ,       __A						:							Tuple      =						self.model_tester.prepare_config_and_inputs_for_common()

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



  def     A_					(self	:		List[Any] )		->				Optional[int]:
   __A     ,       __A						:							Tuple      =						self.model_tester.prepare_config_and_inputs_for_common()

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

    __A						:							Tuple      =						['pixel_values']
    self.assertListEqual(arg_names[:1]					,      lowercase_ )



  @slow
  def     A_					(self	:		Any )		->				int:
   for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __A						:							Optional[int]      =						SwinaSRModel.from_pretrained(lowercase_ )
    self.assertIsNotNone(lowercase_ )



  def     A_					(self	:		str )		->				Any:
   __A     ,       __A						:							Optional[int]      =						self.model_tester.prepare_config_and_inputs_for_common()

   __A						:							Tuple      =						_config_zero_init(lowercase_ )
   for model_class in self.all_model_classes:
    __A						:							Dict      =						model_class(config=lowercase_ )
    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	:		List[str] )		->				Tuple:
   __A     ,       __A						:							Dict      =						self.model_tester.prepare_config_and_inputs_for_common()
   __A						:							str      =						True

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

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

    self.assertListEqual(
        list(attentions[0].shape[-3:] )					,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,      )
    __A						:							Dict      =						len(lowercase_ )

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

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

    __A						:							Optional[Any]      =						outputs.attentions

    self.assertEqual(len(lowercase_ )					,      lowercase_ )

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



  def     A_					(self	:		List[str] )		->				List[Any]:
   __A						:							List[Any]      =						SwinaSRImageProcessor()
   __A						:							Optional[Any]      =						SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64' ).to(lowercase_ )

   __A						:							int      =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
   __A						:							Dict      =						processor(images=lowercase_					,      return_tensors='pt' ).to(lowercase_ )

   # forward pass
   with torch.no_grad():
    __A						:							Union[str, Any]      =						model(**lowercase_ )

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













"""simple docstring"""


import numpy as np

_UpperCamelCase :    int      =			[
    ["""a""", """b""", """c""", """d""", """e"""],
    ["""f""", """g""", """h""", """i""", """k"""],
    ["""l""", """m""", """n""", """o""", """p"""],
    ["""q""", """r""", """s""", """t""", """u"""],
    ["""v""", """w""", """x""", """y""", """z"""],
]






class __a :



  def __init__(self	:		Any )		->				None:
   __A						:							Any      =						np.array(lowercase_ )



  def     A_					(self	:		Dict					,      lowercase_	:		str )		->				np.ndarray:
   __A     ,       __A						:							Any      =						np.where(letter == self.SQUARE )
   __A						:							Tuple      =						np.concatenate([indexa + 1, indexa + 1] )
   return indexes



  def     A_					(self	:		Tuple					,      lowercase_	:		int					,      lowercase_	:		int )		->				str:
   return self.SQUARE[indexa - 1, indexa - 1]



  def     A_					(self	:		Union[str, Any]					,      lowercase_	:		str )		->				str:
   __A						:							Any      =						message.lower()
   __A						:							Optional[Any]      =						message.replace('j'					,      'i' )

   __A						:							Union[str, Any]      =						''
   for letter_index in range(len(lowercase_ ) ):
    if message[letter_index] != " ":
     __A						:							Union[str, Any]      =						self.letter_to_numbers(message[letter_index] )
     __A						:							Union[str, Any]      =						encoded_message + str(numbers[0] ) + str(numbers[1] )
    elif message[letter_index] == " ":
     __A						:							Optional[Any]      =						encoded_message + ' '

   return encoded_message



  def     A_					(self	:		Dict					,      lowercase_	:		str )		->				str:
   __A						:							List[str]      =						message.replace(' '					,      '  ' )
   __A						:							List[Any]      =						''
   for numbers_index in range(int(len(lowercase_ ) / 2 ) ):
    if message[numbers_index * 2] != " ":
     __A						:							Any      =						message[numbers_index * 2]
     __A						:							Tuple      =						message[numbers_index * 2 + 1]

     __A						:							Dict      =						self.numbers_to_letter(int(lowercase_ )					,      int(lowercase_ ) )
     __A						:							Union[str, Any]      =						decoded_message + letter
    elif message[numbers_index * 2] == " ":
     __A						:							int      =						decoded_message + ' '

   return decoded_message





