

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        A__(a_,  unittest.TestCase							):
						"""simple docstring"""






						_A    :				Dict       					=			AudioLDMPipeline
						_A    :				Union[str, Any]       					=			TEXT_TO_AUDIO_PARAMS
						_A    :				int       					=			TEXT_TO_AUDIO_BATCH_PARAMS
						_A    :				Any       					=			frozenset(
						    [
						        '''num_inference_steps''',
						        '''num_waveforms_per_prompt''',
						        '''generator''',
						        '''latents''',
						        '''output_type''',
						        '''return_dict''',
						        '''callback''',
						        '''callback_steps''',
						    ]							)





						def 			UpperCamelCase__					(    self    )     -> Tuple:
									torch.manual_seed(0    )
									a_						:						Union[str, Any] 							= 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  ,      )
									a_						:						List[Any] 							= DDIMScheduler(
									    beta_start=0.0_0_0_8_5  ,      beta_end=0.0_1_2  ,      beta_schedule="""scaled_linear"""  ,      clip_sample=_lowercase  ,      set_alpha_to_one=_lowercase  ,      )
									torch.manual_seed(0    )
									a_						:						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    )
									a_						:						int 							= 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=1_000  ,      projection_dim=32  ,      )
									a_						:						List[Any] 							= ClapTextModelWithProjection(_lowercase    )
									a_						:						Optional[Any] 							= RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta"""  ,      model_max_length=77    )

									a_						:						Union[str, Any] 							= SpeechTaHifiGanConfig(
									    model_in_dim=8  ,      sampling_rate=16_000  ,      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  ,      )

									a_						:						List[Any] 							= SpeechTaHifiGan(_lowercase    )

									a_						:						Optional[Any] 							= {
									    """unet""": unet,
									    """scheduler""": scheduler,
									    """vae""": vae,
									    """text_encoder""": text_encoder,
									    """tokenizer""": tokenizer,
									    """vocoder""": vocoder,
									}
									return components





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





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						Union[str, Any] 							= """cpu"""  # ensure determinism for the device-dependent torch.Generator

									a_						:						Optional[Any] 							= self.get_dummy_components()
									a_						:						Union[str, Any] 							= AudioLDMPipeline(**_lowercase    )
									a_						:						Union[str, Any] 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						Optional[int] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						Union[str, Any] 							= audioldm_pipe(**_lowercase    )
									a_						:						List[Any] 							= output.audios[0]

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

									a_						:						str 							= audio[:10]
									a_						:						List[str] 							= 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    )     -> Optional[int]:
									a_						:						str 							= self.get_dummy_components()
									a_						:						str 							= AudioLDMPipeline(**_lowercase    )
									a_						:						Optional[Any] 							= audioldm_pipe.to(_lowercase    )
									a_						:						List[Any] 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						Optional[Any] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						str 							= 3 * [inputs["""prompt"""]]

									# forward
									a_						:						Any 							= audioldm_pipe(**_lowercase    )
									a_						:						str 							= output.audios[0]

									a_						:						List[str] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						Optional[Any] 							= 3 * [inputs.pop("""prompt"""    )]

									a_						:						Any 							= audioldm_pipe.tokenizer(
									    _lowercase  ,      padding="""max_length"""  ,      max_length=audioldm_pipe.tokenizer.model_max_length  ,      truncation=_lowercase  ,      return_tensors="""pt"""  ,      )
									a_						:						List[Any] 							= text_inputs["""input_ids"""].to(_lowercase    )

									a_						:						Dict 							= audioldm_pipe.text_encoder(
									    _lowercase  ,      )
									a_						:						int 							= prompt_embeds.text_embeds
									# additional L_2 normalization over each hidden-state
									a_						:						int 							= F.normalize(_lowercase  ,      dim=-1    )

									a_						:						Optional[Any] 							= prompt_embeds

									# forward
									a_						:						Optional[int] 							= audioldm_pipe(**_lowercase    )
									a_						:						Dict 							= output.audios[0]

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





						def 			UpperCamelCase__					(    self    )     -> Dict:
									a_						:						int 							= self.get_dummy_components()
									a_						:						Optional[Any] 							= AudioLDMPipeline(**_lowercase    )
									a_						:						Optional[int] 							= audioldm_pipe.to(_lowercase    )
									a_						:						Optional[int] 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						List[Any] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						Any 							= 3 * ["""this is a negative prompt"""]
									a_						:						str 							= negative_prompt
									a_						:						str 							= 3 * [inputs["""prompt"""]]

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

									a_						:						Optional[int] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						str 							= 3 * [inputs.pop("""prompt"""    )]

									a_						:						Optional[int] 							= []
									for p in [prompt, negative_prompt]:
												a_						:						Dict 							= audioldm_pipe.tokenizer(
												    _lowercase  ,      padding="""max_length"""  ,      max_length=audioldm_pipe.tokenizer.model_max_length  ,      truncation=_lowercase  ,      return_tensors="""pt"""  ,      )
												a_						:						Optional[int] 							= text_inputs["""input_ids"""].to(_lowercase    )

												a_						:						List[str] 							= audioldm_pipe.text_encoder(
												    _lowercase  ,      )
												a_						:						str 							= text_embeds.text_embeds
												# additional L_2 normalization over each hidden-state
												a_						:						Union[str, Any] 							= F.normalize(_lowercase  ,      dim=-1    )

												embeds.append(_lowercase    )

									a_							,					a_						:						Optional[int] 							= embeds

									# forward
									a_						:						List[Any] 							= audioldm_pipe(**_lowercase    )
									a_						:						Union[str, Any] 							= output.audios[0]

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





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						List[Any] 							= """cpu"""  # ensure determinism for the device-dependent torch.Generator
									a_						:						Tuple 							= self.get_dummy_components()
									a_						:						Union[str, Any] 							= PNDMScheduler(skip_prk_steps=_lowercase    )
									a_						:						Dict 							= AudioLDMPipeline(**_lowercase    )
									a_						:						int 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						List[Any] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						Tuple 							= """egg cracking"""
									a_						:						Union[str, Any] 							= audioldm_pipe(**_lowercase  ,      negative_prompt=_lowercase    )
									a_						:						Dict 							= output.audios[0]

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

									a_						:						List[str] 							= audio[:10]
									a_						:						Dict 							= 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    )     -> Any:
									a_						:						int 							= """cpu"""  # ensure determinism for the device-dependent torch.Generator
									a_						:						Any 							= self.get_dummy_components()
									a_						:						Any 							= PNDMScheduler(skip_prk_steps=_lowercase    )
									a_						:						Optional[Any] 							= AudioLDMPipeline(**_lowercase    )
									a_						:						List[str] 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						int 							= """A hammer hitting a wooden surface"""

									# test num_waveforms_per_prompt=1 (default)
									a_						:						Union[str, 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
									a_						:						Tuple 							= 2
									a_						:						int 							= audioldm_pipe([prompt] * batch_size  ,      num_inference_steps=2    ).audios

									assert audios.shape == (batch_size, 256)

									# test num_waveforms_per_prompt for single prompt
									a_						:						str 							= 2
									a_						:						Optional[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
									a_						:						Union[str, Any] 							= 2
									a_						:						Tuple 							= 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 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									a_						:						Optional[Any] 							= """cpu"""  # ensure determinism for the device-dependent torch.Generator
									a_						:						List[str] 							= self.get_dummy_components()
									a_						:						str 							= AudioLDMPipeline(**_lowercase    )
									a_						:						List[str] 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )
									a_						:						int 							= audioldm_pipe.vocoder.config.sampling_rate

									a_						:						Union[str, Any] 							= self.get_dummy_inputs(_lowercase    )
									a_						:						Union[str, Any] 							= audioldm_pipe(audio_length_in_s=0.0_1_6  ,      **_lowercase    )
									a_						:						Tuple 							= output.audios[0]

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

									a_						:						Optional[Any] 							= audioldm_pipe(audio_length_in_s=0.0_3_2  ,      **_lowercase    )
									a_						:						List[Any] 							= output.audios[0]

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





						def 			UpperCamelCase__					(    self    )     -> Tuple:
									a_						:						Dict 							= self.get_dummy_components()
									a_						:						str 							= AudioLDMPipeline(**_lowercase    )
									a_						:						Dict 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						List[Any] 							= ["""hey"""]

									a_						:						Optional[int] 							= audioldm_pipe(_lowercase  ,      num_inference_steps=1    )
									a_						:						Optional[int] 							= output.audios.shape
									assert audio_shape == (1, 256)

									a_						:						Tuple 							= audioldm_pipe.vocoder.config
									config.model_in_dim *= 2
									a_						:						Optional[Any] 							= SpeechTaHifiGan(_lowercase    ).to(_lowercase    )
									a_						:						Union[str, Any] 							= audioldm_pipe(_lowercase  ,      num_inference_steps=1    )
									a_						:						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 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> int:
									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 			UpperCamelCase__					(    self    )     -> Dict:
									self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_lowercase    )







@slow
class        A__(unittest.TestCase							):
						"""simple docstring"""






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





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





						def 			UpperCamelCase__					(    self    )     -> str:
									a_						:						Optional[int] 							= AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""    )
									a_						:						Optional[int] 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						Optional[Any] 							= self.get_inputs(_lowercase    )
									a_						:						List[Any] 							= 25
									a_						:						List[Any] 							= audioldm_pipe(**_lowercase    ).audios[0]

									assert audio.ndim == 1
									assert len(_lowercase    ) == 81_920

									a_						:						Tuple 							= audio[77_230:77_240]
									a_						:						Optional[int] 							= 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]    )
									a_						:						Optional[int] 							= np.abs(expected_slice - audio_slice    ).max()
									assert max_diff < 1e-2





						def 			UpperCamelCase__					(    self    )     -> int:
									a_						:						List[str] 							= AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""    )
									a_						:						str 							= LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config    )
									a_						:						Tuple 							= audioldm_pipe.to(_lowercase    )
									audioldm_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						List[Any] 							= self.get_inputs(_lowercase    )
									a_						:						str 							= audioldm_pipe(**_lowercase    ).audios[0]

									assert audio.ndim == 1
									assert len(_lowercase    ) == 81_920

									a_						:						Dict 							= audio[27_780:27_790]
									a_						:						Union[str, Any] 							= 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]    )
									a_						:						Tuple 							= np.abs(expected_slice - audio_slice    ).max()
									assert max_diff < 3e-2





from __future__ import annotations

# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
__snake_case				:      Optional[Any]   		=			10


def 					_UpperCAmelCase				(						a__  ,	a__  ,	a__  ,	a__):

			'''simple docstring'''



			for i in range(a__  ,	a__):
						if array[i] == target:
									return i
			return -1


def 					_UpperCAmelCase				(						a__  ,	a__):

			'''simple docstring'''



			a_						:						Any 							= 0
			a_						:						List[str] 							= len(a__)
			while left <= right:
						if right - left < precision:
									return lin_search(a__  ,	a__  ,	a__  ,	a__)

						a_						:						Dict 							= (left + right) // 3 + 1
						a_						:						Optional[Any] 							= 2 * (left + right) // 3 + 1

						if array[one_third] == target:
									return one_third
						elif array[two_third] == target:
									return two_third

						elif target < array[one_third]:
									a_						:						int 							= one_third - 1
						elif array[two_third] < target:
									a_						:						Any 							= two_third + 1

						else:
									a_						:						Optional[int] 							= one_third + 1
									a_						:						int 							= two_third - 1
			else:
						return -1


def 					_UpperCAmelCase				(						a__  ,	a__  ,	a__  ,	a__):

			'''simple docstring'''



			if left < right:
						if right - left < precision:
									return lin_search(a__  ,	a__  ,	a__  ,	a__)
						a_						:						Optional[int] 							= (left + right) // 3 + 1
						a_						:						Union[str, Any] 							= 2 * (left + right) // 3 + 1

						if array[one_third] == target:
									return one_third
						elif array[two_third] == target:
									return two_third

						elif target < array[one_third]:
									return rec_ternary_search(a__  ,	one_third - 1  ,	a__  ,	a__)
						elif array[two_third] < target:
									return rec_ternary_search(two_third + 1  ,	a__  ,	a__  ,	a__)
						else:
									return rec_ternary_search(one_third + 1  ,	two_third - 1  ,	a__  ,	a__)
			else:
						return -1


if __name__ == "__main__":
	import doctest

	doctest.testmod()

	__snake_case				:      Optional[int]   		=			input("""Enter numbers separated by comma:\n""").strip()
	__snake_case				:      Optional[int]   		=			[int(item.strip()) for item in user_input.split(""",""")]
	assert collection == sorted(collection), F"List must be ordered.\n{collection}."
	__snake_case				:      int   		=			int(input("""Enter the number to be found in the list:\n""").strip())
	__snake_case				:      List[Any]   		=			ite_ternary_search(collection, target)
	__snake_case				:      Optional[int]   		=			rec_ternary_search(0, len(collection) - 1, collection, target)
	if resulta != -1:
		print(F"""Iterative search: {target} found at positions: {resulta}""")
		print(F"""Recursive search: {target} found at positions: {resulta}""")
	else:
		print("""Not found""")


