

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 			_SCREAMING_SNAKE_CASE (   __snake_case					,       unittest.TestCase		):







   '''simple docstring'''




   lowerCamelCase__				=      LDMTextToImagePipeline
   lowerCamelCase__				=      TEXT_TO_IMAGE_PARAMS - {
       "negative_prompt",
       "negative_prompt_embeds",
       "cross_attention_kwargs",
       "prompt_embeds",
   }
   lowerCamelCase__				=      PipelineTesterMixin.required_optional_params - {
       "num_images_per_prompt",
       "callback",
       "callback_steps",
   }
   lowerCamelCase__				=      TEXT_TO_IMAGE_BATCH_PARAMS
   lowerCamelCase__				=      False





   def      _snake_case		(       self					:			List[Any]			):
       torch.manual_seed(0			)
       SCREAMING_SNAKE_CASE										=   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     , )
       SCREAMING_SNAKE_CASE										=   DDIMScheduler(
           beta_start=0.00_085     , beta_end=0.012     , beta_schedule="scaled_linear"     , clip_sample=__lowerCamelCase     , set_alpha_to_one=__lowerCamelCase     , )
       torch.manual_seed(0			)
       SCREAMING_SNAKE_CASE										=   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			)
       SCREAMING_SNAKE_CASE										=   CLIPTextConfig(
           bos_token_id=0     , eos_token_id=2     , hidden_size=32     , intermediate_size=37     , layer_norm_eps=1e-05     , num_attention_heads=4     , num_hidden_layers=5     , pad_token_id=1     , vocab_size=1000     , )
       SCREAMING_SNAKE_CASE										=   CLIPTextModel(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"			)

       SCREAMING_SNAKE_CASE										=   {
           "unet": unet,
           "scheduler": scheduler,
           "vqvae": vae,
           "bert": text_encoder,
           "tokenizer": tokenizer,
       }
       return components





   def      _snake_case		(       self					:			Optional[int]     , __lowerCamelCase					:			Optional[Any]     , __lowerCamelCase					:			Tuple=0			):
       if str(__lowerCamelCase			).startswith("mps"			):
           SCREAMING_SNAKE_CASE										=   torch.manual_seed(__lowerCamelCase			)
       else:
           SCREAMING_SNAKE_CASE										=   torch.Generator(device=__lowerCamelCase			).manual_seed(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   {
           "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      _snake_case		(       self					:			List[str]			):
       SCREAMING_SNAKE_CASE										=   "cpu"  # ensure determinism for the device-dependent torch.Generator

       SCREAMING_SNAKE_CASE										=   self.get_dummy_components()
       SCREAMING_SNAKE_CASE										=   LDMTextToImagePipeline(**__lowerCamelCase			)
       pipe.to(__lowerCamelCase			)
       pipe.set_progress_bar_config(disable=__lowerCamelCase			)

       SCREAMING_SNAKE_CASE										=   self.get_dummy_inputs(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   pipe(**__lowerCamelCase			).images
       SCREAMING_SNAKE_CASE										=   image[0, -3:, -3:, -1]

       assert image.shape == (1, 16, 16, 3)
       SCREAMING_SNAKE_CASE										=   np.array([0.6_101, 0.6_156, 0.5_622, 0.4_895, 0.6_661, 0.3_804, 0.5_748, 0.6_136, 0.5_014]			)

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





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







   '''simple docstring'''




   def      _snake_case		(       self					:			str			):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





   def      _snake_case		(       self					:			List[Any]     , __lowerCamelCase					:			Tuple     , __lowerCamelCase					:			Optional[Any]=torch.floataa     , __lowerCamelCase					:			List[Any]=0			):
       SCREAMING_SNAKE_CASE										=   torch.manual_seed(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   np.random.RandomState(__lowerCamelCase			).standard_normal((1, 4, 32, 32)			)
       SCREAMING_SNAKE_CASE										=   torch.from_numpy(__lowerCamelCase			).to(device=__lowerCamelCase     , dtype=__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   {
           "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      _snake_case		(       self					:			Dict			):
       SCREAMING_SNAKE_CASE										=   LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"			).to(__lowerCamelCase			)
       pipe.set_progress_bar_config(disable=__lowerCamelCase			)

       SCREAMING_SNAKE_CASE										=   self.get_inputs(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   pipe(**__lowerCamelCase			).images
       SCREAMING_SNAKE_CASE										=   image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 256, 256, 3)
       SCREAMING_SNAKE_CASE										=   np.array([0.51_825, 0.52_850, 0.52_543, 0.54_258, 0.52_304, 0.52_569, 0.54_363, 0.55_276, 0.56_878]			)
       SCREAMING_SNAKE_CASE										=   np.abs(expected_slice - image_slice			).max()
       assert max_diff < 1e-3





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







   '''simple docstring'''




   def      _snake_case		(       self					:			List[Any]			):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





   def      _snake_case		(       self					:			Union[str, Any]     , __lowerCamelCase					:			Any     , __lowerCamelCase					:			List[str]=torch.floataa     , __lowerCamelCase					:			List[str]=0			):
       SCREAMING_SNAKE_CASE										=   torch.manual_seed(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   np.random.RandomState(__lowerCamelCase			).standard_normal((1, 4, 32, 32)			)
       SCREAMING_SNAKE_CASE										=   torch.from_numpy(__lowerCamelCase			).to(device=__lowerCamelCase     , dtype=__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   {
           "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      _snake_case		(       self					:			Any			):
       SCREAMING_SNAKE_CASE										=   LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"			).to(__lowerCamelCase			)
       pipe.set_progress_bar_config(disable=__lowerCamelCase			)

       SCREAMING_SNAKE_CASE										=   self.get_inputs(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   pipe(**__lowerCamelCase			).images[0]

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


def 	__a     (      A__			:  int       ):
    if not isinstance(A__			,  A__       ):
        raise ValueError("Input must be an integer"       )
    if input_num <= 0:
        raise ValueError("Input must be positive"       )
    return sum(
        divisor for divisor in range(1			,  input_num // 2 + 1       ) if input_num % divisor == 0       )


if __name__ == "__main__":
    import doctest

    doctest.testmod()