

"""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__			:					Optional[int]							  =					'''./tests/fixtures/elise_format0.mid'''






@unittest.skip("""The note-seq package currently throws an error on import""")
class       _UpperCAmelCase     (						snake_case__      ,       unittest.TestCase):
			__a	:    Union[str, Any]			   =							SpectrogramDiffusionPipeline
			__a	:    Optional[Any]			   =							PipelineTesterMixin.required_optional_params - {
			    '''callback''',
			    '''latents''',
			    '''callback_steps''',
			    '''output_type''',
			    '''num_images_per_prompt''',
			}
			__a	:    Dict			   =							False
			__a	:    Tuple			   =							False
			__a	:    str			   =							TOKENS_TO_AUDIO_GENERATION_PARAMS
			__a	:    List[Any]			   =							TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS
			def 							__snake_case	(						self       )      ->      Dict:






				'''simple docstring'''







				torch.manual_seed(0       )
				_UpperCAmelCase      :							Dict       =   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      :							Optional[int]       =   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      :							Optional[Any]       =   TaFilmDecoder(
				    input_dims=1_28 ,						targets_length=2_56 ,						max_decoder_noise_time=2_00_00.0 ,						d_model=7_68 ,						num_layers=1 ,						num_heads=1 ,						d_kv=4 ,						d_ff=20_48 ,						dropout_rate=0.1 ,						)

				_UpperCAmelCase      :							Dict       =   DDPMScheduler()

				_UpperCAmelCase      :							List[str]       =   {
				    'notes_encoder': notes_encoder.eval(),
				    'continuous_encoder': continuous_encoder.eval(),
				    'decoder': decoder.eval(),
				    'scheduler': scheduler,
				    'melgan': None,
				}
				return components
			def 							__snake_case	(						self ,						_A ,						_A=0       )      ->      List[str]:






				'''simple docstring'''







				if str(_A       ).startswith("""mps"""       ):
					_UpperCAmelCase      :							Optional[int]       =   torch.manual_seed(_A       )
				else:
					_UpperCAmelCase      :							Optional[int]       =   torch.Generator(device=_A       ).manual_seed(_A       )
				_UpperCAmelCase      :							Dict       =   {
				    '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 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				_UpperCAmelCase      :							List[Any]       =   'cpu'  # ensure determinism for the device-dependent torch.Generator
				_UpperCAmelCase      :							Dict       =   self.get_dummy_components()
				_UpperCAmelCase      :							List[Any]       =   SpectrogramDiffusionPipeline(**_A       )
				_UpperCAmelCase      :							List[Any]       =   pipe.to(_A       )
				pipe.set_progress_bar_config(disable=_A       )

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

				_UpperCAmelCase      :							Dict       =   mel[0, -3:, -3:]

				assert mel_slice.shape == (3, 3)
				_UpperCAmelCase      :							str       =   np.array(
				    [-11.51_29_25, -4.788215, -0.46172905, -2.051715, -10.53_91_47, -10.97_09_63, -9.091634, 4.0, 4.0]       )
				assert np.abs(mel_slice.flatten() - expected_slice       ).max() < 1e-2
			@skip_mps
			def 							__snake_case	(						self       )      ->      Optional[Any]:






				'''simple docstring'''







				return super().test_save_load_local()
			@skip_mps
			def 							__snake_case	(						self       )      ->      Tuple:






				'''simple docstring'''







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






				'''simple docstring'''







				return super().test_save_load_optional_components()
			@skip_mps
			def 							__snake_case	(						self       )      ->      int:






				'''simple docstring'''







				return super().test_attention_slicing_forward_pass()
			def 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				pass
			def 							__snake_case	(						self       )      ->      List[str]:






				'''simple docstring'''







				pass
			@skip_mps
			def 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				return super().test_progress_bar()






@slow
@require_torch_gpu
@require_onnxruntime
@require_note_seq
class       _UpperCAmelCase     (						unittest.TestCase):
			def 							__snake_case	(						self       )      ->      Optional[int]:






				'''simple docstring'''







				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()
			def 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				_UpperCAmelCase      :							List[Any]       =   torch_device

				_UpperCAmelCase      :							Union[str, Any]       =   SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""       )
				_UpperCAmelCase      :							str       =   pipe.melgan
				_UpperCAmelCase      :							Optional[int]       =   None

				_UpperCAmelCase      :							Optional[int]       =   pipe.to(_A       )
				pipe.set_progress_bar_config(disable=_A       )

				def callback(_A ,						_A       ):
					# decode mel to audio
					_UpperCAmelCase      :							Union[str, Any]       =   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      :							List[str]       =   MidiProcessor()
				_UpperCAmelCase      :							Any       =   processor(_A       )

				_UpperCAmelCase      :							List[Any]       =   input_tokens[:3]
				_UpperCAmelCase      :							Optional[int]       =   torch.manual_seed(0       )
				pipe(_A ,						num_inference_steps=5 ,						generator=_A ,						callback=_A ,						output_type="""mel"""       )
			def 							__snake_case	(						self       )      ->      Any:






				'''simple docstring'''







				_UpperCAmelCase      :							str       =   torch_device

				_UpperCAmelCase      :							Union[str, Any]       =   SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""       )
				_UpperCAmelCase      :							Optional[int]       =   pipe.to(_A       )
				pipe.set_progress_bar_config(disable=_A       )
				_UpperCAmelCase      :							Tuple       =   MidiProcessor()

				_UpperCAmelCase      :							int       =   processor(_A       )
				# just run two denoising loops
				_UpperCAmelCase      :							Union[str, Any]       =   input_tokens[:2]

				_UpperCAmelCase      :							Dict       =   torch.manual_seed(0       )
				_UpperCAmelCase      :							Any       =   pipe(_A ,						num_inference_steps=2 ,						generator=_A       )

				_UpperCAmelCase      :							Any       =   output.audios[0]

				assert abs(np.abs(_A       ).sum() - 36_12.8_41       ) < 1e-1
			def 							__snake_case	(						self       )      ->      Tuple:






				'''simple docstring'''







				_UpperCAmelCase      :							List[Any]       =   torch_device

				_UpperCAmelCase      :							Tuple       =   SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""       )
				_UpperCAmelCase      :							Union[str, Any]       =   pipe.to(_A       )
				pipe.set_progress_bar_config(disable=_A       )

				_UpperCAmelCase      :							Union[str, Any]       =   MidiProcessor()

				_UpperCAmelCase      :							List[str]       =   processor(_A       )

				# just run 4 denoising loops
				_UpperCAmelCase      :							Optional[int]       =   input_tokens[:4]

				_UpperCAmelCase      :							List[Any]       =   torch.manual_seed(0       )
				_UpperCAmelCase      :							List[Any]       =   pipe(_A ,						num_inference_steps=1_00 ,						generator=_A       )

				_UpperCAmelCase      :							Union[str, Any]       =   output.audios[0]
				assert abs(np.abs(_A       ).sum() - 93_89.11_11       ) < 5e-2








"""simple docstring"""






def  UpperCamelCase   (     _lowerCAmelCase       :  float,					_lowerCAmelCase       :  float,					_lowerCAmelCase       :  float	)			->     float:
	if mass < 0:
		raise ValueError("""The mass of the body cannot be negative"""	)
	if radius <= 0:
		raise ValueError("""The radius is always a positive non zero integer"""	)
	return (mass * (velocity) ** 2) / radius


if __name__ == "__main__":
						import doctest

						doctest.testmod(verbose=True)





