






import gc
import unittest

import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
    ClapTextConfig,
    ClapTextModelWithProjection,
    RobertaTokenizer,
    SpeechTaHifiGan,
    SpeechTaHifiGanConfig,
)

from diffusers import (
    AudioLDMPipeline,
    AutoencoderKL,
    DDIMScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class 						SCREAMING_SNAKE_CASE				( snake_case  ,	unittest.TestCase					):





							"""simple docstring"""

							A_						  =					AudioLDMPipeline
							A_						  =					TEXT_TO_AUDIO_PARAMS
							A_						  =					TEXT_TO_AUDIO_BATCH_PARAMS
							A_						  =					frozenset(
							    [
							        "num_inference_steps",
							        "num_waveforms_per_prompt",
							        "generator",
							        "latents",
							        "output_type",
							        "return_dict",
							        "callback",
							        "callback_steps",
							    ]					)

							def       __A (  self:   List[Any]   )    ->				Dict:
												torch.manual_seed(0   )
												_A								= UNetaDConditionModel(
												    block_out_channels=(32, 64)		,     layers_per_block=2		,     sample_size=32		,     in_channels=4		,     out_channels=4		,     down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')		,     up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')		,     cross_attention_dim=(32, 64)		,     class_embed_type='''simple_projection'''		,     projection_class_embeddings_input_dim=32		,     class_embeddings_concat=__A		,     )
												_A								= DDIMScheduler(
												    beta_start=0.00_085		,     beta_end=0.012		,     beta_schedule='''scaled_linear'''		,     clip_sample=__A		,     set_alpha_to_one=__A		,     )
												torch.manual_seed(0   )
												_A								= AutoencoderKL(
												    block_out_channels=[32, 64]		,     in_channels=1		,     out_channels=1		,     down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']		,     up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']		,     latent_channels=4		,     )
												torch.manual_seed(0   )
												_A								= ClapTextConfig(
												    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=10_00		,     projection_dim=32		,     )
												_A								= ClapTextModelWithProjection(__A   )
												_A								= RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta'''		,     model_max_length=77   )

												_A								= SpeechTaHifiGanConfig(
												    model_in_dim=8		,     sampling_rate=1_60_00		,     upsample_initial_channel=16		,     upsample_rates=[2, 2]		,     upsample_kernel_sizes=[4, 4]		,     resblock_kernel_sizes=[3, 7]		,     resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]]		,     normalize_before=__A		,     )

												_A								= SpeechTaHifiGan(__A   )

												_A								= {
												    '''unet''': unet,
												    '''scheduler''': scheduler,
												    '''vae''': vae,
												    '''text_encoder''': text_encoder,
												    '''tokenizer''': tokenizer,
												    '''vocoder''': vocoder,
												}
												return components

							def       __A (  self:   Optional[int]		,     __A:   List[str]		,     __A:   List[str]=0   )    ->				Tuple:
												if str(__A   ).startswith('''mps'''   ):
																	_A								= torch.manual_seed(__A   )
												else:
																	_A								= torch.Generator(device=__A   ).manual_seed(__A   )
												_A								= {
												    '''prompt''': '''A hammer hitting a wooden surface''',
												    '''generator''': generator,
												    '''num_inference_steps''': 2,
												    '''guidance_scale''': 6.0,
												}
												return inputs

							def       __A (  self:   int   )    ->				Dict:
												_A								= '''cpu'''  # ensure determinism for the device-dependent torch.Generator

												_A								= self.get_dummy_components()
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= self.get_dummy_inputs(__A   )
												_A								= audioldm_pipe(**__A   )
												_A								= output.audios[0]

												assert audio.ndim == 1
												assert len(__A   ) == 2_56

												_A								= audio[:10]
												_A								= np.array(
												    [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033]   )

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

							def       __A (  self:   Optional[Any]   )    ->				Tuple:
												_A								= self.get_dummy_components()
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= self.get_dummy_inputs(__A   )
												_A								= 3 * [inputs['''prompt''']]

												# forward
												_A								= audioldm_pipe(**__A   )
												_A								= output.audios[0]

												_A								= self.get_dummy_inputs(__A   )
												_A								= 3 * [inputs.pop('''prompt'''   )]

												_A								= audioldm_pipe.tokenizer(
												    __A		,     padding='''max_length'''		,     max_length=audioldm_pipe.tokenizer.model_max_length		,     truncation=__A		,     return_tensors='''pt'''		,     )
												_A								= text_inputs['''input_ids'''].to(__A   )

												_A								= audioldm_pipe.text_encoder(
												    __A		,     )
												_A								= prompt_embeds.text_embeds
												# additional L_2 normalization over each hidden-state
												_A								= F.normalize(__A		,     dim=-1   )

												_A								= prompt_embeds

												# forward
												_A								= audioldm_pipe(**__A   )
												_A								= output.audios[0]

												assert np.abs(audio_a - audio_a   ).max() < 1e-2

							def       __A (  self:   Union[str, Any]   )    ->				Optional[Any]:
												_A								= self.get_dummy_components()
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= self.get_dummy_inputs(__A   )
												_A								= 3 * ['''this is a negative prompt''']
												_A								= negative_prompt
												_A								= 3 * [inputs['''prompt''']]

												# forward
												_A								= audioldm_pipe(**__A   )
												_A								= output.audios[0]

												_A								= self.get_dummy_inputs(__A   )
												_A								= 3 * [inputs.pop('''prompt'''   )]

												_A								= []
												for p in [prompt, negative_prompt]:
																	_A								= audioldm_pipe.tokenizer(
																	    __A		,     padding='''max_length'''		,     max_length=audioldm_pipe.tokenizer.model_max_length		,     truncation=__A		,     return_tensors='''pt'''		,     )
																	_A								= text_inputs['''input_ids'''].to(__A   )

																	_A								= audioldm_pipe.text_encoder(
																	    __A		,     )
																	_A								= text_embeds.text_embeds
																	# additional L_2 normalization over each hidden-state
																	_A								= F.normalize(__A		,     dim=-1   )

																	embeds.append(__A   )

												_A							,_A								= embeds

												# forward
												_A								= audioldm_pipe(**__A   )
												_A								= output.audios[0]

												assert np.abs(audio_a - audio_a   ).max() < 1e-2

							def       __A (  self:   int   )    ->				str:
												_A								= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
												_A								= self.get_dummy_components()
												_A								= PNDMScheduler(skip_prk_steps=__A   )
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= self.get_dummy_inputs(__A   )
												_A								= '''egg cracking'''
												_A								= audioldm_pipe(**__A		,     negative_prompt=__A   )
												_A								= output.audios[0]

												assert audio.ndim == 1
												assert len(__A   ) == 2_56

												_A								= audio[:10]
												_A								= np.array(
												    [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032]   )

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

							def       __A (  self:   Optional[Any]   )    ->				Union[str, Any]:
												_A								= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
												_A								= self.get_dummy_components()
												_A								= PNDMScheduler(skip_prk_steps=__A   )
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= '''A hammer hitting a wooden surface'''

												# test num_waveforms_per_prompt=1 (default)
												_A								= audioldm_pipe(__A		,     num_inference_steps=2   ).audios

												assert audios.shape == (1, 2_56)

												# test num_waveforms_per_prompt=1 (default) for batch of prompts
												_A								= 2
												_A								= audioldm_pipe([prompt] * batch_size		,     num_inference_steps=2   ).audios

												assert audios.shape == (batch_size, 2_56)

												# test num_waveforms_per_prompt for single prompt
												_A								= 2
												_A								= audioldm_pipe(__A		,     num_inference_steps=2		,     num_waveforms_per_prompt=__A   ).audios

												assert audios.shape == (num_waveforms_per_prompt, 2_56)

												# test num_waveforms_per_prompt for batch of prompts
												_A								= 2
												_A								= audioldm_pipe(
												    [prompt] * batch_size		,     num_inference_steps=2		,     num_waveforms_per_prompt=__A   ).audios

												assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_56)

							def       __A (  self:   Union[str, Any]   )    ->				Any:
												_A								= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
												_A								= self.get_dummy_components()
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )
												_A								= audioldm_pipe.vocoder.config.sampling_rate

												_A								= self.get_dummy_inputs(__A   )
												_A								= audioldm_pipe(audio_length_in_s=0.016		,     **__A   )
												_A								= output.audios[0]

												assert audio.ndim == 1
												assert len(__A   ) / vocoder_sampling_rate == 0.016

												_A								= audioldm_pipe(audio_length_in_s=0.032		,     **__A   )
												_A								= output.audios[0]

												assert audio.ndim == 1
												assert len(__A   ) / vocoder_sampling_rate == 0.032

							def       __A (  self:   str   )    ->				Any:
												_A								= self.get_dummy_components()
												_A								= AudioLDMPipeline(**__A   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= ['''hey''']

												_A								= audioldm_pipe(__A		,     num_inference_steps=1   )
												_A								= output.audios.shape
												assert audio_shape == (1, 2_56)

												_A								= audioldm_pipe.vocoder.config
												config.model_in_dim *= 2
												_A								= SpeechTaHifiGan(__A   ).to(__A   )
												_A								= audioldm_pipe(__A		,     num_inference_steps=1   )
												_A								= output.audios.shape
												# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
												assert audio_shape == (1, 2_56)

							def       __A (  self:   Union[str, Any]   )    ->				Optional[Any]:
												self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__A   )

							def       __A (  self:   int   )    ->				Union[str, Any]:
												self._test_inference_batch_single_identical(test_mean_pixel_difference=__A   )



							@unittest.skipIf(
							    torch_device != '''cuda''' or not is_xformers_available()		,     reason='''XFormers attention is only available with CUDA and `xformers` installed'''		,     )
							def       __A (  self:   Dict   )    ->				Optional[int]:
												self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__A   )





@slow
class 						SCREAMING_SNAKE_CASE				( unittest.TestCase					):





							"""simple docstring"""

							def       __A (  self:   List[str]   )    ->				Optional[int]:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()

							def       __A (  self:   int		,     __A:   Optional[Any]		,     __A:   str="cpu"		,     __A:   Dict=torch.floataa		,     __A:   Union[str, Any]=0   )    ->				Any:
												_A								= torch.Generator(device=__A   ).manual_seed(__A   )
												_A								= np.random.RandomState(__A   ).standard_normal((1, 8, 1_28, 16)   )
												_A								= torch.from_numpy(__A   ).to(device=__A		,     dtype=__A   )
												_A								= {
												    '''prompt''': '''A hammer hitting a wooden surface''',
												    '''latents''': latents,
												    '''generator''': generator,
												    '''num_inference_steps''': 3,
												    '''guidance_scale''': 2.5,
												}
												return inputs

							def       __A (  self:   Any   )    ->				int:
												_A								= AudioLDMPipeline.from_pretrained('''cvssp/audioldm'''   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= self.get_inputs(__A   )
												_A								= 25
												_A								= audioldm_pipe(**__A   ).audios[0]

												assert audio.ndim == 1
												assert len(__A   ) == 8_19_20

												_A								= audio[7_72_30:7_72_40]
												_A								= np.array(
												    [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315]   )
												_A								= np.abs(expected_slice - audio_slice   ).max()
												assert max_diff < 1e-2



							def       __A (  self:   Optional[Any]   )    ->				str:
												_A								= AudioLDMPipeline.from_pretrained('''cvssp/audioldm'''   )
												_A								= LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config   )
												_A								= audioldm_pipe.to(__A   )
												audioldm_pipe.set_progress_bar_config(disable=__A   )

												_A								= self.get_inputs(__A   )
												_A								= audioldm_pipe(**__A   ).audios[0]

												assert audio.ndim == 1
												assert len(__A   ) == 8_19_20

												_A								= audio[2_77_80:2_77_90]
												_A								= np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212]   )
												_A								= np.abs(expected_slice - audio_slice   ).max()
												assert max_diff < 3e-2











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

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput





class 						SCREAMING_SNAKE_CASE				( snake_case  ,	snake_case					):





							"""simple docstring"""

							A_						  =					1

							@register_to_config
							def __init__(  self:   Any		,     __A:   int = 10_00		,     __A:   Optional[Union[np.ndarray, List[float]]] = None   )    ->				List[str]:
												# set `betas`, `alphas`, `timesteps`
												self.set_timesteps(__A   )

												# standard deviation of the initial noise distribution
												_A								= 1.0

												# For now we only support F-PNDM, i.e. the runge-kutta method
												# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
												# mainly at formula (9), (12), (13) and the Algorithm 2.
												_A								= 4

												# running values
												_A								= []

							def       __A (  self:   str		,     __A:   int		,     __A:   Union[str, torch.device] = None   )    ->				int:
												_A								= num_inference_steps
												_A								= torch.linspace(1		,     0		,     num_inference_steps + 1   )[:-1]
												_A								= torch.cat([steps, torch.tensor([0.0]   )]   )

												if self.config.trained_betas is not None:
																	_A								= torch.tensor(self.config.trained_betas		,     dtype=torch.floataa   )
												else:
																	_A								= torch.sin(steps * math.pi / 2   ) ** 2

												_A								= (1.0 - self.betas**2) ** 0.5

												_A								= (torch.atana(self.betas		,     self.alphas   ) / math.pi * 2)[:-1]
												_A								= timesteps.to(__A   )

												_A								= []

							def       __A (  self:   Tuple		,     __A:   torch.FloatTensor		,     __A:   int		,     __A:   torch.FloatTensor		,     __A:   bool = True		,     )    ->				Union[SchedulerOutput, Tuple]:
												if self.num_inference_steps is None:
																	raise ValueError(
																	    '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler'''   )

												_A								= (self.timesteps == timestep).nonzero().item()
												_A								= timestep_index + 1

												_A								= sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
												self.ets.append(__A   )

												if len(self.ets   ) == 1:
																	_A								= self.ets[-1]
												elif len(self.ets   ) == 2:
																	_A								= (3 * self.ets[-1] - self.ets[-2]) / 2
												elif len(self.ets   ) == 3:
																	_A								= (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
												else:
																	_A								= (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])

												_A								= self._get_prev_sample(__A		,     __A		,     __A		,     __A   )

												if not return_dict:
																	return (prev_sample,)

												return SchedulerOutput(prev_sample=__A   )

							def       __A (  self:   Optional[int]		,     __A:   torch.FloatTensor		,     *__A:   Tuple		,     **__A:   List[Any]   )    ->				torch.FloatTensor:
												return sample

							def       __A (  self:   List[str]		,     __A:   Optional[Any]		,     __A:   Optional[Any]		,     __A:   Any		,     __A:   List[Any]   )    ->				List[Any]:
												_A								= self.alphas[timestep_index]
												_A								= self.betas[timestep_index]

												_A								= self.alphas[prev_timestep_index]
												_A								= self.betas[prev_timestep_index]

												_A								= (sample - sigma * ets) / max(__A		,     1e-8   )
												_A								= next_alpha * pred + ets * next_sigma

												return prev_sample



							def __len__(  self:   List[str]   )    ->				Dict:
												return self.config.num_train_timesteps



