'''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    a__				(       A__			):
     lowerCamelCase  :					Tuple							=["vqvae"]






     def __init__(			self		:		List[str]  ,    a		:		AutoencoderKL  ,    a		:		UNetaDConditionModel  ,    a		:		Mel  ,    a		:		Union[DDIMScheduler, DDPMScheduler]  ,    ):





         """simple docstring"""



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






     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]   ):





         """simple docstring"""



         return 50 if isinstance(self.scheduler  ,    __snake_case   ) else 10_00






     @torch.no_grad()
     def __call__(			self		:		Tuple  ,    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		:		Optional[int]=True  ,    ):





         """simple docstring"""



         __lowerCamelCase          =  steps or self.get_default_steps()
         self.scheduler.set_timesteps(__snake_case   )
         __lowerCamelCase          =  step_generator or generator
         # For backwards compatibility
         if type(self.unet.config.sample_size   ) == int:
             __lowerCamelCase          =  (self.unet.config.sample_size, self.unet.config.sample_size)
         if noise is None:
             __lowerCamelCase          =  randn_tensor(
                 (
                     batch_size,
                     self.unet.config.in_channels,
                     self.unet.config.sample_size[0],
                     self.unet.config.sample_size[1],
                 )  ,    generator=__snake_case  ,    device=self.device  ,    )
         __lowerCamelCase          =  noise
         __lowerCamelCase          =  None

         if audio_file is not None or raw_audio is not None:
             self.mel.load_audio(__snake_case  ,    __snake_case   )
             __lowerCamelCase          =  self.mel.audio_slice_to_image(__snake_case   )
             __lowerCamelCase          =  np.frombuffer(input_image.tobytes()  ,    dtype='''uint8'''   ).reshape(
                 (input_image.height, input_image.width)   )
             __lowerCamelCase          =  (input_image / 2_55) * 2 - 1
             __lowerCamelCase          =  torch.tensor(input_image[np.newaxis, :, :]  ,    dtype=torch.float   ).to(self.device   )

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

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

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

         for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]   )   ):
             if isinstance(self.unet  ,    __snake_case   ):
                 __lowerCamelCase          =  self.unet(__snake_case  ,    __snake_case  ,    __snake_case   )['''sample''']
             else:
                 __lowerCamelCase          =  self.unet(__snake_case  ,    __snake_case   )['''sample''']

             if isinstance(self.scheduler  ,    __snake_case   ):
                 __lowerCamelCase          =  self.scheduler.step(
                     model_output=__snake_case  ,    timestep=__snake_case  ,    sample=__snake_case  ,    eta=__snake_case  ,    generator=__snake_case  ,    )['''prev_sample''']
             else:
                 __lowerCamelCase          =  self.scheduler.step(
                     model_output=__snake_case  ,    timestep=__snake_case  ,    sample=__snake_case  ,    generator=__snake_case  ,    )['''prev_sample''']

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

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

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

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

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






     @torch.no_grad()
     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple  ,    a		:		List[Image.Image]  ,    a		:		int = 50   ):





         """simple docstring"""



         assert isinstance(self.scheduler  ,    __snake_case   )
         self.scheduler.set_timesteps(__snake_case   )
         __lowerCamelCase          =  np.array(
             [np.frombuffer(image.tobytes()  ,    dtype='''uint8'''   ).reshape((1, image.height, image.width)   ) for image in images]   )
         __lowerCamelCase          =  (sample / 2_55) * 2 - 1
         __lowerCamelCase          =  torch.Tensor(__snake_case   ).to(self.device   )

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

         return sample






     @staticmethod
     def        SCREAMING_SNAKE_CASE__       (			a		:		torch.Tensor  ,    a		:		torch.Tensor  ,    a		:		float   ):





         """simple docstring"""



         __lowerCamelCase          =  acos(torch.dot(torch.flatten(__snake_case   )  ,    torch.flatten(__snake_case   )   ) / torch.norm(__snake_case   ) / torch.norm(__snake_case   )   )
         return sin((1 - alpha) * theta   ) * xa / sin(__snake_case   ) + sin(alpha * theta   ) * xa / sin(__snake_case   )

'''simple docstring'''




import torch

from diffusers import DPMSolverSDEScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import require_torchsde

from .test_schedulers import SchedulerCommonTest




@require_torchsde
class    a__				(       UpperCAmelCase__			):
     lowerCamelCase  :					Dict							=(DPMSolverSDEScheduler,)
     lowerCamelCase  :					List[str]							=1_0






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    **a		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  {
             '''num_train_timesteps''': 11_00,
             '''beta_start''': 0.00_01,
             '''beta_end''': 0.02,
             '''beta_schedule''': '''linear''',
             '''noise_sampler_seed''': 0,
         }

         config.update(**a   )
         return config






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]   ):





         """simple docstring"""



         for timesteps in [10, 50, 1_00, 10_00]:
             self.check_over_configs(num_train_timesteps=a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]  ,    [0.00_02, 0.0_02, 0.02]   ):
             self.check_over_configs(beta_start=a  ,    beta_end=a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         for schedule in ["linear", "scaled_linear"]:
             self.check_over_configs(beta_schedule=a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         for prediction_type in ["epsilon", "v_prediction"]:
             self.check_over_configs(prediction_type=a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config()
         __lowerCamelCase          =  scheduler_class(**a   )

         scheduler.set_timesteps(self.num_inference_steps   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter * scheduler.init_noise_sigma
         __lowerCamelCase          =  sample.to(a   )

         for i, t in enumerate(scheduler.timesteps   ):
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_67.47_82_10_44_92_18_75   ) < 1e-2
             assert abs(result_mean.item() - 0.21_78_70_59_64_56_52_77   ) < 1e-3
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_71.59_35_21_11_81_64_06   ) < 1e-2
             assert abs(result_mean.item() - 0.2_23_42_90_68_92_29_96_52   ) < 1e-3
         else:
             assert abs(result_sum.item() - 1_62.52_38_34_22_85_15_62   ) < 1e-2
             assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26   ) < 1e-3






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config(prediction_type='''v_prediction'''   )
         __lowerCamelCase          =  scheduler_class(**a   )

         scheduler.set_timesteps(self.num_inference_steps   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter * scheduler.init_noise_sigma
         __lowerCamelCase          =  sample.to(a   )

         for i, t in enumerate(scheduler.timesteps   ):
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_24.77_14_92_00_43_94_53   ) < 1e-2
             assert abs(result_mean.item() - 0.1_62_26_28_90_14_81_62_84   ) < 1e-3
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_28.1_66_33_60_59_57_03   ) < 1e-2
             assert abs(result_mean.item() - 0.1_66_88_32_60_01_16_72_97   ) < 1e-3
         else:
             assert abs(result_sum.item() - 1_19.8_48_75_48_82_81_25   ) < 1e-2
             assert abs(result_mean.item() - 0.15_60_53_06_62_53_66_21   ) < 1e-3






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config()
         __lowerCamelCase          =  scheduler_class(**a   )

         scheduler.set_timesteps(self.num_inference_steps  ,    device=a   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter.to(a   ) * scheduler.init_noise_sigma

         for t in scheduler.timesteps:
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_67.46_95_73_97_46_09_38   ) < 1e-2
             assert abs(result_mean.item() - 0.2_18_05_93_46_07_98_26_35   ) < 1e-3
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_71.59_35_36_37_69_53_12   ) < 1e-2
             assert abs(result_mean.item() - 0.2_23_42_90_83_82_41_57_71   ) < 1e-3
         else:
             assert abs(result_sum.item() - 1_62.52_38_34_22_85_15_62   ) < 1e-2
             assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26   ) < 1e-3






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config()
         __lowerCamelCase          =  scheduler_class(**a  ,    use_karras_sigmas=a   )

         scheduler.set_timesteps(self.num_inference_steps  ,    device=a   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter.to(a   ) * scheduler.init_noise_sigma
         __lowerCamelCase          =  sample.to(a   )

         for t in scheduler.timesteps:
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_76.66_97_41_35_74_21_88   ) < 1e-2
             assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11   ) < 1e-2
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_77.63_65_35_64_45_31_25   ) < 1e-2
             assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11   ) < 1e-2
         else:
             assert abs(result_sum.item() - 1_70.3_13_52_23_38_86_72   ) < 1e-2
             assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11   ) < 1e-2
