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


__snake_case  : List[str]		       =    './tests/fixtures/elise_format0.mid'




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





       '''simple docstring'''



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

       def    __A			( self					)						->	Tuple:
           torch.manual_seed(0					)
           A_      =  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'''       ,	)

           A_      =  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'''       ,	)

           A_      =  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=2048       ,	dropout_rate=0.1       ,	)

           A_      =  DDPMScheduler()

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

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE=0					)						->	Any:
           if str(_SCREAMING_SNAKE_CASE					).startswith('''mps'''					):
               A_      =  torch.manual_seed(_SCREAMING_SNAKE_CASE					)
           else:
               A_      =  torch.Generator(device=_SCREAMING_SNAKE_CASE					).manual_seed(_SCREAMING_SNAKE_CASE					)
           A_      =  {
               '''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					)						->	Any:
           A_      =  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           A_      =  self.get_dummy_components()
           A_      =  SpectrogramDiffusionPipeline(**_SCREAMING_SNAKE_CASE					)
           A_      =  pipe.to(_SCREAMING_SNAKE_CASE					)
           pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE					)

           A_      =  self.get_dummy_inputs(_SCREAMING_SNAKE_CASE					)
           A_      =  pipe(**_SCREAMING_SNAKE_CASE					)
           A_      =  output.audios

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

           assert mel_slice.shape == (3, 3)
           A_      =  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					)						->	List[Any]:
           return super().test_save_load_local()

       @skip_mps
       def    __A			( self					)						->	Union[str, Any]:
           return super().test_dict_tuple_outputs_equivalent()

       @skip_mps
       def    __A			( self					)						->	str:
           return super().test_save_load_optional_components()

       @skip_mps
       def    __A			( self					)						->	Tuple:
           return super().test_attention_slicing_forward_pass()

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

       def    __A			( self					)						->	Optional[Any]:
           pass

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




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





       '''simple docstring'''



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

       def    __A			( self					)						->	Optional[int]:
           # TODO - test that pipeline can decode tokens in a callback
           # so that music can be played live
           A_      =  torch_device

           A_      =  SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''					)
           A_      =  pipe.melgan
           A_      =  None

           A_      =  pipe.to(_SCREAMING_SNAKE_CASE					)
           pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE					)

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

           A_      =  MidiProcessor()
           A_      =  processor(_SCREAMING_SNAKE_CASE					)

           A_      =  input_tokens[:3]
           A_      =  torch.manual_seed(0					)
           pipe(_SCREAMING_SNAKE_CASE       ,	num_inference_steps=5       ,	generator=_SCREAMING_SNAKE_CASE       ,	callback=_SCREAMING_SNAKE_CASE       ,	output_type='''mel'''					)

       def    __A			( self					)						->	Dict:
           A_      =  torch_device

           A_      =  SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''					)
           A_      =  pipe.to(_SCREAMING_SNAKE_CASE					)
           pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE					)
           A_      =  MidiProcessor()

           A_      =  processor(_SCREAMING_SNAKE_CASE					)
           # just run two denoising loops
           A_      =  input_tokens[:2]

           A_      =  torch.manual_seed(0					)
           A_      =  pipe(_SCREAMING_SNAKE_CASE       ,	num_inference_steps=2       ,	generator=_SCREAMING_SNAKE_CASE					)

           A_      =  output.audios[0]

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

       def    __A			( self					)						->	Optional[int]:
           A_      =  torch_device

           A_      =  SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''					)
           A_      =  pipe.to(_SCREAMING_SNAKE_CASE					)
           pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE					)

           A_      =  MidiProcessor()

           A_      =  processor(_SCREAMING_SNAKE_CASE					)

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

           A_      =  torch.manual_seed(0					)
           A_      =  pipe(_SCREAMING_SNAKE_CASE       ,	num_inference_steps=100       ,	generator=_SCREAMING_SNAKE_CASE					)

           A_      =  output.audios[0]
           assert abs(np.abs(_SCREAMING_SNAKE_CASE					).sum() - 9_389.1_111					) < 5E-2







'''simple docstring'''




def 	_UpperCAmelCase       (				_UpperCamelCase       :      list[list[int]],  _UpperCamelCase       :      list[list[int]]  )      -> list[list[int]]:
    A_      =  []
    A_      =  len(_UpperCamelCase  )
    for i in range(_UpperCamelCase  ):
        A_      =  []
        for j in range(_UpperCamelCase  ):
            A_      =  0
            for k in range(_UpperCamelCase  ):
                A_      =  val + matrix_a[i][k] * matrix_b[k][j]
            list_a.append(_UpperCamelCase  )
        matrix_c.append(_UpperCamelCase  )
    return matrix_c





def 	_UpperCAmelCase       (				_UpperCamelCase       :      int  )      -> list[list[int]]:
    return [[int(row == column  ) for column in range(_UpperCamelCase  )] for row in range(_UpperCamelCase  )]





def 	_UpperCAmelCase       (				_UpperCamelCase       :      int  )      -> int:
    if n <= 1:
        return n
    A_      =  identity(2  )
    A_      =  [[1, 1], [1, 0]]
    A_      =  n - 1
    while n > 0:
        if n % 2 == 1:
            A_      =  multiply(_UpperCamelCase,  _UpperCamelCase  )
        A_      =  multiply(_UpperCamelCase,  _UpperCamelCase  )
        A_      =  int(n / 2  )
    return res_matrix[0][0]





def 	_UpperCAmelCase       (				_UpperCamelCase       :      int  )      -> int:
    if n <= 1:
        return n
    A_      =  0
    A_      =  1
    for _ in range(2,  n + 1  ):
        A_  ,A_      =  fiba, fiba + fiba
    return fiba





def 	_UpperCAmelCase       (				)      -> None:
    for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split():
        A_      =  int(''''''.join(c for c in ordinal if c in '''0123456789'''  )  )  # 1000th --> 1000
        print(
            F'''{ordinal} fibonacci number using matrix exponentiation is '''
            F'''{nth_fibonacci_matrix(_UpperCamelCase  )} and using bruteforce is '''
            F'''{nth_fibonacci_bruteforce(_UpperCamelCase  )}\n'''  )
    # from timeit import timeit
    # print(timeit("nth_fibonacci_matrix(1000000)",
    #              "from main import nth_fibonacci_matrix", number=5))
    # print(timeit("nth_fibonacci_bruteforce(1000000)",
    #              "from main import nth_fibonacci_bruteforce", number=5))
    # 2.3342058970001744
    # 57.256506615000035


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()






