





'''simple docstring'''






import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


A__    :       Optional[Any]              =False




class 			UpperCAmelCase					(      unittest.TestCase       ):
      pass




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




      def     lowercase__   (      self      :			Dict  )    ->				Optional[Any]:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




      def     lowercase__   (      self      :			str  )    ->				Optional[int]:
            _lowerCAmelCase												=							VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion"""      ,      torch_dtype=torch.floataa  )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""  )

            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe.dual_guided(
                prompt="""first prompt"""      ,      image=__snake_case      ,      text_to_image_strength=0.75      ,      generator=__snake_case      ,      guidance_scale=7.5      ,      num_inference_steps=2      ,      output_type="""numpy"""      ,      ).images

            with tempfile.TemporaryDirectory() as tmpdirname:
                  pipe.save_pretrained(__snake_case  )
                  _lowerCAmelCase												=							VersatileDiffusionPipeline.from_pretrained(__snake_case      ,      torch_dtype=torch.floataa  )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							generator.manual_seed(0  )
            _lowerCAmelCase												=							pipe.dual_guided(
                prompt="""first prompt"""      ,      image=__snake_case      ,      text_to_image_strength=0.75      ,      generator=__snake_case      ,      guidance_scale=7.5      ,      num_inference_steps=2      ,      output_type="""numpy"""      ,      ).images

            assert np.abs(image - new_image  ).sum() < 1E-5, "Models don't have the same forward pass"




      def     lowercase__   (      self      :			Optional[int]  )    ->				List[str]:
            _lowerCAmelCase												=							VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion"""      ,      torch_dtype=torch.floataa  )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							"""cyberpunk 2077"""
            _lowerCAmelCase												=							load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""  )
            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe.dual_guided(
                prompt=__snake_case      ,      image=__snake_case      ,      text_to_image_strength=0.75      ,      generator=__snake_case      ,      guidance_scale=7.5      ,      num_inference_steps=50      ,      output_type="""numpy"""      ,      ).images

            _lowerCAmelCase												=							image[0, 2_53:2_56, 2_53:2_56, -1]

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase												=							np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01]  )

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

            _lowerCAmelCase												=							"""A painting of a squirrel eating a burger """
            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe.text_to_image(
                prompt=__snake_case      ,      generator=__snake_case      ,      guidance_scale=7.5      ,      num_inference_steps=50      ,      output_type="""numpy"""  ).images

            _lowerCAmelCase												=							image[0, 2_53:2_56, 2_53:2_56, -1]

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase												=							np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78]  )

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

            _lowerCAmelCase												=							pipe.image_variation(__snake_case      ,      generator=__snake_case      ,      output_type="""numpy"""  ).images

            _lowerCAmelCase												=							image[0, 2_53:2_56, 2_53:2_56, -1]

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase												=							np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56]  )

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













'''simple docstring'''






from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


A__    :       Optional[int]              ='''CompVis/stable-diffusion-v1-1'''
A__    :       Optional[int]              ='''CompVis/stable-diffusion-v1-2'''
A__    :       List[str]              ='''CompVis/stable-diffusion-v1-3'''
A__    :       Optional[int]              ='''CompVis/stable-diffusion-v1-4'''




class 			UpperCAmelCase					(      snake_case_       ):




      def __init__(      self      :			Any      ,      __snake_case      :			AutoencoderKL      ,      __snake_case      :			CLIPTextModel      ,      __snake_case      :			CLIPTokenizer      ,      __snake_case      :			UNetaDConditionModel      ,      __snake_case      :			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,      __snake_case      :			StableDiffusionSafetyChecker      ,      __snake_case      :			CLIPImageProcessor      ,      __snake_case      :			bool = True      ,      )    ->				Any:
            super()._init_()

            _lowerCAmelCase												=							StableDiffusionPipeline.from_pretrained(__snake_case  )
            _lowerCAmelCase												=							StableDiffusionPipeline.from_pretrained(__snake_case  )
            _lowerCAmelCase												=							StableDiffusionPipeline.from_pretrained(__snake_case  )
            _lowerCAmelCase												=							StableDiffusionPipeline(
                vae=__snake_case      ,      text_encoder=__snake_case      ,      tokenizer=__snake_case      ,      unet=__snake_case      ,      scheduler=__snake_case      ,      safety_checker=__snake_case      ,      feature_extractor=__snake_case      ,      requires_safety_checker=__snake_case      ,      )

            self.register_modules(pipelinea=self.pipea      ,      pipelinea=self.pipea      ,      pipelinea=self.pipea      ,      pipelinea=self.pipea  )




      @property
      def     lowercase__   (      self      :			List[Any]  )    ->				Dict[str, Any]:
            return {k: getattr(self      ,      __snake_case  ) for k in self.config.keys() if not k.startswith("""_"""  )}




      def     lowercase__   (      self      :			List[Any]      ,      __snake_case      :			Optional[Union[str, int]] = "auto"  )    ->				Tuple:
            if slice_size == "auto":
                  # half the attention head size is usually a good trade-off between
                  # speed and memory
                  _lowerCAmelCase												=							self.unet.config.attention_head_dim // 2
            self.unet.set_attention_slice(__snake_case  )




      def     lowercase__   (      self      :			str  )    ->				int:
            self.enable_attention_slicing(__snake_case  )




      @torch.no_grad()
      def     lowercase__   (      self      :			Any      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			Tuple      ,      )    ->				Tuple:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Dict      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			int      ,      )    ->				List[Any]:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Any      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			Tuple      ,      )    ->				Dict:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Dict      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			str      ,      )    ->				List[Any]:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			Tuple      ,      )    ->				Optional[Any]:
            _lowerCAmelCase												=							"""cuda""" if torch.cuda.is_available() else """cpu"""
            self.to(__snake_case  )

            # Checks if the height and width are divisible by 8 or not
            if height % 8 != 0 or width % 8 != 0:
                  raise ValueError(f"`height` and `width` must be divisible by 8 but are {height} and {width}."  )

            # Get first result from Stable Diffusion Checkpoint v1.1
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get first result from Stable Diffusion Checkpoint v1.2
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get first result from Stable Diffusion Checkpoint v1.3
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get first result from Stable Diffusion Checkpoint v1.4
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
            return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]  )






