"""simple docstring"""





from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


__A  =				logging.get_logger(__name__)
class  _snake_case     (					a__		):
						snake_case__			  =			["input_values", "padding_mask"]






						def __init__(       self      :			Tuple							,					UpperCAmelCase      :			int = 1							,					UpperCAmelCase      :			int = 24000							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			float = None							,					UpperCAmelCase      :			float = None							,					**UpperCAmelCase      :			int							,					):
													super().__init__(feature_size=UpperCAmelCase							,					sampling_rate=UpperCAmelCase							,					padding_value=UpperCAmelCase							,					**UpperCAmelCase    )
													__lowerCamelCase					:		List[Any]		   =     chunk_length_s
													__lowerCamelCase					:		str		   =     overlap






						@property
						def       lowerCamelCase__     (       self      :			Dict    ):
													if self.chunk_length_s is None:
																				return None
													else:
																				return int(self.chunk_length_s * self.sampling_rate    )






						@property
						def       lowerCamelCase__     (       self      :			Optional[int]    ):
													if self.chunk_length_s is None or self.overlap is None:
																				return None
													else:
																				return max(1							,					int((1.0 - self.overlap) * self.chunk_length    )    )







						def __call__(       self      :			Dict							,					UpperCAmelCase      :			Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,					UpperCAmelCase      :			Optional[Union[bool, str, PaddingStrategy]] = None							,					UpperCAmelCase      :			Optional[bool] = False							,					UpperCAmelCase      :			Optional[int] = None							,					UpperCAmelCase      :			Optional[Union[str, TensorType]] = None							,					UpperCAmelCase      :			Optional[int] = None							,					):
													if sampling_rate is not None:
																				if sampling_rate != self.sampling_rate:
																											raise ValueError(
																											    F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
																											    F""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"""
																											    F""" {self.sampling_rate} and not {sampling_rate}."""    )
													else:
																				logger.warning(
																				    "It is strongly recommended to pass the `sampling_rate` argument to this function. "
																				    "Failing to do so can result in silent errors that might be hard to debug."    )

													if padding and truncation:
																				raise ValueError("Both padding and truncation were set. Make sure you only set one."    )
													elif padding is None:
																				# by default let's pad the inputs
																				__lowerCamelCase					:		List[Any]		   =     True

													__lowerCamelCase					:		Any		   =     bool(
													    isinstance(UpperCAmelCase							,					(list, tuple)    ) and (isinstance(raw_audio[0]							,					(np.ndarray, tuple, list)    ))    )

													if is_batched:
																				__lowerCamelCase					:		Any		   =     [np.asarray(UpperCAmelCase							,					dtype=np.floataa    ).T for audio in raw_audio]
													elif not is_batched and not isinstance(UpperCAmelCase							,					np.ndarray    ):
																				__lowerCamelCase					:		int		   =     np.asarray(UpperCAmelCase							,					dtype=np.floataa    )
													elif isinstance(UpperCAmelCase							,					np.ndarray    ) and raw_audio.dtype is np.dtype(np.floataa    ):
																				__lowerCamelCase					:		List[str]		   =     raw_audio.astype(np.floataa    )

													# always return batch
													if not is_batched:
																				__lowerCamelCase					:		int		   =     [np.asarray(UpperCAmelCase    ).T]

													# verify inputs are valid
													for idx, example in enumerate(UpperCAmelCase    ):
																				if example.ndim > 2:
																											raise ValueError(F"""Expected input shape (channels, length) but got shape {example.shape}"""    )
																				if self.feature_size == 1 and example.ndim != 1:
																											raise ValueError(F"""Expected mono audio but example has {example.shape[-1]} channels"""    )
																				if self.feature_size == 2 and example.shape[-1] != 2:
																											raise ValueError(F"""Expected stereo audio but example has {example.shape[-1]} channels"""    )

													__lowerCamelCase					:		List[str]		   =     None
													__lowerCamelCase					:		str		   =     BatchFeature({"input_values": raw_audio}    )
													if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
																				if truncation:
																											__lowerCamelCase					:		Dict		   =     min(array.shape[0] for array in raw_audio    )
																											__lowerCamelCase					:		Optional[int]		   =     int(np.floor(max_length / self.chunk_stride    )    )
																											__lowerCamelCase					:		Any		   =     (nb_step - 1) * self.chunk_stride + self.chunk_length
																				elif padding:
																											__lowerCamelCase					:		List[str]		   =     max(array.shape[0] for array in raw_audio    )
																											__lowerCamelCase					:		Dict		   =     int(np.ceil(max_length / self.chunk_stride    )    )
																											__lowerCamelCase					:		str		   =     (nb_step - 1) * self.chunk_stride + self.chunk_length
																											__lowerCamelCase					:		Tuple		   =     "max_length"
																				else:
																											__lowerCamelCase					:		int		   =     input_values

        # normal padding on batch
													if padded_inputs is None:
																				__lowerCamelCase					:		str		   =     self.pad(
																				    UpperCAmelCase							,					max_length=UpperCAmelCase							,					truncation=UpperCAmelCase							,					padding=UpperCAmelCase							,					return_attention_mask=UpperCAmelCase							,					)
																				if padding:
																											__lowerCamelCase					:		List[str]		   =     padded_inputs.pop("attention_mask"    )

													__lowerCamelCase					:		Optional[int]		   =     []
													for example in padded_inputs.pop("input_values"    ):
																				if self.feature_size == 1:
																											__lowerCamelCase					:		Dict		   =     example[..., None]
																				input_values.append(example.T    )

													__lowerCamelCase					:		Any		   =     input_values
													if return_tensors is not None:
																				__lowerCamelCase					:		int		   =     padded_inputs.convert_to_tensors(UpperCAmelCase    )

													return padded_inputs
"""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  =				'''CompVis/stable-diffusion-v1-1'''
__A  =				'''CompVis/stable-diffusion-v1-2'''
__A  =				'''CompVis/stable-diffusion-v1-3'''
__A  =				'''CompVis/stable-diffusion-v1-4'''
class  _snake_case     (					a__		):






						def __init__(       self      :			int							,					UpperCAmelCase      :			AutoencoderKL							,					UpperCAmelCase      :			CLIPTextModel							,					UpperCAmelCase      :			CLIPTokenizer							,					UpperCAmelCase      :			UNetaDConditionModel							,					UpperCAmelCase      :			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]							,					UpperCAmelCase      :			StableDiffusionSafetyChecker							,					UpperCAmelCase      :			CLIPImageProcessor							,					UpperCAmelCase      :			bool = True							,					):
													super()._init_()

													__lowerCamelCase					:		Optional[int]		   =     StableDiffusionPipeline.from_pretrained(UpperCAmelCase    )
													__lowerCamelCase					:		Optional[int]		   =     StableDiffusionPipeline.from_pretrained(UpperCAmelCase    )
													__lowerCamelCase					:		Tuple		   =     StableDiffusionPipeline.from_pretrained(UpperCAmelCase    )
													__lowerCamelCase					:		List[str]		   =     StableDiffusionPipeline(
													    vae=UpperCAmelCase							,					text_encoder=UpperCAmelCase							,					tokenizer=UpperCAmelCase							,					unet=UpperCAmelCase							,					scheduler=UpperCAmelCase							,					safety_checker=UpperCAmelCase							,					feature_extractor=UpperCAmelCase							,					requires_safety_checker=UpperCAmelCase							,					)

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






						@property
						def       lowerCamelCase__     (       self      :			Dict    ):
													return {k: getattr(self							,					UpperCAmelCase    ) for k in self.config.keys() if not k.startswith("_"    )}






						def       lowerCamelCase__     (       self      :			str							,					UpperCAmelCase      :			Optional[Union[str, int]] = "auto"    ):
													if slice_size == "auto":
																				# half the attention head size is usually a good trade-off between
																				# speed and memory
																				__lowerCamelCase					:		Optional[int]		   =     self.unet.config.attention_head_dim // 2
													self.unet.set_attention_slice(UpperCAmelCase    )






						def       lowerCamelCase__     (       self      :			Tuple    ):
													self.enable_attention_slicing(UpperCAmelCase    )






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Dict							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Optional[Any]							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Dict							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Union[str, Any]							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Tuple							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Dict							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Optional[Any]							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			List[str]							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)







						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			str							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Tuple							,					):
													__lowerCamelCase					:		Optional[int]		   =     "cuda" if torch.cuda.is_available() else "cpu"
													self.to(UpperCAmelCase    )

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

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

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

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

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