





'''simple docstring'''






import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs




class 			UpperCAmelCase					(      snake_case_       ):




      def __init__(      self      :			Optional[Any]      ,      __snake_case      :			Any      ,      __snake_case      :			List[Any]=None      ,      __snake_case      :			Any=True      ,      __snake_case      :			List[Any]=None      ,      **__snake_case      :			int  )    ->				str:
            _lowerCAmelCase												=							parent
            _lowerCAmelCase												=							config_class
            _lowerCAmelCase												=							has_text_modality
            _lowerCAmelCase												=							kwargs
            _lowerCAmelCase												=							common_properties




      def     lowercase__   (      self      :			Union[str, Any]  )    ->				List[str]:
            _lowerCAmelCase												=							self.config_class(**self.inputs_dict  )
            _lowerCAmelCase												=							(
                ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""]
                if self.common_properties is None
                else self.common_properties
            )

            # Add common fields for text models
            if self.has_text_modality:
                  common_properties.extend(["""vocab_size"""]  )

            # Test that config has the common properties as getters
            for prop in common_properties:
                  self.parent.assertTrue(hasattr(__snake_case      ,      __snake_case  )      ,      msg=f"`{prop}` does not exist"  )

            # Test that config has the common properties as setter
            for idx, name in enumerate(__snake_case  ):
                  try:
                        setattr(__snake_case      ,      __snake_case      ,      __snake_case  )
                        self.parent.assertEqual(
                            getattr(__snake_case      ,      __snake_case  )      ,      __snake_case      ,      msg=f"`{name} value {idx} expected, but was {getattr(__snake_case      ,      __snake_case  )}"  )
                  except NotImplementedError:
                        # Some models might not be able to implement setters for common_properties
                        # In that case, a NotImplementedError is raised
                        pass

        # Test if config class can be called with Config(prop_name=..)
            for idx, name in enumerate(__snake_case  ):
                  try:
                        _lowerCAmelCase												=							self.config_class(**{name: idx}  )
                        self.parent.assertEqual(
                            getattr(__snake_case      ,      __snake_case  )      ,      __snake_case      ,      msg=f"`{name} value {idx} expected, but was {getattr(__snake_case      ,      __snake_case  )}"  )
                  except NotImplementedError:
                        # Some models might not be able to implement setters for common_properties
                        # In that case, a NotImplementedError is raised
                        pass




      def     lowercase__   (      self      :			str  )    ->				Optional[int]:
            _lowerCAmelCase												=							self.config_class(**self.inputs_dict  )
            _lowerCAmelCase												=							json.loads(config.to_json_string()  )
            for key, value in self.inputs_dict.items():
                  self.parent.assertEqual(obj[key]      ,      __snake_case  )




      def     lowercase__   (      self      :			List[Any]  )    ->				str:
            _lowerCAmelCase												=							self.config_class(**self.inputs_dict  )

            with tempfile.TemporaryDirectory() as tmpdirname:
                  _lowerCAmelCase												=							os.path.join(__snake_case      ,      """config.json"""  )
                  config_first.to_json_file(__snake_case  )
                  _lowerCAmelCase												=							self.config_class.from_json_file(__snake_case  )

            self.parent.assertEqual(config_second.to_dict()      ,      config_first.to_dict()  )




      def     lowercase__   (      self      :			Tuple  )    ->				int:
            _lowerCAmelCase												=							self.config_class(**self.inputs_dict  )

            with tempfile.TemporaryDirectory() as tmpdirname:
                  config_first.save_pretrained(__snake_case  )
                  _lowerCAmelCase												=							self.config_class.from_pretrained(__snake_case  )

            self.parent.assertEqual(config_second.to_dict()      ,      config_first.to_dict()  )




      def     lowercase__   (      self      :			Dict  )    ->				Union[str, Any]:
            _lowerCAmelCase												=							self.config_class(**self.inputs_dict  )

            _lowerCAmelCase												=							"""test"""
            with tempfile.TemporaryDirectory() as tmpdirname:
                  _lowerCAmelCase												=							os.path.join(__snake_case      ,      __snake_case  )
                  config_first.save_pretrained(__snake_case  )
                  _lowerCAmelCase												=							self.config_class.from_pretrained(__snake_case      ,      subfolder=__snake_case  )

            self.parent.assertEqual(config_second.to_dict()      ,      config_first.to_dict()  )




      def     lowercase__   (      self      :			Tuple  )    ->				List[Any]:
            _lowerCAmelCase												=							self.config_class(**self.inputs_dict      ,      num_labels=5  )
            self.parent.assertEqual(len(config.idalabel  )      ,      5  )
            self.parent.assertEqual(len(config.labelaid  )      ,      5  )

            _lowerCAmelCase												=							3
            self.parent.assertEqual(len(config.idalabel  )      ,      3  )
            self.parent.assertEqual(len(config.labelaid  )      ,      3  )




      def     lowercase__   (      self      :			List[str]  )    ->				List[Any]:
            if self.config_class.is_composition:
                  return
            _lowerCAmelCase												=							self.config_class()
            self.parent.assertIsNotNone(__snake_case  )




      def     lowercase__   (      self      :			str  )    ->				Optional[int]:
            _lowerCAmelCase												=							copy.deepcopy(__snake_case  )
            _lowerCAmelCase												=							self.config_class(**__snake_case  )
            _lowerCAmelCase												=							[]
            for key, value in config_common_kwargs.items():
                  if key == "torch_dtype":
                        if not is_torch_available():
                              continue
                        else:
                              import torch

                              if config.torch_dtype != torch.floataa:
                                    wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa)  )
                  elif getattr(__snake_case      ,      __snake_case  ) != value:
                        wrong_values.append((key, getattr(__snake_case      ,      __snake_case  ), value)  )

            if len(__snake_case  ) > 0:
                  _lowerCAmelCase												=							"""\n""".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values]  )
                  raise ValueError(f"The following keys were not properly set in the config:\n{errors}"  )




      def     lowercase__   (      self      :			Union[str, Any]  )    ->				List[Any]:
            self.create_and_test_config_common_properties()
            self.create_and_test_config_to_json_string()
            self.create_and_test_config_to_json_file()
            self.create_and_test_config_from_and_save_pretrained()
            self.create_and_test_config_from_and_save_pretrained_subfolder()
            self.create_and_test_config_with_num_labels()
            self.check_config_can_be_init_without_params()
            self.check_config_arguments_init()













'''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]]  )






