





'''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 							__lowercase       (      lowerCAmelCase__						):







	'''simple docstring'''

	a    :				Dict											=       ["vqvae"]


	def __init__(self     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,)							->							Tuple:







				'''simple docstring'''





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


	def 						_UpperCAmelCase     (self )							->							int:







				'''simple docstring'''





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


	@torch.no_grad()
	def __call__(self     ,_lowerCamelCase = 1     ,_lowerCamelCase = None     ,_lowerCamelCase = None     ,_lowerCamelCase = 0     ,_lowerCamelCase = 0     ,_lowerCamelCase = None     ,_lowerCamelCase = None     ,_lowerCamelCase = 0     ,_lowerCamelCase = 0     ,_lowerCamelCase = None     ,_lowerCamelCase = 0     ,_lowerCamelCase = None     ,_lowerCamelCase = None     ,_lowerCamelCase=True     ,)							->							Union[
	    Union[AudioPipelineOutput, ImagePipelineOutput],
	    Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]],
	]:







				'''simple docstring'''





				__lowercase										=							steps or self.get_default_steps()
				self.scheduler.set_timesteps(_lowerCamelCase )
				__lowercase										=							step_generator or generator
				# For backwards compatibility
				if type(self.unet.config.sample_size ) == int:
							__lowercase										=							(self.unet.config.sample_size, self.unet.config.sample_size)
				if noise is None:
							__lowercase										=							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     ,)
				__lowercase										=							noise
				__lowercase										=							None

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

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

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

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

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

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

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

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

				__lowercase										=							[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 						_UpperCAmelCase     (self     ,_lowerCamelCase     ,_lowerCamelCase = 50 )							->							np.ndarray:







				'''simple docstring'''





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

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

				return sample


	@staticmethod
	def 						_UpperCAmelCase     (_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase )							->							torch.Tensor:







				'''simple docstring'''





				__lowercase										=							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 math




def    _lowerCAmelCase						(				lowerCamelCase_			:  int				):
			assert isinstance(lowerCamelCase_		,       lowerCamelCase_				) and (
			    number >= 0
			), "'number' must been an int and positive"

			if 1 < number < 4:
						# 2 and 3 are primes
						return True
			elif number < 2 or not number % 2:
						# Negatives, 0, 1 and all even numbers are not primes
						return False

			__lowercase										=							range(3		,       int(math.sqrt(lowerCamelCase_				) + 1				)		,       2				)
			return not any(not number % i for i in odd_numbers				)




def    _lowerCAmelCase						(				lowerCamelCase_			:  Dict		,       lowerCamelCase_			:  Any=1		,       **lowerCamelCase_			:  Tuple				):
			__lowercase										=							factor * value
			__lowercase										=							value

			while not is_prime(lowerCamelCase_				):
						value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1

			if value == first_value_val:
						return next_prime(value + 1		,       **lowerCamelCase_				)
			return value





