

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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A_	:			str  	=      logging.get_logger(__name__)



class    _a						(__magic_name__    ):


					'''simple docstring'''






					UpperCAmelCase__:       Optional[Any]  							=	['''pixel_values''']






					def __init__(			self   ,	A__ = True   ,	A__ = None   ,	A__ = PILImageResampling.BICUBIC   ,	A__ = True   ,	A__ = True   ,	A__ = 1 / 255   ,	A__ = None   ,	A__ = True   ,	A__ = None   ,	A__ = None   ,	**A__   ,	):
						super().__init__(**A__      )
						A__							:   Optional[int]					       =		size if size is not None else {"""height""": 224, """width""": 224}
						A__							:   Optional[int]					       =		get_size_dict(A__      )
						A__							:   Tuple					       =		crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
						A__							:   Dict					       =		get_size_dict(A__   ,	default_to_square=A__   ,	param_name="""crop_size"""      )

						A__							:   Optional[int]					       =		do_resize
						A__							:   Tuple					       =		do_rescale
						A__							:   Any					       =		do_normalize
						A__							:   List[str]					       =		do_center_crop
						A__							:   Optional[Any]					       =		crop_size
						A__							:   List[Any]					       =		size
						A__							:   Tuple					       =		resample
						A__							:   Dict					       =		rescale_factor
						A__							:   int					       =		image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
						A__							:   int					       =		image_std if image_std is not None else IMAGENET_DEFAULT_STD






					def   __A      (			self   ,	A__   ,	A__   ,	A__ = PILImageResampling.BILINEAR   ,	A__ = None   ,	**A__   ,	):
						A__							:   str					       =		get_size_dict(A__      )

						if "shortest_edge" in size:
							A__							:   str					       =		get_resize_output_image_size(A__   ,	size=size["""shortest_edge"""]   ,	default_to_square=A__      )
							# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
						elif "height" in size and "width" in size:
							A__							:   List[str]					       =		(size["""height"""], size["""width"""])
						else:
							raise ValueError(F"""Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}"""      )
						return resize(A__   ,	size=A__   ,	resample=A__   ,	data_format=A__   ,	**A__      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__ = None   ,	**A__   ,	):
						A__							:   str					       =		get_size_dict(A__      )
						if "height" not in size or "width" not in size:
							raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""      )
						return center_crop(A__   ,	size=(size["""height"""], size["""width"""])   ,	data_format=A__   ,	**A__      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__ = None   ,	**A__      ):
						return rescale(A__   ,	scale=A__   ,	data_format=A__   ,	**A__      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__   ,	A__ = None   ,	**A__   ,	):
						return normalize(A__   ,	mean=A__   ,	std=A__   ,	data_format=A__   ,	**A__      )






					def   __A      (			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__   ,	):
						A__							:   List[str]					       =		do_resize if do_resize is not None else self.do_resize
						A__							:   int					       =		do_rescale if do_rescale is not None else self.do_rescale
						A__							:   List[Any]					       =		do_normalize if do_normalize is not None else self.do_normalize
						A__							:   Union[str, Any]					       =		do_center_crop if do_center_crop is not None else self.do_center_crop
						A__							:   List[Any]					       =		crop_size if crop_size is not None else self.crop_size
						A__							:   Dict					       =		get_size_dict(A__   ,	param_name="""crop_size"""   ,	default_to_square=A__      )
						A__							:   Dict					       =		resample if resample is not None else self.resample
						A__							:   Dict					       =		rescale_factor if rescale_factor is not None else self.rescale_factor
						A__							:   Any					       =		image_mean if image_mean is not None else self.image_mean
						A__							:   Dict					       =		image_std if image_std is not None else self.image_std

						A__							:   int					       =		size if size is not None else self.size
						A__							:   Dict					       =		get_size_dict(A__      )

						if not is_batched(A__      ):
							A__							:   Tuple					       =		[images]

						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."""      )

						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."""      )

						# All transformations expect numpy arrays.
						A__							:   List[Any]					       =		[to_numpy_array(A__      ) for image in images]

						if do_resize:
							A__							:   int					       =		[self.resize(image=A__   ,	size=A__   ,	resample=A__      ) for image in images]

						if do_center_crop:
							A__							:   Union[str, Any]					       =		[self.center_crop(image=A__   ,	size=A__      ) for image in images]

						if do_rescale:
							A__							:   Optional[int]					       =		[self.rescale(image=A__   ,	scale=A__      ) for image in images]

						if do_normalize:
							A__							:   int					       =		[self.normalize(image=A__   ,	mean=A__   ,	std=A__      ) for image in images]

						A__							:   Union[str, Any]					       =		[to_channel_dimension_format(A__   ,	A__      ) for image in images]

						A__							:   Optional[int]					       =		{"""pixel_values""": images}
						return BatchFeature(data=A__   ,	tensor_type=A__      )






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


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



class    _a						(__magic_name__    ):


					'''simple docstring'''






					def __init__(			self   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	):
						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=A__   ,	speech_processor=A__   ,	vae=A__   ,	text_encoder=A__   ,	tokenizer=A__   ,	unet=A__   ,	scheduler=A__   ,	feature_extractor=A__   ,	)






					def   __A      (			self   ,	A__ = "auto"      ):
						if slice_size == "auto":
							A__							:   Optional[Any]					       =		self.unet.config.attention_head_dim // 2
						self.unet.set_attention_slice(A__      )






					def   __A      (			self      ):
						self.enable_attention_slicing(A__      )






					@torch.no_grad()
					def __call__(			self   ,	A__   ,	A__=1_6000   ,	A__ = 512   ,	A__ = 512   ,	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__   ,	):
						A__							:   Any					       =		self.speech_processor.feature_extractor(
						    A__   ,	return_tensors="""pt"""   ,	sampling_rate=A__      ).input_features.to(self.device      )
						A__							:   Optional[Any]					       =		self.speech_model.generate(A__   ,	max_length=48_0000      )

						A__							:   Union[str, Any]					       =		self.speech_processor.tokenizer.batch_decode(A__   ,	skip_special_tokens=A__   ,	normalize=A__      )[
						    0
						]

						if isinstance(A__   ,	A__      ):
							A__							:   Dict					       =		1
						elif isinstance(A__   ,	A__      ):
							A__							:   Optional[int]					       =		len(A__      )
						else:
							raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(A__      )}"""      )

						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(A__   ,	A__      ) or callback_steps <= 0)
						):
							raise ValueError(
							    F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
							    F""" {type(A__      )}."""      )

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

						if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
							A__							:   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}"""      )
							A__							:   Dict					       =		text_input_ids[:, : self.tokenizer.model_max_length]
						A__							:   int					       =		self.text_encoder(text_input_ids.to(self.device      )      )[0]

						# duplicate text embeddings for each generation per prompt, using mps friendly method
						A__       ,       A__       ,       A__							:   List[str]					       =		text_embeddings.shape
						A__							:   Dict					       =		text_embeddings.repeat(1   ,	A__   ,	1      )
						A__							:   Union[str, Any]					       =		text_embeddings.view(bs_embed * num_images_per_prompt   ,	A__   ,	-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.
						A__							:   int					       =		guidance_scale > 1.0
						# get unconditional embeddings for classifier free guidance
						if do_classifier_free_guidance:
							A__							:   List[str]
							if negative_prompt is None:
								A__							:   Union[str, Any]					       =		[""""""] * batch_size
							elif type(A__      ) is not type(A__      ):
								raise TypeError(
								    F"""`negative_prompt` should be the same type to `prompt`, but got {type(A__      )} !="""
								    F""" {type(A__      )}."""      )
							elif isinstance(A__   ,	A__      ):
								A__							:   Union[str, Any]					       =		[negative_prompt]
							elif batch_size != len(A__      ):
								raise ValueError(
								    F"""`negative_prompt`: {negative_prompt} has batch size {len(A__      )}, but `prompt`:"""
								    F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
								    """ the batch size of `prompt`."""      )
							else:
								A__							:   int					       =		negative_prompt

							A__							:   Union[str, Any]					       =		text_input_ids.shape[-1]
							A__							:   int					       =		self.tokenizer(
							    A__   ,	padding="""max_length"""   ,	max_length=A__   ,	truncation=A__   ,	return_tensors="""pt"""   ,	)
							A__							:   Any					       =		self.text_encoder(uncond_input.input_ids.to(self.device      )      )[0]

							# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
							A__							:   List[Any]					       =		uncond_embeddings.shape[1]
							A__							:   Any					       =		uncond_embeddings.repeat(1   ,	A__   ,	1      )
							A__							:   Optional[Any]					       =		uncond_embeddings.view(batch_size * num_images_per_prompt   ,	A__   ,	-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
							A__							:   Any					       =		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`.
						A__							:   List[Any]					       =		(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
						A__							:   Dict					       =		text_embeddings.dtype
						if latents is None:
							if self.device.type == "mps":
								# randn does not exist on mps
								A__							:   Optional[Any]					       =		torch.randn(A__   ,	generator=A__   ,	device="""cpu"""   ,	dtype=A__      ).to(
								    self.device      )
							else:
								A__							:   str					       =		torch.randn(A__   ,	generator=A__   ,	device=self.device   ,	dtype=A__      )
						else:
							if latents.shape != latents_shape:
								raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""      )
							A__							:   Any					       =		latents.to(self.device      )

						# set timesteps
						self.scheduler.set_timesteps(A__      )

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

						# scale the initial noise by the standard deviation required by the scheduler
						A__							:   Tuple					       =		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]
						A__							:   Any					       =		"""eta""" in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
						A__							:   Tuple					       =		{}
						if accepts_eta:
							A__							:   str					       =		eta

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

							# predict the noise residual
							A__							:   Union[str, Any]					       =		self.unet(A__   ,	A__   ,	encoder_hidden_states=A__      ).sample

							# perform guidance
							if do_classifier_free_guidance:
								A__       ,       A__							:   List[Any]					       =		noise_pred.chunk(2      )
								A__							:   Dict					       =		noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

							# compute the previous noisy sample x_t -> x_t-1
							A__							:   Tuple					       =		self.scheduler.step(A__   ,	A__   ,	A__   ,	**A__      ).prev_sample

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

						A__							:   str					       =		1 / 0.1_8_2_1_5 * latents
						A__							:   Optional[Any]					       =		self.vae.decode(A__      ).sample

						A__							:   Tuple					       =		(image / 2 + 0.5).clamp(0   ,	1      )

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

						if output_type == "pil":
							A__							:   Optional[Any]					       =		self.numpy_to_pil(A__      )

						if not return_dict:
							return image

						return StableDiffusionPipelineOutput(images=A__   ,	nsfw_content_detected=A__      )



