






"""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()


a  :						Dict					       =							'''./tests/fixtures/elise_format0.mid'''


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



    '''simple docstring'''


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


    def 		A__      (      self			):
     torch.manual_seed(0			)
     UpperCAmelCase__ 						=				SpectrogramNotesEncoder(
         max_length=2048   ,			vocab_size=1536   ,			d_model=768   ,			dropout_rate=0.1   ,			num_layers=1   ,			num_heads=1   ,			d_kv=4   ,			d_ff=2048   ,			feed_forward_proj="""gated-gelu"""   ,			)

     UpperCAmelCase__ 						=				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=2048   ,			feed_forward_proj="""gated-gelu"""   ,			)

     UpperCAmelCase__ 						=				TaFilmDecoder(
         input_dims=128   ,			targets_length=256   ,			max_decoder_noise_time=20000.0   ,			d_model=768   ,			num_layers=1   ,			num_heads=1   ,			d_kv=4   ,			d_ff=2048   ,			dropout_rate=0.1   ,			)

     UpperCAmelCase__ 						=				DDPMScheduler()

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


    def 		A__      (      self   ,			__lowercase   ,			__lowercase=0			):
     if str(__lowercase			).startswith("""mps"""			):
      UpperCAmelCase__ 						=				torch.manual_seed(__lowercase			)
     else:
      UpperCAmelCase__ 						=				torch.Generator(device=__lowercase			).manual_seed(__lowercase			)
     UpperCAmelCase__ 						=				{
         """input_tokens""": [
             [1134, 90, 1135, 1133, 1080, 112, 1132, 1080, 1133, 1079, 133, 1132, 1079, 1133, 1] + [0] * 2033
         ],
         """generator""": generator,
         """num_inference_steps""": 4,
         """output_type""": """mel""",
     }
     return inputs


    def 		A__      (      self			):
     UpperCAmelCase__ 						=				"""cpu"""  # ensure determinism for the device-dependent torch.Generator
     UpperCAmelCase__ 						=				self.get_dummy_components()
     UpperCAmelCase__ 						=				SpectrogramDiffusionPipeline(**__lowercase			)
     UpperCAmelCase__ 						=				pipe.to(__lowercase			)
     pipe.set_progress_bar_config(disable=__lowercase			)

     UpperCAmelCase__ 						=				self.get_dummy_inputs(__lowercase			)
     UpperCAmelCase__ 						=				pipe(**__lowercase			)
     UpperCAmelCase__ 						=				output.audios

     UpperCAmelCase__ 						=				mel[0, -3:, -3:]

     assert mel_slice.shape == (3, 3)
     UpperCAmelCase__ 						=				np.array(
         [-11.512_925, -4.788_215, -0.46_172_905, -2.051_715, -10.539_147, -10.970_963, -9.091_634, 4.0, 4.0]			)
     assert np.abs(mel_slice.flatten() - expected_slice			).max() < 1e-2


    @skip_mps
    def 		A__      (      self			):
     return super().test_save_load_local()


    @skip_mps
    def 		A__      (      self			):
     return super().test_dict_tuple_outputs_equivalent()


    @skip_mps
    def 		A__      (      self			):
     return super().test_save_load_optional_components()


    @skip_mps
    def 		A__      (      self			):
     return super().test_attention_slicing_forward_pass()


    def 		A__      (      self			):
     pass


    def 		A__      (      self			):
     pass






    @skip_mps
    def 		A__      (      self			):
     return super().test_progress_bar()



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



    '''simple docstring'''


    def 		A__      (      self			):
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()


    def 		A__      (      self			):
     # TODO - test that pipeline can decode tokens in a callback
     # so that music can be played live
     UpperCAmelCase__ 						=				torch_device

     UpperCAmelCase__ 						=				SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""			)
     UpperCAmelCase__ 						=				pipe.melgan
     UpperCAmelCase__ 						=				None

     UpperCAmelCase__ 						=				pipe.to(__lowercase			)
     pipe.set_progress_bar_config(disable=__lowercase			)

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

     UpperCAmelCase__ 						=				MidiProcessor()
     UpperCAmelCase__ 						=				processor(__lowercase			)

     UpperCAmelCase__ 						=				input_tokens[:3]
     UpperCAmelCase__ 						=				torch.manual_seed(0			)
     pipe(__lowercase   ,			num_inference_steps=5   ,			generator=__lowercase   ,			callback=__lowercase   ,			output_type="""mel"""			)


    def 		A__      (      self			):
     UpperCAmelCase__ 						=				torch_device

     UpperCAmelCase__ 						=				SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""			)
     UpperCAmelCase__ 						=				pipe.to(__lowercase			)
     pipe.set_progress_bar_config(disable=__lowercase			)
     UpperCAmelCase__ 						=				MidiProcessor()

     UpperCAmelCase__ 						=				processor(__lowercase			)
     # just run two denoising loops
     UpperCAmelCase__ 						=				input_tokens[:2]

     UpperCAmelCase__ 						=				torch.manual_seed(0			)
     UpperCAmelCase__ 						=				pipe(__lowercase   ,			num_inference_steps=2   ,			generator=__lowercase			)

     UpperCAmelCase__ 						=				output.audios[0]

     assert abs(np.abs(__lowercase			).sum() - 3612.841			) < 1e-1






    def 		A__      (      self			):
     UpperCAmelCase__ 						=				torch_device

     UpperCAmelCase__ 						=				SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""			)
     UpperCAmelCase__ 						=				pipe.to(__lowercase			)
     pipe.set_progress_bar_config(disable=__lowercase			)

     UpperCAmelCase__ 						=				MidiProcessor()

     UpperCAmelCase__ 						=				processor(__lowercase			)

     # just run 4 denoising loops
     UpperCAmelCase__ 						=				input_tokens[:4]

     UpperCAmelCase__ 						=				torch.manual_seed(0			)
     UpperCAmelCase__ 						=				pipe(__lowercase   ,			num_inference_steps=100   ,			generator=__lowercase			)

     UpperCAmelCase__ 						=				output.audios[0]
     assert abs(np.abs(__lowercase			).sum() - 9389.1111			) < 5e-2






from math import cos, sin







def      snake_case__							(  lowerCAmelCase_     ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE 		=float(lowerCAmelCase_     )
     return [[scaling_factor * int(x == y     ) for x in range(2     )] for y in range(2     )]







def      snake_case__							(  lowerCAmelCase_     ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE		,    SCREAMING_SNAKE_CASE 		=cos(lowerCAmelCase_     ), sin(lowerCAmelCase_     )
     return [[c, -s], [s, c]]







def      snake_case__							(  lowerCAmelCase_     ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE		,    SCREAMING_SNAKE_CASE 		=cos(lowerCAmelCase_     ), sin(lowerCAmelCase_     )
     SCREAMING_SNAKE_CASE 		=c * s
     return [[c * c, cs], [cs, s * s]]







def      snake_case__							(  lowerCAmelCase_     ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE		,    SCREAMING_SNAKE_CASE 		=cos(lowerCAmelCase_     ), sin(lowerCAmelCase_     )
     SCREAMING_SNAKE_CASE 		=c * s
     return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]


print(f'    {scaling(5) = }')
print(f'  {rotation(45) = }')
print(f'{projection(45) = }')



print(f'{reflection(45) = }')

