





from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict						   =       ['vqvae']





      def __init__(			self	,							A_	,							A_	,							A_	,							A_	,							):
       '''simple docstring'''




       super().__init__()
       self.register_modules(unet=A_	,							scheduler=A_	,							mel=A_	,							vqvae=A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return 50 if isinstance(self.scheduler	,							A_       ) else 1000





      @torch.no_grad()
      def __call__(			self	,							A_ = 1	,							A_ = None	,							A_ = None	,							A_ = 0	,							A_ = 0	,							A_ = None	,							A_ = None	,							A_ = 0	,							A_ = 0	,							A_ = None	,							A_ = 0	,							A_ = None	,							A_ = None	,							A_=True	,							):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       steps or self.get_default_steps()
       self.scheduler.set_timesteps(A_       )
       UpperCamelCase     : Optional[int]	     =       step_generator or generator
       # For backwards compatibility
       if type(self.unet.config.sample_size       ) == int:
        UpperCamelCase     : Union[str, Any]	     =       (self.unet.config.sample_size, self.unet.config.sample_size)
       if noise is None:
        UpperCamelCase     : List[str]	     =       randn_tensor(
            (
                batch_size,
                self.unet.config.in_channels,
                self.unet.config.sample_size[0],
                self.unet.config.sample_size[1],
            )	,							generator=A_	,							device=self.device	,							)
       UpperCamelCase     : int	     =       noise
       UpperCamelCase     : Tuple	     =       None

       if audio_file is not None or raw_audio is not None:
        self.mel.load_audio(A_	,							A_       )
        UpperCamelCase     : Optional[Any]	     =       self.mel.audio_slice_to_image(A_       )
        UpperCamelCase     : Optional[int]	     =       np.frombuffer(input_image.tobytes()	,							dtype="uint8"       ).reshape(
            (input_image.height, input_image.width)       )
        UpperCamelCase     : int	     =       (input_image / 255) * 2 - 1
        UpperCamelCase     : Union[str, Any]	     =       torch.tensor(input_image[np.newaxis, :, :]	,							dtype=torch.float       ).to(self.device       )

        if self.vqvae is not None:
         UpperCamelCase     : Optional[int]	     =       self.vqvae.encode(torch.unsqueeze(A_	,							0       )       ).latent_dist.sample(
             generator=A_       )[0]
         UpperCamelCase     : List[str]	     =       self.vqvae.config.scaling_factor * input_images

        if start_step > 0:
         UpperCamelCase     : Optional[int]	     =       self.scheduler.add_noise(A_	,							A_	,							self.scheduler.timesteps[start_step - 1]       )

        UpperCamelCase     : Any	     =       (
            self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
        )
        UpperCamelCase     : Any	     =       int(mask_start_secs * pixels_per_second       )
        UpperCamelCase     : Dict	     =       int(mask_end_secs * pixels_per_second       )
        UpperCamelCase     : str	     =       self.scheduler.add_noise(A_	,							A_	,							torch.tensor(self.scheduler.timesteps[start_step:]       )       )

       for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]       )       ):
        if isinstance(self.unet	,							A_       ):
         UpperCamelCase     : Optional[int]	     =       self.unet(A_	,							A_	,							A_       )["sample"]
        else:
         UpperCamelCase     : List[Any]	     =       self.unet(A_	,							A_       )["sample"]

        if isinstance(self.scheduler	,							A_       ):
         UpperCamelCase     : List[Any]	     =       self.scheduler.step(
             model_output=A_	,							timestep=A_	,							sample=A_	,							eta=A_	,							generator=A_	,							)["prev_sample"]
        else:
         UpperCamelCase     : Tuple	     =       self.scheduler.step(
             model_output=A_	,							timestep=A_	,							sample=A_	,							generator=A_	,							)["prev_sample"]

        if mask is not None:
         if mask_start > 0:
          UpperCamelCase     : str	     =       mask[:, step, :, :mask_start]
         if mask_end > 0:
          UpperCamelCase     : str	     =       mask[:, step, :, -mask_end:]

       if self.vqvae is not None:
        # 0.18215 was scaling factor used in training to ensure unit variance
        UpperCamelCase     : Optional[int]	     =       1 / self.vqvae.config.scaling_factor * images
        UpperCamelCase     : Union[str, Any]	     =       self.vqvae.decode(A_       )["sample"]

       UpperCamelCase     : Tuple	     =       (images / 2 + 0.5).clamp(0	,							1       )
       UpperCamelCase     : List[Any]	     =       images.cpu().permute(0	,							2	,							3	,							1       ).numpy()
       UpperCamelCase     : Dict	     =       (images * 255).round().astype("uint8"       )
       UpperCamelCase     : List[str]	     =       list(
           (Image.fromarray(_[:, :, 0]       ) for _ in images)
           if images.shape[3] == 1
           else (Image.fromarray(A_	,							mode="RGB"       ).convert("L"       ) for _ in images)       )

       UpperCamelCase     : Any	     =       [self.mel.image_to_audio(A_       ) for _ in images]
       if not return_dict:
        return images, (self.mel.get_sample_rate(), audios)

       return BaseOutput(**AudioPipelineOutput(np.array(A_       )[:, np.newaxis, :]       )	,							**ImagePipelineOutput(A_       )       )





      @torch.no_grad()
      def 	__UpperCamelCase(			self	,							A_	,							A_ = 50       ):
       '''simple docstring'''




       assert isinstance(self.scheduler	,							A_       )
       self.scheduler.set_timesteps(A_       )
       UpperCamelCase     : Dict	     =       np.array(
           [np.frombuffer(image.tobytes()	,							dtype="uint8"       ).reshape((1, image.height, image.width)       ) for image in images]       )
       UpperCamelCase     : Dict	     =       (sample / 255) * 2 - 1
       UpperCamelCase     : List[Any]	     =       torch.Tensor(A_       ).to(self.device       )

       for t in self.progress_bar(torch.flip(self.scheduler.timesteps	,							(0,)       )       ):
        UpperCamelCase     : Optional[int]	     =       t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
        UpperCamelCase     : str	     =       self.scheduler.alphas_cumprod[t]
        UpperCamelCase     : Tuple	     =       (
            self.scheduler.alphas_cumprod[prev_timestep]
            if prev_timestep >= 0
            else self.scheduler.final_alpha_cumprod
        )
        UpperCamelCase     : Optional[Any]	     =       1 - alpha_prod_t
        UpperCamelCase     : Union[str, Any]	     =       self.unet(A_	,							A_       )["sample"]
        UpperCamelCase     : Optional[int]	     =       (1 - alpha_prod_t_prev) ** 0.5 * model_output
        UpperCamelCase     : List[Any]	     =       (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
        UpperCamelCase     : Tuple	     =       sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

       return sample





      @staticmethod
      def 	__UpperCamelCase(			A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       acos(torch.dot(torch.flatten(A_       )	,							torch.flatten(A_       )       ) / torch.norm(A_       ) / torch.norm(A_       )       )
       return sin((1 - alpha) * theta       ) * xa / sin(A_       ) + sin(alpha * theta       ) * xa / sin(A_       )







from scipy.stats import spearmanr

import datasets


__lowerCamelCase	:					List[str]			  =					"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

__lowerCamelCase	:					List[Any]			  =					"""
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

__lowerCamelCase	:					Optional[int]			  =					r"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
"""



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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return datasets.MetricInfo(
           description=_DESCRIPTION	,							citation=_CITATION	,							inputs_description=_KWARGS_DESCRIPTION	,							features=datasets.Features(
               {
                   "predictions": datasets.Value("float"       ),
                   "references": datasets.Value("float"       ),
               }       )	,							reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"]	,							)





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       spearmanr(A_	,							A_       )
       if return_pvalue:
        return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
       else:
        return {"spearmanr": results[0]}
