

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



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



      """simple docstring"""







      __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 			_lowerCAmelCase	( self	:				int							):
           torch.manual_seed(0							)
           SCREAMING_SNAKE_CASE 		=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'     ,)

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

           SCREAMING_SNAKE_CASE 		=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     ,)

           SCREAMING_SNAKE_CASE 		=DDPMScheduler()

           SCREAMING_SNAKE_CASE 		={
               'notes_encoder': notes_encoder.eval(),
               'continuous_encoder': continuous_encoder.eval(),
               'decoder': decoder.eval(),
               'scheduler': scheduler,
               'melgan': None,
           }
           return components
      def 			_lowerCAmelCase	( self	:				Any     ,snake_case	:				Dict     ,snake_case	:				Tuple=0							):
           if str(snake_case							).startswith('mps'							):
                SCREAMING_SNAKE_CASE 		=torch.manual_seed(snake_case							)
           else:
                SCREAMING_SNAKE_CASE 		=torch.Generator(device=snake_case							).manual_seed(snake_case							)
           SCREAMING_SNAKE_CASE 		={
               '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 			_lowerCAmelCase	( self	:				Optional[Any]							):
           SCREAMING_SNAKE_CASE 		='cpu'  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE 		=self.get_dummy_components()
           SCREAMING_SNAKE_CASE 		=SpectrogramDiffusionPipeline(**snake_case							)
           SCREAMING_SNAKE_CASE 		=pipe.to(snake_case							)
           pipe.set_progress_bar_config(disable=snake_case							)

           SCREAMING_SNAKE_CASE 		=self.get_dummy_inputs(snake_case							)
           SCREAMING_SNAKE_CASE 		=pipe(**snake_case							)
           SCREAMING_SNAKE_CASE 		=output.audios

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

           assert mel_slice.shape == (3, 3)
           SCREAMING_SNAKE_CASE 		=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 			_lowerCAmelCase	( self	:				str							):
           return super().test_save_load_local()
      @skip_mps
      def 			_lowerCAmelCase	( self	:				Tuple							):
           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	:				str							):
           pass
      def 			_lowerCAmelCase	( self	:				List[Any]							):
           pass


      @skip_mps
      def 			_lowerCAmelCase	( self	:				Optional[Any]							):
           return super().test_progress_bar()







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



      """simple docstring"""







      def 			_lowerCAmelCase	( self	:				Tuple							):
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
      def 			_lowerCAmelCase	( self	:				Optional[Any]							):
           # TODO - test that pipeline can decode tokens in a callback
           # so that music can be played live
           SCREAMING_SNAKE_CASE 		=torch_device

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

           SCREAMING_SNAKE_CASE 		=pipe.to(snake_case							)
           pipe.set_progress_bar_config(disable=snake_case							)

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

           SCREAMING_SNAKE_CASE 		=MidiProcessor()
           SCREAMING_SNAKE_CASE 		=processor(snake_case							)

           SCREAMING_SNAKE_CASE 		=input_tokens[:3]
           SCREAMING_SNAKE_CASE 		=torch.manual_seed(0							)
           pipe(snake_case     ,num_inference_steps=5     ,generator=snake_case     ,callback=snake_case     ,output_type='mel'							)
      def 			_lowerCAmelCase	( self	:				Optional[Any]							):
           SCREAMING_SNAKE_CASE 		=torch_device

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

           SCREAMING_SNAKE_CASE 		=processor(snake_case							)
           # just run two denoising loops
           SCREAMING_SNAKE_CASE 		=input_tokens[:2]

           SCREAMING_SNAKE_CASE 		=torch.manual_seed(0							)
           SCREAMING_SNAKE_CASE 		=pipe(snake_case     ,num_inference_steps=2     ,generator=snake_case							)

           SCREAMING_SNAKE_CASE 		=output.audios[0]

           assert abs(np.abs(snake_case							).sum() - 3_612.841							) < 1e-1


      def 			_lowerCAmelCase	( self	:				List[Any]							):
           SCREAMING_SNAKE_CASE 		=torch_device

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

           SCREAMING_SNAKE_CASE 		=MidiProcessor()

           SCREAMING_SNAKE_CASE 		=processor(snake_case							)

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

           SCREAMING_SNAKE_CASE 		=torch.manual_seed(0							)
           SCREAMING_SNAKE_CASE 		=pipe(snake_case     ,num_inference_steps=100     ,generator=snake_case							)

           SCREAMING_SNAKE_CASE 		=output.audios[0]
           assert abs(np.abs(snake_case							).sum() - 9_389.1_111							) < 5e-2




from __future__ import annotations

_lowerCamelCase							={1: 1}







def      snake_case__							(  lowerCAmelCase_     ):





     """simple docstring"""







     if n in COLLATZ_SEQUENCE_LENGTHS:
          return COLLATZ_SEQUENCE_LENGTHS[n]
     SCREAMING_SNAKE_CASE 		=n // 2 if n % 2 == 0 else 3 * n + 1
     SCREAMING_SNAKE_CASE 		=collatz_sequence_length(lowerCAmelCase_     ) + 1
     SCREAMING_SNAKE_CASE 		=sequence_length
     return sequence_length







def      snake_case__							(  lowerCAmelCase_ = 1000000     ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE 		=max((collatz_sequence_length(lowerCAmelCase_     ), i) for i in range(1,       lowerCAmelCase_     )     )
     return result[1]


if __name__ == "__main__":
 print(solution(int(input().strip())))

