





import gc
import random
import unittest

import numpy as np
import torch

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()





class      lowercase__    (							__A     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  KandinskyVaaControlnetPipeline
  __UpperCamelCase	     =  ["""image_embeds""", """negative_image_embeds""", """hint"""]
  __UpperCamelCase	     =  ["""image_embeds""", """negative_image_embeds""", """hint"""]
  __UpperCamelCase	     =  [
      """generator""",
      """height""",
      """width""",
      """latents""",
      """guidance_scale""",
      """num_inference_steps""",
      """return_dict""",
      """guidance_scale""",
      """num_images_per_prompt""",
      """output_type""",
      """return_dict""",
  ]
  __UpperCamelCase	     =  False







  @property
  def 	UpperCAmelCase__		(	self						):
       return 32







  @property
  def 	UpperCAmelCase__		(	self						):
       return 32







  @property
  def 	UpperCAmelCase__		(	self						):
       return self.time_input_dim







  @property
  def 	UpperCAmelCase__		(	self						):
       return self.time_input_dim * 4







  @property
  def 	UpperCAmelCase__		(	self						):
       return 100







  @property
  def 	UpperCAmelCase__		(	self						):
       torch.manual_seed(0						)

       lowerCAmelCase_					:       List[Any]    =		{
           """in_channels""": 8,
           # Out channels is double in channels because predicts mean and variance
           """out_channels""": 8,
           """addition_embed_type""": """image_hint""",
           """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
           """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
           """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
           """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
           """layers_per_block""": 1,
           """encoder_hid_dim""": self.text_embedder_hidden_size,
           """encoder_hid_dim_type""": """image_proj""",
           """cross_attention_dim""": self.cross_attention_dim,
           """attention_head_dim""": 4,
           """resnet_time_scale_shift""": """scale_shift""",
           """class_embed_type""": None,
       }

       lowerCAmelCase_					:       Union[str, Any]    =		UNetaDConditionModel(**_lowercase						)
       return model







  @property
  def 	UpperCAmelCase__		(	self						):
       return {
           "block_out_channels": [32, 32, 64, 64],
           "down_block_types": [
               "DownEncoderBlock2D",
               "DownEncoderBlock2D",
               "DownEncoderBlock2D",
               "AttnDownEncoderBlock2D",
           ],
           "in_channels": 3,
           "latent_channels": 4,
           "layers_per_block": 1,
           "norm_num_groups": 8,
           "norm_type": "spatial",
           "num_vq_embeddings": 12,
           "out_channels": 3,
           "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
           "vq_embed_dim": 4,
       }







  @property
  def 	UpperCAmelCase__		(	self						):
       torch.manual_seed(0						)
       lowerCAmelCase_					:       Optional[int]    =		VQModel(**self.dummy_movq_kwargs						)
       return model







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Any    =		self.dummy_unet
       lowerCAmelCase_					:       Dict    =		self.dummy_movq

       lowerCAmelCase_					:       List[Any]    =		DDIMScheduler(
           num_train_timesteps=1_000    ,						beta_schedule="""linear"""    ,						beta_start=0.0_0085    ,						beta_end=0.012    ,						clip_sample=_lowercase    ,						set_alpha_to_one=_lowercase    ,						steps_offset=1    ,						prediction_type="""epsilon"""    ,						thresholding=_lowercase    ,						)

       lowerCAmelCase_					:       Tuple    =		{
           """unet""": unet,
           """scheduler""": scheduler,
           """movq""": movq,
       }
       return components







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase=0						):
       lowerCAmelCase_					:       Optional[Any]    =		floats_tensor((1, self.text_embedder_hidden_size)    ,						rng=random.Random(_lowercase						)						).to(_lowercase						)
       lowerCAmelCase_					:       List[Any]    =		floats_tensor((1, self.text_embedder_hidden_size)    ,						rng=random.Random(seed + 1						)						).to(
           _lowercase						)

       # create hint
       lowerCAmelCase_					:       Optional[int]    =		floats_tensor((1, 3, 64, 64)    ,						rng=random.Random(_lowercase						)						).to(_lowercase						)

       if str(_lowercase						).startswith("""mps"""						):
            lowerCAmelCase_					:       Tuple    =		torch.manual_seed(_lowercase						)
       else:
            lowerCAmelCase_					:       Optional[int]    =		torch.Generator(device=_lowercase						).manual_seed(_lowercase						)
       lowerCAmelCase_					:       Any    =		{
           """image_embeds""": image_embeds,
           """negative_image_embeds""": negative_image_embeds,
           """hint""": hint,
           """generator""": generator,
           """height""": 64,
           """width""": 64,
           """guidance_scale""": 4.0,
           """num_inference_steps""": 2,
           """output_type""": """np""",
       }
       return inputs







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[Any]    =		"""cpu"""

       lowerCAmelCase_					:       Tuple    =		self.get_dummy_components()

       lowerCAmelCase_					:       Union[str, Any]    =		self.pipeline_class(**_lowercase						)
       lowerCAmelCase_					:       Dict    =		pipe.to(_lowercase						)

       pipe.set_progress_bar_config(disable=_lowercase						)

       lowerCAmelCase_					:       int    =		pipe(**self.get_dummy_inputs(_lowercase						)						)
       lowerCAmelCase_					:       List[str]    =		output.images

       lowerCAmelCase_					:       List[str]    =		pipe(
           **self.get_dummy_inputs(_lowercase						)    ,						return_dict=_lowercase    ,						)[0]

       lowerCAmelCase_					:       int    =		image[0, -3:, -3:, -1]
       lowerCAmelCase_					:       Union[str, Any]    =		image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)

       lowerCAmelCase_					:       str    =		np.array(
           [0.695_9826, 0.86_8279, 0.755_8092, 0.6876_9467, 0.8580_5804, 0.6597_7496, 0.4488_5302, 0.595_9111, 0.425_1595]						)

       assert (
           np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
       ), F' expected_slice {expected_slice}, but got {image_slice.flatten()}'

       assert (
           np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1e-2
       ), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'





@slow
@require_torch_gpu
class      lowercase__    (							unittest.TestCase  ):







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







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Any    =		load_numpy(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
           """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy"""						)

       lowerCAmelCase_					:       Dict    =		load_image(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
           """/kandinskyv22/hint_image_cat.png"""						)
       lowerCAmelCase_					:       Tuple    =		torch.from_numpy(np.array(_lowercase						)						).float() / 255.0
       lowerCAmelCase_					:       str    =		hint.permute(2    ,						0    ,						1						).unsqueeze(0						)

       lowerCAmelCase_					:       str    =		KandinskyVaaPriorPipeline.from_pretrained(
           """kandinsky-community/kandinsky-2-2-prior"""    ,						torch_dtype=torch.floataa						)
       pipe_prior.to(_lowercase						)

       lowerCAmelCase_					:       int    =		KandinskyVaaControlnetPipeline.from_pretrained(
           """kandinsky-community/kandinsky-2-2-controlnet-depth"""    ,						torch_dtype=torch.floataa						)
       lowerCAmelCase_					:       Union[str, Any]    =		pipeline.to(_lowercase						)
       pipeline.set_progress_bar_config(disable=_lowercase						)

       lowerCAmelCase_					:       Union[str, Any]    =		"""A robot, 4k photo"""

       lowerCAmelCase_					:       str    =		torch.Generator(device="""cuda"""						).manual_seed(0						)
       lowerCAmelCase_   ,  lowerCAmelCase_					:       Tuple    =		pipe_prior(
           _lowercase    ,						generator=_lowercase    ,						num_inference_steps=5    ,						negative_prompt=""""""    ,						).to_tuple()

       lowerCAmelCase_					:       Tuple    =		torch.Generator(device="""cuda"""						).manual_seed(0						)
       lowerCAmelCase_					:       Optional[Any]    =		pipeline(
           image_embeds=_lowercase    ,						negative_image_embeds=_lowercase    ,						hint=_lowercase    ,						generator=_lowercase    ,						num_inference_steps=100    ,						output_type="""np"""    ,						)

       lowerCAmelCase_					:       Union[str, Any]    =		output.images[0]

       assert image.shape == (512, 512, 3)

       assert_mean_pixel_difference(_lowercase    ,						_lowercase						)







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__    (							__A  ):
  __UpperCamelCase	     =  ["""vqvae"""]







  def __init__(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						):
       super().__init__()
       self.register_modules(unet=_lowercase    ,						scheduler=_lowercase    ,						mel=_lowercase    ,						vqvae=_lowercase						)







  def 	UpperCAmelCase__		(	self						):
       return 50 if isinstance(self.scheduler    ,						_lowercase						) else 1_000







  @torch.no_grad()
  def __call__(	self    ,						_lowercase = 1    ,						_lowercase = None    ,						_lowercase = None    ,						_lowercase = 0    ,						_lowercase = 0    ,						_lowercase = None    ,						_lowercase = None    ,						_lowercase = 0    ,						_lowercase = 0    ,						_lowercase = None    ,						_lowercase = 0    ,						_lowercase = None    ,						_lowercase = None    ,						_lowercase=True    ,						):
       lowerCAmelCase_					:       Tuple    =		steps or self.get_default_steps()
       self.scheduler.set_timesteps(_lowercase						)
       lowerCAmelCase_					:       Union[str, Any]    =		step_generator or generator
       # For backwards compatibility
       if type(self.unet.config.sample_size						) == int:
            lowerCAmelCase_					:       Optional[Any]    =		(self.unet.config.sample_size, self.unet.config.sample_size)
       if noise is None:
            lowerCAmelCase_					:       Tuple    =		randn_tensor(
                (
                    batch_size,
                    self.unet.config.in_channels,
                    self.unet.config.sample_size[0],
                    self.unet.config.sample_size[1],
                )    ,						generator=_lowercase    ,						device=self.device    ,						)
       lowerCAmelCase_					:       List[str]    =		noise
       lowerCAmelCase_					:       List[str]    =		None

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

            if self.vqvae is not None:
                 lowerCAmelCase_					:       List[Any]    =		self.vqvae.encode(torch.unsqueeze(_lowercase    ,						0						)						).latent_dist.sample(
                     generator=_lowercase						)[0]
                 lowerCAmelCase_					:       str    =		self.vqvae.config.scaling_factor * input_images

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

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

       for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]						)						):
            if isinstance(self.unet    ,						_lowercase						):
                 lowerCAmelCase_					:       List[Any]    =		self.unet(_lowercase    ,						_lowercase    ,						_lowercase						)["""sample"""]
            else:
                 lowerCAmelCase_					:       Any    =		self.unet(_lowercase    ,						_lowercase						)["""sample"""]

            if isinstance(self.scheduler    ,						_lowercase						):
                 lowerCAmelCase_					:       str    =		self.scheduler.step(
                     model_output=_lowercase    ,						timestep=_lowercase    ,						sample=_lowercase    ,						eta=_lowercase    ,						generator=_lowercase    ,						)["""prev_sample"""]
            else:
                 lowerCAmelCase_					:       List[str]    =		self.scheduler.step(
                     model_output=_lowercase    ,						timestep=_lowercase    ,						sample=_lowercase    ,						generator=_lowercase    ,						)["""prev_sample"""]

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

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

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

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

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







  @torch.no_grad()
  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase = 50						):
       assert isinstance(self.scheduler    ,						_lowercase						)
       self.scheduler.set_timesteps(_lowercase						)
       lowerCAmelCase_					:       List[Any]    =		np.array(
           [np.frombuffer(image.tobytes()    ,						dtype="""uint8"""						).reshape((1, image.height, image.width)						) for image in images]						)
       lowerCAmelCase_					:       List[str]    =		(sample / 255) * 2 - 1
       lowerCAmelCase_					:       Optional[Any]    =		torch.Tensor(_lowercase						).to(self.device						)

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

       return sample







  @staticmethod
  def 	UpperCAmelCase__		(	_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Optional[int]    =		acos(torch.dot(torch.flatten(_lowercase						)    ,						torch.flatten(_lowercase						)						) / torch.norm(_lowercase						) / torch.norm(_lowercase						)						)
       return sin((1 - alpha) * theta						) * xa / sin(_lowercase						) + sin(alpha * theta						) * xa / sin(_lowercase						)
