





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__  (			__snake_case			,  unittest.TestCase     ):
      _UpperCAmelCase      :Union[str, Any]		       =  AudioLDMPipeline
      _UpperCAmelCase      :Union[str, Any]		       =  TEXT_TO_AUDIO_PARAMS
      _UpperCAmelCase      :Optional[Any]		       =  TEXT_TO_AUDIO_BATCH_PARAMS
      _UpperCAmelCase      :Any		       =  frozenset(
          [
              'num_inference_steps',
              'num_waveforms_per_prompt',
              'generator',
              'latents',
              'output_type',
              'return_dict',
              'callback',
              'callback_steps',
          ]     )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       torch.manual_seed(0  )
       UpperCamelCase      :   List[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=A_			,				)
       UpperCamelCase      :   Union[str, Any]			      =  DDIMScheduler(
           beta_start=0.0_00_85			,				beta_end=0.0_12			,				beta_schedule="scaled_linear"			,				clip_sample=A_			,				set_alpha_to_one=A_			,				)
       torch.manual_seed(0  )
       UpperCamelCase      :   Optional[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  )
       UpperCamelCase      :   str			      =  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			,				)
       UpperCamelCase      :   Optional[Any]			      =  ClapTextModelWithProjection(A_  )
       UpperCamelCase      :   Any			      =  RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta"			,				model_max_length=77  )

       UpperCamelCase      :   List[str]			      =  SpeechTaHifiGanConfig(
           model_in_dim=8			,				sampling_rate=1_6000			,				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_			,				)

       UpperCamelCase      :   List[Any]			      =  SpeechTaHifiGan(A_  )

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





      def 			__UpperCamelCase(					self			,				A_			,				A_=0  ):
       '''simple docstring'''




       if str(A_  ).startswith("mps"  ):
        UpperCamelCase      :   int			      =  torch.manual_seed(A_  )
       else:
        UpperCamelCase      :   List[str]			      =  torch.Generator(device=A_  ).manual_seed(A_  )
       UpperCamelCase      :   Union[str, Any]			      =  {
           "prompt": "A hammer hitting a wooden surface",
           "generator": generator,
           "num_inference_steps": 2,
           "guidance_scale": 6.0,
       }
       return inputs





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Tuple			      =  "cpu"  # ensure determinism for the device-dependent torch.Generator

       UpperCamelCase      :   Any			      =  self.get_dummy_components()
       UpperCamelCase      :   Union[str, Any]			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   int			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   Union[str, Any]			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   str			      =  audioldm_pipe(**A_  )
       UpperCamelCase      :   Tuple			      =  output.audios[0]

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

       UpperCamelCase      :   List[str]			      =  audio[:10]
       UpperCamelCase      :   Tuple			      =  np.array(
           [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33]  )

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





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  self.get_dummy_components()
       UpperCamelCase      :   Any			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   List[str]			      =  audioldm_pipe.to(A_  )
       UpperCamelCase      :   Any			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   str			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   int			      =  3 * [inputs["prompt"]]

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

       UpperCamelCase      :   Tuple			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   int			      =  3 * [inputs.pop("prompt"  )]

       UpperCamelCase      :   Dict			      =  audioldm_pipe.tokenizer(
           A_			,				padding="max_length"			,				max_length=audioldm_pipe.tokenizer.model_max_length			,				truncation=A_			,				return_tensors="pt"			,				)
       UpperCamelCase      :   str			      =  text_inputs["input_ids"].to(A_  )

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

       UpperCamelCase      :   List[str]			      =  prompt_embeds

       # forward
       UpperCamelCase      :   int			      =  audioldm_pipe(**A_  )
       UpperCamelCase      :   Union[str, Any]			      =  output.audios[0]

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





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  self.get_dummy_components()
       UpperCamelCase      :   Optional[Any]			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   List[str]			      =  audioldm_pipe.to(A_  )
       UpperCamelCase      :   Dict			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   Union[str, Any]			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   Union[str, Any]			      =  3 * ["this is a negative prompt"]
       UpperCamelCase      :   List[Any]			      =  negative_prompt
       UpperCamelCase      :   int			      =  3 * [inputs["prompt"]]

       # forward
       UpperCamelCase      :   Dict			      =  audioldm_pipe(**A_  )
       UpperCamelCase      :   Union[str, Any]			      =  output.audios[0]

       UpperCamelCase      :   Optional[Any]			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   Optional[int]			      =  3 * [inputs.pop("prompt"  )]

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

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

        embeds.append(A_  )

       UpperCamelCase      ,       UpperCamelCase      :   Union[str, Any]			      =  embeds

       # forward
       UpperCamelCase      :   Dict			      =  audioldm_pipe(**A_  )
       UpperCamelCase      :   Tuple			      =  output.audios[0]

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





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  "cpu"  # ensure determinism for the device-dependent torch.Generator
       UpperCamelCase      :   List[Any]			      =  self.get_dummy_components()
       UpperCamelCase      :   str			      =  PNDMScheduler(skip_prk_steps=A_  )
       UpperCamelCase      :   Dict			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   Dict			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   List[str]			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   Union[str, Any]			      =  "egg cracking"
       UpperCamelCase      :   Optional[Any]			      =  audioldm_pipe(**A_			,				negative_prompt=A_  )
       UpperCamelCase      :   Any			      =  output.audios[0]

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

       UpperCamelCase      :   str			      =  audio[:10]
       UpperCamelCase      :   List[Any]			      =  np.array(
           [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32]  )

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





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   int			      =  "cpu"  # ensure determinism for the device-dependent torch.Generator
       UpperCamelCase      :   Tuple			      =  self.get_dummy_components()
       UpperCamelCase      :   int			      =  PNDMScheduler(skip_prk_steps=A_  )
       UpperCamelCase      :   Any			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   str			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   Any			      =  "A hammer hitting a wooden surface"

       # test num_waveforms_per_prompt=1 (default)
       UpperCamelCase      :   Optional[int]			      =  audioldm_pipe(A_			,				num_inference_steps=2  ).audios

       assert audios.shape == (1, 256)

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

       assert audios.shape == (batch_size, 256)

       # test num_waveforms_per_prompt for single prompt
       UpperCamelCase      :   List[Any]			      =  2
       UpperCamelCase      :   Optional[Any]			      =  audioldm_pipe(A_			,				num_inference_steps=2			,				num_waveforms_per_prompt=A_  ).audios

       assert audios.shape == (num_waveforms_per_prompt, 256)

       # test num_waveforms_per_prompt for batch of prompts
       UpperCamelCase      :   Any			      =  2
       UpperCamelCase      :   Any			      =  audioldm_pipe(
           [prompt] * batch_size			,				num_inference_steps=2			,				num_waveforms_per_prompt=A_  ).audios

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





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   int			      =  "cpu"  # ensure determinism for the device-dependent torch.Generator
       UpperCamelCase      :   Any			      =  self.get_dummy_components()
       UpperCamelCase      :   str			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   Optional[Any]			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )
       UpperCamelCase      :   Optional[int]			      =  audioldm_pipe.vocoder.config.sampling_rate

       UpperCamelCase      :   List[str]			      =  self.get_dummy_inputs(A_  )
       UpperCamelCase      :   Tuple			      =  audioldm_pipe(audio_length_in_s=0.0_16			,				**A_  )
       UpperCamelCase      :   Any			      =  output.audios[0]

       assert audio.ndim == 1
       assert len(A_  ) / vocoder_sampling_rate == 0.0_16

       UpperCamelCase      :   List[str]			      =  audioldm_pipe(audio_length_in_s=0.0_32			,				**A_  )
       UpperCamelCase      :   List[Any]			      =  output.audios[0]

       assert audio.ndim == 1
       assert len(A_  ) / vocoder_sampling_rate == 0.0_32





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Tuple			      =  self.get_dummy_components()
       UpperCamelCase      :   Dict			      =  AudioLDMPipeline(**A_  )
       UpperCamelCase      :   Optional[Any]			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   Optional[int]			      =  ["hey"]

       UpperCamelCase      :   Tuple			      =  audioldm_pipe(A_			,				num_inference_steps=1  )
       UpperCamelCase      :   str			      =  output.audios.shape
       assert audio_shape == (1, 256)

       UpperCamelCase      :   str			      =  audioldm_pipe.vocoder.config
       config.model_in_dim *= 2
       UpperCamelCase      :   Optional[int]			      =  SpeechTaHifiGan(A_  ).to(A_  )
       UpperCamelCase      :   List[str]			      =  audioldm_pipe(A_			,				num_inference_steps=1  )
       UpperCamelCase      :   int			      =  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  ):
       '''simple docstring'''




       self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A_  )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       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  ):
       '''simple docstring'''




       self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A_  )



@slow
class    A__  (			unittest.TestCase     ):





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





      def 			__UpperCamelCase(					self			,				A_			,				A_="cpu"			,				A_=torch.floataa			,				A_=0  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  torch.Generator(device=A_  ).manual_seed(A_  )
       UpperCamelCase      :   Optional[Any]			      =  np.random.RandomState(A_  ).standard_normal((1, 8, 128, 16)  )
       UpperCamelCase      :   int			      =  torch.from_numpy(A_  ).to(device=A_			,				dtype=A_  )
       UpperCamelCase      :   str			      =  {
           "prompt": "A hammer hitting a wooden surface",
           "latents": latents,
           "generator": generator,
           "num_inference_steps": 3,
           "guidance_scale": 2.5,
       }
       return inputs





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[Any]			      =  AudioLDMPipeline.from_pretrained("cvssp/audioldm"  )
       UpperCamelCase      :   Tuple			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   List[Any]			      =  self.get_inputs(A_  )
       UpperCamelCase      :   int			      =  25
       UpperCamelCase      :   Any			      =  audioldm_pipe(**A_  ).audios[0]

       assert audio.ndim == 1
       assert len(A_  ) == 8_1920

       UpperCamelCase      :   Optional[Any]			      =  audio[7_7230:7_7240]
       UpperCamelCase      :   Optional[Any]			      =  np.array(
           [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15]  )
       UpperCamelCase      :   Union[str, Any]			      =  np.abs(expected_slice - audio_slice  ).max()
       assert max_diff < 1e-2





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   List[Any]			      =  AudioLDMPipeline.from_pretrained("cvssp/audioldm"  )
       UpperCamelCase      :   Tuple			      =  LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config  )
       UpperCamelCase      :   Optional[Any]			      =  audioldm_pipe.to(A_  )
       audioldm_pipe.set_progress_bar_config(disable=A_  )

       UpperCamelCase      :   Optional[Any]			      =  self.get_inputs(A_  )
       UpperCamelCase      :   Any			      =  audioldm_pipe(**A_  ).audios[0]

       assert audio.ndim == 1
       assert len(A_  ) == 8_1920

       UpperCamelCase      :   Optional[int]			      =  audio[2_7780:2_7790]
       UpperCamelCase      :   Dict			      =  np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12]  )
       UpperCamelCase      :   Dict			      =  np.abs(expected_slice - audio_slice  ).max()
       assert max_diff < 3e-2







from __future__ import annotations

import math



def 						A_							(	_lowerCAmelCase				,  _lowerCAmelCase	)		->					float:
 UpperCamelCase      :   Tuple			      =  u
 for i in range(1				,  _lowerCAmelCase	):
  UpperCamelCase      :   Any			      =  temp * (u - i)
 return temp



def 						A_							(	)		->					None:
 UpperCamelCase      :   Union[str, Any]			      =  int(input("enter the numbers of values: "	)	)
 UpperCamelCase      :   list[list[float]]			      =  []
 for _ in range(_lowerCAmelCase	):
  y.append([]	)
 for i in range(_lowerCAmelCase	):
  for j in range(_lowerCAmelCase	):
   y[i].append(_lowerCAmelCase	)
   UpperCamelCase      :   List[str]			      =  0

 print("enter the values of parameters in a list: "	)
 UpperCamelCase      :   Optional[Any]			      =  list(map(_lowerCAmelCase				,  input().split()	)	)

 print("enter the values of corresponding parameters: "	)
 for i in range(_lowerCAmelCase	):
  UpperCamelCase      :   Tuple			      =  float(input()	)

 UpperCamelCase      :   Any			      =  int(input("enter the value to interpolate: "	)	)
 UpperCamelCase      :   List[Any]			      =  (value - x[0]) / (x[1] - x[0])

 # for calculating forward difference table

 for i in range(1				,  _lowerCAmelCase	):
  for j in range(n - i	):
   UpperCamelCase      :   Optional[Any]			      =  y[j + 1][i - 1] - y[j][i - 1]

 UpperCamelCase      :   List[str]			      =  y[0][0]
 for i in range(1				,  _lowerCAmelCase	):
  summ += (ucal(_lowerCAmelCase				,  _lowerCAmelCase	) * y[0][i]) / math.factorial(_lowerCAmelCase	)

 print(F"""the value at {value} is {summ}"""	)


if __name__ == "__main__":
    main()
