import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
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


enable_full_determinism()



class  UpperCamelCase				( unittest.TestCase ):

     '''simple docstring'''

     def 		UpperCamelCase_						(					self						) ->				List[Any]:






           """simple docstring"""
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



     @property
     def 		UpperCamelCase_						(					self						) ->				Dict:






           """simple docstring"""
           _lowerCamelCase			    =				1
           _lowerCamelCase			    =				3
           _lowerCamelCase			    =				(32, 32)

           _lowerCamelCase			    =				floats_tensor((batch_size, num_channels) + sizes				,				rng=random.Random(0						)						).to(A_						)
           return image



     @property
     def 		UpperCamelCase_						(					self						) ->				Optional[Any]:






           """simple docstring"""
           torch.manual_seed(0						)
           _lowerCamelCase			    =				UNetaDConditionModel(
               block_out_channels=(32, 32, 64)				,				layers_per_block=2				,				sample_size=32				,				in_channels=7				,				out_channels=4				,				down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''')				,				up_block_types=('''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''', '''UpBlock2D''')				,				cross_attention_dim=32				,				attention_head_dim=8				,				use_linear_projection=A_				,				only_cross_attention=(True, True, False)				,				num_class_embeds=1_00				,				)
           return model



     @property
     def 		UpperCamelCase_						(					self						) ->				Optional[Any]:






           """simple docstring"""
           torch.manual_seed(0						)
           _lowerCamelCase			    =				AutoencoderKL(
               block_out_channels=[32, 32, 64]				,				in_channels=3				,				out_channels=3				,				down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D''']				,				up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D''']				,				latent_channels=4				,				)
           return model



     @property
     def 		UpperCamelCase_						(					self						) ->				List[Any]:






           """simple docstring"""
           torch.manual_seed(0						)
           _lowerCamelCase			    =				CLIPTextConfig(
               bos_token_id=0				,				eos_token_id=2				,				hidden_size=32				,				intermediate_size=37				,				layer_norm_eps=1E-0_5				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=10_00				,				hidden_act='''gelu'''				,				projection_dim=5_12				,				)
           return CLIPTextModel(A_						)



     def 		UpperCamelCase_						(					self						) ->				Optional[Any]:






           """simple docstring"""
           _lowerCamelCase			    =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
           _lowerCamelCase			    =				self.dummy_cond_unet_upscale
           _lowerCamelCase			    =				DDPMScheduler()
           _lowerCamelCase			    =				DDIMScheduler(prediction_type='''v_prediction'''						)
           _lowerCamelCase			    =				self.dummy_vae
           _lowerCamelCase			    =				self.dummy_text_encoder
           _lowerCamelCase			    =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

           _lowerCamelCase			    =				self.dummy_image.cpu().permute(0				,				2				,				3				,				1						)[0]
           _lowerCamelCase			    =				Image.fromarray(np.uinta(A_						)						).convert('''RGB'''						).resize((64, 64)						)

           # make sure here that pndm scheduler skips prk
           _lowerCamelCase			    =				StableDiffusionUpscalePipeline(
               unet=A_				,				low_res_scheduler=A_				,				scheduler=A_				,				vae=A_				,				text_encoder=A_				,				tokenizer=A_				,				max_noise_level=3_50				,				)
           _lowerCamelCase			    =				sd_pipe.to(A_						)
           sd_pipe.set_progress_bar_config(disable=A_						)

           _lowerCamelCase			    =				'''A painting of a squirrel eating a burger'''
           _lowerCamelCase			    =				torch.Generator(device=A_						).manual_seed(0						)
           _lowerCamelCase			    =				sd_pipe(
               [prompt]				,				image=A_				,				generator=A_				,				guidance_scale=6.0				,				noise_level=20				,				num_inference_steps=2				,				output_type='''np'''				,				)

           _lowerCamelCase			    =				output.images

           _lowerCamelCase			    =				torch.Generator(device=A_						).manual_seed(0						)
           _lowerCamelCase			    =				sd_pipe(
               [prompt]				,				image=A_				,				generator=A_				,				guidance_scale=6.0				,				noise_level=20				,				num_inference_steps=2				,				output_type='''np'''				,				return_dict=A_				,				)[0]

           _lowerCamelCase			    =				image[0, -3:, -3:, -1]
           _lowerCamelCase			    =				image_from_tuple[0, -3:, -3:, -1]

           _lowerCamelCase			    =				low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)
           _lowerCamelCase			    =				np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]						)

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



     def 		UpperCamelCase_						(					self						) ->				int:






           """simple docstring"""
           _lowerCamelCase			    =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
           _lowerCamelCase			    =				self.dummy_cond_unet_upscale
           _lowerCamelCase			    =				DDPMScheduler()
           _lowerCamelCase			    =				DDIMScheduler(prediction_type='''v_prediction'''						)
           _lowerCamelCase			    =				self.dummy_vae
           _lowerCamelCase			    =				self.dummy_text_encoder
           _lowerCamelCase			    =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

           _lowerCamelCase			    =				self.dummy_image.cpu().permute(0				,				2				,				3				,				1						)[0]
           _lowerCamelCase			    =				Image.fromarray(np.uinta(A_						)						).convert('''RGB'''						).resize((64, 64)						)

           # make sure here that pndm scheduler skips prk
           _lowerCamelCase			    =				StableDiffusionUpscalePipeline(
               unet=A_				,				low_res_scheduler=A_				,				scheduler=A_				,				vae=A_				,				text_encoder=A_				,				tokenizer=A_				,				max_noise_level=3_50				,				)
           _lowerCamelCase			    =				sd_pipe.to(A_						)
           sd_pipe.set_progress_bar_config(disable=A_						)

           _lowerCamelCase			    =				'''A painting of a squirrel eating a burger'''
           _lowerCamelCase			    =				sd_pipe(
               2 * [prompt]				,				image=2 * [low_res_image]				,				guidance_scale=6.0				,				noise_level=20				,				num_inference_steps=2				,				output_type='''np'''				,				)
           _lowerCamelCase			    =				output.images
           assert image.shape[0] == 2

           _lowerCamelCase			    =				torch.Generator(device=A_						).manual_seed(0						)
           _lowerCamelCase			    =				sd_pipe(
               [prompt]				,				image=A_				,				generator=A_				,				num_images_per_prompt=2				,				guidance_scale=6.0				,				noise_level=20				,				num_inference_steps=2				,				output_type='''np'''				,				)
           _lowerCamelCase			    =				output.images
           assert image.shape[0] == 2





     @unittest.skipIf(torch_device != '''cuda'''				,				'''This test requires a GPU'''						)
     def 		UpperCamelCase_						(					self						) ->				int:






           """simple docstring"""
           _lowerCamelCase			    =				self.dummy_cond_unet_upscale
           _lowerCamelCase			    =				DDPMScheduler()
           _lowerCamelCase			    =				DDIMScheduler(prediction_type='''v_prediction'''						)
           _lowerCamelCase			    =				self.dummy_vae
           _lowerCamelCase			    =				self.dummy_text_encoder
           _lowerCamelCase			    =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

           _lowerCamelCase			    =				self.dummy_image.cpu().permute(0				,				2				,				3				,				1						)[0]
           _lowerCamelCase			    =				Image.fromarray(np.uinta(A_						)						).convert('''RGB'''						).resize((64, 64)						)

           # put models in fp16, except vae as it overflows in fp16
           _lowerCamelCase			    =				unet.half()
           _lowerCamelCase			    =				text_encoder.half()

           # make sure here that pndm scheduler skips prk
           _lowerCamelCase			    =				StableDiffusionUpscalePipeline(
               unet=A_				,				low_res_scheduler=A_				,				scheduler=A_				,				vae=A_				,				text_encoder=A_				,				tokenizer=A_				,				max_noise_level=3_50				,				)
           _lowerCamelCase			    =				sd_pipe.to(A_						)
           sd_pipe.set_progress_bar_config(disable=A_						)

           _lowerCamelCase			    =				'''A painting of a squirrel eating a burger'''
           _lowerCamelCase			    =				torch.manual_seed(0						)
           _lowerCamelCase			    =				sd_pipe(
               [prompt]				,				image=A_				,				generator=A_				,				num_inference_steps=2				,				output_type='''np'''				,				).images

           _lowerCamelCase			    =				low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)





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

     '''simple docstring'''

     def 		UpperCamelCase_						(					self						) ->				Optional[Any]:






           """simple docstring"""
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



     def 		UpperCamelCase_						(					self						) ->				Optional[int]:






           """simple docstring"""
           _lowerCamelCase			    =				load_image(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
               '''/sd2-upscale/low_res_cat.png'''						)
           _lowerCamelCase			    =				load_numpy(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
               '''/upsampled_cat.npy'''						)

           _lowerCamelCase			    =				'''stabilityai/stable-diffusion-x4-upscaler'''
           _lowerCamelCase			    =				StableDiffusionUpscalePipeline.from_pretrained(A_						)
           pipe.to(A_						)
           pipe.set_progress_bar_config(disable=A_						)
           pipe.enable_attention_slicing()

           _lowerCamelCase			    =				'''a cat sitting on a park bench'''

           _lowerCamelCase			    =				torch.manual_seed(0						)
           _lowerCamelCase			    =				pipe(
               prompt=A_				,				image=A_				,				generator=A_				,				output_type='''np'''				,				)
           _lowerCamelCase			    =				output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image						).max() < 1E-3



     def 		UpperCamelCase_						(					self						) ->				int:






           """simple docstring"""
           _lowerCamelCase			    =				load_image(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
               '''/sd2-upscale/low_res_cat.png'''						)
           _lowerCamelCase			    =				load_numpy(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
               '''/upsampled_cat_fp16.npy'''						)

           _lowerCamelCase			    =				'''stabilityai/stable-diffusion-x4-upscaler'''
           _lowerCamelCase			    =				StableDiffusionUpscalePipeline.from_pretrained(
               A_				,				torch_dtype=torch.floataa				,				)
           pipe.to(A_						)
           pipe.set_progress_bar_config(disable=A_						)
           pipe.enable_attention_slicing()

           _lowerCamelCase			    =				'''a cat sitting on a park bench'''

           _lowerCamelCase			    =				torch.manual_seed(0						)
           _lowerCamelCase			    =				pipe(
               prompt=A_				,				image=A_				,				generator=A_				,				output_type='''np'''				,				)
           _lowerCamelCase			    =				output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image						).max() < 5E-1





     def 		UpperCamelCase_						(					self						) ->				List[str]:






           """simple docstring"""
           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           _lowerCamelCase			    =				load_image(
               '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
               '''/sd2-upscale/low_res_cat.png'''						)

           _lowerCamelCase			    =				'''stabilityai/stable-diffusion-x4-upscaler'''
           _lowerCamelCase			    =				StableDiffusionUpscalePipeline.from_pretrained(
               A_				,				torch_dtype=torch.floataa				,				)
           pipe.to(A_						)
           pipe.set_progress_bar_config(disable=A_						)
           pipe.enable_attention_slicing(1						)
           pipe.enable_sequential_cpu_offload()

           _lowerCamelCase			    =				'''a cat sitting on a park bench'''

           _lowerCamelCase			    =				torch.manual_seed(0						)
           _lowerCamelCase			    =				pipe(
               prompt=A_				,				image=A_				,				generator=A_				,				num_inference_steps=5				,				output_type='''np'''				,				)

           _lowerCamelCase			    =				torch.cuda.max_memory_allocated()
           # make sure that less than 2.9 GB is allocated
           assert mem_bytes < 2.9 * 10**9
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  UpperCamelCase				( __lowercase ):

     '''simple docstring'''

     A_										=  ['vqvae']



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






           """simple docstring"""
           super().__init__()
           self.register_modules(unet=A_				,				scheduler=A_				,				mel=A_				,				vqvae=A_						)



     def 		UpperCamelCase_						(					self						) ->				int:






           """simple docstring"""
           return 50 if isinstance(self.scheduler				,				A_						) else 10_00



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






           """simple docstring"""
           _lowerCamelCase			    =				steps or self.get_default_steps()
           self.scheduler.set_timesteps(A_						)
           _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=A_				,				device=self.device				,				)
           _lowerCamelCase			    =				noise
           _lowerCamelCase			    =				None

           if audio_file is not None or raw_audio is not None:
                 self.mel.load_audio(A_				,				A_						)
                 _lowerCamelCase			    =				self.mel.audio_slice_to_image(A_						)
                 _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(A_				,				0						)						).latent_dist.sample(
                           generator=A_						)[0]
                       _lowerCamelCase			    =				self.vqvae.config.scaling_factor * input_images

                 if start_step > 0:
                       _lowerCamelCase			    =				self.scheduler.add_noise(A_				,				A_				,				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(A_				,				A_				,				torch.tensor(self.scheduler.timesteps[start_step:]						)						)

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

                 if isinstance(self.scheduler				,				A_						):
                       _lowerCamelCase			    =				self.scheduler.step(
                           model_output=A_				,				timestep=A_				,				sample=A_				,				eta=A_				,				generator=A_				,				)['''prev_sample''']
                 else:
                       _lowerCamelCase			    =				self.scheduler.step(
                           model_output=A_				,				timestep=A_				,				sample=A_				,				generator=A_				,				)['''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(A_						)['''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(A_				,				mode='''RGB'''						).convert('''L'''						) for _ in images)						)

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

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



     @torch.no_grad()
     def 		UpperCamelCase_						(					self				,				A_				,				A_ = 50						) ->				np.ndarray:






           """simple docstring"""
           assert isinstance(self.scheduler				,				A_						)
           self.scheduler.set_timesteps(A_						)
           _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(A_						).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(A_				,				A_						)['''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 		UpperCamelCase_						(					A_				,				A_				,				A_						) ->				torch.Tensor:






           """simple docstring"""
           _lowerCamelCase			    =				acos(torch.dot(torch.flatten(A_						)				,				torch.flatten(A_						)						) / torch.norm(A_						) / torch.norm(A_						)						)
           return sin((1 - alpha) * theta						) * xa / sin(A_						) + sin(alpha * theta						) * xa / sin(A_						)