






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,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
	import PIL


lowercase    				=   logging.get_logger(__name__)





def 		__UpperCAmelCase     (	a_):
							if isinstance(a_				,	(list, tuple)) and isinstance(videos[0]				,	(list, tuple)) and is_valid_image(videos[0][0]):
														return videos

							elif isinstance(a_				,	(list, tuple)) and is_valid_image(videos[0]):
														return [videos]

							elif is_valid_image(a_):
														return [[videos]]

							raise ValueError(f'''Could not make batched video from {videos}''')




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	lowerCAmelCase						=					['''pixel_values''']




	def __init__(			self			,     a = True			,     a = None			,     a = PILImageResampling.BILINEAR			,     a = True			,     a = None			,     a = True			,     a = 1 / 2_55			,     a = True			,     a = None			,     a = None			,     **a			,     )			->       None:
								super().__init__(**a   )
								snake_case_           =				size if size is not None else {'shortest_edge': 2_24}
								snake_case_           =				get_size_dict(a			,     default_to_square=a   )
								snake_case_           =				crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
								snake_case_           =				get_size_dict(a			,     param_name='crop_size'   )

								snake_case_           =				do_resize
								snake_case_           =				size
								snake_case_           =				do_center_crop
								snake_case_           =				crop_size
								snake_case_           =				resample
								snake_case_           =				do_rescale
								snake_case_           =				rescale_factor
								snake_case_           =				do_normalize
								snake_case_           =				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
								snake_case_           =				image_std if image_std is not None else IMAGENET_STANDARD_STD




	def 				_UpperCamelCase     (			self			,     a			,     a			,     a = PILImageResampling.BILINEAR			,     a = None			,     **a			,     )			->       np.ndarray:
								snake_case_           =				get_size_dict(a			,     default_to_square=a   )
								if "shortest_edge" in size:
															snake_case_           =				get_resize_output_image_size(a			,     size['shortest_edge']			,     default_to_square=a   )
								elif "height" in size and "width" in size:
															snake_case_           =				(size['height'], size['width'])
								else:
															raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''   )
								return resize(a			,     size=a			,     resample=a			,     data_format=a			,     **a   )




	def 				_UpperCamelCase     (			self			,     a			,     a			,     a = None			,     **a			,     )			->       np.ndarray:
								snake_case_           =				get_size_dict(a   )
								if "height" not in size or "width" not in size:
															raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}'''   )
								return center_crop(a			,     size=(size['height'], size['width'])			,     data_format=a			,     **a   )




	def 				_UpperCamelCase     (			self			,     a			,     a			,     a = None			,     **a			,     )			->       List[str]:
								return rescale(a			,     scale=a			,     data_format=a			,     **a   )




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




	def 				_UpperCamelCase     (			self			,     a			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = ChannelDimension.FIRST			,     )			->       np.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_center_crop and crop_size is None:
															raise ValueError('Crop size must be specified if do_center_crop is True.'   )

								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.
								snake_case_           =				to_numpy_array(a   )

								if do_resize:
															snake_case_           =				self.resize(image=a			,     size=a			,     resample=a   )

								if do_center_crop:
															snake_case_           =				self.center_crop(a			,     size=a   )

								if do_rescale:
															snake_case_           =				self.rescale(image=a			,     scale=a   )

								if do_normalize:
															snake_case_           =				self.normalize(image=a			,     mean=a			,     std=a   )

								snake_case_           =				to_channel_dimension_format(a			,     a   )
								return image






	def 				_UpperCamelCase     (			self			,     a			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = None			,     a = ChannelDimension.FIRST			,     **a			,     )			->       PIL.Image.Image:
								snake_case_           =				do_resize if do_resize is not None else self.do_resize
								snake_case_           =				resample if resample is not None else self.resample
								snake_case_           =				do_center_crop if do_center_crop is not None else self.do_center_crop
								snake_case_           =				do_rescale if do_rescale is not None else self.do_rescale
								snake_case_           =				rescale_factor if rescale_factor is not None else self.rescale_factor
								snake_case_           =				do_normalize if do_normalize is not None else self.do_normalize
								snake_case_           =				image_mean if image_mean is not None else self.image_mean
								snake_case_           =				image_std if image_std is not None else self.image_std

								snake_case_           =				size if size is not None else self.size
								snake_case_           =				get_size_dict(a			,     default_to_square=a   )
								snake_case_           =				crop_size if crop_size is not None else self.crop_size
								snake_case_           =				get_size_dict(a			,     param_name='crop_size'   )

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

								snake_case_           =				make_batched(a   )

								snake_case_           =				[
								    [
								        self._preprocess_image(
								            image=a			,     do_resize=a			,     size=a			,     resample=a			,     do_center_crop=a			,     crop_size=a			,     do_rescale=a			,     rescale_factor=a			,     do_normalize=a			,     image_mean=a			,     image_std=a			,     data_format=a			,     )
								        for img in video
								    ]
								    for video in videos
								]

								snake_case_           =				{'pixel_values': videos}
								return BatchFeature(data=a			,     tensor_type=a   )













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


lowercase    				=   "CompVis/stable-diffusion-v1-1"
lowercase    				=   "CompVis/stable-diffusion-v1-2"
lowercase    				=   "CompVis/stable-diffusion-v1-3"
lowercase    				=   "CompVis/stable-diffusion-v1-4"




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	def __init__(			self			,     a			,     a			,     a			,     a			,     a			,     a			,     a			,     a = True			,     )			->       int:
								super()._init_()

								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline(
								    vae=a			,     text_encoder=a			,     tokenizer=a			,     unet=a			,     scheduler=a			,     safety_checker=a			,     feature_extractor=a			,     requires_safety_checker=a			,     )

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




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




	def 				_UpperCamelCase     (			self			,     a = "auto"   )			->       Dict:
								if slice_size == "auto":
															# half the attention head size is usually a good trade-off between
															# speed and memory
															snake_case_           =				self.unet.config.attention_head_dim // 2
								self.unet.set_attention_slice(a   )




	def 				_UpperCamelCase     (			self   )			->       List[Any]:
								self.enable_attention_slicing(a   )




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




	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       int:
								return self.pipea(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )




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




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






	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     a = 50			,     a = 7.5			,     a = None			,     a = 1			,     a = 0.0			,     a = None			,     a = None			,     a = "pil"			,     a = True			,     a = None			,     a = 1			,     **a			,     )			->       Optional[Any]:
								snake_case_           =				'cuda' if torch.cuda.is_available() else 'cpu'
								self.to(a   )

								# 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
								snake_case_           =				self.textaimg_sda_a(
								    prompt=a			,     height=a			,     width=a			,     num_inference_steps=a			,     guidance_scale=a			,     negative_prompt=a			,     num_images_per_prompt=a			,     eta=a			,     generator=a			,     latents=a			,     output_type=a			,     return_dict=a			,     callback=a			,     callback_steps=a			,     **a			,     )

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

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

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

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





