



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   __lowerCAmelCase  (		UpperCAmelCase_   ):
					"""simple docstring"""






					A__					:		str      							=     ["vqvae"]



					def __init__(  self       :							int					,       _snake_case       :							AutoencoderKL					,       _snake_case       :							UNetaDConditionModel					,       _snake_case       :							Mel					,       _snake_case       :							Union[DDIMScheduler, DDPMScheduler]					,       ):






								"""simple docstring"""


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



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


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



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






								"""simple docstring"""


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

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

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

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

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

											if isinstance(self.scheduler					,       _snake_case       ):
														A__	  =     self.scheduler.step(
														    model_output=_snake_case					,       timestep=_snake_case					,       sample=_snake_case					,       eta=_snake_case					,       generator=_snake_case					,       )['prev_sample']
											else:
														A__	  =     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:
																	A__	  =     mask[:, step, :, :mask_start]
														if mask_end > 0:
																	A__	  =     mask[:, step, :, -mask_end:]

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

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

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






								"""simple docstring"""


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

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

								return sample



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






								"""simple docstring"""


								A__	  =     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 gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()
@slow
@require_torch_gpu
class     _UpperCamelCase    (  unittest.TestCase						):
							'''simple docstring'''







							def      snake_case							(	self      ):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4"      )
										__lowerCAmelCase							       =     sd_pipe.to(__a      )
										sd_pipe.set_progress_bar_config(disable=__a      )

										sd_pipe.set_scheduler("sample_euler"      )

										__lowerCAmelCase							       =     "A painting of a squirrel eating a burger"
										__lowerCAmelCase							       =     torch.manual_seed(0      )
										__lowerCAmelCase							       =     sd_pipe([prompt]       ,  generator=__a       ,  guidance_scale=9.0       ,  num_inference_steps=20       ,  output_type="np"      )

										__lowerCAmelCase							       =     output.images

										__lowerCAmelCase							       =     image[0, -3:, -3:, -1]

										assert image.shape == (1, 5_12, 5_12, 3)
										__lowerCAmelCase							       =     np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9]      )

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

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base"      )
										__lowerCAmelCase							       =     sd_pipe.to(__a      )
										sd_pipe.set_progress_bar_config(disable=__a      )

										sd_pipe.set_scheduler("sample_euler"      )

										__lowerCAmelCase							       =     "A painting of a squirrel eating a burger"
										__lowerCAmelCase							       =     torch.manual_seed(0      )
										__lowerCAmelCase							       =     sd_pipe([prompt]       ,  generator=__a       ,  guidance_scale=9.0       ,  num_inference_steps=20       ,  output_type="np"      )

										__lowerCAmelCase							       =     output.images

										__lowerCAmelCase							       =     image[0, -3:, -3:, -1]

										assert image.shape == (1, 5_12, 5_12, 3)
										__lowerCAmelCase							       =     np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2]      )

										assert np.abs(image_slice.flatten() - expected_slice      ).max() < 5e-1



							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base"      )
										__lowerCAmelCase							       =     sd_pipe.to(__a      )
										sd_pipe.set_progress_bar_config(disable=__a      )

										sd_pipe.set_scheduler("sample_dpmpp_2m"      )

										__lowerCAmelCase							       =     "A painting of a squirrel eating a burger"
										__lowerCAmelCase							       =     torch.manual_seed(0      )
										__lowerCAmelCase							       =     sd_pipe(
										    [prompt]       ,  generator=__a       ,  guidance_scale=7.5       ,  num_inference_steps=15       ,  output_type="np"       ,  use_karras_sigmas=__a       ,  )

										__lowerCAmelCase							       =     output.images

										__lowerCAmelCase							       =     image[0, -3:, -3:, -1]

										assert image.shape == (1, 5_12, 5_12, 3)
										__lowerCAmelCase							       =     np.array(
										    [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8]      )

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




