
import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

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


enable_full_determinism()




class    _SCREAMING_SNAKE_CASE					( __UpperCamelCase    ,   __UpperCamelCase    ,   unittest.TestCase	):
      _A  :						Tuple      		=       StableDiffusionParadigmsPipeline
      _A  :						Optional[int]      		=       TEXT_TO_IMAGE_PARAMS
      _A  :						List[str]      		=       TEXT_TO_IMAGE_BATCH_PARAMS
      _A  :						str      		=       TEXT_TO_IMAGE_IMAGE_PARAMS
      _A  :						List[Any]      		=       TEXT_TO_IMAGE_IMAGE_PARAMS
      def A_     (     self	):
          torch.manual_seed(0	)
          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						,		attention_head_dim=(2, 4)						,		use_linear_projection=lowerCamelCase						,		)
          snake_case__  =			DDIMParallelScheduler(
              beta_start=0.0_0_0_8_5						,		beta_end=0.0_1_2						,		beta_schedule="scaled_linear"						,		clip_sample=lowerCamelCase						,		set_alpha_to_one=lowerCamelCase						,		)
          torch.manual_seed(0	)
          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						,		sample_size=1_28						,		)
          torch.manual_seed(0	)
          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=10_00						,		hidden_act="gelu"						,		projection_dim=5_12						,		)
          snake_case__  =			CLIPTextModel(lowerCamelCase	)
          snake_case__  =			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

          snake_case__  =			{
              "unet": unet,
              "scheduler": scheduler,
              "vae": vae,
              "text_encoder": text_encoder,
              "tokenizer": tokenizer,
              "safety_checker": None,
              "feature_extractor": None,
          }
          return components
      def A_     (     self						,		lowerCamelCase						,		lowerCamelCase=0	):
          if str(lowerCamelCase	).startswith("mps"	):
              snake_case__  =			torch.manual_seed(lowerCamelCase	)
          else:
              snake_case__  =			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)
          snake_case__  =			{
              "prompt": "a photograph of an astronaut riding a horse",
              "generator": generator,
              "num_inference_steps": 10,
              "guidance_scale": 6.0,
              "output_type": "numpy",
              "parallel": 3,
              "debug": True,
          }
          return inputs
      def A_     (     self	):
          snake_case__  =			"cpu"  # ensure determinism for the device-dependent torch.Generator
          snake_case__  =			self.get_dummy_components()
          snake_case__  =			StableDiffusionParadigmsPipeline(**lowerCamelCase	)
          snake_case__  =			sd_pipe.to(lowerCamelCase	)
          sd_pipe.set_progress_bar_config(disable=lowerCamelCase	)

          snake_case__  =			self.get_dummy_inputs(lowerCamelCase	)
          snake_case__  =			sd_pipe(**lowerCamelCase	).images
          snake_case__  =			image[0, -3:, -3:, -1]
          assert image.shape == (1, 64, 64, 3)

          snake_case__  =			np.array([0.4_7_7_3, 0.5_4_1_7, 0.4_7_2_3, 0.4_9_2_5, 0.5_6_3_1, 0.4_7_5_2, 0.5_2_4_0, 0.4_9_3_5, 0.5_0_2_3]	)

          assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-2
      def A_     (     self	):
          snake_case__  =			"cpu"  # ensure determinism for the device-dependent torch.Generator
          snake_case__  =			self.get_dummy_components()
          torch.manual_seed(0	)
          snake_case__  =			DDPMParallelScheduler()
          torch.manual_seed(0	)
          snake_case__  =			StableDiffusionParadigmsPipeline(**lowerCamelCase	)
          snake_case__  =			sd_pipe.to(lowerCamelCase	)
          sd_pipe.set_progress_bar_config(disable=lowerCamelCase	)

          snake_case__  =			self.get_dummy_inputs(lowerCamelCase	)
          snake_case__  =			sd_pipe(**lowerCamelCase	).images
          snake_case__  =			image[0, -3:, -3:, -1]
          assert image.shape == (1, 64, 64, 3)

          snake_case__  =			np.array([0.3_5_7_3, 0.4_4_2_0, 0.4_9_6_0, 0.4_7_9_9, 0.3_7_9_6, 0.3_8_7_9, 0.4_8_1_9, 0.4_3_6_5, 0.4_4_6_8]	)

          assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-2
      def A_     (     self	):
          super().test_inference_batch_consistent(batch_sizes=[1, 2]	)
      def A_     (     self	):
          super().test_inference_batch_single_identical(batch_size=2						,		expected_max_diff=3e-3	)



      def A_     (     self	):
          snake_case__  =			"cpu"  # ensure determinism for the device-dependent torch.Generator
          snake_case__  =			self.get_dummy_components()
          snake_case__  =			StableDiffusionParadigmsPipeline(**lowerCamelCase	)
          snake_case__  =			sd_pipe.to(lowerCamelCase	)
          sd_pipe.set_progress_bar_config(disable=lowerCamelCase	)

          snake_case__  =			self.get_dummy_inputs(lowerCamelCase	)
          snake_case__  =			"french fries"
          snake_case__  =			sd_pipe(**lowerCamelCase						,		negative_prompt=lowerCamelCase	)
          snake_case__  =			output.images
          snake_case__  =			image[0, -3:, -3:, -1]

          assert image.shape == (1, 64, 64, 3)

          snake_case__  =			np.array([0.4_7_7_1, 0.5_4_2_0, 0.4_6_8_3, 0.4_9_1_8, 0.5_6_3_6, 0.4_7_2_5, 0.5_2_3_0, 0.4_9_2_3, 0.5_0_1_5]	)

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





@slow
@require_torch_gpu
class    _SCREAMING_SNAKE_CASE					( unittest.TestCase	):
      def A_     (     self	):
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()
      def A_     (     self						,		lowerCamelCase=0	):
          snake_case__  =			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)
          snake_case__  =			{
              "prompt": "a photograph of an astronaut riding a horse",
              "generator": generator,
              "num_inference_steps": 10,
              "guidance_scale": 7.5,
              "output_type": "numpy",
              "parallel": 3,
              "debug": True,
          }
          return inputs



      def A_     (     self	):
          snake_case__  =			"stabilityai/stable-diffusion-2-base"
          snake_case__  =			DDIMParallelScheduler.from_pretrained(lowerCamelCase						,		subfolder="scheduler"	)
          snake_case__  =			StableDiffusionParadigmsPipeline.from_pretrained(lowerCamelCase						,		scheduler=lowerCamelCase						,		safety_checker=lowerCamelCase	)
          pipe.to(lowerCamelCase	)
          pipe.set_progress_bar_config(disable=lowerCamelCase	)
          pipe.enable_attention_slicing()

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

          assert image.shape == (1, 5_12, 5_12, 3)

          snake_case__  =			np.array([0.9_6_2_2, 0.9_6_0_2, 0.9_7_4_8, 0.9_5_9_1, 0.9_6_3_0, 0.9_6_9_1, 0.9_6_6_1, 0.9_6_3_1, 0.9_7_4_1]	)

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





def 		SCREAMING_SNAKE_CASE__      ( __lowerCAmelCase							):
    if len(__lowerCAmelCase							) > 1:
        snake_case__  =			len(__lowerCAmelCase							) // 2  # Finds the middle of the array
        snake_case__  =			arr[
            :middle_length
        ]  # Creates an array of the elements in the first half.
        snake_case__  =			arr[
            middle_length:
        ]  # Creates an array of the elements in the second half.
        snake_case__  =			len(__lowerCAmelCase							)
        snake_case__  =			len(__lowerCAmelCase							)
        merge(__lowerCAmelCase							)  # Starts sorting the left.
        merge(__lowerCAmelCase							)  # Starts sorting the right
        snake_case__  =			0  # Left Counter
        snake_case__  =			0  # Right Counter
        snake_case__  =			0  # Position Counter
        while (
            left_index < left_size and right_index < right_size
        ):  # Runs until the lowers size of the left and right are sorted.
            if left_array[left_index] < right_array[right_index]:
                snake_case__  =			left_array[left_index]
                left_index += 1
            else:
                snake_case__  =			right_array[right_index]
                right_index += 1
            index += 1
        while (
            left_index < left_size
        ):  # Adds the left over elements in the left half of the array
            snake_case__  =			left_array[left_index]
            left_index += 1
            index += 1
        while (
            right_index < right_size
        ):  # Adds the left over elements in the right half of the array
            snake_case__  =			right_array[right_index]
            right_index += 1
            index += 1
    return arr


if __name__ == "__main__":
     import doctest

     doctest.testmod()



