





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


UpperCamelCase_           ="""./tests/fixtures/elise_format0.mid"""




@unittest.skip('''The note-seq package currently throws an error on import'''				)
class  _a						(      _lowerCAmelCase	,				unittest.TestCase				):
				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 				snake_case	( self		:    Optional[int]							)	->      List[str]:




										'''simple docstring'''



										torch.manual_seed(0							)
										_UpperCamelCase			:					Optional[int]     =    SpectrogramNotesEncoder(
										    max_length=2_0_4_8, vocab_size=1_5_3_6, d_model=7_6_8, dropout_rate=0.1, num_layers=1, num_heads=1, d_kv=4, d_ff=2_0_4_8, feed_forward_proj='''gated-gelu''', )

										_UpperCamelCase			:					Any     =    SpectrogramContEncoder(
										    input_dims=1_2_8, targets_context_length=2_5_6, d_model=7_6_8, dropout_rate=0.1, num_layers=1, num_heads=1, d_kv=4, d_ff=2_0_4_8, feed_forward_proj='''gated-gelu''', )

										_UpperCamelCase			:					Optional[Any]     =    TaFilmDecoder(
										    input_dims=1_2_8, targets_length=2_5_6, max_decoder_noise_time=20_000.0, d_model=7_6_8, num_layers=1, num_heads=1, d_kv=4, d_ff=2_0_4_8, dropout_rate=0.1, )

										_UpperCamelCase			:					Tuple     =    DDPMScheduler()

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






				def 				snake_case	( self		:    Tuple, lowerCAmelCase__		:    Any, lowerCAmelCase__		:    Optional[Any]=0							)	->      List[str]:




										'''simple docstring'''



										if str(lowerCAmelCase__							).startswith('''mps'''							):
																_UpperCamelCase			:					Any     =    torch.manual_seed(lowerCAmelCase__							)
										else:
																_UpperCamelCase			:					List[str]     =    torch.Generator(device=lowerCAmelCase__							).manual_seed(lowerCAmelCase__							)
										_UpperCamelCase			:					Dict     =    {
										    '''input_tokens''': [
										        [1_1_3_4, 9_0, 1_1_3_5, 1_1_3_3, 1_0_8_0, 1_1_2, 1_1_3_2, 1_0_8_0, 1_1_3_3, 1_0_7_9, 1_3_3, 1_1_3_2, 1_0_7_9, 1_1_3_3, 1] + [0] * 2_0_3_3
										    ],
										    '''generator''': generator,
										    '''num_inference_steps''': 4,
										    '''output_type''': '''mel''',
										}
										return inputs






				def 				snake_case	( self		:    List[Any]							)	->      Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										_UpperCamelCase			:					Optional[Any]     =    self.get_dummy_components()
										_UpperCamelCase			:					Any     =    SpectrogramDiffusionPipeline(**lowerCAmelCase__							)
										_UpperCamelCase			:					int     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					List[Any]     =    self.get_dummy_inputs(lowerCAmelCase__							)
										_UpperCamelCase			:					Dict     =    pipe(**lowerCAmelCase__							)
										_UpperCamelCase			:					Optional[Any]     =    output.audios

										_UpperCamelCase			:					Tuple     =    mel[0, -3:, -3:]

										assert mel_slice.shape == (3, 3)
										_UpperCamelCase			:					int     =    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 				snake_case	( self		:    Any							)	->      Tuple:




										'''simple docstring'''



										return super().test_save_load_local()






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




										'''simple docstring'''



										return super().test_dict_tuple_outputs_equivalent()






				@skip_mps
				def 				snake_case	( self		:    str							)	->      str:




										'''simple docstring'''



										return super().test_save_load_optional_components()






				@skip_mps
				def 				snake_case	( self		:    str							)	->      int:




										'''simple docstring'''



										return super().test_attention_slicing_forward_pass()






				def 				snake_case	( self		:    List[Any]							)	->      str:




										'''simple docstring'''



										pass






				def 				snake_case	( self		:    Dict							)	->      List[Any]:




										'''simple docstring'''



										pass






				@skip_mps
				def 				snake_case	( self		:    Any							)	->      Dict:




										'''simple docstring'''



										return super().test_progress_bar()




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






				def 				snake_case	( self		:    Dict							)	->      List[Any]:




										'''simple docstring'''



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






				def 				snake_case	( self		:    Tuple							)	->      List[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					Optional[Any]     =    torch_device

										_UpperCamelCase			:					int     =    SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''							)
										_UpperCamelCase			:					Any     =    pipe.melgan
										_UpperCamelCase			:					Any     =    None

										_UpperCamelCase			:					Union[str, Any]     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										def callback(lowerCAmelCase__		:    Optional[int], lowerCAmelCase__		:    Optional[Any]							):
																# decode mel to audio
																_UpperCamelCase			:					Union[str, Any]     =    melgan(input_features=mel_output.astype(np.floataa							)							)[0]
																assert len(audio[0]							) == 8_1_9_2_0 * (step + 1)
																# simulate that audio is played
																return audio

										_UpperCamelCase			:					int     =    MidiProcessor()
										_UpperCamelCase			:					Optional[Any]     =    processor(lowerCAmelCase__							)

										_UpperCamelCase			:					Optional[int]     =    input_tokens[:3]
										_UpperCamelCase			:					Optional[int]     =    torch.manual_seed(0							)
										pipe(lowerCAmelCase__, num_inference_steps=5, generator=lowerCAmelCase__, callback=lowerCAmelCase__, output_type='''mel'''							)






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




										'''simple docstring'''



										_UpperCamelCase			:					Dict     =    torch_device

										_UpperCamelCase			:					Dict     =    SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''							)
										_UpperCamelCase			:					Optional[int]     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)
										_UpperCamelCase			:					str     =    MidiProcessor()

										_UpperCamelCase			:					Any     =    processor(lowerCAmelCase__							)
										# just run two denoising loops
										_UpperCamelCase			:					Any     =    input_tokens[:2]

										_UpperCamelCase			:					Optional[int]     =    torch.manual_seed(0							)
										_UpperCamelCase			:					List[Any]     =    pipe(lowerCAmelCase__, num_inference_steps=2, generator=lowerCAmelCase__							)

										_UpperCamelCase			:					Dict     =    output.audios[0]

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






				def 				snake_case	( self		:    List[Any]							)	->      Tuple:




										'''simple docstring'''



										_UpperCamelCase			:					Optional[int]     =    torch_device

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

										_UpperCamelCase			:					List[str]     =    MidiProcessor()

										_UpperCamelCase			:					Dict     =    processor(lowerCAmelCase__							)

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

										_UpperCamelCase			:					Union[str, Any]     =    torch.manual_seed(0							)
										_UpperCamelCase			:					List[Any]     =    pipe(lowerCAmelCase__, num_inference_steps=1_0_0, generator=lowerCAmelCase__							)

										_UpperCamelCase			:					Dict     =    output.audios[0]
										assert abs(np.abs(lowerCAmelCase__							).sum() - 9_389.1_111							) < 5e-2










"""simple docstring"""




from sklearn.metrics import mean_absolute_error

import datasets


UpperCamelCase_           ="""\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
"""

UpperCamelCase_           ="""\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
"""


UpperCamelCase_           ="""
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

                 \"raw_values\" : Returns a full set of errors in case of multioutput input.

                 \"uniform_average\" : Errors of all outputs are averaged with uniform weight.

Returns:
    mae : mean absolute error.
        If multioutput is \"raw_values\", then mean absolute error is returned for each output separately. If multioutput is \"uniform_average\" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric(\"mae\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mae': 0.5}

    If you're using multi-dimensional lists, then set the config as follows :

    >>> mae_metric = datasets.load_metric(\"mae\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mae': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results)
    {'mae': array([0.5, 1. ])}
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,				_KWARGS_DESCRIPTION				)
class  _a						(      datasets.Metric				):






				def 				snake_case	( self		:    Optional[int]							)	->      List[Any]:




										'''simple docstring'''



										return datasets.MetricInfo(
										    description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(self._get_feature_types()							), reference_urls=[
										        '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html'''
										    ], )






				def 				snake_case	( self		:    Dict							)	->      Union[str, Any]:




										'''simple docstring'''



										if self.config_name == "multilist":
																return {
																    "predictions": datasets.Sequence(datasets.Value('''float'''							)							),
																    "references": datasets.Sequence(datasets.Value('''float'''							)							),
																}
										else:
																return {
																    "predictions": datasets.Value('''float'''							),
																    "references": datasets.Value('''float'''							),
																}






				def 				snake_case	( self		:    List[Any], lowerCAmelCase__		:    Dict, lowerCAmelCase__		:    Union[str, Any], lowerCAmelCase__		:    Tuple=None, lowerCAmelCase__		:    Tuple="uniform_average"							)	->      Optional[int]:




										'''simple docstring'''



										_UpperCamelCase			:					List[str]     =    mean_absolute_error(lowerCAmelCase__, lowerCAmelCase__, sample_weight=lowerCAmelCase__, multioutput=lowerCAmelCase__							)

										return {"mae": mae_score}



