


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


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




class 		a__    (							lowerCamelCase__  ):





							'''simple docstring'''






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







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ = "auto"       )	->							List[str]:
														if slice_size == "auto":
																					lowerCAmelCase__	       =     self.unet.config.attention_head_dim // 2
														self.unet.set_attention_slice(lowercase__       )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Optional[Any]:
														self.enable_attention_slicing(lowercase__       )







							@torch.no_grad()
							def __call__(		self ,   lowerCamelCase_ ,   lowerCamelCase_=1_60_00 ,   lowerCamelCase_ = 5_12 ,   lowerCamelCase_ = 5_12 ,   lowerCamelCase_ = 50 ,   lowerCamelCase_ = 7.5 ,   lowerCamelCase_ = None ,   lowerCamelCase_ = 1 ,   lowerCamelCase_ = 0.0 ,   lowerCamelCase_ = None ,   lowerCamelCase_ = None ,   lowerCamelCase_ = "pil" ,   lowerCamelCase_ = True ,   lowerCamelCase_ = None ,   lowerCamelCase_ = 1 ,   **lowerCamelCase_ ,   )	->							str:
														lowerCAmelCase__	       =     self.speech_processor.feature_extractor(
														    lowercase__ ,   return_tensors='''pt''' ,   sampling_rate=lowercase__       ).input_features.to(self.device       )
														lowerCAmelCase__	       =     self.speech_model.generate(lowercase__ ,   max_length=48_00_00       )

														lowerCAmelCase__	       =     self.speech_processor.tokenizer.batch_decode(lowercase__ ,   skip_special_tokens=lowercase__ ,   normalize=lowercase__       )[
														    0
														]

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

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

														# get prompt text embeddings
														lowerCAmelCase__	       =     self.tokenizer(
														    lowercase__ ,   padding='''max_length''' ,   max_length=self.tokenizer.model_max_length ,   return_tensors='''pt''' ,   )
														lowerCAmelCase__	       =     text_inputs.input_ids

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

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

																					lowerCAmelCase__	       =     text_input_ids.shape[-1]
																					lowerCAmelCase__	       =     self.tokenizer(
																					    lowercase__ ,   padding='''max_length''' ,   max_length=lowercase__ ,   truncation=lowercase__ ,   return_tensors='''pt''' ,   )
																					lowerCAmelCase__	       =     self.text_encoder(uncond_input.input_ids.to(self.device       )       )[0]

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

														# set timesteps
														self.scheduler.set_timesteps(lowercase__       )

														# Some schedulers like PNDM have timesteps as arrays
														# It's more optimized to move all timesteps to correct device beforehand
														lowerCAmelCase__	       =     self.scheduler.timesteps.to(self.device       )

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

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

																					# predict the noise residual
																					lowerCAmelCase__	       =     self.unet(lowercase__ ,   lowercase__ ,   encoder_hidden_states=lowercase__       ).sample

																					# perform guidance
																					if do_classifier_free_guidance:
																												lowerCAmelCase__       , lowerCAmelCase__	       =     noise_pred.chunk(2       )
																												lowerCAmelCase__	       =     noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

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

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

														lowerCAmelCase__	       =     1 / 0.18_215 * latents
														lowerCAmelCase__	       =     self.vae.decode(lowercase__       ).sample

														lowerCAmelCase__	       =     (image / 2 + 0.5).clamp(0 ,   1       )

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

														if output_type == "pil":
																					lowerCAmelCase__	       =     self.numpy_to_pil(lowercase__       )

														if not return_dict:
																					return image

														return StableDiffusionPipelineOutput(images=lowercase__ ,   nsfw_content_detected=lowercase__       )



'''simple docstring'''






import numpy as np

import datasets


__UpperCAmelCase       =							'''
Compute the Mahalanobis Distance

Mahalonobis distance is the distance between a point and a distribution.
And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.
It was introduced by Prof. P. C. Mahalanobis in 1936
and has been used in various statistical applications ever since
[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]
'''

__UpperCAmelCase       =							'''\
@article{de2000mahalanobis,
  title={The mahalanobis distance},
  author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},
  journal={Chemometrics and intelligent laboratory systems},
  volume={50},
  number={1},
  pages={1--18},
  year={2000},
  publisher={Elsevier}
}
'''

__UpperCAmelCase       =							'''
Args:
    X: List of datapoints to be compared with the `reference_distribution`.
    reference_distribution: List of datapoints from the reference distribution we want to compare to.
Returns:
    mahalanobis: The Mahalonobis distance for each datapoint in `X`.
Examples:

    >>> mahalanobis_metric = datasets.load_metric("mahalanobis")
    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])
    >>> print(results)
    {\'mahalanobis\': array([0.5])}
'''




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,    _KWARGS_DESCRIPTION  )
class 		a__    (							datasets.Metric  ):





							'''simple docstring'''






							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Any:
														return datasets.MetricInfo(
														    description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
														        {
														            '''X''': datasets.Sequence(datasets.Value('''float''' ,   id='''sequence'''       ) ,   id='''X'''       ),
														        }       ) ,   )







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							str:
														# convert to numpy arrays
														lowerCAmelCase__	       =     np.array(lowerCamelCase_       )
														lowerCAmelCase__	       =     np.array(lowerCamelCase_       )

														# Assert that arrays are 2D
														if len(X.shape       ) != 2:
																					raise ValueError('''Expected `X` to be a 2D vector'''       )
														if len(reference_distribution.shape       ) != 2:
																					raise ValueError('''Expected `reference_distribution` to be a 2D vector'''       )
														if reference_distribution.shape[0] < 2:
																					raise ValueError(
																					    '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension'''       )

														# Get mahalanobis distance for each prediction
														lowerCAmelCase__	       =     X - np.mean(lowerCamelCase_       )
														lowerCAmelCase__	       =     np.cov(reference_distribution.T       )
														try:
																					lowerCAmelCase__	       =     np.linalg.inv(lowerCamelCase_       )
														except np.linalg.LinAlgError:
																					lowerCAmelCase__	       =     np.linalg.pinv(lowerCamelCase_       )
														lowerCAmelCase__	       =     np.dot(lowerCamelCase_ ,   lowerCamelCase_       )
														lowerCAmelCase__	       =     np.dot(lowerCamelCase_ ,   X_minus_mu.T       ).diagonal()

														return {"mahalanobis": mahal_dist}