


"""simple docstring"""






import gc
import unittest

import numpy as np
import torch

from diffusers import DDPMScheduler, MidiProcessor, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder
from diffusers.utils import require_torch_gpu, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_note_seq, require_onnxruntime

from ..pipeline_params import TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS, TOKENS_TO_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


lowercase  		=			"""./tests/fixtures/elise_format0.mid"""


@unittest.skip('''The note-seq package currently throws an error on import''')
class 			SCREAMING_SNAKE_CASE_  (   __A	,      unittest.TestCase):




							'''simple docstring'''





							__magic_name__					:     List[str]				  =  SpectrogramDiffusionPipeline
							__magic_name__					:     Any				  =  PipelineTesterMixin.required_optional_params - {
							    """callback""",
							    """latents""",
							    """callback_steps""",
							    """output_type""",
							    """num_images_per_prompt""",
							}
							__magic_name__					:     int				  =  False
							__magic_name__					:     Tuple				  =  False
							__magic_name__					:     Tuple				  =  TOKENS_TO_AUDIO_GENERATION_PARAMS
							__magic_name__					:     Optional[int]				  =  TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS




							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								torch.manual_seed(0)
								snake_case__  :						Any		=      SpectrogramNotesEncoder(
								    max_length=2_048	,					vocab_size=1_536	,					d_model=768	,					dropout_rate=0.1	,					num_layers=1	,					num_heads=1	,					d_kv=4	,					d_ff=2_048	,					feed_forward_proj="gated-gelu"	,					)

								snake_case__  :						Optional[Any]		=      SpectrogramContEncoder(
								    input_dims=128	,					targets_context_length=256	,					d_model=768	,					dropout_rate=0.1	,					num_layers=1	,					num_heads=1	,					d_kv=4	,					d_ff=2_048	,					feed_forward_proj="gated-gelu"	,					)

								snake_case__  :						Any		=      TaFilmDecoder(
								    input_dims=128	,					targets_length=256	,					max_decoder_noise_time=20_000.0	,					d_model=768	,					num_layers=1	,					num_heads=1	,					d_kv=4	,					d_ff=2_048	,					dropout_rate=0.1	,					)

								snake_case__  :						Any		=      DDPMScheduler()

								snake_case__  :						str		=      {
								    "notes_encoder": notes_encoder.eval(),
								    "continuous_encoder": continuous_encoder.eval(),
								    "decoder": decoder.eval(),
								    "scheduler": scheduler,
								    "melgan": None,
								}
								return components




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__=0)   ->	Any:







								'''simple docstring'''




								if str(lowerCamelCase__).startswith("mps"):
									snake_case__  :						List[Any]		=      torch.manual_seed(lowerCamelCase__)
								else:
									snake_case__  :						Optional[int]		=      torch.Generator(device=lowerCamelCase__).manual_seed(lowerCamelCase__)
								snake_case__  :						Any		=      {
								    "input_tokens": [
								        [1_134, 90, 1_135, 1_133, 1_080, 112, 1_132, 1_080, 1_133, 1_079, 133, 1_132, 1_079, 1_133, 1] + [0] * 2_033
								    ],
								    "generator": generator,
								    "num_inference_steps": 4,
								    "output_type": "mel",
								}
								return inputs




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						List[str]		=      "cpu"  # ensure determinism for the device-dependent torch.Generator
								snake_case__  :						Union[str, Any]		=      self.get_dummy_components()
								snake_case__  :						int		=      SpectrogramDiffusionPipeline(**lowerCamelCase__)
								snake_case__  :						Dict		=      pipe.to(lowerCamelCase__)
								pipe.set_progress_bar_config(disable=lowerCamelCase__)

								snake_case__  :						Any		=      self.get_dummy_inputs(lowerCamelCase__)
								snake_case__  :						Tuple		=      pipe(**lowerCamelCase__)
								snake_case__  :						Optional[Any]		=      output.audios

								snake_case__  :						Optional[int]		=      mel[0, -3:, -3:]

								assert mel_slice.shape == (3, 3)
								snake_case__  :						List[str]		=      np.array(
								    [-11.51_29_25, -4.78_82_15, -0.46_17_29_05, -2.05_17_15, -10.53_91_47, -10.97_09_63, -9.09_16_34, 4.0, 4.0])
								assert np.abs(mel_slice.flatten() - expected_slice).max() < 1E-2




							@skip_mps
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								return super().test_save_load_local()




							@skip_mps
							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								return super().test_dict_tuple_outputs_equivalent()




							@skip_mps
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								return super().test_save_load_optional_components()




							@skip_mps
							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								return super().test_attention_slicing_forward_pass()




							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								pass




							def        UpperCAmelCase (						self)   ->	Union[str, Any]:







								'''simple docstring'''




								pass







							@skip_mps
							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								return super().test_progress_bar()


@slow
@require_torch_gpu
@require_onnxruntime
@require_note_seq
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




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




							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								snake_case__  :						Dict		=      torch_device

								snake_case__  :						int		=      SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
								snake_case__  :						Optional[int]		=      pipe.melgan
								snake_case__  :						Any		=      None

								snake_case__  :						Union[str, Any]		=      pipe.to(lowerCamelCase__)
								pipe.set_progress_bar_config(disable=lowerCamelCase__)

								def callback(lowerCamelCase__	,					lowerCamelCase__):
									# decode mel to audio
									snake_case__  :						int		=      melgan(input_features=mel_output.astype(np.floataa))[0]
									assert len(audio[0]) == 81_920 * (step + 1)
									# simulate that audio is played
									return audio

								snake_case__  :						Optional[int]		=      MidiProcessor()
								snake_case__  :						Any		=      processor(lowerCamelCase__)

								snake_case__  :						Any		=      input_tokens[:3]
								snake_case__  :						int		=      torch.manual_seed(0)
								pipe(lowerCamelCase__	,					num_inference_steps=5	,					generator=lowerCamelCase__	,					callback=lowerCamelCase__	,					output_type="mel")




							def        UpperCAmelCase (						self)   ->	Union[str, Any]:







								'''simple docstring'''




								snake_case__  :						int		=      torch_device

								snake_case__  :						Tuple		=      SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
								snake_case__  :						Dict		=      pipe.to(lowerCamelCase__)
								pipe.set_progress_bar_config(disable=lowerCamelCase__)
								snake_case__  :						Any		=      MidiProcessor()

								snake_case__  :						Optional[int]		=      processor(lowerCamelCase__)
								# just run two denoising loops
								snake_case__  :						Tuple		=      input_tokens[:2]

								snake_case__  :						Union[str, Any]		=      torch.manual_seed(0)
								snake_case__  :						Tuple		=      pipe(lowerCamelCase__	,					num_inference_steps=2	,					generator=lowerCamelCase__)

								snake_case__  :						str		=      output.audios[0]

								assert abs(np.abs(lowerCamelCase__).sum() - 3_612.841) < 1E-1







							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      torch_device

								snake_case__  :						List[str]		=      SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
								snake_case__  :						Dict		=      pipe.to(lowerCamelCase__)
								pipe.set_progress_bar_config(disable=lowerCamelCase__)

								snake_case__  :						int		=      MidiProcessor()

								snake_case__  :						List[Any]		=      processor(lowerCamelCase__)

								# just run 4 denoising loops
								snake_case__  :						Optional[Any]		=      input_tokens[:4]

								snake_case__  :						str		=      torch.manual_seed(0)
								snake_case__  :						Optional[int]		=      pipe(lowerCamelCase__	,					num_inference_steps=100	,					generator=lowerCamelCase__)

								snake_case__  :						Union[str, Any]		=      output.audios[0]
								assert abs(np.abs(lowerCamelCase__).sum() - 9_389.1_111) < 5E-2











'''simple docstring'''
from math import gcd
def 							snake_case_    (  a__						:      int = 1_20_00     ):



    """simple docstring"""




    __lowercase     							=		0
    for d in range(max_d + 1     ):
        for n in range(d // 3 + 1       ,(d + 1) // 2     ):
            if gcd(a__       ,a__     ) == 1:
                fractions_number += 1
    return fractions_number


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




