

"""simple docstring"""





import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()




class       _lowerCAmelCase						(			unittest.TestCase     ):







 """simple docstring"""







 __UpperCAmelCase			:      List[str]     	=			"hf-internal-testing/tiny-stable-diffusion-pipe"
 __UpperCAmelCase			:      List[Any]     	=			1
 __UpperCAmelCase			:      List[Any]     	=			7_7
 __UpperCAmelCase			:      str     	=			3_2
 __UpperCAmelCase			:      Any     	=			4
 __UpperCAmelCase			:      Optional[int]     	=			6_4
 __UpperCAmelCase			:      List[Any]     	=			torch.manual_seed(0     )


 def       _lowercase				(    self							:    Optional[int],      UpperCAmelCase__							:    List[Any]=0.9_999			):
    __lowercase			=		UNetaDConditionModel.from_pretrained(self.model_id,      subfolder="unet"			)
    __lowercase			=		unet.to(UpperCAmelCase__			)
    __lowercase			=		EMAModel(unet.parameters(),      decay=UpperCAmelCase__,      model_cls=UpperCAmelCase__,      model_config=unet.config			)
    return unet, ema_unet


 def       _lowercase				(    self							:    Tuple			):
    __lowercase			=		torch.randn(
        self.batch_size,      self.num_in_channels,      self.latent_height,      self.latent_width,      generator=self.generator			).to(UpperCAmelCase__			)
    __lowercase			=		torch.randint(0,      1_0_0_0,      size=(self.batch_size,),      generator=self.generator			).to(UpperCAmelCase__			)
    __lowercase			=		torch.randn(
        self.batch_size,      self.prompt_length,      self.text_encoder_hidden_dim,      generator=self.generator			).to(UpperCAmelCase__			)
    return noisy_latents, timesteps, encoder_hidden_states


 def       _lowercase				(    self							:    int,      UpperCAmelCase__							:    List[str]			):
    __lowercase			=		{}
    for k, param in unet.state_dict().items():
       __lowercase			=		torch.randn_like(UpperCAmelCase__			) + (param * torch.randn_like(UpperCAmelCase__			))
       updated_state_dict.update({k: updated_param}			)
    unet.load_state_dict(UpperCAmelCase__			)
    return unet


 def       _lowercase				(    self							:    Optional[Any]			):
    __lowercase	,__lowercase			=		self.get_models()
    # Take the first (hypothetical) EMA step.
    ema_unet.step(unet.parameters()			)
    assert ema_unet.optimization_step == 1

    # Take two more.
    for _ in range(2			):
       ema_unet.step(unet.parameters()			)
    assert ema_unet.optimization_step == 3


 def       _lowercase				(    self							:    Dict			):
    __lowercase	,__lowercase			=		self.get_models()
    # Since the `unet` is not being updated (i.e., backprop'd)
    # there won't be any difference between the `params` of `unet`
    # and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
    ema_unet.step(unet.parameters()			)
    __lowercase			=		list(unet.parameters()			)
    for s_param, param in zip(ema_unet.shadow_params,      UpperCAmelCase__			):
       assert torch.allclose(UpperCAmelCase__,      UpperCAmelCase__			)

    # The above holds true even if we call `ema.step()` multiple times since
    # `unet` params are still not being updated.
    for _ in range(4			):
       ema_unet.step(unet.parameters()			)
    for s_param, param in zip(ema_unet.shadow_params,      UpperCAmelCase__			):
       assert torch.allclose(UpperCAmelCase__,      UpperCAmelCase__			)


 def       _lowercase				(    self							:    int			):
    __lowercase	,__lowercase			=		self.get_models()
    # Here we simulate the parameter updates for `unet`. Since there might
    # be some parameters which are initialized to zero we take extra care to
    # initialize their values to something non-zero before the multiplication.
    __lowercase			=		self.simulate_backprop(UpperCAmelCase__			)

    # Take the EMA step.
    ema_unet.step(unet_pseudo_updated_step_one.parameters()			)

    # Now the EMA'd parameters won't be equal to the original model parameters.
    __lowercase			=		list(unet_pseudo_updated_step_one.parameters()			)
    for s_param, param in zip(ema_unet.shadow_params,      UpperCAmelCase__			):
       assert ~torch.allclose(UpperCAmelCase__,      UpperCAmelCase__			)

    # Ensure this is the case when we take multiple EMA steps.
    for _ in range(4			):
       ema_unet.step(unet.parameters()			)
    for s_param, param in zip(ema_unet.shadow_params,      UpperCAmelCase__			):
       assert ~torch.allclose(UpperCAmelCase__,      UpperCAmelCase__			)


 def       _lowercase				(    self							:    Union[str, Any]			):
    # If we call EMA step after a backpropagation consecutively for two times,
    # the shadow params from those two steps should be different.
    __lowercase	,__lowercase			=		self.get_models()

    # First backprop + EMA
    __lowercase			=		self.simulate_backprop(UpperCAmelCase__			)
    ema_unet.step(unet_step_one.parameters()			)
    __lowercase			=		ema_unet.shadow_params

    # Second backprop + EMA
    __lowercase			=		self.simulate_backprop(UpperCAmelCase__			)
    ema_unet.step(unet_step_two.parameters()			)
    __lowercase			=		ema_unet.shadow_params

    for step_one, step_two in zip(UpperCAmelCase__,      UpperCAmelCase__			):
       assert ~torch.allclose(UpperCAmelCase__,      UpperCAmelCase__			)


 def       _lowercase				(    self							:    Dict			):
    # If there's no decay even if there are backprops, EMA steps
    # won't take any effect i.e., the shadow params would remain the
    # same.
    __lowercase	,__lowercase			=		self.get_models(decay=0.0			)
    __lowercase			=		self.simulate_backprop(UpperCAmelCase__			)
    ema_unet.step(unet_step_one.parameters()			)
    __lowercase			=		ema_unet.shadow_params

    __lowercase			=		self.simulate_backprop(UpperCAmelCase__			)
    ema_unet.step(unet_step_two.parameters()			)
    __lowercase			=		ema_unet.shadow_params

    for step_one, step_two in zip(UpperCAmelCase__,      UpperCAmelCase__			):
       assert torch.allclose(UpperCAmelCase__,      UpperCAmelCase__			)



 @skip_mps
 def       _lowercase				(    self							:    Optional[int]			):
    __lowercase	,__lowercase			=		self.get_models()
    __lowercase	,__lowercase	,__lowercase			=		self.get_dummy_inputs()

    with tempfile.TemporaryDirectory() as tmpdir:
       ema_unet.save_pretrained(UpperCAmelCase__			)
       __lowercase			=		UNetaDConditionModel.from_pretrained(UpperCAmelCase__,      model_cls=UpperCAmelCase__			)
       __lowercase			=		loaded_unet.to(unet.device			)

    # Since no EMA step has been performed the outputs should match.
    __lowercase			=		unet(UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__			).sample
    __lowercase			=		loaded_unet(UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__			).sample

    assert torch.allclose(UpperCAmelCase__,      UpperCAmelCase__,      atol=1E-4			)







"""simple docstring"""





import shutil

import requests




def 						_A						(						UpperCamelCase_  : str,    UpperCamelCase_  : bool = False,    UpperCamelCase_  : str = ".")			->		dict:
   '''simple docstring'''


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




def 						_A						(						UpperCamelCase_  : str,    UpperCamelCase_  : str = ".")			->		dict:
   '''simple docstring'''


   __lowercase			=		get_apod_data(UpperCamelCase_)
   __lowercase			=		apod_data["url"]
   __lowercase			=		img_url.split("/")[-1]
   __lowercase			=		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 						_A						(						UpperCamelCase_  : str)			->		dict:
   '''simple docstring'''


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


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




