
'''simple docstring'''






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        __snake_case	(       _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase       			= ['vqvae']

    def __init__(       self   :  Dict   ,						lowerCamelCase   :  AutoencoderKL   ,						lowerCamelCase   :  UNetaDConditionModel   ,						lowerCamelCase   :  Mel   ,						lowerCamelCase   :  Union[DDIMScheduler, DDPMScheduler]   ,						)       ->  Union[str, Any]:
      super().__init__()
      self.register_modules(unet=lowerCamelCase   ,						scheduler=lowerCamelCase   ,						mel=lowerCamelCase   ,						vqvae=lowerCamelCase		)

    def __lowercase       (       self   :  Any		)       ->  int:
      return 50 if isinstance(self.scheduler   ,						lowerCamelCase		) else 10_00

    @torch.no_grad()
    def __call__(       self   :  int   ,						lowerCamelCase   :  int = 1   ,						lowerCamelCase   :  str = None   ,						lowerCamelCase   :  np.ndarray = None   ,						lowerCamelCase   :  int = 0   ,						lowerCamelCase   :  int = 0   ,						lowerCamelCase   :  int = None   ,						lowerCamelCase   :  torch.Generator = None   ,						lowerCamelCase   :  float = 0   ,						lowerCamelCase   :  float = 0   ,						lowerCamelCase   :  torch.Generator = None   ,						lowerCamelCase   :  float = 0   ,						lowerCamelCase   :  torch.Tensor = None   ,						lowerCamelCase   :  torch.Tensor = None   ,						lowerCamelCase   :  Optional[Any]=True   ,						)       ->  Union[
        Union[AudioPipelineOutput, ImagePipelineOutput],
        Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]],
    ]:
      lowerCAmelCase_      :				List[str]      =       steps or self.get_default_steps()
      self.scheduler.set_timesteps(lowerCamelCase		)
      lowerCAmelCase_      :				str      =       step_generator or generator
      # For backwards compatibility
      if type(self.unet.config.sample_size		) == int:
        lowerCAmelCase_      :				List[Any]      =       (self.unet.config.sample_size, self.unet.config.sample_size)
      if noise is None:
        lowerCAmelCase_      :				List[str]      =       randn_tensor(
            (
                batch_size,
                self.unet.config.in_channels,
                self.unet.config.sample_size[0],
                self.unet.config.sample_size[1],
            )   ,						generator=lowerCamelCase   ,						device=self.device   ,						)
      lowerCAmelCase_      :				Optional[int]      =       noise
      lowerCAmelCase_      :				int      =       None

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

        if self.vqvae is not None:
          lowerCAmelCase_      :				Optional[Any]      =       self.vqvae.encode(torch.unsqueeze(lowerCamelCase   ,						0		)		).latent_dist.sample(
              generator=lowerCamelCase		)[0]
          lowerCAmelCase_      :				Tuple      =       self.vqvae.config.scaling_factor * input_images

        if start_step > 0:
          lowerCAmelCase_      :				str      =       self.scheduler.add_noise(lowerCamelCase   ,						lowerCamelCase   ,						self.scheduler.timesteps[start_step - 1]		)

        lowerCAmelCase_      :				Optional[Any]      =       (
            self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
        )
        lowerCAmelCase_      :				Optional[int]      =       int(mask_start_secs * pixels_per_second		)
        lowerCAmelCase_      :				Optional[Any]      =       int(mask_end_secs * pixels_per_second		)
        lowerCAmelCase_      :				Tuple      =       self.scheduler.add_noise(lowerCamelCase   ,						lowerCamelCase   ,						torch.tensor(self.scheduler.timesteps[start_step:]		)		)

      for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]		)		):
        if isinstance(self.unet   ,						lowerCamelCase		):
          lowerCAmelCase_      :				List[str]      =       self.unet(lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase		)["""sample"""]
        else:
          lowerCAmelCase_      :				Dict      =       self.unet(lowerCamelCase   ,						lowerCamelCase		)["""sample"""]

        if isinstance(self.scheduler   ,						lowerCamelCase		):
          lowerCAmelCase_      :				List[Any]      =       self.scheduler.step(
              model_output=lowerCamelCase   ,						timestep=lowerCamelCase   ,						sample=lowerCamelCase   ,						eta=lowerCamelCase   ,						generator=lowerCamelCase   ,						)["""prev_sample"""]
        else:
          lowerCAmelCase_      :				List[str]      =       self.scheduler.step(
              model_output=lowerCamelCase   ,						timestep=lowerCamelCase   ,						sample=lowerCamelCase   ,						generator=lowerCamelCase   ,						)["""prev_sample"""]

        if mask is not None:
          if mask_start > 0:
            lowerCAmelCase_      :				List[str]      =       mask[:, step, :, :mask_start]
          if mask_end > 0:
            lowerCAmelCase_      :				Optional[int]      =       mask[:, step, :, -mask_end:]

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

      lowerCAmelCase_      :				Optional[int]      =       (images / 2 + 0.5).clamp(0   ,						1		)
      lowerCAmelCase_      :				Any      =       images.cpu().permute(0   ,						2   ,						3   ,						1		).numpy()
      lowerCAmelCase_      :				Optional[Any]      =       (images * 2_55).round().astype("""uint8"""		)
      lowerCAmelCase_      :				Optional[Any]      =       list(
          (Image.fromarray(_[:, :, 0]		) for _ in images)
          if images.shape[3] == 1
          else (Image.fromarray(lowerCamelCase   ,						mode="""RGB"""		).convert("""L"""		) for _ in images)		)

      lowerCAmelCase_      :				List[str]      =       [self.mel.image_to_audio(lowerCamelCase		) for _ in images]
      if not return_dict:
        return images, (self.mel.get_sample_rate(), audios)

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

    @torch.no_grad()
    def __lowercase       (       self   :  List[str]   ,						lowerCamelCase   :  List[Image.Image]   ,						lowerCamelCase   :  int = 50		)       ->  np.ndarray:
      assert isinstance(self.scheduler   ,						lowerCamelCase		)
      self.scheduler.set_timesteps(lowerCamelCase		)
      lowerCAmelCase_      :				str      =       np.array(
          [np.frombuffer(image.tobytes()   ,						dtype="""uint8"""		).reshape((1, image.height, image.width)		) for image in images]		)
      lowerCAmelCase_      :				List[Any]      =       (sample / 2_55) * 2 - 1
      lowerCAmelCase_      :				Any      =       torch.Tensor(lowerCamelCase		).to(self.device		)

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

      return sample





    @staticmethod
    def __lowercase       (       lowerCamelCase   :  torch.Tensor   ,						lowerCamelCase   :  torch.Tensor   ,						lowerCamelCase   :  float		)       ->  torch.Tensor:
      lowerCAmelCase_      :				Union[str, Any]      =       acos(torch.dot(torch.flatten(lowerCamelCase		)   ,						torch.flatten(lowerCamelCase		)		) / torch.norm(lowerCamelCase		) / torch.norm(lowerCamelCase		)		)
      return sin((1 - alpha) * theta		) * xa / sin(lowerCamelCase		) + sin(alpha * theta		) * xa / sin(lowerCamelCase		)







'''simple docstring'''






import unittest

import numpy as np
import torch

from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()






class        __snake_case	(       unittest.TestCase):







    """simple docstring"""



    @property
    def __lowercase       (       self   :  str		)       ->  List[Any]:
      torch.manual_seed(0		)
      lowerCAmelCase_      :				Optional[Any]      =       UNetaDModel(
          block_out_channels=(32, 64)   ,						layers_per_block=2   ,						sample_size=32   ,						in_channels=3   ,						out_channels=3   ,						down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")   ,						up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")   ,						)
      return model





    def __lowercase       (       self   :  Tuple		)       ->  Optional[Any]:
      lowerCAmelCase_      :				Optional[int]      =       self.dummy_uncond_unet
      lowerCAmelCase_      :				Tuple      =       PNDMScheduler()

      lowerCAmelCase_      :				List[Any]      =       PNDMPipeline(unet=lowerCamelCase   ,						scheduler=lowerCamelCase		)
      pndm.to(lowerCamelCase		)
      pndm.set_progress_bar_config(disable=lowerCamelCase		)

      lowerCAmelCase_      :				Dict      =       torch.manual_seed(0		)
      lowerCAmelCase_      :				List[Any]      =       pndm(generator=lowerCamelCase   ,						num_inference_steps=20   ,						output_type="""numpy"""		).images

      lowerCAmelCase_      :				str      =       torch.manual_seed(0		)
      lowerCAmelCase_      :				int      =       pndm(generator=lowerCamelCase   ,						num_inference_steps=20   ,						output_type="""numpy"""   ,						return_dict=lowerCamelCase		)[0]

      lowerCAmelCase_      :				Optional[int]      =       image[0, -3:, -3:, -1]
      lowerCAmelCase_      :				Optional[Any]      =       image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 32, 32, 3)
      lowerCAmelCase_      :				int      =       np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]		)

      assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice		).max() < 1E-2







@slow
@require_torch
class        __snake_case	(       unittest.TestCase):







    """simple docstring"""



    def __lowercase       (       self   :  str		)       ->  Tuple:
      lowerCAmelCase_      :				str      =       """google/ddpm-cifar10-32"""

      lowerCAmelCase_      :				Dict      =       UNetaDModel.from_pretrained(lowerCamelCase		)
      lowerCAmelCase_      :				Dict      =       PNDMScheduler()

      lowerCAmelCase_      :				Union[str, Any]      =       PNDMPipeline(unet=lowerCamelCase   ,						scheduler=lowerCamelCase		)
      pndm.to(lowerCamelCase		)
      pndm.set_progress_bar_config(disable=lowerCamelCase		)
      lowerCAmelCase_      :				Any      =       torch.manual_seed(0		)
      lowerCAmelCase_      :				Union[str, Any]      =       pndm(generator=lowerCamelCase   ,						output_type="""numpy"""		).images

      lowerCAmelCase_      :				Optional[int]      =       image[0, -3:, -3:, -1]

      assert image.shape == (1, 32, 32, 3)
      lowerCAmelCase_      :				List[Any]      =       np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125]		)

      assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2



