




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





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

           # here we set some attributes to make tests pass
           snake_case__					:      Dict  			=						len(__lowerCamelCase )
           snake_case__					:      List[Any]  			=						embed_dim
           snake_case__					:      Optional[int]  			=						(image_size // patch_size) ** 2





     def  _lowerCAmelCase			(    self    :				Optional[Any] ):
           snake_case__					:      Tuple  			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

           snake_case__					:      str  			=						self.get_config()

           return config, pixel_values, labels





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

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





     def  _lowerCAmelCase			(    self    :				List[Any]    ,       __lowerCamelCase    :				str    ,       __lowerCamelCase    :				Union[str, Any]    ,       __lowerCamelCase    :				Tuple ):
           snake_case__					:      int  			=						SwinaSRForImageSuperResolution(__lowerCamelCase )
           model.to(__lowerCamelCase )
           model.eval()
           snake_case__					:      Tuple  			=						model(__lowerCamelCase )

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






@require_torch
class 					lowercase_			(	lowerCAmelCase_	,					lowerCAmelCase_	,					unittest.TestCase       ):
     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  _lowerCAmelCase			(    self    :				int ):
           snake_case__					:      int  			=						SwinaSRModelTester(self )
           snake_case__					:      Optional[Any]  			=						ConfigTester(self    ,       config_class=__lowerCamelCase    ,       embed_dim=37 )





     def  _lowerCAmelCase			(    self    :				List[Any] ):
           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    :				int ):
           snake_case__					:      Any  			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__lowerCamelCase )





     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           snake_case__					:      Tuple  			=						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  _lowerCAmelCase			(    self    :				str ):
           pass





     @unittest.skip(reason='Swin2SR does not use inputs_embeds' )
     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           pass





     @unittest.skip(reason='Swin2SR does not support training yet' )
     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           pass





     @unittest.skip(reason='Swin2SR does not support training yet' )
     def  _lowerCAmelCase			(    self    :				List[str] ):
           pass





     def  _lowerCAmelCase			(    self    :				int ):
           snake_case__			,       snake_case__					:      Union[str, Any]  			=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 snake_case__					:      int  			=						model_class(__lowerCamelCase )
                 self.assertIsInstance(model.get_input_embeddings()    ,       (nn.Module) )
                 snake_case__					:      List[Any]  			=						model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(__lowerCamelCase    ,       nn.Linear ) )





     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           snake_case__			,       snake_case__					:      Optional[int]  			=						self.model_tester.prepare_config_and_inputs_for_common()

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

                 snake_case__					:      Dict  			=						['pixel_values']
                 self.assertListEqual(arg_names[:1]    ,       __lowerCamelCase )





     @slow
     def  _lowerCAmelCase			(    self    :				str ):
           for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case__					:      str  			=						SwinaSRModel.from_pretrained(__lowerCamelCase )
                 self.assertIsNotNone(__lowerCamelCase )





     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           snake_case__			,       snake_case__					:      List[Any]  			=						self.model_tester.prepare_config_and_inputs_for_common()

           snake_case__					:      Dict  			=						_config_zero_init(__lowerCamelCase )
           for model_class in self.all_model_classes:
                 snake_case__					:      Optional[int]  			=						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  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           snake_case__			,       snake_case__					:      Dict  			=						self.model_tester.prepare_config_and_inputs_for_common()
           snake_case__					:      str  			=						True

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

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

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

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

                 snake_case__					:      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       ):





     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           snake_case__					:      Optional[int]  			=						SwinaSRImageProcessor()
           snake_case__					:      List[Any]  			=						SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64' ).to(__lowerCamelCase )

           snake_case__					:      List[Any]  			=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
           snake_case__					:      Any  			=						processor(images=__lowerCamelCase    ,       return_tensors='pt' ).to(__lowerCamelCase )

           # forward pass
           with torch.no_grad():
                 snake_case__					:      Dict  			=						model(**__lowerCamelCase )

           # verify the logits
           snake_case__					:      List[str]  			=						torch.Size([1, 3, 976, 1296] )
           self.assertEqual(outputs.reconstruction.shape    ,       __lowerCamelCase )
           snake_case__					:      List[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 bsa
import requests






def 		UpperCamelCase__			(		__SCREAMING_SNAKE_CASE		)						->      dict[str, str]:
      return {
          "name": soup.ha.a.text,
          "genre": soup.find('span'							,			class_='genre'		).text.strip(),
          "rating": soup.strong.text,
          "page_link": f"https://www.imdb.com{soup.a.get('href'		)}",
      }






def 		UpperCamelCase__			(		__SCREAMING_SNAKE_CASE = 5		)						->      tuple:
      snake_case__					:      Tuple  			=						int(float(__SCREAMING_SNAKE_CASE		)		)
      if num_movies < 1:
            return ()
      snake_case__					:      Any  			=						(
          'https://www.imdb.com/search/title?title_type='
          f"feature&sort=num_votes,desc&count={num_movies}"
      )
      snake_case__					:      Union[str, Any]  			=						bsa.BeautifulSoup(requests.get(__SCREAMING_SNAKE_CASE		).content							,			'html.parser'		)
      return tuple(
          get_movie_data_from_soup(__SCREAMING_SNAKE_CASE		)
          for movie in source.find_all('div'							,			class_='lister-item mode-advanced'		)		)


if __name__ == "__main__":
      import json

      A_ 			=		int(input("How many movies would you like to see? "))
      print(
          ", ".join(
              json.dumps(movie, indent=4) for movie in get_imdb_top_movies(num_movies)
          )
      )
