




from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import (
    BaseOutput,
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_onnx_available,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)

@dataclass
class  _lowerCamelCase						(			_SCREAMING_SNAKE_CASE   ):

      """simple docstring"""

      lowerCAmelCase__			: Union[List[PIL.Image.Image], np.ndarray]
      lowerCAmelCase__			: Optional[List[bool]]


try:
 if not (is_transformers_available() and is_torch_available()):
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
 from .pipeline_cycle_diffusion import CycleDiffusionPipeline
 from .pipeline_stable_diffusion import StableDiffusionPipeline
 from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline
 from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline
 from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline
 from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy
 from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline
 from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline
 from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline
 from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline
 from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline
 from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline
 from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline
 from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
 from .pipeline_stable_unclip import StableUnCLIPPipeline
 from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline
 from .safety_checker import StableDiffusionSafetyChecker
 from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer

try:
 if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")):
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline
else:
 from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline


try:
 if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.26.0")):
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 from ...utils.dummy_torch_and_transformers_objects import (
     StableDiffusionDepthaImgPipeline,
     StableDiffusionDiffEditPipeline,
     StableDiffusionPixaPixZeroPipeline,
 )
else:
 from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline
 from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline
 from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline


try:
 if not (
     is_torch_available()
     and is_transformers_available()
     and is_k_diffusion_available()
     and is_k_diffusion_version(">=", "0.0.12")
 ):
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
 from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline

try:
 if not (is_transformers_available() and is_onnx_available()):
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 from ...utils.dummy_onnx_objects import *  # noqa F403
else:
 from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline
 from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline
 from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline
 from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy
 from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline

if is_transformers_available() and is_flax_available():
 import flax

 @flax.struct.dataclass
 class  _lowerCamelCase						(			_SCREAMING_SNAKE_CASE   ):

       """simple docstring"""

       lowerCAmelCase__			: np.ndarray
       lowerCAmelCase__			: List[bool]







 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState
 from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline
 from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline
 from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline
 from .safety_checker_flax import FlaxStableDiffusionSafetyChecker












import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class  _lowerCamelCase						(			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			unittest.TestCase   ):

      """simple docstring"""

      lowerCAmelCase__			: Optional[int]    =					StableDiffusionXLImgaImgPipeline
      lowerCAmelCase__			: List[str]    =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
      lowerCAmelCase__			: int    =					PipelineTesterMixin.required_optional_params - {"latents"}
      lowerCAmelCase__			: Tuple    =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
      lowerCAmelCase__			: int    =					IMAGE_TO_IMAGE_IMAGE_PARAMS
      lowerCAmelCase__			: List[Any]    =					IMAGE_TO_IMAGE_IMAGE_PARAMS







      def       snake_case	(     self					: Union[str, Any]				):
          torch.manual_seed(0				)
          __UpperCamelCase  		=						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''') ,       attention_head_dim=(2, 4) ,       use_linear_projection=snake_case ,       addition_embed_type='''text_time''' ,       addition_time_embed_dim=8 ,       transformer_layers_per_block=(1, 2) ,       projection_class_embeddings_input_dim=80 ,       cross_attention_dim=64 ,       )
          __UpperCamelCase  		=						EulerDiscreteScheduler(
              beta_start=0.0_00_85 ,       beta_end=0.0_12 ,       steps_offset=1 ,       beta_schedule='''scaled_linear''' ,       timestep_spacing='''leading''' ,       )
          torch.manual_seed(0				)
          __UpperCamelCase  		=						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=128 ,       )
          torch.manual_seed(0				)
          __UpperCamelCase  		=						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 ,       hidden_act='''gelu''' ,       projection_dim=32 ,       )
          __UpperCamelCase  		=						CLIPTextModel(snake_case				)
          __UpperCamelCase  		=						CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,       local_files_only=snake_case				)

          __UpperCamelCase  		=						CLIPTextModelWithProjection(snake_case				)
          __UpperCamelCase  		=						CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,       local_files_only=snake_case				)

          __UpperCamelCase  		=						{
              '''unet''': unet,
              '''scheduler''': scheduler,
              '''vae''': vae,
              '''text_encoder''': text_encoder,
              '''tokenizer''': tokenizer,
              '''text_encoder_2''': text_encoder_a,
              '''tokenizer_2''': tokenizer_a,
              # "safety_checker": None,
              # "feature_extractor": None,
          }
          return components







      def       snake_case	(     self					: List[Any] ,       snake_case					: List[Any] ,       snake_case					: str=0				):
          __UpperCamelCase  		=						floats_tensor((1, 3, 32, 32) ,       rng=random.Random(snake_case				)				).to(snake_case				)
          __UpperCamelCase  		=						image / 2 + 0.5
          if str(snake_case				).startswith('''mps'''				):
              __UpperCamelCase  		=						torch.manual_seed(snake_case				)
          else:
              __UpperCamelCase  		=						torch.Generator(device=snake_case				).manual_seed(snake_case				)
          __UpperCamelCase  		=						{
              '''prompt''': '''A painting of a squirrel eating a burger''',
              '''image''': image,
              '''generator''': generator,
              '''num_inference_steps''': 2,
              '''guidance_scale''': 5.0,
              '''output_type''': '''numpy''',
              '''strength''': 0.75,
          }
          return inputs







      def       snake_case	(     self					: Tuple				):
          __UpperCamelCase  		=						'''cpu'''  # ensure determinism for the device-dependent torch.Generator
          __UpperCamelCase  		=						self.get_dummy_components()
          __UpperCamelCase  		=						StableDiffusionXLImgaImgPipeline(**snake_case				)
          __UpperCamelCase  		=						sd_pipe.to(snake_case				)
          sd_pipe.set_progress_bar_config(disable=snake_case				)

          __UpperCamelCase  		=						self.get_dummy_inputs(snake_case				)
          __UpperCamelCase  		=						sd_pipe(**snake_case				).images
          __UpperCamelCase  		=						image[0, -3:, -3:, -1]

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

          __UpperCamelCase  		=						np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]				)

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







      def       snake_case	(     self					: Optional[int]				):
          super().test_attention_slicing_forward_pass(expected_max_diff=3E-3				)







      def       snake_case	(     self					: Optional[Any]				):
          super().test_inference_batch_single_identical(expected_max_diff=3E-3				)







      def       snake_case	(     self					: Optional[Any]				):
          pass







      def       snake_case	(     self					: str				):
          __UpperCamelCase  		=						self.get_dummy_components()
          __UpperCamelCase  		=						StableDiffusionXLImgaImgPipeline(**snake_case				)
          __UpperCamelCase  		=						sd_pipe.to(snake_case				)
          __UpperCamelCase  		=						sd_pipe.to(snake_case				)
          sd_pipe.set_progress_bar_config(disable=snake_case				)

          # forward without prompt embeds
          __UpperCamelCase  		=						self.get_dummy_inputs(snake_case				)
          __UpperCamelCase  		=						3 * ['''this is a negative prompt''']
          __UpperCamelCase  		=						negative_prompt
          __UpperCamelCase  		=						3 * [inputs['''prompt''']]

          __UpperCamelCase  		=						sd_pipe(**snake_case				)
          __UpperCamelCase  		=						output.images[0, -3:, -3:, -1]

          # forward with prompt embeds
          __UpperCamelCase  		=						self.get_dummy_inputs(snake_case				)
          __UpperCamelCase  		=						3 * ['''this is a negative prompt''']
          __UpperCamelCase  		=						3 * [inputs.pop('''prompt'''				)]

          (
              (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      
          )  		=						sd_pipe.encode_prompt(snake_case ,       negative_prompt=snake_case				)

          __UpperCamelCase  		=						sd_pipe(
              **snake_case ,       prompt_embeds=snake_case ,       negative_prompt_embeds=snake_case ,       pooled_prompt_embeds=snake_case ,       negative_pooled_prompt_embeds=snake_case ,       )
          __UpperCamelCase  		=						output.images[0, -3:, -3:, -1]

          # make sure that it's equal
          assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()				).max() < 1E-4







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

      """simple docstring"""

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







      def       snake_case	(     self					: str ,       snake_case					: List[Any] ,       snake_case					: str="cpu" ,       snake_case					: int=torch.floataa ,       snake_case					: Optional[int]=0				):
          __UpperCamelCase  		=						torch.Generator(device=snake_case				).manual_seed(snake_case				)
          __UpperCamelCase  		=						np.random.RandomState(snake_case				).standard_normal((1, 4, 64, 64)				)
          __UpperCamelCase  		=						torch.from_numpy(snake_case				).to(device=snake_case ,       dtype=snake_case				)
          __UpperCamelCase  		=						{
              '''prompt''': '''a photograph of an astronaut riding a horse''',
              '''latents''': latents,
              '''generator''': generator,
              '''num_inference_steps''': 3,
              '''guidance_scale''': 7.5,
              '''output_type''': '''numpy''',
          }
          return inputs







      def       snake_case	(     self					: Dict				):
          __UpperCamelCase  		=						DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''				)
          pipe.to(snake_case				)
          pipe.set_progress_bar_config(disable=snake_case				)

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

          assert image.shape == (1, 512, 512, 3)
          __UpperCamelCase  		=						np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]				)
          assert np.abs(image_slice - expected_slice				).max() < 7E-3






