




'''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      :     List[Any]	,	lowercase__      :     Optional[int]	,	lowercase__      :     Optional[int]=13	,	lowercase__      :     Any=32	,	lowercase__      :     Union[str, Any]=1	,	lowercase__      :     List[str]=3	,	lowercase__      :     Tuple=16	,	lowercase__      :     Optional[int]=[1, 2, 1]	,	lowercase__      :     Tuple=[2, 2, 4]	,	lowercase__      :     List[str]=2	,	lowercase__      :     Optional[Any]=2.0	,	lowercase__      :     Any=True	,	lowercase__      :     Any=0.0	,	lowercase__      :     int=0.0	,	lowercase__      :     Optional[Any]=0.1	,	lowercase__      :     List[Any]="gelu"	,	lowercase__      :     Any=False	,	lowercase__      :     str=True	,	lowercase__      :     Tuple=0.02	,	lowercase__      :     int=1e-5	,	lowercase__      :     Dict=True	,	lowercase__      :     Tuple=None	,	lowercase__      :     int=False	,	lowercase__      :     int=2	,	):


           '''simple docstring'''

           a_    :       List[str]    	=     parent
           a_    :       Tuple    	=     batch_size
           a_    :       List[str]    	=     image_size
           a_    :       Any    	=     patch_size
           a_    :       Optional[Any]    	=     num_channels
           a_    :       List[Any]    	=     embed_dim
           a_    :       Any    	=     depths
           a_    :       Union[str, Any]    	=     num_heads
           a_    :       Any    	=     window_size
           a_    :       Optional[int]    	=     mlp_ratio
           a_    :       Dict    	=     qkv_bias
           a_    :       Dict    	=     hidden_dropout_prob
           a_    :       int    	=     attention_probs_dropout_prob
           a_    :       Dict    	=     drop_path_rate
           a_    :       Optional[int]    	=     hidden_act
           a_    :       int    	=     use_absolute_embeddings
           a_    :       str    	=     patch_norm
           a_    :       Dict    	=     layer_norm_eps
           a_    :       Optional[int]    	=     initializer_range
           a_    :       int    	=     is_training
           a_    :       Optional[Any]    	=     scope
           a_    :       Union[str, Any]    	=     use_labels
           a_    :       int    	=     upscale

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






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       List[str]    	=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

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

           return config, pixel_values, labels






      def        lowercase_	(   self      :     Any					):


           '''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        lowercase_	(   self      :     Dict	,	lowercase__      :     List[str]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Dict					):


           '''simple docstring'''

           a_    :       List[str]    	=     SwinaSRModel(config=lowercase__					)
           model.to(lowercase__					)
           model.eval()
           a_    :       Union[str, Any]    	=     model(lowercase__					)

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






      def        lowercase_	(   self      :     Optional[Any]	,	lowercase__      :     List[Any]	,	lowercase__      :     Tuple	,	lowercase__      :     Tuple					):


           '''simple docstring'''

           a_    :       str    	=     SwinaSRForImageSuperResolution(lowercase__					)
           model.to(lowercase__					)
           model.eval()
           a_    :       Optional[int]    	=     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        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       Dict    	=     self.prepare_config_and_inputs()
           a_	,    a_	,    a_    :       List[str]    	=     config_and_inputs
           a_    :       Optional[Any]    	=     {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_torch
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					str             =				(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
      __magic_name__     :					int             =				{'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

      __magic_name__     :					Optional[int]             =				False
      __magic_name__     :					Union[str, Any]             =				False
      __magic_name__     :					int             =				False
      __magic_name__     :					int             =				False
      __magic_name__     :					Any             =				False






      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           a_    :       int    	=     SwinaSRModelTester(self					)
           a_    :       Tuple    	=     ConfigTester(self	,	config_class=lowercase__	,	embed_dim=37					)






      def        lowercase_	(   self      :     Union[str, Any]					):


           '''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        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       Tuple    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase__					)






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           a_    :       Tuple    	=     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        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""Swin2SR does not use inputs_embeds"""					)
      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""Swin2SR does not support training yet"""					)
      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""Swin2SR does not support training yet"""					)
      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           a_	,    a_    :       List[Any]    	=     self.model_tester.prepare_config_and_inputs_for_common()

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






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_	,    a_    :       int    	=     self.model_tester.prepare_config_and_inputs_for_common()

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

                a_    :       Any    	=     ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]	,	lowercase__					)






      @slow
      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                a_    :       Any    	=     SwinaSRModel.from_pretrained(lowercase__					)
                self.assertIsNotNone(lowercase__					)






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_	,    a_    :       List[Any]    	=     self.model_tester.prepare_config_and_inputs_for_common()

           a_    :       Tuple    	=     _config_zero_init(lowercase__					)
           for model_class in self.all_model_classes:
                a_    :       int    	=     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        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           a_	,    a_    :       str    	=     self.model_tester.prepare_config_and_inputs_for_common()
           a_    :       List[str]    	=     True

           for model_class in self.all_model_classes:
                a_    :       List[Any]    	=     True
                a_    :       Dict    	=     False
                a_    :       Dict    	=     True
                a_    :       Union[str, Any]    	=     model_class(lowercase__					)
                model.to(lowercase__					)
                model.eval()
                with torch.no_grad():
                     a_    :       Any    	=     model(**self._prepare_for_class(lowercase__	,	lowercase__					)					)
                a_    :       List[Any]    	=     outputs.attentions
                a_    :       str    	=     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_    :       List[Any]    	=     model_class(lowercase__					)
                model.to(lowercase__					)
                model.eval()
                with torch.no_grad():
                     a_    :       Union[str, Any]    	=     model(**self._prepare_for_class(lowercase__	,	lowercase__					)					)
                a_    :       Tuple    	=     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_    :       Optional[Any]    	=     len(lowercase__					)

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

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

                a_    :       List[str]    	=     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     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     SwinaSRImageProcessor()
           a_    :       Union[str, Any]    	=     SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""					).to(lowercase__					)

           a_    :       Union[str, Any]    	=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
           a_    :       Any    	=     processor(images=lowercase__	,	return_tensors="""pt"""					).to(lowercase__					)

           # forward pass
           with torch.no_grad():
                a_    :       Dict    	=     model(**lowercase__					)

           # verify the logits
           a_    :       Tuple    	=     torch.Size([1, 3, 976, 1296]					)
           self.assertEqual(outputs.reconstruction.shape	,	lowercase__					)
           a_    :       Optional[Any]    	=     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 shutil

import requests



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				str   ,						UpperCamelCase__						:				bool = False   ,						UpperCamelCase__						:				str = "."							):




     """simple docstring"""


     a_    :       Any    	=     """https://api.nasa.gov/planetary/apod"""
     return requests.get(UpperCamelCase__   ,						params={"""api_key""": api_key}							).json()



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				str   ,						UpperCamelCase__						:				str = "."							):




     """simple docstring"""


     a_    :       Tuple    	=     get_apod_data(UpperCamelCase__							)
     a_    :       Tuple    	=     apod_data["""url"""]
     a_    :       Any    	=     img_url.split("""/"""							)[-1]
     a_    :       Tuple    	=     requests.get(UpperCamelCase__   ,						stream=UpperCamelCase__							)

     with open(F"{path}/{img_name}"   ,						"""wb+"""							) as img_file:
          shutil.copyfileobj(response.raw   ,						UpperCamelCase__							)
     del response
     return apod_data



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				str							):




     """simple docstring"""


     a_    :       str    	=     """https://images-api.nasa.gov/search"""
     return requests.get(UpperCamelCase__   ,						params={"""q""": query}							).json()


if __name__ == "__main__":
 print(save_apod('YOUR API KEY'))
 lowerCAmelCase_			:     int							    =     get_archive_data('apollo 2011')['collection']['items']
 print(apollo_aaaa_items[0]['data'][0]['description'])
