

'''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    a__  (							lowerCamelCase_  ,      unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE    :     List[str]	       =							LDMTextToImagePipeline
   _SCREAMING_SNAKE_CASE    :     str	       =							TEXT_TO_IMAGE_PARAMS - {
       'negative_prompt',
       'negative_prompt_embeds',
       'cross_attention_kwargs',
       'prompt_embeds',
   }
   _SCREAMING_SNAKE_CASE    :     Dict	       =							PipelineTesterMixin.required_optional_params - {
       'num_images_per_prompt',
       'callback',
       'callback_steps',
   }
   _SCREAMING_SNAKE_CASE    :     Dict	       =							TEXT_TO_IMAGE_BATCH_PARAMS
   _SCREAMING_SNAKE_CASE    :     Tuple	       =							False


   def 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      torch.manual_seed(0  )
      _lowercase			:      Union[str, 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			,				)
      _lowercase			:      Optional[int]			     =   DDIMScheduler(
          beta_start=0.0_0_0_8_5			,				beta_end=0.0_1_2			,				beta_schedule="scaled_linear"			,				clip_sample=__a			,				set_alpha_to_one=__a			,				)
      torch.manual_seed(0  )
      _lowercase			:      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  )
      _lowercase			:      str			     =   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			,				)
      _lowercase			:      Any			     =   CLIPTextModel(__a  )
      _lowercase			:      Optional[Any]			     =   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"  )

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


   def 						_lowerCamelCase   ( self			,				_UpperCamelCase			,				_UpperCamelCase=0  ):





      """simple docstring"""





      if str(__a  ).startswith("mps"  ):
         _lowercase			:      Any			     =   torch.manual_seed(__a  )
      else:
         _lowercase			:      Optional[Any]			     =   torch.Generator(device=__a  ).manual_seed(__a  )
      _lowercase			:      Dict			     =   {
          "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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      _lowercase			:      List[str]			     =   "cpu"  # ensure determinism for the device-dependent torch.Generator

      _lowercase			:      Dict			     =   self.get_dummy_components()
      _lowercase			:      Optional[Any]			     =   LDMTextToImagePipeline(**__a  )
      pipe.to(__a  )
      pipe.set_progress_bar_config(disable=__a  )

      _lowercase			:      str			     =   self.get_dummy_inputs(__a  )
      _lowercase			:      Optional[int]			     =   pipe(**__a  ).images
      _lowercase			:      Dict			     =   image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _lowercase			:      Any			     =   np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]  )

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




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


   def 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()


   def 						_lowerCamelCase   ( self			,				_UpperCamelCase			,				_UpperCamelCase=torch.floataa			,				_UpperCamelCase=0  ):





      """simple docstring"""





      _lowercase			:      Optional[int]			     =   torch.manual_seed(__a  )
      _lowercase			:      Any			     =   np.random.RandomState(__a  ).standard_normal((1, 4, 32, 32)  )
      _lowercase			:      Optional[int]			     =   torch.from_numpy(__a  ).to(device=__a			,				dtype=__a  )
      _lowercase			:      Tuple			     =   {
          "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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      _lowercase			:      int			     =   LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"  ).to(__a  )
      pipe.set_progress_bar_config(disable=__a  )

      _lowercase			:      Union[str, Any]			     =   self.get_inputs(__a  )
      _lowercase			:      List[Any]			     =   pipe(**__a  ).images
      _lowercase			:      str			     =   image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 256, 256, 3)
      _lowercase			:      List[str]			     =   np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]  )
      _lowercase			:      str			     =   np.abs(expected_slice - image_slice  ).max()
      assert max_diff < 1E-3




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


   def 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()


   def 						_lowerCamelCase   ( self			,				_UpperCamelCase			,				_UpperCamelCase=torch.floataa			,				_UpperCamelCase=0  ):





      """simple docstring"""





      _lowercase			:      Optional[Any]			     =   torch.manual_seed(__a  )
      _lowercase			:      Dict			     =   np.random.RandomState(__a  ).standard_normal((1, 4, 32, 32)  )
      _lowercase			:      str			     =   torch.from_numpy(__a  ).to(device=__a			,				dtype=__a  )
      _lowercase			:      Dict			     =   {
          "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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      _lowercase			:      int			     =   LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"  ).to(__a  )
      pipe.set_progress_bar_config(disable=__a  )

      _lowercase			:      Optional[Any]			     =   self.get_inputs(__a  )
      _lowercase			:      List[str]			     =   pipe(**__a  ).images[0]

      _lowercase			:      Optional[int]			     =   load_numpy(
          "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"  )
      _lowercase			:      Dict			     =   np.abs(expected_image - image  ).max()
      assert max_diff < 1E-3











from __future__ import annotations

from math import pi
from typing import Protocol

import matplotlib.pyplot as plt
import numpy as np



class   UpperCAmelCase_    (       a):







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														return 0.0






def 				A				(					_lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							Optional[Any]    =    min([-20, np.min(fft_results[1 : samplerate // 2 - 1]  )]  )
							_lowerCAmelCase     :							Optional[int]    =    max([20, np.max(fft_results[1 : samplerate // 2 - 1]  )]  )
							return lowest, highest






def 				A				(					_lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							int    =    512
							_lowerCAmelCase     :							Union[str, Any]    =    [1] + [0] * (size - 1)
							_lowerCAmelCase     :							Optional[Any]    =    [filter_type.process(_lowerCamelCase  ) for item in inputs]

							_lowerCAmelCase     :							int    =    [0] * (samplerate - size)  # zero-padding
							outputs += filler
							_lowerCAmelCase     :							str    =    np.abs(np.fft.fft(_lowerCamelCase  )  )
							_lowerCAmelCase     :							Union[str, Any]    =    20 * np.logaa(_lowerCamelCase  )

							# Frequencies on log scale from 24 to nyquist frequency
							plt.xlim(24				, samplerate / 2 - 1  )
							plt.xlabel("Frequency (Hz)"  )
							plt.xscale("log"  )

							# Display within reasonable bounds
							_lowerCAmelCase     :							List[Any]    =    get_bounds(_lowerCamelCase				, _lowerCamelCase  )
							plt.ylim(max([-80, bounds[0]]  )				, min([80, bounds[1]]  )  )
							plt.ylabel("Gain (dB)"  )

							plt.plot(_lowerCamelCase  )
							plt.show()






def 				A				(					_lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							Union[str, Any]    =    512
							_lowerCAmelCase     :							Optional[Any]    =    [1] + [0] * (size - 1)
							_lowerCAmelCase     :							str    =    [filter_type.process(_lowerCamelCase  ) for item in inputs]

							_lowerCAmelCase     :							Optional[Any]    =    [0] * (samplerate - size)  # zero-padding
							outputs += filler
							_lowerCAmelCase     :							Optional[Any]    =    np.angle(np.fft.fft(_lowerCamelCase  )  )

							# Frequencies on log scale from 24 to nyquist frequency
							plt.xlim(24				, samplerate / 2 - 1  )
							plt.xlabel("Frequency (Hz)"  )
							plt.xscale("log"  )

							plt.ylim(-2 * pi				, 2 * pi  )
							plt.ylabel("Phase shift (Radians)"  )
							plt.plot(np.unwrap(_lowerCamelCase				, -2 * pi  )  )
							plt.show()
