


"""simple docstring"""
import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class 	lowercase__				(					A_ ,unittest.TestCase				):
   __UpperCAmelCase							       =					LDMTextToImagePipeline
   __UpperCAmelCase							       =					TEXT_TO_IMAGE_PARAMS - {
       '''negative_prompt''',
       '''negative_prompt_embeds''',
       '''cross_attention_kwargs''',
       '''prompt_embeds''',
   }
   __UpperCAmelCase							       =					PipelineTesterMixin.required_optional_params - {
       '''num_images_per_prompt''',
       '''callback''',
       '''callback_steps''',
   }
   __UpperCAmelCase							       =					TEXT_TO_IMAGE_BATCH_PARAMS
   __UpperCAmelCase							       =					False





   def 		UpperCamelCase_  (							self)  ->  List[str]:
      torch.manual_seed(0)
      _lowerCamelCase	:					Any   =		UNetaDConditionModel(
          block_out_channels=(32, 64)      ,   layers_per_block=2      ,   sample_size=32      ,   in_channels=4      ,   out_channels=4      ,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")      ,   up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")      ,   cross_attention_dim=32      ,   )
      _lowerCamelCase	:					List[Any]   =		DDIMScheduler(
          beta_start=0.0_00_85      ,   beta_end=0.0_12      ,   beta_schedule="""scaled_linear"""      ,   clip_sample=SCREAMING_SNAKE_CASE      ,   set_alpha_to_one=SCREAMING_SNAKE_CASE      ,   )
      torch.manual_seed(0)
      _lowerCamelCase	:					int   =		AutoencoderKL(
          block_out_channels=(32, 64)      ,   in_channels=3      ,   out_channels=3      ,   down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")      ,   up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")      ,   latent_channels=4      ,   )
      torch.manual_seed(0)
      _lowerCamelCase	:					Tuple   =		CLIPTextConfig(
          bos_token_id=0      ,   eos_token_id=2      ,   hidden_size=32      ,   intermediate_size=37      ,   layer_norm_eps=1e-0_5      ,   num_attention_heads=4      ,   num_hidden_layers=5      ,   pad_token_id=1      ,   vocab_size=1000      ,   )
      _lowerCamelCase	:					str   =		CLIPTextModel(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Tuple   =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

      _lowerCamelCase	:					List[str]   =		{
          """unet""": unet,
          """scheduler""": scheduler,
          """vqvae""": vae,
          """bert""": text_encoder,
          """tokenizer""": tokenizer,
      }
      return components





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=0)  ->  str:
      if str(SCREAMING_SNAKE_CASE).startswith("""mps"""):
         _lowerCamelCase	:					Dict   =		torch.manual_seed(SCREAMING_SNAKE_CASE)
      else:
         _lowerCamelCase	:					Optional[int]   =		torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Any   =		{
          """prompt""": """A painting of a squirrel eating a burger""",
          """generator""": generator,
          """num_inference_steps""": 2,
          """guidance_scale""": 6.0,
          """output_type""": """numpy""",
      }
      return inputs





   def 		UpperCamelCase_  (							self)  ->  List[Any]:
      _lowerCamelCase	:					Optional[int]   =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator

      _lowerCamelCase	:					List[Any]   =		self.get_dummy_components()
      _lowerCamelCase	:					int   =		LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE)
      pipe.to(SCREAMING_SNAKE_CASE)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Dict   =		self.get_dummy_inputs(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					List[Any]   =		pipe(**SCREAMING_SNAKE_CASE).images
      _lowerCamelCase	:					Tuple   =		image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _lowerCamelCase	:					Optional[Any]   =		np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14])

      assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3







@slow
@require_torch_gpu
class 	lowercase__				(					unittest.TestCase				):





   def 		UpperCamelCase_  (							self)  ->  str:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=torch.floataa      ,   SCREAMING_SNAKE_CASE=0)  ->  List[Any]:
      _lowerCamelCase	:					Optional[int]   =		torch.manual_seed(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					List[str]   =		np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
      _lowerCamelCase	:					List[Any]   =		torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE      ,   dtype=SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					int   =		{
          """prompt""": """A painting of a squirrel eating a burger""",
          """latents""": latents,
          """generator""": generator,
          """num_inference_steps""": 3,
          """guidance_scale""": 6.0,
          """output_type""": """numpy""",
      }
      return inputs





   def 		UpperCamelCase_  (							self)  ->  Union[str, Any]:
      _lowerCamelCase	:					Any   =		LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(SCREAMING_SNAKE_CASE)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Dict   =		self.get_inputs(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					List[Any]   =		pipe(**SCREAMING_SNAKE_CASE).images
      _lowerCamelCase	:					Tuple   =		image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 256, 256, 3)
      _lowerCamelCase	:					str   =		np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78])
      _lowerCamelCase	:					Optional[int]   =		np.abs(expected_slice - image_slice).max()
      assert max_diff < 1e-3







@nightly
@require_torch_gpu
class 	lowercase__				(					unittest.TestCase				):





   def 		UpperCamelCase_  (							self)  ->  Optional[int]:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=torch.floataa      ,   SCREAMING_SNAKE_CASE=0)  ->  int:
      _lowerCamelCase	:					Union[str, Any]   =		torch.manual_seed(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Any   =		np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
      _lowerCamelCase	:					str   =		torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE      ,   dtype=SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Tuple   =		{
          """prompt""": """A painting of a squirrel eating a burger""",
          """latents""": latents,
          """generator""": generator,
          """num_inference_steps""": 50,
          """guidance_scale""": 6.0,
          """output_type""": """numpy""",
      }
      return inputs





   def 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      _lowerCamelCase	:					Union[str, Any]   =		LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(SCREAMING_SNAKE_CASE)
      pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					str   =		self.get_inputs(SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Any   =		pipe(**SCREAMING_SNAKE_CASE).images[0]

      _lowerCamelCase	:					Union[str, Any]   =		load_numpy(
          """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""")
      _lowerCamelCase	:					str   =		np.abs(expected_image - image).max()
      assert max_diff < 1e-3





"""simple docstring"""
from datetime import datetime

import matplotlib.pyplot as plt
import torch

def 				_snake_case      (   __snake_case							:      List[str]   ):




   """simple docstring"""







   for param in module.parameters():
      _lowerCamelCase	:					Optional[Any]   =		False

def 				_snake_case      (   ):




   """simple docstring"""







   _lowerCamelCase	:					Any   =		"""cuda""" if torch.cuda.is_available() else """cpu"""
   if torch.backends.mps.is_available() and torch.backends.mps.is_built():
      _lowerCamelCase	:					Any   =		"""mps"""
   if device == "mps":
      print(
          """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch"""
          """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues"""
          """ with generations."""   )
   return device

def 				_snake_case      (   __snake_case							:      Union[str, Any]   ):




   """simple docstring"""







   _lowerCamelCase	:					int   =		plt.imshow(__snake_case   )
   fig.axes.get_xaxis().set_visible(__snake_case   )
   fig.axes.get_yaxis().set_visible(__snake_case   )
   plt.show()





def 				_snake_case      (   ):




   """simple docstring"""







   _lowerCamelCase	:					Tuple   =		datetime.now()
   _lowerCamelCase	:					Optional[Any]   =		current_time.strftime("""%H:%M:%S"""   )
   return timestamp

