
"""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__   :						Tuple 							=     """./tests/fixtures/elise_format0.mid"""







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


     '''simple docstring'''





     _A		    =				SpectrogramDiffusionPipeline
     _A		    =				PipelineTesterMixin.required_optional_params - {
         'callback',
         'latents',
         'callback_steps',
         'output_type',
         'num_images_per_prompt',
     }
     _A		    =				False
     _A		    =				False
     _A		    =				TOKENS_TO_AUDIO_GENERATION_PARAMS
     _A		    =				TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS



     def 			lowerCAmelCase__							(   self	)->       str:
          torch.manual_seed(0	)
          UpperCAmelCase__				:			Optional[int]							=    SpectrogramNotesEncoder(
              max_length=20_48			,      vocab_size=15_36			,      d_model=7_68			,      dropout_rate=0.1			,      num_layers=1			,      num_heads=1			,      d_kv=4			,      d_ff=20_48			,      feed_forward_proj="gated-gelu"			,      )

          UpperCAmelCase__				:			List[Any]							=    SpectrogramContEncoder(
              input_dims=1_28			,      targets_context_length=2_56			,      d_model=7_68			,      dropout_rate=0.1			,      num_layers=1			,      num_heads=1			,      d_kv=4			,      d_ff=20_48			,      feed_forward_proj="gated-gelu"			,      )

          UpperCAmelCase__				:			Union[str, Any]							=    TaFilmDecoder(
              input_dims=1_28			,      targets_length=2_56			,      max_decoder_noise_time=2_0000.0			,      d_model=7_68			,      num_layers=1			,      num_heads=1			,      d_kv=4			,      d_ff=20_48			,      dropout_rate=0.1			,      )

          UpperCAmelCase__				:			str							=    DDPMScheduler()

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



     def 			lowerCAmelCase__							(   self			,      __UpperCamelCase			,      __UpperCamelCase=0	)->       List[str]:
          if str(__UpperCamelCase	).startswith("mps"	):
               UpperCAmelCase__				:			List[Any]							=    torch.manual_seed(__UpperCamelCase	)
          else:
               UpperCAmelCase__				:			Tuple							=    torch.Generator(device=__UpperCamelCase	).manual_seed(__UpperCamelCase	)
          UpperCAmelCase__				:			Optional[Any]							=    {
              "input_tokens": [
                  [11_34, 90, 11_35, 11_33, 10_80, 1_12, 11_32, 10_80, 11_33, 10_79, 1_33, 11_32, 10_79, 11_33, 1] + [0] * 20_33
              ],
              "generator": generator,
              "num_inference_steps": 4,
              "output_type": "mel",
          }
          return inputs



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

          UpperCAmelCase__				:			Any							=    self.get_dummy_inputs(__UpperCamelCase	)
          UpperCAmelCase__				:			Tuple							=    pipe(**__UpperCamelCase	)
          UpperCAmelCase__				:			Any							=    output.audios

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

          assert mel_slice.shape == (3, 3)
          UpperCAmelCase__				:			Union[str, Any]							=    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 			lowerCAmelCase__							(   self	)->       Any:
          return super().test_save_load_local()



     @skip_mps
     def 			lowerCAmelCase__							(   self	)->       Dict:
          return super().test_dict_tuple_outputs_equivalent()



     @skip_mps
     def 			lowerCAmelCase__							(   self	)->       List[Any]:
          return super().test_save_load_optional_components()



     @skip_mps
     def 			lowerCAmelCase__							(   self	)->       int:
          return super().test_attention_slicing_forward_pass()



     def 			lowerCAmelCase__							(   self	)->       List[Any]:
          pass



     def 			lowerCAmelCase__							(   self	)->       str:
          pass



     @skip_mps
     def 			lowerCAmelCase__							(   self	)->       int:
          return super().test_progress_bar()







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


     '''simple docstring'''





     def 			lowerCAmelCase__							(   self	)->       Optional[Any]:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()



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

          UpperCAmelCase__				:			Tuple							=    SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"	)
          UpperCAmelCase__				:			List[Any]							=    pipe.melgan
          UpperCAmelCase__				:			List[Any]							=    None

          UpperCAmelCase__				:			Any							=    pipe.to(__UpperCamelCase	)
          pipe.set_progress_bar_config(disable=__UpperCamelCase	)

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

          UpperCAmelCase__				:			Union[str, Any]							=    MidiProcessor()
          UpperCAmelCase__				:			Union[str, Any]							=    processor(__UpperCamelCase	)

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



     def 			lowerCAmelCase__							(   self	)->       Dict:
          UpperCAmelCase__				:			int							=    torch_device

          UpperCAmelCase__				:			int							=    SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"	)
          UpperCAmelCase__				:			Dict							=    pipe.to(__UpperCamelCase	)
          pipe.set_progress_bar_config(disable=__UpperCamelCase	)
          UpperCAmelCase__				:			Optional[int]							=    MidiProcessor()

          UpperCAmelCase__				:			List[Any]							=    processor(__UpperCamelCase	)
          # just run two denoising loops
          UpperCAmelCase__				:			Union[str, Any]							=    input_tokens[:2]

          UpperCAmelCase__				:			List[str]							=    torch.manual_seed(0	)
          UpperCAmelCase__				:			Tuple							=    pipe(__UpperCamelCase			,      num_inference_steps=2			,      generator=__UpperCamelCase	)

          UpperCAmelCase__				:			List[str]							=    output.audios[0]

          assert abs(np.abs(__UpperCamelCase	).sum() - 3612.841	) < 1E-1



     def 			lowerCAmelCase__							(   self	)->       int:
          UpperCAmelCase__				:			List[str]							=    torch_device

          UpperCAmelCase__				:			Optional[Any]							=    SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"	)
          UpperCAmelCase__				:			List[Any]							=    pipe.to(__UpperCamelCase	)
          pipe.set_progress_bar_config(disable=__UpperCamelCase	)

          UpperCAmelCase__				:			Dict							=    MidiProcessor()

          UpperCAmelCase__				:			str							=    processor(__UpperCamelCase	)

          # just run 4 denoising loops
          UpperCAmelCase__				:			Union[str, Any]							=    input_tokens[:4]

          UpperCAmelCase__				:			Optional[Any]							=    torch.manual_seed(0	)
          UpperCAmelCase__				:			List[Any]							=    pipe(__UpperCamelCase			,      num_inference_steps=1_00			,      generator=__UpperCamelCase	)

          UpperCAmelCase__				:			Dict							=    output.audios[0]
          assert abs(np.abs(__UpperCamelCase	).sum() - 9389.1111	) < 5E-2





"""simple docstring"""




def 				a__			(					lowerCAmelCase						:							str							,     lowerCAmelCase						:							int = 13		):






     '''simple docstring'''
     UpperCAmelCase__				:			Any							=    ""
     for c in s:
          if "A" <= c <= "Z":
               out += chr(ord("A"		) + (ord(lowerCAmelCase		) - ord("A"		) + n) % 26		)
          elif "a" <= c <= "z":
               out += chr(ord("a"		) + (ord(lowerCAmelCase		) - ord("a"		) + n) % 26		)
          else:
               out += c
     return out



def 				a__			(					):






     '''simple docstring'''
     UpperCAmelCase__				:			Optional[int]							=    input("Enter message: "		)

     UpperCAmelCase__				:			Optional[Any]							=    dencrypt(lowerCAmelCase							,     13		)
     print("Encryption:"							,     lowerCAmelCase		)

     UpperCAmelCase__				:			List[str]							=    dencrypt(lowerCAmelCase							,     13		)
     print("Decryption: "							,     lowerCAmelCase		)


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    main()



