


'''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 _lowerCamelCase       (						lowerCAmelCase__		,     unittest.TestCase							):



		'''simple docstring'''







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







		def    __lowerCAmelCase		(					self		:						List[Any]			)  -> Any:
			torch.manual_seed(0			)
			__magic_name__       :    Dict     	=     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=lowercase_  ,     )
			__magic_name__       :    List[Any]     	=     DDIMScheduler(
			    beta_start=0.0_0085  ,     beta_end=0.012  ,     beta_schedule='scaled_linear'  ,     clip_sample=lowercase_  ,     set_alpha_to_one=lowercase_  ,     )
			torch.manual_seed(0			)
			__magic_name__       :    List[Any]     	=     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			)
			__magic_name__       :    Dict     	=     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=1000  ,     projection_dim=32  ,     )
			__magic_name__       :    Union[str, Any]     	=     ClapTextModelWithProjection(lowercase_			)
			__magic_name__       :    Dict     	=     RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta'  ,     model_max_length=77			)

			__magic_name__       :    int     	=     SpeechTaHifiGanConfig(
			    model_in_dim=8  ,     sampling_rate=16000  ,     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=lowercase_  ,     )

			__magic_name__       :    List[str]     	=     SpeechTaHifiGan(lowercase_			)

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







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







		def    __lowerCAmelCase		(					self		:						Tuple			)  -> List[str]:
			__magic_name__       :    int     	=     '''cpu'''  # ensure determinism for the device-dependent torch.Generator

			__magic_name__       :    Tuple     	=     self.get_dummy_components()
			__magic_name__       :    Tuple     	=     AudioLDMPipeline(**lowercase_			)
			__magic_name__       :    Any     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    List[Any]     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    List[str]     	=     audioldm_pipe(**lowercase_			)
			__magic_name__       :    Any     	=     output.audios[0]

			assert audio.ndim == 1
			assert len(lowercase_			) == 256

			__magic_name__       :    List[Any]     	=     audio[:10]
			__magic_name__       :    Tuple     	=     np.array(
			    [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033]			)

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







		def    __lowerCAmelCase		(					self		:						Optional[Any]			)  -> Optional[int]:
			__magic_name__       :    Tuple     	=     self.get_dummy_components()
			__magic_name__       :    str     	=     AudioLDMPipeline(**lowercase_			)
			__magic_name__       :    Optional[int]     	=     audioldm_pipe.to(lowercase_			)
			__magic_name__       :    Optional[int]     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    str     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    Optional[int]     	=     3 * [inputs['''prompt''']]

			# forward
			__magic_name__       :    List[Any]     	=     audioldm_pipe(**lowercase_			)
			__magic_name__       :    Optional[int]     	=     output.audios[0]

			__magic_name__       :    Tuple     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    str     	=     3 * [inputs.pop('prompt'			)]

			__magic_name__       :    str     	=     audioldm_pipe.tokenizer(
			    lowercase_  ,     padding='max_length'  ,     max_length=audioldm_pipe.tokenizer.model_max_length  ,     truncation=lowercase_  ,     return_tensors='pt'  ,     )
			__magic_name__       :    int     	=     text_inputs['''input_ids'''].to(lowercase_			)

			__magic_name__       :    Tuple     	=     audioldm_pipe.text_encoder(
			    lowercase_  ,     )
			__magic_name__       :    Optional[int]     	=     prompt_embeds.text_embeds
			# additional L_2 normalization over each hidden-state
			__magic_name__       :    int     	=     F.normalize(lowercase_  ,     dim=-1			)

			__magic_name__       :    Tuple     	=     prompt_embeds

			# forward
			__magic_name__       :    Dict     	=     audioldm_pipe(**lowercase_			)
			__magic_name__       :    List[Any]     	=     output.audios[0]

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







		def    __lowerCAmelCase		(					self		:						List[Any]			)  -> Optional[Any]:
			__magic_name__       :    Dict     	=     self.get_dummy_components()
			__magic_name__       :    int     	=     AudioLDMPipeline(**lowercase_			)
			__magic_name__       :    Tuple     	=     audioldm_pipe.to(lowercase_			)
			__magic_name__       :    Union[str, Any]     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    Tuple     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    int     	=     3 * ['''this is a negative prompt''']
			__magic_name__       :    int     	=     negative_prompt
			__magic_name__       :    Union[str, Any]     	=     3 * [inputs['''prompt''']]

			# forward
			__magic_name__       :    Union[str, Any]     	=     audioldm_pipe(**lowercase_			)
			__magic_name__       :    Any     	=     output.audios[0]

			__magic_name__       :    Optional[int]     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    Any     	=     3 * [inputs.pop('prompt'			)]

			__magic_name__       :    List[Any]     	=     []
			for p in [prompt, negative_prompt]:
				__magic_name__       :    Union[str, Any]     	=     audioldm_pipe.tokenizer(
				    lowercase_  ,     padding='max_length'  ,     max_length=audioldm_pipe.tokenizer.model_max_length  ,     truncation=lowercase_  ,     return_tensors='pt'  ,     )
				__magic_name__       :    str     	=     text_inputs['''input_ids'''].to(lowercase_			)

				__magic_name__       :    Optional[Any]     	=     audioldm_pipe.text_encoder(
				    lowercase_  ,     )
				__magic_name__       :    Tuple     	=     text_embeds.text_embeds
				# additional L_2 normalization over each hidden-state
				__magic_name__       :    List[str]     	=     F.normalize(lowercase_  ,     dim=-1			)

				embeds.append(lowercase_			)

			__magic_name__       :    str     	=     embeds

			# forward
			__magic_name__       :    Optional[Any]     	=     audioldm_pipe(**lowercase_			)
			__magic_name__       :    int     	=     output.audios[0]

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







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

			__magic_name__       :    Union[str, Any]     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    Tuple     	=     '''egg cracking'''
			__magic_name__       :    Optional[int]     	=     audioldm_pipe(**lowercase_  ,     negative_prompt=lowercase_			)
			__magic_name__       :    Any     	=     output.audios[0]

			assert audio.ndim == 1
			assert len(lowercase_			) == 256

			__magic_name__       :    int     	=     audio[:10]
			__magic_name__       :    Union[str, Any]     	=     np.array(
			    [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032]			)

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







		def    __lowerCAmelCase		(					self		:						List[str]			)  -> Tuple:
			__magic_name__       :    List[Any]     	=     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			__magic_name__       :    Union[str, Any]     	=     self.get_dummy_components()
			__magic_name__       :    Dict     	=     PNDMScheduler(skip_prk_steps=lowercase_			)
			__magic_name__       :    Any     	=     AudioLDMPipeline(**lowercase_			)
			__magic_name__       :    Any     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    int     	=     '''A hammer hitting a wooden surface'''

			# test num_waveforms_per_prompt=1 (default)
			__magic_name__       :    Optional[Any]     	=     audioldm_pipe(lowercase_  ,     num_inference_steps=2			).audios

			assert audios.shape == (1, 256)

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

			assert audios.shape == (batch_size, 256)

			# test num_waveforms_per_prompt for single prompt
			__magic_name__       :    List[str]     	=     2
			__magic_name__       :    Union[str, Any]     	=     audioldm_pipe(lowercase_  ,     num_inference_steps=2  ,     num_waveforms_per_prompt=lowercase_			).audios

			assert audios.shape == (num_waveforms_per_prompt, 256)

			# test num_waveforms_per_prompt for batch of prompts
			__magic_name__       :    List[str]     	=     2
			__magic_name__       :    Dict     	=     audioldm_pipe(
			    [prompt] * batch_size  ,     num_inference_steps=2  ,     num_waveforms_per_prompt=lowercase_			).audios

			assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)







		def    __lowerCAmelCase		(					self		:						int			)  -> Tuple:
			__magic_name__       :    int     	=     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			__magic_name__       :    Dict     	=     self.get_dummy_components()
			__magic_name__       :    Optional[Any]     	=     AudioLDMPipeline(**lowercase_			)
			__magic_name__       :    str     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)
			__magic_name__       :    Optional[Any]     	=     audioldm_pipe.vocoder.config.sampling_rate

			__magic_name__       :    Any     	=     self.get_dummy_inputs(lowercase_			)
			__magic_name__       :    Tuple     	=     audioldm_pipe(audio_length_in_s=0.016  ,     **lowercase_			)
			__magic_name__       :    Optional[Any]     	=     output.audios[0]

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

			__magic_name__       :    List[str]     	=     audioldm_pipe(audio_length_in_s=0.032  ,     **lowercase_			)
			__magic_name__       :    Tuple     	=     output.audios[0]

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







		def    __lowerCAmelCase		(					self		:						Any			)  -> int:
			__magic_name__       :    List[str]     	=     self.get_dummy_components()
			__magic_name__       :    str     	=     AudioLDMPipeline(**lowercase_			)
			__magic_name__       :    Optional[int]     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    int     	=     ['''hey''']

			__magic_name__       :    int     	=     audioldm_pipe(lowercase_  ,     num_inference_steps=1			)
			__magic_name__       :    Optional[Any]     	=     output.audios.shape
			assert audio_shape == (1, 256)

			__magic_name__       :    List[str]     	=     audioldm_pipe.vocoder.config
			config.model_in_dim *= 2
			__magic_name__       :    str     	=     SpeechTaHifiGan(lowercase_			).to(lowercase_			)
			__magic_name__       :    List[str]     	=     audioldm_pipe(lowercase_  ,     num_inference_steps=1			)
			__magic_name__       :    List[str]     	=     output.audios.shape
			# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
			assert audio_shape == (1, 256)







		def    __lowerCAmelCase		(					self		:						List[Any]			)  -> Tuple:
			self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowercase_			)







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







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







@slow
class _lowerCamelCase       (						unittest.TestCase							):



		'''simple docstring'''







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







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







		def    __lowerCAmelCase		(					self		:						List[Any]			)  -> Tuple:
			__magic_name__       :    Optional[int]     	=     AudioLDMPipeline.from_pretrained('cvssp/audioldm'			)
			__magic_name__       :    List[str]     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    Optional[Any]     	=     self.get_inputs(lowercase_			)
			__magic_name__       :    Tuple     	=     25
			__magic_name__       :    int     	=     audioldm_pipe(**lowercase_			).audios[0]

			assert audio.ndim == 1
			assert len(lowercase_			) == 81920

			__magic_name__       :    Tuple     	=     audio[77230:77240]
			__magic_name__       :    Any     	=     np.array(
			    [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315]			)
			__magic_name__       :    Union[str, Any]     	=     np.abs(expected_slice - audio_slice			).max()
			assert max_diff < 1E-2







		def    __lowerCAmelCase		(					self		:						Union[str, Any]			)  -> Union[str, Any]:
			__magic_name__       :    Optional[int]     	=     AudioLDMPipeline.from_pretrained('cvssp/audioldm'			)
			__magic_name__       :    Dict     	=     LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config			)
			__magic_name__       :    List[Any]     	=     audioldm_pipe.to(lowercase_			)
			audioldm_pipe.set_progress_bar_config(disable=lowercase_			)

			__magic_name__       :    str     	=     self.get_inputs(lowercase_			)
			__magic_name__       :    Tuple     	=     audioldm_pipe(**lowercase_			).audios[0]

			assert audio.ndim == 1
			assert len(lowercase_			) == 81920

			__magic_name__       :    Dict     	=     audio[27780:27790]
			__magic_name__       :    Optional[Any]     	=     np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212]			)
			__magic_name__       :    int     	=     np.abs(expected_slice - audio_slice			).max()
			assert max_diff < 3E-2




"""simple docstring"""

from __future__ import annotations




def __lowercase			(							_a		,			_a		,			_a		,			):
    if (stress, tangential_force, area).count(0    ) != 1:
        raise ValueError('''You cannot supply more or less than 2 values'''    )
    elif stress < 0:
        raise ValueError('''Stress cannot be negative'''    )
    elif tangential_force < 0:
        raise ValueError('''Tangential Force cannot be negative'''    )
    elif area < 0:
        raise ValueError('''Area cannot be negative'''    )
    elif stress == 0:
        return (
            "stress",
            tangential_force / area,
        )
    elif tangential_force == 0:
        return (
            "tangential_force",
            stress * area,
        )
    else:
        return (
            "area",
            tangential_force / stress,
        )


if __name__ == "__main__":
     import doctest

     doctest.testmod()





