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


_lowerCamelCase :				List[Any]														= """./tests/fixtures/elise_format0.mid"""




@unittest.skip("""The note-seq package currently throws an error on import"""     )
class    lowerCamelCase__  (   __snake_case       ,				unittest.TestCase     ):
   __UpperCAmelCase           =						SpectrogramDiffusionPipeline
   __UpperCAmelCase           =						PipelineTesterMixin.required_optional_params - {
       """callback""",
       """latents""",
       """callback_steps""",
       """output_type""",
       """num_images_per_prompt""",
   }
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						False
   __UpperCAmelCase           =						TOKENS_TO_AUDIO_GENERATION_PARAMS
   __UpperCAmelCase           =						TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS



   def  _UpperCamelCase		(    self     )				->     Any:
        """simple docstring"""





        torch.manual_seed(0     )
        _UpperCamelCase  :List[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"""					,      )

        _UpperCamelCase  :Optional[int]       =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"""					,      )

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

        _UpperCamelCase  :Any       =DDPMScheduler()

        _UpperCamelCase  :int       ={
            """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     )				->     str:
        """simple docstring"""





        if str(lowerCAmelCase__     ).startswith("""mps"""     ):
             _UpperCamelCase  :Tuple       =torch.manual_seed(lowerCAmelCase__     )
        else:
             _UpperCamelCase  :List[Any]       =torch.Generator(device=lowerCAmelCase__     ).manual_seed(lowerCAmelCase__     )
        _UpperCamelCase  :List[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     )				->     List[Any]:
        """simple docstring"""





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

        _UpperCamelCase  :List[str]       =self.get_dummy_inputs(lowerCAmelCase__     )
        _UpperCamelCase  :List[Any]       =pipe(**lowerCAmelCase__     )
        _UpperCamelCase  :List[Any]       =output.audios

        _UpperCamelCase  :Tuple       =mel[0, -3:, -3:]

        assert mel_slice.shape == (3, 3)
        _UpperCamelCase  :Optional[int]       =np.array(
            [-11.51_2925, -4.78_8215, -0.4617_2905, -2.05_1715, -10.53_9147, -10.97_0963, -9.09_1634, 4.0, 4.0]     )
        assert np.abs(mel_slice.flatten() - expected_slice     ).max() < 1e-2



   @skip_mps
   def  _UpperCamelCase		(    self     )				->     Dict:
        """simple docstring"""





        return super().test_save_load_local()



   @skip_mps
   def  _UpperCamelCase		(    self     )				->     int:
        """simple docstring"""





        return super().test_dict_tuple_outputs_equivalent()



   @skip_mps
   def  _UpperCamelCase		(    self     )				->     Dict:
        """simple docstring"""





        return super().test_save_load_optional_components()



   @skip_mps
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        return super().test_attention_slicing_forward_pass()



   def  _UpperCamelCase		(    self     )				->     Dict:
        """simple docstring"""





        pass



   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        pass




   @skip_mps
   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        return super().test_progress_bar()




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



   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





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



   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





        _UpperCamelCase  :Dict       =torch_device

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

        _UpperCamelCase  :Optional[int]       =pipe.to(lowerCAmelCase__     )
        pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

        def callback(lowerCAmelCase__					,      lowerCAmelCase__     ):
             # decode mel to audio
             _UpperCamelCase  :Optional[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

        _UpperCamelCase  :Optional[Any]       =MidiProcessor()
        _UpperCamelCase  :Optional[Any]       =processor(lowerCAmelCase__     )

        _UpperCamelCase  :Tuple       =input_tokens[:3]
        _UpperCamelCase  :Optional[int]       =torch.manual_seed(0     )
        pipe(lowerCAmelCase__					,      num_inference_steps=5					,      generator=lowerCAmelCase__					,      callback=lowerCAmelCase__					,      output_type="""mel"""     )



   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase  :Optional[int]       =torch_device

        _UpperCamelCase  :Tuple       =SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""     )
        _UpperCamelCase  :Tuple       =pipe.to(lowerCAmelCase__     )
        pipe.set_progress_bar_config(disable=lowerCAmelCase__     )
        _UpperCamelCase  :Optional[Any]       =MidiProcessor()

        _UpperCamelCase  :List[str]       =processor(lowerCAmelCase__     )
        # just run two denoising loops
        _UpperCamelCase  :Optional[Any]       =input_tokens[:2]

        _UpperCamelCase  :Union[str, Any]       =torch.manual_seed(0     )
        _UpperCamelCase  :Optional[int]       =pipe(lowerCAmelCase__					,      num_inference_steps=2					,      generator=lowerCAmelCase__     )

        _UpperCamelCase  :Optional[int]       =output.audios[0]

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




   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[Any]       =torch_device

        _UpperCamelCase  :Tuple       =SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""     )
        _UpperCamelCase  :Any       =pipe.to(lowerCAmelCase__     )
        pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

        _UpperCamelCase  :Optional[Any]       =MidiProcessor()

        _UpperCamelCase  :int       =processor(lowerCAmelCase__     )

        # just run 4 denoising loops
        _UpperCamelCase  :Tuple       =input_tokens[:4]

        _UpperCamelCase  :Dict       =torch.manual_seed(0     )
        _UpperCamelCase  :Optional[int]       =pipe(lowerCAmelCase__					,      num_inference_steps=100					,      generator=lowerCAmelCase__     )

        _UpperCamelCase  :Any       =output.audios[0]
        assert abs(np.abs(lowerCAmelCase__     ).sum() - 9389.1111     ) < 5e-2




def 						snake_case__							(       __lowercase							)		->		int:







						"""simple docstring"""

						A__						:				Any         =			0
						for plain_chr in plain_text:
												A__						:				List[str]         =			(
												    ord(__lowercase							) + (hash_value << 6) + (hash_value << 1_6) - hash_value
												)
						return hash_value