






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

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    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(       A   ,     A   ,     unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_       :				str     						=  StableDiffusionSAGPipeline
       SCREAMING_SNAKE_CASE_       :				List[str]     						=  TEXT_TO_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE_       :				Optional[Any]     						=  TEXT_TO_IMAGE_BATCH_PARAMS
       SCREAMING_SNAKE_CASE_       :				List[Any]     						=  TEXT_TO_IMAGE_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE_       :				List[Any]     						=  TEXT_TO_IMAGE_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE_       :				str     						=  False




       def    _UpperCamelCase					(						self							)      ->				Union[str, Any]:





             """simple docstring"""






             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  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       :Dict		    =  DDIMScheduler(
                 beta_start=0.0_0_0_8_5		,beta_end=0.0_1_2		,beta_schedule='''scaled_linear'''		,clip_sample=SCREAMING_SNAKE_CASE__		,set_alpha_to_one=SCREAMING_SNAKE_CASE__		,)
             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  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       :List[str]		    =  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		,)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  CLIPTextModel(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Any		    =  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

             __SCREAMING_SNAKE_CASE       :int		    =  {
                 '''unet''': unet,
                 '''scheduler''': scheduler,
                 '''vae''': vae,
                 '''text_encoder''': text_encoder,
                 '''tokenizer''': tokenizer,
                 '''safety_checker''': None,
                 '''feature_extractor''': None,
             }
             return components




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0							)      ->				Dict:





             """simple docstring"""






             if str(SCREAMING_SNAKE_CASE__							).startswith('''mps'''							):
                   __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             else:
                   __SCREAMING_SNAKE_CASE       :Optional[int]		    =  torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :int		    =  {
                 '''prompt''': '''.''',
                 '''generator''': generator,
                 '''num_inference_steps''': 2,
                 '''guidance_scale''': 1.0,
                 '''sag_scale''': 1.0,
                 '''output_type''': '''numpy''',
             }
             return inputs




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






             super().test_inference_batch_single_identical(expected_max_diff=3E-3							)






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




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






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




       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Tuple		    =  StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''							)
             __SCREAMING_SNAKE_CASE       :Tuple		    =  sag_pipe.to(SCREAMING_SNAKE_CASE__							)
             sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :Any		    =  '''.'''
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  sag_pipe(
                 [prompt]		,generator=SCREAMING_SNAKE_CASE__		,guidance_scale=7.5		,sag_scale=1.0		,num_inference_steps=20		,output_type='''np'''							)

             __SCREAMING_SNAKE_CASE       :str		    =  output.images

             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  image[0, -3:, -3:, -1]

             assert image.shape == (1, 5_12, 5_12, 3)
             __SCREAMING_SNAKE_CASE       :int		    =  np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 5E-2




       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sag_pipe.to(SCREAMING_SNAKE_CASE__							)
             sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :int		    =  '''.'''
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  sag_pipe(
                 [prompt]		,generator=SCREAMING_SNAKE_CASE__		,guidance_scale=7.5		,sag_scale=1.0		,num_inference_steps=20		,output_type='''np'''							)

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  output.images

             __SCREAMING_SNAKE_CASE       :List[str]		    =  image[0, -3:, -3:, -1]

             assert image.shape == (1, 5_12, 5_12, 3)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 5E-2




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sag_pipe.to(SCREAMING_SNAKE_CASE__							)
             sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  '''.'''
             __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sag_pipe(
                 [prompt]		,width=7_68		,height=5_12		,generator=SCREAMING_SNAKE_CASE__		,guidance_scale=7.5		,sag_scale=1.0		,num_inference_steps=20		,output_type='''np'''		,)

             __SCREAMING_SNAKE_CASE       :List[str]		    =  output.images

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






"""simple docstring"""
import colorsys

from PIL import Image  # type: ignore



def 					__lowerCamelCase       (							a_					:		float			,       a_					:		float			,       a_					:		int							)      ->				float:
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  x
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  y
      for step in range(a_							):  # noqa: B007
            __SCREAMING_SNAKE_CASE       :Dict		    =  a * a - b * b + x
            __SCREAMING_SNAKE_CASE       :Tuple		    =  2 * a * b + y
            __SCREAMING_SNAKE_CASE       :Dict		    =  a_new

            # divergence happens for all complex number with an absolute value
            # greater than 4
            if a * a + b * b > 4:
                  break
      return step / (max_step - 1)



def 					__lowerCamelCase       (							a_					:		float							)      ->				tuple:
      if distance == 1:
            return (0, 0, 0)
      else:
            return (2_55, 2_55, 2_55)



def 					__lowerCamelCase       (							a_					:		float							)      ->				tuple:
      if distance == 1:
            return (0, 0, 0)
      else:
            return tuple(round(i * 2_55							) for i in colorsys.hsv_to_rgb(a_			,       1			,       1							)							)



def 					__lowerCamelCase       (							a_					:		int = 8_00			,       a_					:		int = 6_00			,       a_					:		float = -0.6			,       a_					:		float = 0			,       a_					:		float = 3.2			,       a_					:		int = 50			,       a_					:		bool = True			,       )      ->				Image.Image:
      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  Image.new('''RGB'''			,       (image_width, image_height)							)
      __SCREAMING_SNAKE_CASE       :Tuple		    =  img.load()

      # loop through the image-coordinates
      for image_x in range(a_							):
            for image_y in range(a_							):
                  # determine the figure-coordinates based on the image-coordinates
                  __SCREAMING_SNAKE_CASE       :Dict		    =  figure_width / image_width * image_height
                  __SCREAMING_SNAKE_CASE       :str		    =  figure_center_x + (image_x / image_width - 0.5) * figure_width
                  __SCREAMING_SNAKE_CASE       :Tuple		    =  figure_center_y + (image_y / image_height - 0.5) * figure_height

                  __SCREAMING_SNAKE_CASE       :List[Any]		    =  get_distance(a_			,       a_			,       a_							)

                  # color the corresponding pixel based on the selected coloring-function
                  if use_distance_color_coding:
                        __SCREAMING_SNAKE_CASE       :Optional[int]		    =  get_color_coded_rgb(a_							)
                  else:
                        __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  get_black_and_white_rgb(a_							)

      return img


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  # colored version, full figure
  lowerCamelCase_       =		get_image()

  # uncomment for colored version, different section, zoomed in
  # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
  # figure_width = 0.8)

  # uncomment for black and white version, full figure
  # img = get_image(use_distance_color_coding = False)

  # uncomment to save the image
  # img.save("mandelbrot.png")

  img.show()