

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


lowercase     :       Optional[Any]        =       "./tests/fixtures/elise_format0.mid"
@unittest.skip('The note-seq package currently throws an error on import'   )
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__						,	unittest.TestCase   ):







						"""simple docstring"""




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

						def __lowerCamelCase					(				self    )							->	Dict:




									'''simple docstring'''


									torch.manual_seed(0    )
									__UpperCamelCase    :    List[str]								=      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    :    List[str]								=      TaFilmDecoder(
									    input_dims=1_28 , targets_length=2_56 , max_decoder_noise_time=20000.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[int]								=      {
									    "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    )							->	Optional[int]:




									'''simple docstring'''


									if str(__UpperCamelCase    ).startswith("mps"    ):
												__UpperCamelCase    :    List[Any]								=      torch.manual_seed(__UpperCamelCase    )
									else:
												__UpperCamelCase    :    str								=      torch.Generator(device=__UpperCamelCase    ).manual_seed(__UpperCamelCase    )
									__UpperCamelCase    :    List[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    )							->	int:




									'''simple docstring'''


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

									__UpperCamelCase    :    int								=      self.get_dummy_inputs(__UpperCamelCase    )
									__UpperCamelCase    :    Tuple								=      pipe(**__UpperCamelCase    )
									__UpperCamelCase    :    str								=      output.audios

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

									assert mel_slice.shape == (3, 3)
									__UpperCamelCase    :    List[str]								=      np.array(
									    [-11.512925, -4.788215, -0.46172905, -2.051715, -10.539147, -10.970963, -9.091634, 4.0, 4.0]    )
									assert np.abs(mel_slice.flatten() - expected_slice    ).max() < 1E-2

						@skip_mps
						def __lowerCamelCase					(				self    )							->	Optional[Any]:




									'''simple docstring'''


									return super().test_save_load_local()

						@skip_mps
						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									return super().test_dict_tuple_outputs_equivalent()

						@skip_mps
						def __lowerCamelCase					(				self    )							->	Dict:




									'''simple docstring'''


									return super().test_save_load_optional_components()

						@skip_mps
						def __lowerCamelCase					(				self    )							->	Union[str, Any]:




									'''simple docstring'''


									return super().test_attention_slicing_forward_pass()

						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									pass

						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									pass




						@skip_mps
						def __lowerCamelCase					(				self    )							->	Union[str, Any]:




									'''simple docstring'''


									return super().test_progress_bar()







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







						"""simple docstring"""




						def __lowerCamelCase					(				self    )							->	Dict:




									'''simple docstring'''


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

						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[int]								=      torch_device

									__UpperCamelCase    :    Dict								=      SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"    )
									__UpperCamelCase    :    Tuple								=      pipe.melgan
									__UpperCamelCase    :    Any								=      None

									__UpperCamelCase    :    Optional[Any]								=      pipe.to(__UpperCamelCase    )
									pipe.set_progress_bar_config(disable=__UpperCamelCase    )

									def callback(__UpperCamelCase , __UpperCamelCase    ):
												# decode mel to audio
												__UpperCamelCase    :    Dict								=      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    :    int								=      MidiProcessor()
									__UpperCamelCase    :    int								=      processor(__UpperCamelCase    )

									__UpperCamelCase    :    List[str]								=      input_tokens[:3]
									__UpperCamelCase    :    Tuple								=      torch.manual_seed(0    )
									pipe(__UpperCamelCase , num_inference_steps=5 , generator=__UpperCamelCase , callback=__UpperCamelCase , output_type="mel"    )

						def __lowerCamelCase					(				self    )							->	Dict:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      torch_device

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

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

									__UpperCamelCase    :    Tuple								=      torch.manual_seed(0    )
									__UpperCamelCase    :    Optional[Any]								=      pipe(__UpperCamelCase , num_inference_steps=2 , generator=__UpperCamelCase    )

									__UpperCamelCase    :    Dict								=      output.audios[0]

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




						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[int]								=      torch_device

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

									__UpperCamelCase    :    Optional[Any]								=      MidiProcessor()

									__UpperCamelCase    :    Any								=      processor(__UpperCamelCase    )

									# just run 4 denoising loops
									__UpperCamelCase    :    str								=      input_tokens[:4]

									__UpperCamelCase    :    Union[str, Any]								=      torch.manual_seed(0    )
									__UpperCamelCase    :    Tuple								=      pipe(__UpperCamelCase , num_inference_steps=1_00 , generator=__UpperCamelCase    )

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


from collections.abc import Callable

lowercase     :       Optional[Any]        =       Callable[[float], float]  # type alias for a real -> real function







def  UpperCAmelCase_   (_lowerCAmelCase :		RealFunc     ,			_lowerCAmelCase :		RealFunc     ,			_lowerCAmelCase :		int     ,			):
			__UpperCamelCase    :    Any								=      float(_lowerCAmelCase		)
			while True:
						try:
									__UpperCamelCase    :    List[Any]								=      prev_guess - function(_lowerCAmelCase		) / derivative(_lowerCAmelCase		)
						except ZeroDivisionError:
									raise ZeroDivisionError("Could not find root"		) from None
						if abs(prev_guess - next_guess		) < 10**-5:
									return next_guess
						__UpperCamelCase    :    Tuple								=      next_guess







def  UpperCAmelCase_   (_lowerCAmelCase :		float		):
			return (x**3) - (2 * x) - 5







def  UpperCAmelCase_   (_lowerCAmelCase :		float		):
			return 3 * (x**2) - 2


if __name__ == "__main__":
					print(newton(f, fa, 3))