




"""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  lowercase(					__a	,      unittest.TestCase			):







 '''simple docstring'''





 lowercase__			 = AudioLDMPipeline
 lowercase__			 = TEXT_TO_AUDIO_PARAMS
 lowercase__			 = TEXT_TO_AUDIO_BATCH_PARAMS
 lowercase__			 = frozenset(
     [
         "num_inference_steps",
         "num_waveforms_per_prompt",
         "generator",
         "latents",
         "output_type",
         "return_dict",
         "callback",
         "callback_steps",
     ]			)


 def 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   torch.manual_seed(0		)
   _snake_case							:		str								=  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_,				)
   _snake_case							:		Tuple								=  DDIMScheduler(
       beta_start=0.00_085,				beta_end=0.012,				beta_schedule="""scaled_linear""",				clip_sample=a_,				set_alpha_to_one=a_,				)
   torch.manual_seed(0		)
   _snake_case							:		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		)
   _snake_case							:		List[Any]								=  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,				)
   _snake_case							:		Optional[Any]								=  ClapTextModelWithProjection(a_		)
   _snake_case							:		List[Any]								=  RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""",				model_max_length=77		)

   _snake_case							:		List[str]								=  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=a_,				)

   _snake_case							:		Optional[int]								=  SpeechTaHifiGan(a_		)

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


 def 			UpperCamelCase_       (    self:		Tuple,				a_:		int,				a_:		int=0		):




   '''simple docstring'''



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


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  """cpu"""  # ensure determinism for the device-dependent torch.Generator

   _snake_case							:		str								=  self.get_dummy_components()
   _snake_case							:		Optional[Any]								=  AudioLDMPipeline(**a_		)
   _snake_case							:		List[Any]								=  audioldm_pipe.to(a_		)
   audioldm_pipe.set_progress_bar_config(disable=a_		)

   _snake_case							:		Dict								=  self.get_dummy_inputs(a_		)
   _snake_case							:		int								=  audioldm_pipe(**a_		)
   _snake_case							:		Any								=  output.audios[0]

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

   _snake_case							:		Any								=  audio[:10]
   _snake_case							:		Dict								=  np.array(
       [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033]		)

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


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



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

   _snake_case							:		Any								=  self.get_dummy_inputs(a_		)
   _snake_case							:		Union[str, Any]								=  3 * [inputs["""prompt"""]]

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

   _snake_case							:		Tuple								=  self.get_dummy_inputs(a_		)
   _snake_case							:		Any								=  3 * [inputs.pop("""prompt"""		)]

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

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

   _snake_case							:		List[str]								=  prompt_embeds

   # forward
   _snake_case							:		List[str]								=  audioldm_pipe(**a_		)
   _snake_case							:		Optional[int]								=  output.audios[0]

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


 def 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   _snake_case							:		str								=  self.get_dummy_components()
   _snake_case							:		Any								=  AudioLDMPipeline(**a_		)
   _snake_case							:		str								=  audioldm_pipe.to(a_		)
   _snake_case							:		Any								=  audioldm_pipe.to(a_		)
   audioldm_pipe.set_progress_bar_config(disable=a_		)

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

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

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

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

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

     embeds.append(a_		)

   _snake_case		, _snake_case							:		int								=  embeds

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

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


 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



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

   _snake_case							:		List[str]								=  self.get_dummy_inputs(a_		)
   _snake_case							:		int								=  """egg cracking"""
   _snake_case							:		Dict								=  audioldm_pipe(**a_,				negative_prompt=a_		)
   _snake_case							:		Dict								=  output.audios[0]

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

   _snake_case							:		List[str]								=  audio[:10]
   _snake_case							:		Optional[int]								=  np.array(
       [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032]		)

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


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



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

   _snake_case							:		Tuple								=  """A hammer hitting a wooden surface"""

   # test num_waveforms_per_prompt=1 (default)
   _snake_case							:		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
   _snake_case							:		Union[str, Any]								=  2
   _snake_case							:		Union[str, 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
   _snake_case							:		Optional[int]								=  2
   _snake_case							:		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
   _snake_case							:		Optional[int]								=  2
   _snake_case							:		Optional[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:		int		):




   '''simple docstring'''



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

   _snake_case							:		List[Any]								=  self.get_dummy_inputs(a_		)
   _snake_case							:		Tuple								=  audioldm_pipe(audio_length_in_s=0.016,				**a_		)
   _snake_case							:		Union[str, Any]								=  output.audios[0]

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

   _snake_case							:		Any								=  audioldm_pipe(audio_length_in_s=0.032,				**a_		)
   _snake_case							:		int								=  output.audios[0]

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


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



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

   _snake_case							:		str								=  ["""hey"""]

   _snake_case							:		str								=  audioldm_pipe(a_,				num_inference_steps=1		)
   _snake_case							:		Union[str, Any]								=  output.audios.shape
   assert audio_shape == (1, 256)

   _snake_case							:		Union[str, Any]								=  audioldm_pipe.vocoder.config
   config.model_in_dim *= 2
   _snake_case							:		List[Any]								=  SpeechTaHifiGan(a_		).to(a_		)
   _snake_case							:		Optional[int]								=  audioldm_pipe(a_,				num_inference_steps=1		)
   _snake_case							:		Optional[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:		Optional[Any]		):




   '''simple docstring'''



   self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a_		)


 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''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:		Union[str, Any]		):




   '''simple docstring'''



   self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a_		)







@slow
class  lowercase(					unittest.TestCase			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



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


 def 			UpperCamelCase_       (    self:		Dict,				a_:		Dict,				a_:		str="cpu",				a_:		Optional[Any]=torch.floataa,				a_:		Any=0		):




   '''simple docstring'''



   _snake_case							:		Dict								=  torch.Generator(device=a_		).manual_seed(a_		)
   _snake_case							:		List[Any]								=  np.random.RandomState(a_		).standard_normal((1, 8, 128, 16)		)
   _snake_case							:		Union[str, Any]								=  torch.from_numpy(a_		).to(device=a_,				dtype=a_		)
   _snake_case							:		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:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		Dict								=  AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""		)
   _snake_case							:		Tuple								=  audioldm_pipe.to(a_		)
   audioldm_pipe.set_progress_bar_config(disable=a_		)

   _snake_case							:		Tuple								=  self.get_inputs(a_		)
   _snake_case							:		Tuple								=  25
   _snake_case							:		Union[str, Any]								=  audioldm_pipe(**a_		).audios[0]

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

   _snake_case							:		List[str]								=  audio[77_230:77_240]
   _snake_case							:		List[Any]								=  np.array(
       [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315]		)
   _snake_case							:		Tuple								=  np.abs(expected_slice - audio_slice		).max()
   assert max_diff < 1E-2


 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



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

   _snake_case							:		Any								=  self.get_inputs(a_		)
   _snake_case							:		Any								=  audioldm_pipe(**a_		).audios[0]

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

   _snake_case							:		Tuple								=  audio[27_780:27_790]
   _snake_case							:		Dict								=  np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212]		)
   _snake_case							:		str								=  np.abs(expected_slice - audio_slice		).max()
   assert max_diff < 3E-2








"""simple docstring"""


def  UpperCAmelCase__	(snake_case__							: int = 10_00   ):
  """simple docstring"""

  _snake_case		, _snake_case							:		List[Any]								=  1, 1
  _snake_case							:		str								=  []
  for i in range(1		,       n + 1   ):
    _snake_case							:		Any								=  prev_numerator + 2 * prev_denominator
    _snake_case							:		Optional[Any]								=  prev_numerator + prev_denominator
    if len(str(snake_case__   )   ) > len(str(snake_case__   )   ):
      result.append(snake_case__   )
    _snake_case							:		int								=  numerator
    _snake_case							:		Any								=  denominator

  return len(snake_case__   )


if __name__ == "__main__":
     print(F'''{solution() = }''')


