




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


UpperCamelCase__              =						'./tests/fixtures/elise_format0.mid'


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

					def 	lowercase_							(				self					):







						'''simple docstring'''




						torch.manual_seed(0					)
						lowerCamelCase_							:		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' ,       )

						lowerCamelCase_							:		List[Any]							   =							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' ,       )

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

						lowerCamelCase_							:		str							   =							DDPMScheduler()

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

					def 	lowercase_							(				self ,       __lowercase ,       __lowercase=0					):







						'''simple docstring'''




						if str(__lowercase					).startswith('mps'					):
							lowerCamelCase_							:		List[str]							   =							torch.manual_seed(__lowercase					)
						else:
							lowerCamelCase_							:		Union[str, Any]							   =							torch.Generator(device=__lowercase					).manual_seed(__lowercase					)
						lowerCamelCase_							:		Dict							   =							{
						    '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 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Tuple							   =							'cpu'  # ensure determinism for the device-dependent torch.Generator
						lowerCamelCase_							:		str							   =							self.get_dummy_components()
						lowerCamelCase_							:		Tuple							   =							SpectrogramDiffusionPipeline(**__lowercase					)
						lowerCamelCase_							:		List[str]							   =							pipe.to(__lowercase					)
						pipe.set_progress_bar_config(disable=__lowercase					)

						lowerCamelCase_							:		int							   =							self.get_dummy_inputs(__lowercase					)
						lowerCamelCase_							:		Optional[int]							   =							pipe(**__lowercase					)
						lowerCamelCase_							:		Any							   =							output.audios

						lowerCamelCase_							:		Optional[Any]							   =							mel[0, -3:, -3:]

						assert mel_slice.shape == (3, 3)
						lowerCamelCase_							:		Optional[Any]							   =							np.array(
						    [-11.51_29_25, -4.78_82_15, -0.46_17_29_05, -2.05_17_15, -10.53_91_47, -10.97_09_63, -9.09_16_34, 4.0, 4.0]					)
						assert np.abs(mel_slice.flatten() - expected_slice					).max() < 1E-2

					@skip_mps
					def 	lowercase_							(				self					):







						'''simple docstring'''




						return super().test_save_load_local()

					@skip_mps
					def 	lowercase_							(				self					):







						'''simple docstring'''




						return super().test_dict_tuple_outputs_equivalent()

					@skip_mps
					def 	lowercase_							(				self					):







						'''simple docstring'''




						return super().test_save_load_optional_components()

					@skip_mps
					def 	lowercase_							(				self					):







						'''simple docstring'''




						return super().test_attention_slicing_forward_pass()

					def 	lowercase_							(				self					):







						'''simple docstring'''




						pass

					def 	lowercase_							(				self					):







						'''simple docstring'''




						pass





					@skip_mps
					def 	lowercase_							(				self					):







						'''simple docstring'''




						return super().test_progress_bar()


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

					def 	lowercase_							(				self					):







						'''simple docstring'''




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

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		str							   =							torch_device

						lowerCamelCase_							:		Optional[Any]							   =							SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'					)
						lowerCamelCase_							:		Tuple							   =							pipe.melgan
						lowerCamelCase_							:		List[str]							   =							None

						lowerCamelCase_							:		List[Any]							   =							pipe.to(__lowercase					)
						pipe.set_progress_bar_config(disable=__lowercase					)

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

						lowerCamelCase_							:		Tuple							   =							MidiProcessor()
						lowerCamelCase_							:		List[str]							   =							processor(__lowercase					)

						lowerCamelCase_							:		Optional[Any]							   =							input_tokens[:3]
						lowerCamelCase_							:		str							   =							torch.manual_seed(0					)
						pipe(__lowercase ,       num_inference_steps=5 ,       generator=__lowercase ,       callback=__lowercase ,       output_type='mel'					)

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Dict							   =							torch_device

						lowerCamelCase_							:		Tuple							   =							SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'					)
						lowerCamelCase_							:		str							   =							pipe.to(__lowercase					)
						pipe.set_progress_bar_config(disable=__lowercase					)
						lowerCamelCase_							:		str							   =							MidiProcessor()

						lowerCamelCase_							:		List[str]							   =							processor(__lowercase					)
						# just run two denoising loops
						lowerCamelCase_							:		List[str]							   =							input_tokens[:2]

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

						lowerCamelCase_							:		Union[str, Any]							   =							output.audios[0]

						assert abs(np.abs(__lowercase					).sum() - 36_12.8_41					) < 1E-1





					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Tuple							   =							torch_device

						lowerCamelCase_							:		str							   =							SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'					)
						lowerCamelCase_							:		List[Any]							   =							pipe.to(__lowercase					)
						pipe.set_progress_bar_config(disable=__lowercase					)

						lowerCamelCase_							:		Optional[int]							   =							MidiProcessor()

						lowerCamelCase_							:		str							   =							processor(__lowercase					)

						# just run 4 denoising loops
						lowerCamelCase_							:		Dict							   =							input_tokens[:4]

						lowerCamelCase_							:		Tuple							   =							torch.manual_seed(0					)
						lowerCamelCase_							:		str							   =							pipe(__lowercase ,       num_inference_steps=100 ,       generator=__lowercase					)

						lowerCamelCase_							:		List[str]							   =							output.audios[0]
						assert abs(np.abs(__lowercase					).sum() - 93_89.11_11					) < 5E-2






def 					snake_case					(							A			)							->							int:




	'''simple docstring'''


	if not isinstance(A						,   A			):
		raise ValueError('double_factorial() only accepts integral values'			)
	if n < 0:
		raise ValueError('double_factorial() not defined for negative values'			)
	return 1 if n <= 1 else n * double_factorial(n - 2			)


if __name__ == "__main__":
							import doctest

							doctest.testmod()
