



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

									# here we set some attributes to make tests pass
									lowercase  :      Union[str, Any]					=   len(A_			)
									lowercase  :      Dict					=   embed_dim
									lowercase  :      Tuple					=   (image_size // patch_size) ** 2


			def        lowercase				(							self      :							Tuple			)    ->       Tuple:
									lowercase  :      List[Any]					=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

									lowercase  :      Tuple					=   None
									if self.use_labels:
															lowercase  :      int					=   ids_tensor([self.batch_size],     self.type_sequence_label_size			)

									lowercase  :      List[Any]					=   self.get_config()

									return config, pixel_values, labels


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

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


			def        lowercase				(							self      :							Any,     lowerCAmelCase      :							Tuple,     lowerCAmelCase      :							Any,     lowerCAmelCase      :							Dict			)    ->       List[Any]:
									lowercase  :      List[str]					=   SwinaSRForImageSuperResolution(A_			)
									model.to(A_			)
									model.eval()
									lowercase  :      Union[str, Any]					=   model(A_			)

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




@require_torch
class   a__		(						SCREAMING_SNAKE_CASE__,  SCREAMING_SNAKE_CASE__,  unittest.TestCase     ):
			_lowerCamelCase												=				(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
			_lowerCamelCase												=				{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

			_lowerCamelCase												=				False
			_lowerCamelCase												=				False
			_lowerCamelCase												=				False
			_lowerCamelCase												=				False
			_lowerCamelCase												=				False


			def        lowercase				(							self      :							List[str]			)    ->       List[str]:
									lowercase  :      List[str]					=   SwinaSRModelTester(self			)
									lowercase  :      List[Any]					=   ConfigTester(self,     config_class=A_,     embed_dim=37			)


			def        lowercase				(							self      :							Optional[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        lowercase				(							self      :							Tuple			)    ->       Optional[Any]:
									lowercase  :      int					=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*A_			)


			def        lowercase				(							self      :							Any			)    ->       List[str]:
									lowercase  :      Optional[int]					=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_super_resolution(*A_			)


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


			@unittest.skip(reason='Swin2SR does not use inputs_embeds'			)
			def        lowercase				(							self      :							str			)    ->       Tuple:
									pass


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


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


			def        lowercase				(							self      :							List[Any]			)    ->       Tuple:
									lowercase	,    lowercase  :      List[str]					=   self.model_tester.prepare_config_and_inputs_for_common()

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


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

									for model_class in self.all_model_classes:
															lowercase  :      Union[str, Any]					=   model_class(A_			)
															lowercase  :      Optional[int]					=   inspect.signature(model.forward			)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															lowercase  :      Dict					=   [*signature.parameters.keys()]

															lowercase  :      int					=   ['pixel_values']
															self.assertListEqual(arg_names[:1],     A_			)


			@slow
			def        lowercase				(							self      :							List[Any]			)    ->       Any:
									for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															lowercase  :      Union[str, Any]					=   SwinaSRModel.from_pretrained(A_			)
															self.assertIsNotNone(A_			)


			def        lowercase				(							self      :							Optional[int]			)    ->       Tuple:
									lowercase	,    lowercase  :      Tuple					=   self.model_tester.prepare_config_and_inputs_for_common()

									lowercase  :      Any					=   _config_zero_init(A_			)
									for model_class in self.all_model_classes:
															lowercase  :      Optional[int]					=   model_class(config=A_			)
															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        lowercase				(							self      :							Any			)    ->       Any:
									lowercase	,    lowercase  :      Dict					=   self.model_tester.prepare_config_and_inputs_for_common()
									lowercase  :      Tuple					=   True

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

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

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

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

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

															lowercase  :      Any					=   outputs.attentions

															self.assertEqual(len(A_			),     A_			)

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

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

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

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





"""simple docstring"""




import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin


class   a__		(						SCREAMING_SNAKE_CASE__     ):
   _lowerCamelCase												=				'AutoFeatureExtractor'
   _lowerCamelCase												=				'Speech2Text2Tokenizer'


   def __init__(							self      :							str,     lowerCAmelCase      :							List[str],     lowerCAmelCase      :							Optional[Any]			)    ->       Dict:
         super().__init__(lowerCAmelCase,     lowerCAmelCase			)
         lowercase  :      Tuple					=   self.feature_extractor
         lowercase  :      Any					=   False


   def __call__(							self      :							Tuple,     *lowerCAmelCase      :							Tuple,     **lowerCAmelCase      :							Tuple			)    ->       Dict:
         # For backward compatibility
         if self._in_target_context_manager:
               return self.current_processor(*lowerCAmelCase,     **lowerCAmelCase			)

         if "raw_speech" in kwargs:
               warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'			)
               lowercase  :      str					=   kwargs.pop('raw_speech'			)
         else:
               lowercase  :      str					=   kwargs.pop('audio',     lowerCAmelCase			)
         lowercase  :      Dict					=   kwargs.pop('sampling_rate',     lowerCAmelCase			)
         lowercase  :      Optional[Any]					=   kwargs.pop('text',     lowerCAmelCase			)
         if len(lowerCAmelCase			) > 0:
               lowercase  :      Any					=   args[0]
               lowercase  :      int					=   args[1:]

         if audio is None and text is None:
               raise ValueError('You need to specify either an `audio` or `text` input to process.'			)

         if audio is not None:
               lowercase  :      List[Any]					=   self.feature_extractor(lowerCAmelCase,     *lowerCAmelCase,     sampling_rate=lowerCAmelCase,     **lowerCAmelCase			)
         if text is not None:
               lowercase  :      str					=   self.tokenizer(lowerCAmelCase,     **lowerCAmelCase			)

         if text is None:
               return inputs
         elif audio is None:
               return encodings
         else:
               lowercase  :      Tuple					=   encodings['input_ids']
               return inputs


   def        lowercase				(							self      :							str,     *lowerCAmelCase      :							List[str],     **lowerCAmelCase      :							Union[str, Any]			)    ->       str:
         return self.tokenizer.batch_decode(*lowerCAmelCase,     **lowerCAmelCase			)


   def        lowercase				(							self      :							Tuple,     *lowerCAmelCase      :							Union[str, Any],     **lowerCAmelCase      :							int			)    ->       Dict:
         return self.tokenizer.decode(*lowerCAmelCase,     **lowerCAmelCase			)






   @contextmanager
   def        lowercase				(							self      :							str			)    ->       Any:
         warnings.warn(
             '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '
             'labels by using the argument `text` of the regular `__call__` method (either in the same call as '
             'your audio inputs, or in a separate call.'			)
         lowercase  :      Optional[Any]					=   True
         lowercase  :      Any					=   self.tokenizer
         yield
         lowercase  :      Any					=   self.feature_extractor
         lowercase  :      Any					=   False
