



# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation

import warnings

from .state import AcceleratorState, GradientState


warnings.filterwarnings("""ignore""", category=UserWarning, module="""torch.optim.lr_scheduler""")

class       _SCREAMING_SNAKE_CASE	:





     def __init__(       self :							Union[str, Any]     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							bool = False				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	scheduler
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	optimizers if isinstance(UpperCamelCase     ,  (list, tuple)				) else [optimizers]
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	split_batches
      __SCREAMING_SNAKE_CASE       :    int       =	step_with_optimizer
      __SCREAMING_SNAKE_CASE       :    Any       =	GradientState()





     def 	__snake_case    (       self :							Any     ,  *UpperCamelCase :							List[Any]     ,  **UpperCamelCase :							Optional[Any]				)->Optional[int]:
      if not self.step_with_optimizer:
       # No link between scheduler and optimizer -> just step
       self.scheduler.step(*UpperCamelCase     ,  **UpperCamelCase				)
       return

      # Otherwise, first make sure the optimizer was stepped.
      if not self.gradient_state.sync_gradients:
       if self.gradient_state.adjust_scheduler:
        self.scheduler._step_count += 1
       return

      for opt in self.optimizers:
       if opt.step_was_skipped:
        return
      if self.split_batches:
       # Split batches -> the training dataloader batch size is not changed so one step per training step
       self.scheduler.step(*UpperCamelCase     ,  **UpperCamelCase				)
      else:
       # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
       # num_processes steps per training step
       __SCREAMING_SNAKE_CASE       :    Any       =	AcceleratorState().num_processes
       for _ in range(UpperCamelCase				):
        # Special case when using OneCycle and `drop_last` was not used
        if hasattr(self.scheduler     ,  "total_steps"				):
         if self.scheduler._step_count <= self.scheduler.total_steps:
          self.scheduler.step(*UpperCamelCase     ,  **UpperCamelCase				)
        else:
         self.scheduler.step(*UpperCamelCase     ,  **UpperCamelCase				)





     def 	__snake_case    (       self :							Dict				)->Dict:
      return self.scheduler.get_last_lr()





     def 	__snake_case    (       self :							List[str]				)->Dict:
      return self.scheduler.state_dict()





     def 	__snake_case    (       self :							Tuple     ,  UpperCamelCase :							Any				)->Union[str, Any]:
      self.scheduler.load_state_dict(UpperCamelCase				)





     def 	__snake_case    (       self :							Union[str, Any]				)->Optional[int]:
      return self.scheduler.get_lr()






     def 	__snake_case    (       self :							Optional[Any]     ,  *UpperCamelCase :							Dict     ,  **UpperCamelCase :							List[str]				)->Optional[Any]:
      return self.scheduler.print_lr(*UpperCamelCase     ,  **UpperCamelCase				)











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       _SCREAMING_SNAKE_CASE	(UpperCamelCase ):
     lowerCAmelCase					=			["""vqvae"""]





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





     def 	__snake_case    (       self :							List[Any]				)->int:
      return 5_0 if isinstance(self.scheduler     ,  UpperCamelCase				) else 1_0_0_0





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

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

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

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

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

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

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

       if mask is not None:
        if mask_start > 0:
         __SCREAMING_SNAKE_CASE       :    int       =	mask[:, step, :, :mask_start]
        if mask_end > 0:
         __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	mask[:, step, :, -mask_end:]

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

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

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

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





     @torch.no_grad()
     def 	__snake_case    (       self :							Dict     ,  UpperCamelCase :							List[Image.Image]     ,  UpperCamelCase :							int = 5_0				)->np.ndarray:
      assert isinstance(self.scheduler     ,  UpperCamelCase				)
      self.scheduler.set_timesteps(UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    int       =	np.array(
          [np.frombuffer(image.tobytes()     ,  dtype="uint8"				).reshape((1, image.height, image.width)				) for image in images]				)
      __SCREAMING_SNAKE_CASE       :    Dict       =	(sample / 2_5_5) * 2 - 1
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	torch.Tensor(UpperCamelCase				).to(self.device				)

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

      return sample






     @staticmethod
     def 	__snake_case    (       UpperCamelCase :							torch.Tensor     ,  UpperCamelCase :							torch.Tensor     ,  UpperCamelCase :							float				)->torch.Tensor:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	acos(torch.dot(torch.flatten(UpperCamelCase				)     ,  torch.flatten(UpperCamelCase				)				) / torch.norm(UpperCamelCase				) / torch.norm(UpperCamelCase				)				)
      return sin((1 - alpha) * theta				) * xa / sin(UpperCamelCase				) + sin(alpha * theta				) * xa / sin(UpperCamelCase				)






