


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


_UpperCAmelCase			:  List[str]     ="""CompVis/stable-diffusion-v1-1"""
_UpperCAmelCase			:  str     ="""CompVis/stable-diffusion-v1-2"""
_UpperCAmelCase			:  Union[str, Any]     ="""CompVis/stable-diffusion-v1-3"""
_UpperCAmelCase			:  List[str]     ="""CompVis/stable-diffusion-v1-4"""







class 				snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						def __init__(				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase = True   ,						)					->    Tuple:
										super()._init_()

										lowerCAmelCase_ :      List[Any]    				=				StableDiffusionPipeline.from_pretrained(__lowercase							)
										lowerCAmelCase_ :      Optional[Any]    				=				StableDiffusionPipeline.from_pretrained(__lowercase							)
										lowerCAmelCase_ :      List[str]    				=				StableDiffusionPipeline.from_pretrained(__lowercase							)
										lowerCAmelCase_ :      Dict    				=				StableDiffusionPipeline(
										    vae=__lowercase   ,						text_encoder=__lowercase   ,						tokenizer=__lowercase   ,						unet=__lowercase   ,						scheduler=__lowercase   ,						safety_checker=__lowercase   ,						feature_extractor=__lowercase   ,						requires_safety_checker=__lowercase   ,						)

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




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




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




						def 						lowercase_ (				self							)					->    int:
										self.enable_attention_slicing(__lowercase							)




						@torch.no_grad()
						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase = 5_1_2   ,						__lowercase = 5_1_2   ,						__lowercase = 5_0   ,						__lowercase = 7.5   ,						__lowercase = None   ,						__lowercase = 1   ,						__lowercase = 0.0   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = "pil"   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = 1   ,						**__lowercase   ,						)					->    Optional[Any]:
										return self.pipea(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)




						@torch.no_grad()
						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase = 5_1_2   ,						__lowercase = 5_1_2   ,						__lowercase = 5_0   ,						__lowercase = 7.5   ,						__lowercase = None   ,						__lowercase = 1   ,						__lowercase = 0.0   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = "pil"   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = 1   ,						**__lowercase   ,						)					->    Dict:
										return self.pipea(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)




						@torch.no_grad()
						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase = 5_1_2   ,						__lowercase = 5_1_2   ,						__lowercase = 5_0   ,						__lowercase = 7.5   ,						__lowercase = None   ,						__lowercase = 1   ,						__lowercase = 0.0   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = "pil"   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = 1   ,						**__lowercase   ,						)					->    Tuple:
										return self.pipea(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)




						@torch.no_grad()
						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase = 5_1_2   ,						__lowercase = 5_1_2   ,						__lowercase = 5_0   ,						__lowercase = 7.5   ,						__lowercase = None   ,						__lowercase = 1   ,						__lowercase = 0.0   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = "pil"   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = 1   ,						**__lowercase   ,						)					->    Any:
										return self.pipea(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)




						@torch.no_grad()
						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase = 5_1_2   ,						__lowercase = 5_1_2   ,						__lowercase = 5_0   ,						__lowercase = 7.5   ,						__lowercase = None   ,						__lowercase = 1   ,						__lowercase = 0.0   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = "pil"   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = 1   ,						**__lowercase   ,						)					->    List[Any]:
										lowerCAmelCase_ :      Union[str, Any]    				=				'''cuda''' if torch.cuda.is_available() else '''cpu'''
										self.to(__lowercase							)

										# 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_ :      List[str]    				=				self.textaimg_sda_a(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)

										# Get first result from Stable Diffusion Checkpoint v1.2
										lowerCAmelCase_ :      Optional[Any]    				=				self.textaimg_sda_a(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)

										# Get first result from Stable Diffusion Checkpoint v1.3
										lowerCAmelCase_ :      Optional[int]    				=				self.textaimg_sda_a(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)

										# Get first result from Stable Diffusion Checkpoint v1.4
										lowerCAmelCase_ :      Optional[Any]    				=				self.textaimg_sda_a(
										    prompt=__lowercase   ,						height=__lowercase   ,						width=__lowercase   ,						num_inference_steps=__lowercase   ,						guidance_scale=__lowercase   ,						negative_prompt=__lowercase   ,						num_images_per_prompt=__lowercase   ,						eta=__lowercase   ,						generator=__lowercase   ,						latents=__lowercase   ,						output_type=__lowercase   ,						return_dict=__lowercase   ,						callback=__lowercase   ,						callback_steps=__lowercase   ,						**__lowercase   ,						)

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



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
						import PIL


_UpperCAmelCase			:  Any     =logging.get_logger(__name__)







class 				snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  Dict					=							["""pixel_values"""]




						def __init__(				self   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = PILImageResampling.BILINEAR   ,						__lowercase = True   ,						__lowercase = 1 / 2_5_5   ,						__lowercase = True   ,						__lowercase = None   ,						__lowercase = None   ,						**__lowercase   ,						)					->    None:
										super().__init__(**__lowercase							)
										lowerCAmelCase_ :      Dict    				=				size if size is not None else {'''shortest_edge''': 3_8_4}
										lowerCAmelCase_ :      Optional[Any]    				=				get_size_dict(__lowercase   ,						default_to_square=__lowercase							)

										lowerCAmelCase_ :      List[Any]    				=				do_resize
										lowerCAmelCase_ :      Optional[int]    				=				size
										# Default value set here for backwards compatibility where the value in config is None
										lowerCAmelCase_ :      str    				=				crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
										lowerCAmelCase_ :      Tuple    				=				resample
										lowerCAmelCase_ :      Optional[int]    				=				do_rescale
										lowerCAmelCase_ :      Any    				=				rescale_factor
										lowerCAmelCase_ :      List[str]    				=				do_normalize
										lowerCAmelCase_ :      str    				=				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
										lowerCAmelCase_ :      Dict    				=				image_std if image_std is not None else IMAGENET_STANDARD_STD




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase = PILImageResampling.BICUBIC   ,						__lowercase = None   ,						**__lowercase   ,						)					->    np.ndarray:
										lowerCAmelCase_ :      Optional[Any]    				=				get_size_dict(__lowercase   ,						default_to_square=__lowercase							)
										if "shortest_edge" not in size:
														raise ValueError(f"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}"""							)
										lowerCAmelCase_ :      Optional[int]    				=				size['''shortest_edge''']

										if shortest_edge < 3_8_4:
														# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
														lowerCAmelCase_ :      Optional[Any]    				=				int(shortest_edge / crop_pct							)
														lowerCAmelCase_ :      List[str]    				=				get_resize_output_image_size(__lowercase   ,						size=__lowercase   ,						default_to_square=__lowercase							)
														lowerCAmelCase_ :      List[Any]    				=				resize(image=__lowercase   ,						size=__lowercase   ,						resample=__lowercase   ,						data_format=__lowercase   ,						**__lowercase							)
														# then crop to (shortest_edge, shortest_edge)
														return center_crop(image=__lowercase   ,						size=(shortest_edge, shortest_edge)   ,						data_format=__lowercase   ,						**__lowercase							)
										else:
														# warping (no cropping) when evaluated at 384 or larger
														return resize(
														    __lowercase   ,						size=(shortest_edge, shortest_edge)   ,						resample=__lowercase   ,						data_format=__lowercase   ,						**__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase = None   ,						**__lowercase   ,						)					->    Any:
										return rescale(__lowercase   ,						scale=__lowercase   ,						data_format=__lowercase   ,						**__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase   ,						__lowercase = None   ,						**__lowercase   ,						)					->    np.ndarray:
										return normalize(__lowercase   ,						mean=__lowercase   ,						std=__lowercase   ,						data_format=__lowercase   ,						**__lowercase							)




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = None   ,						__lowercase = ChannelDimension.FIRST   ,						**__lowercase   ,						)					->    PIL.Image.Image:
										lowerCAmelCase_ :      Optional[int]    				=				do_resize if do_resize is not None else self.do_resize
										lowerCAmelCase_ :      Any    				=				crop_pct if crop_pct is not None else self.crop_pct
										lowerCAmelCase_ :      str    				=				resample if resample is not None else self.resample
										lowerCAmelCase_ :      Union[str, Any]    				=				do_rescale if do_rescale is not None else self.do_rescale
										lowerCAmelCase_ :      str    				=				rescale_factor if rescale_factor is not None else self.rescale_factor
										lowerCAmelCase_ :      Any    				=				do_normalize if do_normalize is not None else self.do_normalize
										lowerCAmelCase_ :      str    				=				image_mean if image_mean is not None else self.image_mean
										lowerCAmelCase_ :      int    				=				image_std if image_std is not None else self.image_std

										lowerCAmelCase_ :      int    				=				size if size is not None else self.size
										lowerCAmelCase_ :      List[str]    				=				get_size_dict(__lowercase   ,						default_to_square=__lowercase							)

										lowerCAmelCase_ :      Tuple    				=				make_list_of_images(__lowercase							)

										if not valid_images(__lowercase							):
														raise ValueError(
														    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
														    '''torch.Tensor, tf.Tensor or jax.ndarray.'''							)

										if do_resize and size is None or resample is None:
														raise ValueError('''Size and resample must be specified if do_resize is True.'''							)

										if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
														raise ValueError('''crop_pct must be specified if size < 384.'''							)

										if do_rescale and rescale_factor is None:
														raise ValueError('''Rescale factor must be specified if do_rescale is True.'''							)

										if do_normalize and (image_mean is None or image_std is None):
														raise ValueError('''Image mean and std must be specified if do_normalize is True.'''							)

										# All transformations expect numpy arrays.
										lowerCAmelCase_ :      Optional[Any]    				=				[to_numpy_array(__lowercase							) for image in images]

										if do_resize:
														lowerCAmelCase_ :      Union[str, Any]    				=				[self.resize(image=__lowercase   ,						size=__lowercase   ,						crop_pct=__lowercase   ,						resample=__lowercase							) for image in images]

										if do_rescale:
														lowerCAmelCase_ :      Any    				=				[self.rescale(image=__lowercase   ,						scale=__lowercase							) for image in images]

										if do_normalize:
														lowerCAmelCase_ :      List[Any]    				=				[self.normalize(image=__lowercase   ,						mean=__lowercase   ,						std=__lowercase							) for image in images]

										lowerCAmelCase_ :      Optional[Any]    				=				[to_channel_dimension_format(__lowercase   ,						__lowercase							) for image in images]

										lowerCAmelCase_ :      Dict    				=				{'''pixel_values''': images}
										return BatchFeature(data=__lowercase   ,						tensor_type=__lowercase							)