






'''simple docstring'''

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       UpperCAmelCase (						__lowercase			,       unittest.TestCase  ):
		UpperCAmelCase					:	Any 			=		AudioLDMPipeline
		UpperCAmelCase					:	Any 			=		TEXT_TO_AUDIO_PARAMS
		UpperCAmelCase					:	Any 			=		TEXT_TO_AUDIO_BATCH_PARAMS
		UpperCAmelCase					:	Dict 			=		frozenset(
		    [
		        '''num_inference_steps''',
		        '''num_waveforms_per_prompt''',
		        '''generator''',
		        '''latents''',
		        '''output_type''',
		        '''return_dict''',
		        '''callback''',
		        '''callback_steps''',
		    ]  )




		def 				UpperCAmelCase__   (self      :	int				)					-> int:
						torch.manual_seed(0				)
						lowercase         = UNetaDConditionModel(
						    block_out_channels=(3_2, 6_4)							,			layers_per_block=2							,			sample_size=3_2							,			in_channels=4							,			out_channels=4							,			down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")							,			up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")							,			cross_attention_dim=(3_2, 6_4)							,			class_embed_type="simple_projection"							,			projection_class_embeddings_input_dim=3_2							,			class_embeddings_concat=A__							,			)
						lowercase         = DDIMScheduler(
						    beta_start=0.0_0_0_8_5							,			beta_end=0.0_1_2							,			beta_schedule="scaled_linear"							,			clip_sample=A__							,			set_alpha_to_one=A__							,			)
						torch.manual_seed(0				)
						lowercase         = AutoencoderKL(
						    block_out_channels=[3_2, 6_4]							,			in_channels=1							,			out_channels=1							,			down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]							,			up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]							,			latent_channels=4							,			)
						torch.manual_seed(0				)
						lowercase         = ClapTextConfig(
						    bos_token_id=0							,			eos_token_id=2							,			hidden_size=3_2							,			intermediate_size=3_7							,			layer_norm_eps=1e-05							,			num_attention_heads=4							,			num_hidden_layers=5							,			pad_token_id=1							,			vocab_size=1_0_0_0							,			projection_dim=3_2							,			)
						lowercase         = ClapTextModelWithProjection(A__				)
						lowercase         = RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta"							,			model_max_length=7_7				)

						lowercase         = SpeechTaHifiGanConfig(
						    model_in_dim=8							,			sampling_rate=1_6_0_0_0							,			upsample_initial_channel=1_6							,			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__							,			)

						lowercase         = SpeechTaHifiGan(A__				)

						lowercase         = {
						    "unet": unet,
						    "scheduler": scheduler,
						    "vae": vae,
						    "text_encoder": text_encoder,
						    "tokenizer": tokenizer,
						    "vocoder": vocoder,
						}
						return components




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




		def 				UpperCAmelCase__   (self      :	int				)					-> Any:
						lowercase         = "cpu"  # ensure determinism for the device-dependent torch.Generator

						lowercase         = self.get_dummy_components()
						lowercase         = AudioLDMPipeline(**A__				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = audioldm_pipe(**A__				)
						lowercase         = output.audios[0]

						assert audio.ndim == 1
						assert len(A__				) == 2_5_6

						lowercase         = audio[:1_0]
						lowercase         = np.array(
						    [-0.0_0_5_0, 0.0_0_5_0, -0.0_0_6_0, 0.0_0_3_3, -0.0_0_2_6, 0.0_0_3_3, -0.0_0_2_7, 0.0_0_3_3, -0.0_0_2_8, 0.0_0_3_3]				)

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




		def 				UpperCAmelCase__   (self      :	Dict				)					-> str:
						lowercase         = self.get_dummy_components()
						lowercase         = AudioLDMPipeline(**A__				)
						lowercase         = audioldm_pipe.to(A__				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = 3 * [inputs["prompt"]]

						# forward
						lowercase         = audioldm_pipe(**A__				)
						lowercase         = output.audios[0]

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = 3 * [inputs.pop("prompt"				)]

						lowercase         = audioldm_pipe.tokenizer(
						    A__							,			padding="max_length"							,			max_length=audioldm_pipe.tokenizer.model_max_length							,			truncation=A__							,			return_tensors="pt"							,			)
						lowercase         = text_inputs["input_ids"].to(A__				)

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

						lowercase         = prompt_embeds

						# forward
						lowercase         = audioldm_pipe(**A__				)
						lowercase         = output.audios[0]

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




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

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = 3 * ["this is a negative prompt"]
						lowercase         = negative_prompt
						lowercase         = 3 * [inputs["prompt"]]

						# forward
						lowercase         = audioldm_pipe(**A__				)
						lowercase         = output.audios[0]

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = 3 * [inputs.pop("prompt"				)]

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

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

										embeds.append(A__				)

						lowercase         = embeds

						# forward
						lowercase         = audioldm_pipe(**A__				)
						lowercase         = output.audios[0]

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




		def 				UpperCAmelCase__   (self      :	Dict				)					-> int:
						lowercase         = "cpu"  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components()
						lowercase         = PNDMScheduler(skip_prk_steps=A__				)
						lowercase         = AudioLDMPipeline(**A__				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = "egg cracking"
						lowercase         = audioldm_pipe(**A__							,			negative_prompt=A__				)
						lowercase         = output.audios[0]

						assert audio.ndim == 1
						assert len(A__				) == 2_5_6

						lowercase         = audio[:1_0]
						lowercase         = np.array(
						    [-0.0_0_5_1, 0.0_0_5_0, -0.0_0_6_0, 0.0_0_3_4, -0.0_0_2_6, 0.0_0_3_3, -0.0_0_2_7, 0.0_0_3_3, -0.0_0_2_8, 0.0_0_3_2]				)

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




		def 				UpperCAmelCase__   (self      :	List[Any]				)					-> List[str]:
						lowercase         = "cpu"  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components()
						lowercase         = PNDMScheduler(skip_prk_steps=A__				)
						lowercase         = AudioLDMPipeline(**A__				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = "A hammer hitting a wooden surface"

						# test num_waveforms_per_prompt=1 (default)
						lowercase         = audioldm_pipe(A__							,			num_inference_steps=2				).audios

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

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

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

						# test num_waveforms_per_prompt for single prompt
						lowercase         = 2
						lowercase         = audioldm_pipe(A__							,			num_inference_steps=2							,			num_waveforms_per_prompt=A__				).audios

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

						# test num_waveforms_per_prompt for batch of prompts
						lowercase         = 2
						lowercase         = 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_5_6)




		def 				UpperCAmelCase__   (self      :	List[Any]				)					-> str:
						lowercase         = "cpu"  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components()
						lowercase         = AudioLDMPipeline(**A__				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)
						lowercase         = audioldm_pipe.vocoder.config.sampling_rate

						lowercase         = self.get_dummy_inputs(A__				)
						lowercase         = audioldm_pipe(audio_length_in_s=0.0_1_6							,			**A__				)
						lowercase         = output.audios[0]

						assert audio.ndim == 1
						assert len(A__				) / vocoder_sampling_rate == 0.0_1_6

						lowercase         = audioldm_pipe(audio_length_in_s=0.0_3_2							,			**A__				)
						lowercase         = output.audios[0]

						assert audio.ndim == 1
						assert len(A__				) / vocoder_sampling_rate == 0.0_3_2




		def 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> Any:
						lowercase         = self.get_dummy_components()
						lowercase         = AudioLDMPipeline(**A__				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = ["hey"]

						lowercase         = audioldm_pipe(A__							,			num_inference_steps=1				)
						lowercase         = output.audios.shape
						assert audio_shape == (1, 2_5_6)

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




		def 				UpperCAmelCase__   (self      :	Union[str, Any]				)					-> List[str]:
						self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__				)




		def 				UpperCAmelCase__   (self      :	Dict				)					-> List[str]:
						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 				UpperCAmelCase__   (self      :	List[str]				)					-> Union[str, Any]:
						self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__				)




@slow
class       UpperCAmelCase (						unittest.TestCase  ):




		def 				UpperCAmelCase__   (self      :	Union[str, Any]				)					-> List[Any]:
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()




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




		def 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> Optional[Any]:
						lowercase         = AudioLDMPipeline.from_pretrained("cvssp/audioldm"				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = self.get_inputs(A__				)
						lowercase         = 2_5
						lowercase         = audioldm_pipe(**A__				).audios[0]

						assert audio.ndim == 1
						assert len(A__				) == 8_1_9_2_0

						lowercase         = audio[7_7_2_3_0:7_7_2_4_0]
						lowercase         = np.array(
						    [-0.4_8_8_4, -0.4_6_0_7, 0.0_0_2_3, 0.5_0_0_7, 0.5_8_9_6, 0.5_1_5_1, 0.3_8_1_3, -0.0_2_0_8, -0.3_6_8_7, -0.4_3_1_5]				)
						lowercase         = np.abs(expected_slice - audio_slice				).max()
						assert max_diff < 1e-2





		def 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> Union[str, Any]:
						lowercase         = AudioLDMPipeline.from_pretrained("cvssp/audioldm"				)
						lowercase         = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config				)
						lowercase         = audioldm_pipe.to(A__				)
						audioldm_pipe.set_progress_bar_config(disable=A__				)

						lowercase         = self.get_inputs(A__				)
						lowercase         = audioldm_pipe(**A__				).audios[0]

						assert audio.ndim == 1
						assert len(A__				) == 8_1_9_2_0

						lowercase         = audio[2_7_7_8_0:2_7_7_9_0]
						lowercase         = np.array([-0.2_1_3_1, -0.0_8_7_3, -0.0_1_2_4, -0.0_1_8_9, 0.0_5_6_9, 0.1_3_7_3, 0.1_8_8_3, 0.2_8_8_6, 0.3_2_9_7, 0.2_2_1_2]				)
						lowercase         = np.abs(expected_slice - audio_slice				).max()
						assert max_diff < 3e-2











'''simple docstring'''

__lowerCamelCase : str											=			8.314_4598







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_							):

				"""simple docstring"""






				if temperature < 0:
								raise Exception("Temperature cannot be less than 0 K"							)
				if molar_mass <= 0:
								raise Exception("Molar mass cannot be less than or equal to 0 kg/mol"							)
				else:
								return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5


if __name__ == "__main__":
			import doctest

			# run doctest
			doctest.testmod()

			# example
			__lowerCamelCase : Optional[Any]											=			300
			__lowerCamelCase : Tuple											=			28
			__lowerCamelCase : str											=			rms_speed_of_molecule(temperature, molar_mass)
			print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")




