



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__					(  __A ,				unittest.TestCase       ):
				A_   :     Optional[Any]								=     AudioLDMPipeline
				A_   :     Any								=     TEXT_TO_AUDIO_PARAMS
				A_   :     Tuple								=     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      :  Optional[int]       )		->     Union[str, Any]:
											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=__UpperCamelCase						, )
											A      						=    DDIMScheduler(
											    beta_start=0.0_0_0_8_5						, beta_end=0.0_1_2						, beta_schedule='scaled_linear'						, clip_sample=__UpperCamelCase						, set_alpha_to_one=__UpperCamelCase						, )
											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=1_000						, projection_dim=32						, )
											A      						=    ClapTextModelWithProjection(__UpperCamelCase       )
											A      						=    RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta'						, model_max_length=77       )

											A      						=    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=__UpperCamelCase						, )

											A      						=    SpeechTaHifiGan(__UpperCamelCase       )

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


				def __UpperCamelCase						(							self      :  List[Any]						, __UpperCamelCase      :  Any						, __UpperCamelCase      :  Optional[Any]=0       )		->     Union[str, Any]:

											if str(__UpperCamelCase       ).startswith('mps'       ):
																		A      						=    torch.manual_seed(__UpperCamelCase       )
											else:
																		A      						=    torch.Generator(device=__UpperCamelCase       ).manual_seed(__UpperCamelCase       )
											A      						=    {
											    '''prompt''': '''A hammer hitting a wooden surface''',
											    '''generator''': generator,
											    '''num_inference_steps''': 2,
											    '''guidance_scale''': 6.0,
											}
											return inputs


				def __UpperCamelCase						(							self      :  str       )		->     Dict:
											A      						=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator

											A      						=    self.get_dummy_components()
											A      						=    AudioLDMPipeline(**__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

											A      						=    self.get_dummy_inputs(__UpperCamelCase       )
											A      						=    audioldm_pipe(**__UpperCamelCase       )
											A      						=    output.audios[0]

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

											A      						=    audio[:10]
											A      						=    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      :  Tuple       )		->     Optional[int]:
											A      						=    self.get_dummy_components()
											A      						=    AudioLDMPipeline(**__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

											A      						=    self.get_dummy_inputs(__UpperCamelCase       )
											A      						=    3 * [inputs['''prompt''']]

											# forward
											A      						=    audioldm_pipe(**__UpperCamelCase       )
											A      						=    output.audios[0]

											A      						=    self.get_dummy_inputs(__UpperCamelCase       )
											A      						=    3 * [inputs.pop('prompt'       )]

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

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

											A      						=    prompt_embeds

											# forward
											A      						=    audioldm_pipe(**__UpperCamelCase       )
											A      						=    output.audios[0]

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


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     Dict:
											A      						=    self.get_dummy_components()
											A      						=    AudioLDMPipeline(**__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

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

											# forward
											A      						=    audioldm_pipe(**__UpperCamelCase       )
											A      						=    output.audios[0]

											A      						=    self.get_dummy_inputs(__UpperCamelCase       )
											A      						=    3 * [inputs.pop('prompt'       )]

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

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

																		embeds.append(__UpperCamelCase       )

											A      						=    embeds

											# forward
											A      						=    audioldm_pipe(**__UpperCamelCase       )
											A      						=    output.audios[0]

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


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

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

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

											A      						=    audio[:10]
											A      						=    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      :  str       )		->     Union[str, Any]:
											A      						=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
											A      						=    self.get_dummy_components()
											A      						=    PNDMScheduler(skip_prk_steps=__UpperCamelCase       )
											A      						=    AudioLDMPipeline(**__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

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

											# test num_waveforms_per_prompt=1 (default)
											A      						=    audioldm_pipe(__UpperCamelCase						, num_inference_steps=2       ).audios

											assert audios.shape == (1, 256)

											# 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, 256)

											# test num_waveforms_per_prompt for single prompt
											A      						=    2
											A      						=    audioldm_pipe(__UpperCamelCase						, num_inference_steps=2						, num_waveforms_per_prompt=__UpperCamelCase       ).audios

											assert audios.shape == (num_waveforms_per_prompt, 256)

											# 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=__UpperCamelCase       ).audios

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


				def __UpperCamelCase						(							self      :  Tuple       )		->     str:
											A      						=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
											A      						=    self.get_dummy_components()
											A      						=    AudioLDMPipeline(**__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )
											A      						=    audioldm_pipe.vocoder.config.sampling_rate

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

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

											A      						=    audioldm_pipe(audio_length_in_s=0.0_3_2						, **__UpperCamelCase       )
											A      						=    output.audios[0]

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


				def __UpperCamelCase						(							self      :  str       )		->     str:
											A      						=    self.get_dummy_components()
											A      						=    AudioLDMPipeline(**__UpperCamelCase       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

											A      						=    ['''hey''']

											A      						=    audioldm_pipe(__UpperCamelCase						, num_inference_steps=1       )
											A      						=    output.audios.shape
											assert audio_shape == (1, 256)

											A      						=    audioldm_pipe.vocoder.config
											config.model_in_dim *= 2
											A      						=    SpeechTaHifiGan(__UpperCamelCase       ).to(__UpperCamelCase       )
											A      						=    audioldm_pipe(__UpperCamelCase						, 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, 256)


				def __UpperCamelCase						(							self      :  List[Any]       )		->     str:
											self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__UpperCamelCase       )


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


				@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]       )		->     List[Any]:
											self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__UpperCamelCase       )





@slow
class        lowerCAmelCase__					(  unittest.TestCase       ):


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


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


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Optional[Any]:
											A      						=    AudioLDMPipeline.from_pretrained('cvssp/audioldm'       )
											A      						=    audioldm_pipe.to(__UpperCamelCase       )
											audioldm_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

											A      						=    self.get_inputs(__UpperCamelCase       )
											A      						=    25
											A      						=    audioldm_pipe(**__UpperCamelCase       ).audios[0]

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

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


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

											A      						=    self.get_inputs(__UpperCamelCase       )
											A      						=    audioldm_pipe(**__UpperCamelCase       ).audios[0]

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

											A      						=    audio[27_780:27_790]
											A      						=    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      						=    np.abs(expected_slice - audio_slice       ).max()
											assert max_diff < 3e-2







'''simple docstring'''



from __future__ import annotations


def 				lowercase_					(     __A			:							list[list[int]]      )							->   int:



 """simple docstring"""




 for i in range(1       ,   len(matrix[0]      )      ):
  matrix[0][i] += matrix[0][i - 1]

 # preprocessing the first column
 for i in range(1       ,   len(__A      )      ):
  matrix[i][0] += matrix[i - 1][0]

 # updating the path cost for current position
 for i in range(1       ,   len(__A      )      ):
  for j in range(1       ,   len(matrix[0]      )      ):
   matrix[i][j] += min(matrix[i - 1][j]       ,   matrix[i][j - 1]      )

 return matrix[-1][-1]


if __name__ == "__main__":
      import doctest

      doctest.testmod()



