






"""simple docstring"""







import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

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


SCREAMING_SNAKE_CASE									=						logging.get_logger(__name__)  # pylint: disable=invalid-name



class  _lowerCamelCase			(__lowerCamelCase     ):







				def __init__( self    :       Optional[int]			,					lowerCamelCase_    :       WhisperForConditionalGeneration			,					lowerCamelCase_    :       WhisperProcessor			,					lowerCamelCase_    :       AutoencoderKL			,					lowerCamelCase_    :       CLIPTextModel			,					lowerCamelCase_    :       CLIPTokenizer			,					lowerCamelCase_    :       UNetaDConditionModel			,					lowerCamelCase_    :       Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]			,					lowerCamelCase_    :       StableDiffusionSafetyChecker			,					lowerCamelCase_    :       CLIPImageProcessor			,					):

					"""simple docstring"""






					super().__init__()

					if safety_checker is None:
						logger.warning(
						    F'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'''
						    ' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'
						    ' results in services or applications open to the public. Both the diffusers team and Hugging Face'
						    ' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'
						    ' it only for use-cases that involve analyzing network behavior or auditing its results. For more'
						    ' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .'						)

					self.register_modules(
					    speech_model=lowerCamelCase_			,					speech_processor=lowerCamelCase_			,					vae=lowerCamelCase_			,					text_encoder=lowerCamelCase_			,					tokenizer=lowerCamelCase_			,					unet=lowerCamelCase_			,					scheduler=lowerCamelCase_			,					feature_extractor=lowerCamelCase_			,					)







				def 							__UpperCAmelCase					( self    :       List[str]			,					lowerCamelCase_    :       Optional[Union[str, int]] = "auto"						):

					"""simple docstring"""






					if slice_size == "auto":
						_lowercase :    str							=							self.unet.config.attention_head_dim // 2
					self.unet.set_attention_slice(lowerCamelCase_						)







				def 							__UpperCAmelCase					( self    :       Dict						):

					"""simple docstring"""






					self.enable_attention_slicing(lowerCamelCase_						)







				@torch.no_grad()
				def __call__( self    :       Optional[int]			,					lowerCamelCase_    :       Dict			,					lowerCamelCase_    :       Optional[Any]=1_6_0_0_0			,					lowerCamelCase_    :       int = 5_1_2			,					lowerCamelCase_    :       int = 5_1_2			,					lowerCamelCase_    :       int = 5_0			,					lowerCamelCase_    :       float = 7.5			,					lowerCamelCase_    :       Optional[Union[str, List[str]]] = None			,					lowerCamelCase_    :       Optional[int] = 1			,					lowerCamelCase_    :       float = 0.0			,					lowerCamelCase_    :       Optional[torch.Generator] = None			,					lowerCamelCase_    :       Optional[torch.FloatTensor] = None			,					lowerCamelCase_    :       Optional[str] = "pil"			,					lowerCamelCase_    :       bool = True			,					lowerCamelCase_    :       Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,					lowerCamelCase_    :       int = 1			,					**lowerCamelCase_    :       Dict			,					):

					"""simple docstring"""






					_lowercase :    Dict							=							self.speech_processor.feature_extractor(
					    lowerCamelCase_			,					return_tensors='pt'			,					sampling_rate=lowerCamelCase_						).input_features.to(self.device						)
					_lowercase :    List[Any]							=							self.speech_model.generate(lowerCamelCase_			,					max_length=4_8_0_0_0_0						)

					_lowercase :    Tuple							=							self.speech_processor.tokenizer.batch_decode(lowerCamelCase_			,					skip_special_tokens=lowerCamelCase_			,					normalize=lowerCamelCase_						)[
					    0
					]

					if isinstance(lowerCamelCase_			,					lowerCamelCase_						):
						_lowercase :    int							=							1
					elif isinstance(lowerCamelCase_			,					lowerCamelCase_						):
						_lowercase :    str							=							len(lowerCamelCase_						)
					else:
						raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase_						)}'''						)

					if height % 8 != 0 or width % 8 != 0:
						raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.'''						)

					if (callback_steps is None) or (
					    callback_steps is not None and (not isinstance(lowerCamelCase_			,					lowerCamelCase_						) or callback_steps <= 0)
					):
						raise ValueError(
						    F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
						    F''' {type(lowerCamelCase_						)}.'''						)

					# get prompt text embeddings
					_lowercase :    Any							=							self.tokenizer(
					    lowerCamelCase_			,					padding='max_length'			,					max_length=self.tokenizer.model_max_length			,					return_tensors='pt'			,					)
					_lowercase :    Optional[int]							=							text_inputs.input_ids

					if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
						_lowercase :    List[str]							=							self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]						)
						logger.warning(
						    'The following part of your input was truncated because CLIP can only handle sequences up to'
						    F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''						)
						_lowercase :    List[Any]							=							text_input_ids[:, : self.tokenizer.model_max_length]
					_lowercase :    Any							=							self.text_encoder(text_input_ids.to(self.device						)						)[0]

					# duplicate text embeddings for each generation per prompt, using mps friendly method
					_lowercase :    str							=							text_embeddings.shape
					_lowercase :    Union[str, Any]							=							text_embeddings.repeat(1			,					lowerCamelCase_			,					1						)
					_lowercase :    Optional[Any]							=							text_embeddings.view(bs_embed * num_images_per_prompt			,					lowerCamelCase_			,					-1						)

					# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
					# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
					# corresponds to doing no classifier free guidance.
					_lowercase :    Any							=							guidance_scale > 1.0
					# get unconditional embeddings for classifier free guidance
					if do_classifier_free_guidance:
						_lowercase :    List[str]
						if negative_prompt is None:
							_lowercase :    Union[str, Any]							=							[''] * batch_size
						elif type(lowerCamelCase_						) is not type(lowerCamelCase_						):
							raise TypeError(
							    F'''`negative_prompt` should be the same type to `prompt`, but got {type(lowerCamelCase_						)} !='''
							    F''' {type(lowerCamelCase_						)}.'''						)
						elif isinstance(lowerCamelCase_			,					lowerCamelCase_						):
							_lowercase :    Tuple							=							[negative_prompt]
						elif batch_size != len(lowerCamelCase_						):
							raise ValueError(
							    F'''`negative_prompt`: {negative_prompt} has batch size {len(lowerCamelCase_						)}, but `prompt`:'''
							    F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
							    ' the batch size of `prompt`.'						)
						else:
							_lowercase :    str							=							negative_prompt

						_lowercase :    int							=							text_input_ids.shape[-1]
						_lowercase :    int							=							self.tokenizer(
						    lowerCamelCase_			,					padding='max_length'			,					max_length=lowerCamelCase_			,					truncation=lowerCamelCase_			,					return_tensors='pt'			,					)
						_lowercase :    List[Any]							=							self.text_encoder(uncond_input.input_ids.to(self.device						)						)[0]

						# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
						_lowercase :    List[Any]							=							uncond_embeddings.shape[1]
						_lowercase :    List[Any]							=							uncond_embeddings.repeat(1			,					lowerCamelCase_			,					1						)
						_lowercase :    Union[str, Any]							=							uncond_embeddings.view(batch_size * num_images_per_prompt			,					lowerCamelCase_			,					-1						)

						# For classifier free guidance, we need to do two forward passes.
						# Here we concatenate the unconditional and text embeddings into a single batch
						# to avoid doing two forward passes
						_lowercase :    str							=							torch.cat([uncond_embeddings, text_embeddings]						)

					# get the initial random noise unless the user supplied it

					# Unlike in other pipelines, latents need to be generated in the target device
					# for 1-to-1 results reproducibility with the CompVis implementation.
					# However this currently doesn't work in `mps`.
					_lowercase :    Optional[int]							=							(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
					_lowercase :    List[str]							=							text_embeddings.dtype
					if latents is None:
						if self.device.type == "mps":
							# randn does not exist on mps
							_lowercase :    Any							=							torch.randn(lowerCamelCase_			,					generator=lowerCamelCase_			,					device='cpu'			,					dtype=lowerCamelCase_						).to(
							    self.device						)
						else:
							_lowercase :    Any							=							torch.randn(lowerCamelCase_			,					generator=lowerCamelCase_			,					device=self.device			,					dtype=lowerCamelCase_						)
					else:
						if latents.shape != latents_shape:
							raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}'''						)
						_lowercase :    int							=							latents.to(self.device						)

					# set timesteps
					self.scheduler.set_timesteps(lowerCamelCase_						)

					# Some schedulers like PNDM have timesteps as arrays
					# It's more optimized to move all timesteps to correct device beforehand
					_lowercase :    Union[str, Any]							=							self.scheduler.timesteps.to(self.device						)

					# scale the initial noise by the standard deviation required by the scheduler
					_lowercase :    Union[str, Any]							=							latents * self.scheduler.init_noise_sigma

					# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
					# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
					# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
					# and should be between [0, 1]
					_lowercase :    Tuple							=							'eta' in set(inspect.signature(self.scheduler.step						).parameters.keys()						)
					_lowercase :    Union[str, Any]							=							{}
					if accepts_eta:
						_lowercase :    Optional[int]							=							eta

					for i, t in enumerate(self.progress_bar(lowerCamelCase_						)						):
						# expand the latents if we are doing classifier free guidance
						_lowercase :    Optional[Any]							=							torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
						_lowercase :    Tuple							=							self.scheduler.scale_model_input(lowerCamelCase_			,					lowerCamelCase_						)

						# predict the noise residual
						_lowercase :    List[Any]							=							self.unet(lowerCamelCase_			,					lowerCamelCase_			,					encoder_hidden_states=lowerCamelCase_						).sample

						# perform guidance
						if do_classifier_free_guidance:
							_lowercase :    Optional[int]							=							noise_pred.chunk(2						)
							_lowercase :    int							=							noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

						# compute the previous noisy sample x_t -> x_t-1
						_lowercase :    Union[str, Any]							=							self.scheduler.step(lowerCamelCase_			,					lowerCamelCase_			,					lowerCamelCase_			,					**lowerCamelCase_						).prev_sample

						# call the callback, if provided
						if callback is not None and i % callback_steps == 0:
							callback(lowerCamelCase_			,					lowerCamelCase_			,					lowerCamelCase_						)

					_lowercase :    Dict							=							1 / 0.1_8215 * latents
					_lowercase :    Optional[Any]							=							self.vae.decode(lowerCamelCase_						).sample

					_lowercase :    Dict							=							(image / 2 + 0.5).clamp(0			,					1						)

					# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
					_lowercase :    Any							=							image.cpu().permute(0			,					2			,					3			,					1						).float().numpy()

					if output_type == "pil":
						_lowercase :    int							=							self.numpy_to_pil(lowerCamelCase_						)

					if not return_dict:
						return image

					return StableDiffusionPipelineOutput(images=lowerCamelCase_			,					nsfw_content_detected=lowerCamelCase_						)




"""simple docstring"""







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, logging


SCREAMING_SNAKE_CASE									=						logging.get_logger(__name__)



class  _lowerCamelCase			(__lowerCamelCase     ):
				_snake_case     =  ["pixel_values"]







				def __init__( self    :       Optional[int]			,					lowerCamelCase_    :       bool = True			,					lowerCamelCase_    :       Optional[Dict[str, int]] = None			,					lowerCamelCase_    :       PILImageResampling = PILImageResampling.BILINEAR			,					lowerCamelCase_    :       bool = True			,					lowerCamelCase_    :       Dict[str, int] = None			,					lowerCamelCase_    :       bool = True			,					lowerCamelCase_    :       Union[int, float] = 1 / 2_5_5			,					lowerCamelCase_    :       bool = True			,					lowerCamelCase_    :       Optional[Union[float, List[float]]] = None			,					lowerCamelCase_    :       Optional[Union[float, List[float]]] = None			,					**lowerCamelCase_    :       int			,					):

					"""simple docstring"""






					super().__init__(**lowerCamelCase_						)
					_lowercase :    Optional[Any]							=							size if size is not None else {'shortest_edge': 2_5_6}
					_lowercase :    Optional[int]							=							get_size_dict(lowerCamelCase_			,					default_to_square=lowerCamelCase_						)
					_lowercase :    List[str]							=							crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
					_lowercase :    Any							=							get_size_dict(lowerCamelCase_						)
					_lowercase :    Optional[int]							=							do_resize
					_lowercase :    Optional[int]							=							size
					_lowercase :    Union[str, Any]							=							resample
					_lowercase :    Optional[Any]							=							do_center_crop
					_lowercase :    Union[str, Any]							=							crop_size
					_lowercase :    Any							=							do_rescale
					_lowercase :    Tuple							=							rescale_factor
					_lowercase :    Optional[int]							=							do_normalize
					_lowercase :    int							=							image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
					_lowercase :    Any							=							image_std if image_std is not None else IMAGENET_STANDARD_STD







				def 							__UpperCAmelCase					( self    :       List[Any]			,					lowerCamelCase_    :       np.ndarray			,					lowerCamelCase_    :       Dict[str, int]			,					lowerCamelCase_    :       PILImageResampling = PILImageResampling.BICUBIC			,					lowerCamelCase_    :       Optional[Union[str, ChannelDimension]] = None			,					**lowerCamelCase_    :       Tuple			,					):

					"""simple docstring"""






					_lowercase :    Optional[Any]							=							get_size_dict(lowerCamelCase_			,					default_to_square=lowerCamelCase_						)
					if "shortest_edge" not in size:
						raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''						)
					_lowercase :    Dict							=							get_resize_output_image_size(lowerCamelCase_			,					size=size['shortest_edge']			,					default_to_square=lowerCamelCase_						)
					return resize(lowerCamelCase_			,					size=lowerCamelCase_			,					resample=lowerCamelCase_			,					data_format=lowerCamelCase_			,					**lowerCamelCase_						)







				def 							__UpperCAmelCase					( self    :       Dict			,					lowerCamelCase_    :       np.ndarray			,					lowerCamelCase_    :       Dict[str, int]			,					lowerCamelCase_    :       Optional[Union[str, ChannelDimension]] = None			,					**lowerCamelCase_    :       str			,					):

					"""simple docstring"""






					_lowercase :    Tuple							=							get_size_dict(lowerCamelCase_						)
					return center_crop(lowerCamelCase_			,					size=(size['height'], size['width'])			,					data_format=lowerCamelCase_			,					**lowerCamelCase_						)







				def 							__UpperCAmelCase					( self    :       Any			,					lowerCamelCase_    :       np.ndarray			,					lowerCamelCase_    :       float			,					lowerCamelCase_    :       Optional[Union[str, ChannelDimension]] = None			,					**lowerCamelCase_    :       Optional[Any]						):

					"""simple docstring"""






					return rescale(lowerCamelCase_			,					scale=lowerCamelCase_			,					data_format=lowerCamelCase_			,					**lowerCamelCase_						)







				def 							__UpperCAmelCase					( self    :       List[Any]			,					lowerCamelCase_    :       np.ndarray			,					lowerCamelCase_    :       Union[float, List[float]]			,					lowerCamelCase_    :       Union[float, List[float]]			,					lowerCamelCase_    :       Optional[Union[str, ChannelDimension]] = None			,					**lowerCamelCase_    :       List[Any]			,					):

					"""simple docstring"""






					return normalize(lowerCamelCase_			,					mean=lowerCamelCase_			,					std=lowerCamelCase_			,					data_format=lowerCamelCase_			,					**lowerCamelCase_						)







				def 							__UpperCAmelCase					( self    :       List[Any]			,					lowerCamelCase_    :       ImageInput			,					lowerCamelCase_    :       Optional[bool] = None			,					lowerCamelCase_    :       Dict[str, int] = None			,					lowerCamelCase_    :       PILImageResampling = None			,					lowerCamelCase_    :       bool = None			,					lowerCamelCase_    :       Dict[str, int] = None			,					lowerCamelCase_    :       Optional[bool] = None			,					lowerCamelCase_    :       Optional[float] = None			,					lowerCamelCase_    :       Optional[bool] = None			,					lowerCamelCase_    :       Optional[Union[float, List[float]]] = None			,					lowerCamelCase_    :       Optional[Union[float, List[float]]] = None			,					lowerCamelCase_    :       Optional[Union[str, TensorType]] = None			,					lowerCamelCase_    :       Union[str, ChannelDimension] = ChannelDimension.FIRST			,					**lowerCamelCase_    :       int			,					):

					"""simple docstring"""






					_lowercase :    Optional[Any]							=							do_resize if do_resize is not None else self.do_resize
					_lowercase :    List[Any]							=							size if size is not None else self.size
					_lowercase :    Union[str, Any]							=							get_size_dict(lowerCamelCase_			,					default_to_square=lowerCamelCase_						)
					_lowercase :    Any							=							resample if resample is not None else self.resample
					_lowercase :    Tuple							=							do_center_crop if do_center_crop is not None else self.do_center_crop
					_lowercase :    List[Any]							=							crop_size if crop_size is not None else self.crop_size
					_lowercase :    Tuple							=							get_size_dict(lowerCamelCase_						)
					_lowercase :    List[Any]							=							do_rescale if do_rescale is not None else self.do_rescale
					_lowercase :    int							=							rescale_factor if rescale_factor is not None else self.rescale_factor
					_lowercase :    int							=							do_normalize if do_normalize is not None else self.do_normalize
					_lowercase :    str							=							image_mean if image_mean is not None else self.image_mean
					_lowercase :    List[Any]							=							image_std if image_std is not None else self.image_std

					_lowercase :    Union[str, Any]							=							make_list_of_images(lowerCamelCase_						)

					if not valid_images(lowerCamelCase_						):
						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:
						raise ValueError('Size 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.
					_lowercase :    Optional[Any]							=							[to_numpy_array(lowerCamelCase_						) for image in images]

					if do_resize:
						_lowercase :    Optional[Any]							=							[self.resize(image=lowerCamelCase_			,					size=lowerCamelCase_			,					resample=lowerCamelCase_						) for image in images]

					if do_center_crop:
						_lowercase :    List[Any]							=							[self.center_crop(image=lowerCamelCase_			,					size=lowerCamelCase_						) for image in images]

					if do_rescale:
						_lowercase :    str							=							[self.rescale(image=lowerCamelCase_			,					scale=lowerCamelCase_						) for image in images]

					if do_normalize:
						_lowercase :    Any							=							[self.normalize(image=lowerCamelCase_			,					mean=lowerCamelCase_			,					std=lowerCamelCase_						) for image in images]

					_lowercase :    int							=							[to_channel_dimension_format(lowerCamelCase_			,					lowerCamelCase_						) for image in images]

					_lowercase :    Tuple							=							{'pixel_values': images}
					return BatchFeature(data=lowerCamelCase_			,					tensor_type=lowerCamelCase_						)



