






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 				UpperCAmelCase_  (		__A							,      unittest.TestCase		):
     __lowerCamelCase      				=  AudioLDMPipeline
     __lowerCamelCase      				=  TEXT_TO_AUDIO_PARAMS
     __lowerCamelCase      				=  TEXT_TO_AUDIO_BATCH_PARAMS
     __lowerCamelCase      				=  frozenset(
         [
             'num_inference_steps',
             'num_waveforms_per_prompt',
             'generator',
             'latents',
             'output_type',
             'return_dict',
             'callback',
             'callback_steps',
         ]		)




     def   __UpperCAmelCase  (				self		):
          torch.manual_seed(0		)
          UpperCAmelCase__      :  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=UpperCamelCase__	,						)
          UpperCAmelCase__      :  List[Any]				      =			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		)
          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__      :  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=1000	,						projection_dim=32	,						)
          UpperCAmelCase__      :  Union[str, Any]				      =			ClapTextModelWithProjection(UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[int]				      =			RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta"""	,						model_max_length=77		)

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

          UpperCAmelCase__      :  Union[str, Any]				      =			SpeechTaHifiGan(UpperCamelCase__		)

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




     def   __UpperCAmelCase  (				self	,						_lowerCAmelCase	,						_lowerCAmelCase=0		):


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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			"""cpu"""  # ensure determinism for the device-dependent torch.Generator

          UpperCAmelCase__      :  Dict				      =			self.get_dummy_components()
          UpperCAmelCase__      :  str				      =			AudioLDMPipeline(**UpperCamelCase__		)
          UpperCAmelCase__      :  List[Any]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  Dict				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  Tuple				      =			audioldm_pipe(**UpperCamelCase__		)
          UpperCAmelCase__      :  int				      =			output.audios[0]

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

          UpperCAmelCase__      :  Tuple				      =			audio[:10]
          UpperCAmelCase__      :  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		):
          UpperCAmelCase__      :  Union[str, Any]				      =			self.get_dummy_components()
          UpperCAmelCase__      :  Tuple				      =			AudioLDMPipeline(**UpperCamelCase__		)
          UpperCAmelCase__      :  int				      =			audioldm_pipe.to(UpperCamelCase__		)
          UpperCAmelCase__      :  Union[str, Any]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  List[str]				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  int				      =			3 * [inputs["""prompt"""]]

          # forward
          UpperCAmelCase__      :  Optional[int]				      =			audioldm_pipe(**UpperCamelCase__		)
          UpperCAmelCase__      :  int				      =			output.audios[0]

          UpperCAmelCase__      :  str				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  int				      =			3 * [inputs.pop("""prompt"""		)]

          UpperCAmelCase__      :  Optional[int]				      =			audioldm_pipe.tokenizer(
              UpperCamelCase__	,						padding="""max_length"""	,						max_length=audioldm_pipe.tokenizer.model_max_length	,						truncation=UpperCamelCase__	,						return_tensors="""pt"""	,						)
          UpperCAmelCase__      :  Union[str, Any]				      =			text_inputs["""input_ids"""].to(UpperCamelCase__		)

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

          UpperCAmelCase__      :  Dict				      =			prompt_embeds

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

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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[str]				      =			self.get_dummy_components()
          UpperCAmelCase__      :  Dict				      =			AudioLDMPipeline(**UpperCamelCase__		)
          UpperCAmelCase__      :  Union[str, Any]				      =			audioldm_pipe.to(UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[int]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  int				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  List[str]				      =			3 * ["""this is a negative prompt"""]
          UpperCAmelCase__      :  Any				      =			negative_prompt
          UpperCAmelCase__      :  Optional[int]				      =			3 * [inputs["""prompt"""]]

          # forward
          UpperCAmelCase__      :  List[Any]				      =			audioldm_pipe(**UpperCamelCase__		)
          UpperCAmelCase__      :  Tuple				      =			output.audios[0]

          UpperCAmelCase__      :  Tuple				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[Any]				      =			3 * [inputs.pop("""prompt"""		)]

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

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

               embeds.append(UpperCamelCase__		)

          UpperCAmelCase__      ,		UpperCAmelCase__      :  Optional[Any]				      =			embeds

          # forward
          UpperCAmelCase__      :  List[str]				      =			audioldm_pipe(**UpperCamelCase__		)
          UpperCAmelCase__      :  List[Any]				      =			output.audios[0]

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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			"""cpu"""  # ensure determinism for the device-dependent torch.Generator
          UpperCAmelCase__      :  Tuple				      =			self.get_dummy_components()
          UpperCAmelCase__      :  List[Any]				      =			PNDMScheduler(skip_prk_steps=UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[Any]				      =			AudioLDMPipeline(**UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[Any]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  str				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[int]				      =			"""egg cracking"""
          UpperCAmelCase__      :  str				      =			audioldm_pipe(**UpperCamelCase__	,						negative_prompt=UpperCamelCase__		)
          UpperCAmelCase__      :  Tuple				      =			output.audios[0]

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

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

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

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

          UpperCAmelCase__      :  Dict				      =			self.get_dummy_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  Optional[Any]				      =			audioldm_pipe(audio_length_in_s=0.0_1_6	,						**UpperCamelCase__		)
          UpperCAmelCase__      :  Dict				      =			output.audios[0]

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

          UpperCAmelCase__      :  Optional[int]				      =			audioldm_pipe(audio_length_in_s=0.0_3_2	,						**UpperCamelCase__		)
          UpperCAmelCase__      :  Dict				      =			output.audios[0]

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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Any				      =			self.get_dummy_components()
          UpperCAmelCase__      :  Any				      =			AudioLDMPipeline(**UpperCamelCase__		)
          UpperCAmelCase__      :  Union[str, Any]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  int				      =			["""hey"""]

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

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




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







@slow
class 				UpperCAmelCase_  (		unittest.TestCase		):




     def   __UpperCAmelCase  (				self		):
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()




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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""		)
          UpperCAmelCase__      :  Optional[Any]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  Dict				      =			self.get_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  List[Any]				      =			25
          UpperCAmelCase__      :  Dict				      =			audioldm_pipe(**UpperCamelCase__		).audios[0]

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

          UpperCAmelCase__      :  Optional[Any]				      =			audio[77230:77240]
          UpperCAmelCase__      :  List[Any]				      =			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]		)
          UpperCAmelCase__      :  Any				      =			np.abs(expected_slice - audio_slice		).max()
          assert max_diff < 1e-2




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""		)
          UpperCAmelCase__      :  Optional[Any]				      =			LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config		)
          UpperCAmelCase__      :  List[str]				      =			audioldm_pipe.to(UpperCamelCase__		)
          audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  Tuple				      =			self.get_inputs(UpperCamelCase__		)
          UpperCAmelCase__      :  Union[str, Any]				      =			audioldm_pipe(**UpperCamelCase__		).audios[0]

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

          UpperCAmelCase__      :  List[Any]				      =			audio[27780:27790]
          UpperCAmelCase__      :  int				      =			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]		)
          UpperCAmelCase__      :  Optional[Any]				      =			np.abs(expected_slice - audio_slice		).max()
          assert max_diff < 3e-2














'''simple docstring'''







def       __UpperCamelCase					(      lowercase_       :  int = 1_000_000   ):
       """simple docstring"""




       a_						     =			set(range(3   ,       lowercase_   ,       2   )   )
       primes.add(2   )
       for p in range(3   ,       lowercase_   ,       2   ):
              if p not in primes:
                     continue
              primes.difference_update(set(range(p * p   ,       lowercase_   ,       lowercase_   )   )   )

       a_						     =			[float(lowercase_   ) for n in range(limit + 1   )]

       for p in primes:
              for n in range(lowercase_   ,       limit + 1   ,       lowercase_   ):
                     phi[n] *= 1 - 1 / p

       return int(sum(phi[2:]   )   )


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




