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


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






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



						"""simple docstring"""




						lowercase__       =  SpectrogramDiffusionPipeline
						lowercase__       =  PipelineTesterMixin.required_optional_params - {
						    '''callback''',
						    '''latents''',
						    '''callback_steps''',
						    '''output_type''',
						    '''num_images_per_prompt''',
						}
						lowercase__       =  False
						lowercase__       =  False
						lowercase__       =  TOKENS_TO_AUDIO_GENERATION_PARAMS
						lowercase__       =  TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS





						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				Tuple:
													'''simple docstring'''



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

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

													__UpperCamelCase							=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=2048     , dropout_rate=0.1     , )

													__UpperCamelCase							=DDPMScheduler()

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





						def   UpperCAmelCase_ (				self							:    List[Any]     , UpperCamelCase__							:    int     , UpperCamelCase__							:    Union[str, Any]=0				)				->				Optional[int]:
													'''simple docstring'''



													if str(UpperCamelCase__				).startswith('''mps'''				):
																				__UpperCamelCase							=torch.manual_seed(UpperCamelCase__				)
													else:
																				__UpperCamelCase							=torch.Generator(device=UpperCamelCase__				).manual_seed(UpperCamelCase__				)
													__UpperCamelCase							={
													    '''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   UpperCAmelCase_ (				self							:    Dict				)				->				Optional[int]:
													'''simple docstring'''



													__UpperCamelCase							='''cpu'''  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase							=self.get_dummy_components()
													__UpperCamelCase							=SpectrogramDiffusionPipeline(**UpperCamelCase__				)
													__UpperCamelCase							=pipe.to(UpperCamelCase__				)
													pipe.set_progress_bar_config(disable=UpperCamelCase__				)

													__UpperCamelCase							=self.get_dummy_inputs(UpperCamelCase__				)
													__UpperCamelCase							=pipe(**UpperCamelCase__				)
													__UpperCamelCase							=output.audios

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

													assert mel_slice.shape == (3, 3)
													__UpperCamelCase							=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   UpperCAmelCase_ (				self							:    List[str]				)				->				str:
													'''simple docstring'''



													return super().test_save_load_local()





						@skip_mps
						def   UpperCAmelCase_ (				self							:    Optional[int]				)				->				Optional[Any]:
													'''simple docstring'''



													return super().test_dict_tuple_outputs_equivalent()





						@skip_mps
						def   UpperCAmelCase_ (				self							:    Any				)				->				List[str]:
													'''simple docstring'''



													return super().test_save_load_optional_components()





						@skip_mps
						def   UpperCAmelCase_ (				self							:    str				)				->				Union[str, Any]:
													'''simple docstring'''



													return super().test_attention_slicing_forward_pass()





						def   UpperCAmelCase_ (				self							:    Optional[int]				)				->				Optional[Any]:
													'''simple docstring'''



													pass





						def   UpperCAmelCase_ (				self							:    Dict				)				->				Dict:
													'''simple docstring'''



													pass





						@skip_mps
						def   UpperCAmelCase_ (				self							:    int				)				->				Tuple:
													'''simple docstring'''



													return super().test_progress_bar()






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



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Dict				)				->				List[Any]:
													'''simple docstring'''



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





						def   UpperCAmelCase_ (				self							:    int				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=torch_device

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

													__UpperCamelCase							=pipe.to(UpperCamelCase__				)
													pipe.set_progress_bar_config(disable=UpperCamelCase__				)

													def callback(UpperCamelCase__							:    Optional[Any]     , UpperCamelCase__							:    List[str]				):
																				# decode mel to audio
																				__UpperCamelCase							=melgan(input_features=mel_output.astype(np.floataa				)				)[0]
																				assert len(audio[0]				) == 81920 * (step + 1)
																				# simulate that audio is played
																				return audio

													__UpperCamelCase							=MidiProcessor()
													__UpperCamelCase							=processor(UpperCamelCase__				)

													__UpperCamelCase							=input_tokens[:3]
													__UpperCamelCase							=torch.manual_seed(0				)
													pipe(UpperCamelCase__     , num_inference_steps=5     , generator=UpperCamelCase__     , callback=UpperCamelCase__     , output_type='''mel'''				)





						def   UpperCAmelCase_ (				self							:    List[str]				)				->				Dict:
													'''simple docstring'''



													__UpperCamelCase							=torch_device

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

													__UpperCamelCase							=processor(UpperCamelCase__				)
													# just run two denoising loops
													__UpperCamelCase							=input_tokens[:2]

													__UpperCamelCase							=torch.manual_seed(0				)
													__UpperCamelCase							=pipe(UpperCamelCase__     , num_inference_steps=2     , generator=UpperCamelCase__				)

													__UpperCamelCase							=output.audios[0]

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





						def   UpperCAmelCase_ (				self							:    Optional[int]				)				->				Tuple:
													'''simple docstring'''



													__UpperCamelCase							=torch_device

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

													__UpperCamelCase							=MidiProcessor()

													__UpperCamelCase							=processor(UpperCamelCase__				)

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

													__UpperCamelCase							=torch.manual_seed(0				)
													__UpperCamelCase							=pipe(UpperCamelCase__     , num_inference_steps=100     , generator=UpperCamelCase__				)

													__UpperCamelCase							=output.audios[0]
													assert abs(np.abs(UpperCamelCase__				).sum() - 93_89.11_11				) < 5E-2




"""simple docstring"""

from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


__lowercase    =				{
    '''id''': '''5733be284776f41900661182''',
    '''title''': '''University_of_Notre_Dame''',
    '''context''': '''Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.''',
    '''question''': '''To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?''',
    '''answers''': {'''text''': ['''Saint Bernadette Soubirous'''], '''answer_start''': [515]},
}


@pytest.mark.parametrize(
    '''task_cls'''							,					[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]							,					)
def    lowerCAmelCase			(__UpperCamelCase							:    List[str]			):
							"""simple docstring"""


							__UpperCamelCase							=task_cls()
							__UpperCamelCase							=asdict(__UpperCamelCase			)
							__UpperCamelCase							=task_template_from_dict(__UpperCamelCase			)
							assert task == reloaded






class 		_lowercase :



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Union[str, Any]				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=LanguageModeling(text_column='''input_text'''				)
													assert {"input_text": "text"} == task.column_mapping





						def   UpperCAmelCase_ (				self							:    str				)				->				int:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''text''': Value('''string'''				)}				)
													__UpperCamelCase							={'''text_column''': '''input_text'''}
													__UpperCamelCase							=LanguageModeling.from_dict(UpperCamelCase__				)
													assert "language-modeling" == task.task
													assert input_schema == task.input_schema






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				Dict:
													'''simple docstring'''



													__UpperCamelCase							=sorted(['''pos''', '''neg''']				)





						def   UpperCAmelCase_ (				self							:    Tuple				)				->				Tuple:
													'''simple docstring'''



													__UpperCamelCase							=TextClassification(text_column='''input_text'''     , label_column='''input_label'''				)
													self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''}     , task.column_mapping				)





						def   UpperCAmelCase_ (				self							:    Union[str, Any]				)				->				Union[str, Any]:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''text''': Value('''string'''				)}				)
													# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
													__UpperCamelCase							=Features({'''labels''': ClassLabel}				)
													__UpperCamelCase							={'''text_column''': '''input_text''', '''label_column''': '''input_labels'''}
													__UpperCamelCase							=TextClassification.from_dict(UpperCamelCase__				)
													self.assertEqual('''text-classification'''     , task.task				)
													self.assertEqual(UpperCamelCase__     , task.input_schema				)
													self.assertEqual(UpperCamelCase__     , task.label_schema				)





						def   UpperCAmelCase_ (				self							:    Tuple				)				->				Optional[Any]:
													'''simple docstring'''



													__UpperCamelCase							=TextClassification(text_column='''input_text'''     , label_column='''input_label'''				)
													self.assertEqual(task.label_schema['''labels''']     , UpperCamelCase__				)
													__UpperCamelCase							=task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels				)}				)				)
													self.assertEqual(task.label_schema['''labels''']     , ClassLabel(names=self.labels				)				)






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Dict				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=QuestionAnsweringExtractive(
													    context_column='''input_context'''     , question_column='''input_question'''     , answers_column='''input_answers'''				)
													self.assertDictEqual(
													    {'''input_context''': '''context''', '''input_question''': '''question''', '''input_answers''': '''answers'''}     , task.column_mapping				)





						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				Optional[Any]:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''question''': Value('''string'''				), '''context''': Value('''string'''				)}				)
													__UpperCamelCase							=Features(
													    {
													        '''answers''': Sequence(
													            {
													                '''text''': Value('''string'''				),
													                '''answer_start''': Value('''int32'''				),
													            }				)
													    }				)
													__UpperCamelCase							={
													    '''context_column''': '''input_input_context''',
													    '''question_column''': '''input_question''',
													    '''answers_column''': '''input_answers''',
													}
													__UpperCamelCase							=QuestionAnsweringExtractive.from_dict(UpperCamelCase__				)
													self.assertEqual('''question-answering-extractive'''     , task.task				)
													self.assertEqual(UpperCamelCase__     , task.input_schema				)
													self.assertEqual(UpperCamelCase__     , task.label_schema				)






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    List[Any]				)				->				str:
													'''simple docstring'''



													__UpperCamelCase							=Summarization(text_column='''input_text'''     , summary_column='''input_summary'''				)
													self.assertDictEqual({'''input_text''': '''text''', '''input_summary''': '''summary'''}     , task.column_mapping				)





						def   UpperCAmelCase_ (				self							:    int				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''text''': Value('''string'''				)}				)
													__UpperCamelCase							=Features({'''summary''': Value('''string'''				)}				)
													__UpperCamelCase							={'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
													__UpperCamelCase							=Summarization.from_dict(UpperCamelCase__				)
													self.assertEqual('''summarization'''     , task.task				)
													self.assertEqual(UpperCamelCase__     , task.input_schema				)
													self.assertEqual(UpperCamelCase__     , task.label_schema				)






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    List[Any]				)				->				Dict:
													'''simple docstring'''



													__UpperCamelCase							=AutomaticSpeechRecognition(audio_column='''input_audio'''     , transcription_column='''input_transcription'''				)
													self.assertDictEqual({'''input_audio''': '''audio''', '''input_transcription''': '''transcription'''}     , task.column_mapping				)





						def   UpperCAmelCase_ (				self							:    Union[str, Any]				)				->				List[str]:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''audio''': Audio()}				)
													__UpperCamelCase							=Features({'''transcription''': Value('''string'''				)}				)
													__UpperCamelCase							={
													    '''audio_column''': '''input_audio''',
													    '''transcription_column''': '''input_transcription''',
													}
													__UpperCamelCase							=AutomaticSpeechRecognition.from_dict(UpperCamelCase__				)
													self.assertEqual('''automatic-speech-recognition'''     , task.task				)
													self.assertEqual(UpperCamelCase__     , task.input_schema				)
													self.assertEqual(UpperCamelCase__     , task.label_schema				)






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    List[str]				)				->				List[str]:
													'''simple docstring'''



													__UpperCamelCase							=sorted(['''pos''', '''neg''']				)





						def   UpperCAmelCase_ (				self							:    Union[str, Any]				)				->				int:
													'''simple docstring'''



													__UpperCamelCase							=AudioClassification(audio_column='''input_audio'''     , label_column='''input_label'''				)
													self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''}     , task.column_mapping				)





						def   UpperCAmelCase_ (				self							:    Dict				)				->				Any:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''audio''': Audio()}				)
													__UpperCamelCase							=Features({'''labels''': ClassLabel}				)
													__UpperCamelCase							={
													    '''audio_column''': '''input_image''',
													    '''label_column''': '''input_label''',
													}
													__UpperCamelCase							=AudioClassification.from_dict(UpperCamelCase__				)
													self.assertEqual('''audio-classification'''     , task.task				)
													self.assertEqual(UpperCamelCase__     , task.input_schema				)
													self.assertEqual(UpperCamelCase__     , task.label_schema				)





						def   UpperCAmelCase_ (				self							:    Tuple				)				->				List[str]:
													'''simple docstring'''



													__UpperCamelCase							=AudioClassification(audio_column='''input_audio'''     , label_column='''input_label'''				)
													self.assertEqual(task.label_schema['''labels''']     , UpperCamelCase__				)
													__UpperCamelCase							=task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels				)}				)				)
													self.assertEqual(task.label_schema['''labels''']     , ClassLabel(names=self.labels				)				)






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				str:
													'''simple docstring'''



													__UpperCamelCase							=sorted(['''pos''', '''neg''']				)





						def   UpperCAmelCase_ (				self							:    str				)				->				Tuple:
													'''simple docstring'''



													__UpperCamelCase							=ImageClassification(image_column='''input_image'''     , label_column='''input_label'''				)
													self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''}     , task.column_mapping				)





						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				List[str]:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''image''': Image()}				)
													__UpperCamelCase							=Features({'''labels''': ClassLabel}				)
													__UpperCamelCase							={
													    '''image_column''': '''input_image''',
													    '''label_column''': '''input_label''',
													}
													__UpperCamelCase							=ImageClassification.from_dict(UpperCamelCase__				)
													self.assertEqual('''image-classification'''     , task.task				)
													self.assertEqual(UpperCamelCase__     , task.input_schema				)
													self.assertEqual(UpperCamelCase__     , task.label_schema				)





						def   UpperCAmelCase_ (				self							:    str				)				->				Optional[int]:
													'''simple docstring'''



													__UpperCamelCase							=ImageClassification(image_column='''input_image'''     , label_column='''input_label'''				)
													self.assertEqual(task.label_schema['''labels''']     , UpperCamelCase__				)
													__UpperCamelCase							=task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels				)}				)				)
													self.assertEqual(task.label_schema['''labels''']     , ClassLabel(names=self.labels				)				)






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=DatasetInfo(task_templates=QuestionAnsweringExtractive()				)
													__UpperCamelCase							=Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}     , info=UpperCamelCase__				)
													assert isinstance(dataset.info.task_templates     , UpperCamelCase__				)
													assert len(dataset.info.task_templates				) == 1

													def keep_task(UpperCamelCase__							:    Optional[int]				):
																				return x

													def dont_keep_task(UpperCamelCase__							:    Optional[int]				):
																				__UpperCamelCase							=deepcopy(UpperCamelCase__				)
																				__UpperCamelCase							=0
																				return out

													__UpperCamelCase							=dataset.map(UpperCamelCase__				)
													assert mapped_dataset.info.task_templates == dataset.info.task_templates
													# reload from cache
													__UpperCamelCase							=dataset.map(UpperCamelCase__				)
													assert mapped_dataset.info.task_templates == dataset.info.task_templates

													__UpperCamelCase							=dataset.map(UpperCamelCase__				)
													assert mapped_dataset.info.task_templates == []
													# reload from cache
													__UpperCamelCase							=dataset.map(UpperCamelCase__				)
													assert mapped_dataset.info.task_templates == []





						def   UpperCAmelCase_ (				self							:    List[str]				)				->				Dict:
													'''simple docstring'''



													__UpperCamelCase							=Features({'''text''': Value('''string'''				), '''label''': ClassLabel(names=('''pos''', '''neg''')				)}				)
													__UpperCamelCase							=TextClassification(text_column='''text'''     , label_column='''label'''				)
													__UpperCamelCase							=DatasetInfo(features=UpperCamelCase__     , task_templates=UpperCamelCase__				)
													__UpperCamelCase							=Dataset.from_dict({'''text''': ['''A sentence.'''], '''label''': ['''pos''']}     , info=UpperCamelCase__				)

													def process(UpperCamelCase__							:    Any				):
																				return example

													__UpperCamelCase							=dataset.remove_columns('''label'''				)
													__UpperCamelCase							=modified_dataset.map(UpperCamelCase__				)
													assert mapped_dataset.info.task_templates == []



