





import math
from typing import Any, Callable, List, Optional, Tuple, Union

import numpy as np
import torch

from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor


if is_onnx_available():
	from ..onnx_utils import OnnxRuntimeModel

from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder


lowerCAmelCase_    =				logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase_    =				2_5_6



class 					__lowerCAmelCase       (			_a     ):
			lowerCamelCase_     :     Optional[int]       			=      ['''melgan''']






			def __init__(self					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							)     ->   None:


							'''simple docstring'''



							super().__init__()

							# From MELGAN
							snake_case_						:    Tuple				=  math.log(1e-5    )  # Matches MelGAN training.
							snake_case_						:    Union[str, Any]				=  4.0  # Largest value for most examples
							snake_case_						:    Any				=  128

							self.register_modules(
							    notes_encoder=A_					,							continuous_encoder=A_					,							decoder=A_					,							scheduler=A_					,							melgan=A_					,							)






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__=(-1.0, 1.0)					,							__magic_name__=False    )     ->   Optional[Any]:


							'''simple docstring'''



							snake_case_			,							snake_case_						:    str				=  output_range
							if clip:
											snake_case_						:    str				=  torch.clip(A_					,							self.min_value					,							self.max_value    )
							# Scale to [0, 1].
							snake_case_						:    str				=  (features - self.min_value) / (self.max_value - self.min_value)
							# Scale to [min_out, max_out].
							return zero_one * (max_out - min_out) + min_out






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__=(-1.0, 1.0)					,							__magic_name__=False    )     ->   List[str]:


							'''simple docstring'''



							snake_case_			,							snake_case_						:    List[str]				=  input_range
							snake_case_						:    int				=  torch.clip(A_					,							A_					,							A_    ) if clip else outputs
							# Scale to [0, 1].
							snake_case_						:    Optional[int]				=  (outputs - min_out) / (max_out - min_out)
							# Scale to [self.min_value, self.max_value].
							return zero_one * (self.max_value - self.min_value) + self.min_value






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    Optional[Any]				=  input_tokens > 0
							snake_case_			,							snake_case_						:    Union[str, Any]				=  self.notes_encoder(
							    encoder_input_tokens=A_					,							encoder_inputs_mask=A_    )

							snake_case_			,							snake_case_						:    int				=  self.continuous_encoder(
							    encoder_inputs=A_					,							encoder_inputs_mask=A_    )

							return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   Optional[Any]:


							'''simple docstring'''



							snake_case_						:    List[Any]				=  noise_time
							if not torch.is_tensor(A_    ):
											snake_case_						:    int				=  torch.tensor([timesteps]					,							dtype=torch.long					,							device=input_tokens.device    )
							elif torch.is_tensor(A_    ) and len(timesteps.shape    ) == 0:
											snake_case_						:    Union[str, Any]				=  timesteps[None].to(input_tokens.device    )

							# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
							snake_case_						:    Optional[int]				=  timesteps * torch.ones(input_tokens.shape[0]					,							dtype=timesteps.dtype					,							device=timesteps.device    )

							snake_case_						:    str				=  self.decoder(
							    encodings_and_masks=A_					,							decoder_input_tokens=A_					,							decoder_noise_time=A_    )
							return logits






			@torch.no_grad()
			def __call__(self					,							__magic_name__					,							__magic_name__ = None					,							__magic_name__ = 100					,							__magic_name__ = True					,							__magic_name__ = "numpy"					,							__magic_name__ = None					,							__magic_name__ = 1					,							)     ->   Union[AudioPipelineOutput, Tuple]:


							'''simple docstring'''



							if (callback_steps is None) or (
							    callback_steps is not None and (not isinstance(A_					,							A_    ) or callback_steps <= 0)
							):
											raise ValueError(
											    F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
											    F''' {type(A_    )}.'''    )

							snake_case_						:    Optional[Any]				=  np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]					,							dtype=np.floataa    )
							snake_case_						:    List[str]				=  np.zeros([1, 0, self.n_dims]					,							np.floataa    )
							snake_case_						:    str				=  torch.ones((1, TARGET_FEATURE_LENGTH)					,							dtype=A_					,							device=self.device    )

							for i, encoder_input_tokens in enumerate(A_    ):
											if i == 0:
															snake_case_						:    List[str]				=  torch.from_numpy(pred_mel[:1].copy()    ).to(
															    device=self.device					,							dtype=self.decoder.dtype    )
															# The first chunk has no previous context.
															snake_case_						:    Tuple				=  torch.zeros((1, TARGET_FEATURE_LENGTH)					,							dtype=A_					,							device=self.device    )
											else:
															# The full song pipeline does not feed in a context feature, so the mask
															# will be all 0s after the feature converter. Because we know we're
															# feeding in a full context chunk from the previous prediction, set it
															# to all 1s.
															snake_case_						:    Tuple				=  ones

											snake_case_						:    int				=  self.scale_features(
											    A_					,							output_range=[-1.0, 1.0]					,							clip=A_    )

											snake_case_						:    Optional[int]				=  self.encode(
											    input_tokens=torch.IntTensor([encoder_input_tokens]    ).to(device=self.device    )					,							continuous_inputs=A_					,							continuous_mask=A_					,							)

											# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
											snake_case_						:    Tuple				=  randn_tensor(
											    shape=encoder_continuous_inputs.shape					,							generator=A_					,							device=self.device					,							dtype=self.decoder.dtype					,							)

											# set step values
											self.scheduler.set_timesteps(A_    )

											# Denoising diffusion loop
											for j, t in enumerate(self.progress_bar(self.scheduler.timesteps    )    ):
															snake_case_						:    int				=  self.decode(
															    encodings_and_masks=A_					,							input_tokens=A_					,							noise_time=t / self.scheduler.config.num_train_timesteps					,							)

															# Compute previous output: x_t -> x_t-1
															snake_case_						:    List[str]				=  self.scheduler.step(A_					,							A_					,							A_					,							generator=A_    ).prev_sample

											snake_case_						:    List[str]				=  self.scale_to_features(A_					,							input_range=[-1.0, 1.0]    )
											snake_case_						:    int				=  mel[:1]
											snake_case_						:    Dict				=  mel.cpu().float().numpy()

											snake_case_						:    List[str]				=  np.concatenate([full_pred_mel, pred_mel[:1]]					,							axis=1    )

											# call the callback, if provided
											if callback is not None and i % callback_steps == 0:
															callback(A_					,							A_    )

											logger.info('''Generated segment'''					,							A_    )

							if output_type == "numpy" and not is_onnx_available():
											raise ValueError(
											    '''Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.'''    )
							elif output_type == "numpy" and self.melgan is None:
											raise ValueError(
											    '''Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.'''    )

							if output_type == "numpy":
											snake_case_						:    int				=  self.melgan(input_features=full_pred_mel.astype(np.floataa    )    )
							else:
											snake_case_						:    Any				=  full_pred_mel

							if not return_dict:
											return (output,)

							return AudioPipelineOutput(audios=A_    )






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   A(						unittest.TestCase   ):



 '''simple docstring'''


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

       """simple docstring"""






       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()

 @property
 def 				a__ (				self					:  int  )   ->	int:

       """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 				a__ (				self					:  Any  )   ->	List[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=100						,							)
       return model

 @property
 def 				a__ (				self					:  Optional[int]  )   ->	Optional[int]:

       """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 				a__ (				self					:  Union[str, Any]  )   ->	Union[str, 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-05						,							num_attention_heads=4						,							num_hidden_layers=5						,							pad_token_id=1						,							vocab_size=1000						,							hidden_act='gelu'						,							projection_dim=512						,							)
       return CLIPTextModel(A_  )

 def 				a__ (				self					:  Optional[int]  )   ->	List[str]:

       """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=350						,							)
       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 				a__ (				self					:  List[Any]  )   ->	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=350						,							)
       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 				a__ (				self					:  List[Any]  )   ->	str:

       """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=350						,							)
       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   A(						unittest.TestCase   ):



 '''simple docstring'''


 def 				a__ (				self					:  Tuple  )   ->	str:

       """simple docstring"""






       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()

 def 				a__ (				self					:  int  )   ->	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 == (512, 512, 3)
       assert np.abs(expected_image - image  ).max() < 1E-3

 def 				a__ (				self					:  Dict  )   ->	List[str]:

       """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 == (512, 512, 3)
       assert np.abs(expected_image - image  ).max() < 5E-1





 def 				a__ (				self					:  Union[str, Any]  )   ->	Union[str, Any]:

       """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



