
'''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 UpperCAmelCase__	( lowercase__	):





  """simple docstring"""

  __UpperCAmelCase				:				Union[str, Any]   =					['''vqvae''']


  def __init__(		self      :     Dict							,_a      :     AutoencoderKL							,_a      :     UNetaDConditionModel							,_a      :     Mel							,_a      :     Union[DDIMScheduler, DDPMScheduler]							,):


     '''simple docstring'''






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


  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






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


  @torch.no_grad()
  def __call__(		self      :     int							,_a      :     int = 1							,_a      :     str = None							,_a      :     np.ndarray = None							,_a      :     int = 0							,_a      :     int = 0							,_a      :     int = None							,_a      :     torch.Generator = None							,_a      :     float = 0							,_a      :     float = 0							,_a      :     torch.Generator = None							,_a      :     float = 0							,_a      :     torch.Tensor = None							,_a      :     torch.Tensor = None							,_a      :     Union[str, Any]=True							,):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   steps or self.get_default_steps()
     self.scheduler.set_timesteps(_a       )
     _a				:	Optional[int]			=   step_generator or generator
     # For backwards compatibility
     if type(self.unet.config.sample_size       ) == int:
        _a				:	Tuple			=   (self.unet.config.sample_size, self.unet.config.sample_size)
     if noise is None:
        _a				:	Optional[Any]			=   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							,)
     _a				:	Optional[int]			=   noise
     _a				:	str			=   None

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

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

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

        _a				:	int			=   (
            self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
        )
        _a				:	Optional[Any]			=   int(mask_start_secs * pixels_per_second       )
        _a				:	Any			=   int(mask_end_secs * pixels_per_second       )
        _a				:	int			=   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       ):
           _a				:	Union[str, Any]			=   self.unet(_a							,_a							,_a       )['sample']
        else:
           _a				:	List[Any]			=   self.unet(_a							,_a       )['sample']

        if isinstance(self.scheduler							,_a       ):
           _a				:	Optional[Any]			=   self.scheduler.step(
               model_output=_a							,timestep=_a							,sample=_a							,eta=_a							,generator=_a							,)['prev_sample']
        else:
           _a				:	str			=   self.scheduler.step(
               model_output=_a							,timestep=_a							,sample=_a							,generator=_a							,)['prev_sample']

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

     if self.vqvae is not None:
        # 0.18215 was scaling factor used in training to ensure unit variance
        _a				:	Tuple			=   1 / self.vqvae.config.scaling_factor * images
        _a				:	Any			=   self.vqvae.decode(_a       )['sample']

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

     _a				:	int			=   [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   __lowercase		(		self      :     int							,_a      :     List[Image.Image]							,_a      :     int = 50       ):


     '''simple docstring'''






     assert isinstance(self.scheduler							,_a       )
     self.scheduler.set_timesteps(_a       )
     _a				:	int			=   np.array(
         [np.frombuffer(image.tobytes()							,dtype='uint8'       ).reshape((1, image.height, image.width)       ) for image in images]       )
     _a				:	Union[str, Any]			=   (sample / 255) * 2 - 1
     _a				:	str			=   torch.Tensor(_a       ).to(self.device       )

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

     return sample


  @staticmethod
  def   __lowercase		(		_a      :     torch.Tensor							,_a      :     torch.Tensor							,_a      :     float       ):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   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       )





'''simple docstring'''







import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()







class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  @property
  def   __lowercase		(		self      :     Union[str, Any]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	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


  @property
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Union[str, Any]			=   VQModel(
         block_out_channels=[32, 64]							,in_channels=3							,out_channels=3							,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']							,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']							,latent_channels=3							,)
     return model


  @property
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Any			=   CLIPTextConfig(
         bos_token_id=0							,eos_token_id=2							,hidden_size=32							,intermediate_size=37							,layer_norm_eps=1E-05							,num_attention_heads=4							,num_hidden_layers=5							,pad_token_id=1							,vocab_size=1000							,)
     return CLIPTextModel(_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	Dict			=   self.dummy_uncond_unet
     _a				:	List[Any]			=   DDIMScheduler()
     _a				:	List[Any]			=   self.dummy_vq_model

     _a				:	str			=   LDMPipeline(unet=_a							,vqvae=_a							,scheduler=_a       )
     ldm.to(_a       )
     ldm.set_progress_bar_config(disable=_a       )

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	List[str]			=   ldm(generator=_a							,num_inference_steps=2							,output_type='numpy'       ).images

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	Union[str, Any]			=   ldm(generator=_a							,num_inference_steps=2							,output_type='numpy'							,return_dict=_a       )[0]

     _a				:	Tuple			=   image[0, -3:, -3:, -1]
     _a				:	Optional[Any]			=   image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     _a				:	int			=   np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]       )
     _a				:	Any			=   1E-2 if torch_device != 'mps' else 3E-2

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < tolerance







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





  """simple docstring"""

  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	List[str]			=   LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256'       )
     ldm.to(_a       )
     ldm.set_progress_bar_config(disable=_a       )

     _a				:	Optional[int]			=   torch.manual_seed(0       )
     _a				:	Dict			=   ldm(generator=_a							,num_inference_steps=5							,output_type='numpy'       ).images

     _a				:	str			=   image[0, -3:, -3:, -1]

     assert image.shape == (1, 256, 256, 3)
     _a				:	Optional[int]			=   np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447]       )
     _a				:	int			=   1E-2 if torch_device != 'mps' else 3E-2

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance



