





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		:     List[Any] 					={
    """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 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__	):
		lowerCamelCase_  :    Tuple   	=			task_cls()
		lowerCamelCase_  :    Dict   	=			asdict(lowerCAmelCase__	)
		lowerCamelCase_  :    Any   	=			task_template_from_dict(lowerCAmelCase__	)
		assert task == reloaded






class 	UpperCamelCase_     :



					def      __a    (		self    :    List[Any]	):
							lowerCamelCase_  :    Optional[int]   	=			LanguageModeling(text_column='input_text'	)
							assert {"input_text": "text"} == task.column_mapping





					def      __a    (		self    :    int	):
							lowerCamelCase_  :    Union[str, Any]   	=			Features({'text': Value('string'	)}	)
							lowerCamelCase_  :    List[Any]   	=			{'text_column': 'input_text'}
							lowerCamelCase_  :    List[Any]   	=			LanguageModeling.from_dict(lowerCamelCase	)
							assert "language-modeling" == task.task
							assert input_schema == task.input_schema






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    Optional[int]	):
							lowerCamelCase_  :    List[str]   	=			sorted(['pos', 'neg']	)



					def      __a    (		self    :    Dict	):
							lowerCamelCase_  :    int   	=			TextClassification(text_column='input_text'					,			label_column='input_label'	)
							self.assertDictEqual({'input_text': 'text', 'input_label': 'labels'}					,			task.column_mapping	)



					def      __a    (		self    :    Optional[int]	):
							lowerCamelCase_  :    List[Any]   	=			Features({'text': Value('string'	)}	)
							# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
							lowerCamelCase_  :    int   	=			Features({'labels': ClassLabel}	)
							lowerCamelCase_  :    int   	=			{'text_column': 'input_text', 'label_column': 'input_labels'}
							lowerCamelCase_  :    List[str]   	=			TextClassification.from_dict(lowerCamelCase	)
							self.assertEqual('text-classification'					,			task.task	)
							self.assertEqual(lowerCamelCase					,			task.input_schema	)
							self.assertEqual(lowerCamelCase					,			task.label_schema	)





					def      __a    (		self    :    Tuple	):
							lowerCamelCase_  :    Any   	=			TextClassification(text_column='input_text'					,			label_column='input_label'	)
							self.assertEqual(task.label_schema['labels']					,			lowerCamelCase	)
							lowerCamelCase_  :    Optional[int]   	=			task.align_with_features(Features({'input_label': ClassLabel(names=self.labels	)}	)	)
							self.assertEqual(task.label_schema['labels']					,			ClassLabel(names=self.labels	)	)






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    Optional[Any]	):
							lowerCamelCase_  :    Optional[int]   	=			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      __a    (		self    :    Tuple	):
							lowerCamelCase_  :    Union[str, Any]   	=			Features({'question': Value('string'	), 'context': Value('string'	)}	)
							lowerCamelCase_  :    Union[str, Any]   	=			Features(
							    {
							        'answers': Sequence(
							            {
							                'text': Value('string'	),
							                'answer_start': Value('int32'	),
							            }	)
							    }	)
							lowerCamelCase_  :    List[Any]   	=			{
							    'context_column': 'input_input_context',
							    'question_column': 'input_question',
							    'answers_column': 'input_answers',
							}
							lowerCamelCase_  :    Union[str, Any]   	=			QuestionAnsweringExtractive.from_dict(lowerCamelCase	)
							self.assertEqual('question-answering-extractive'					,			task.task	)
							self.assertEqual(lowerCamelCase					,			task.input_schema	)
							self.assertEqual(lowerCamelCase					,			task.label_schema	)






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    List[Any]	):
							lowerCamelCase_  :    Any   	=			Summarization(text_column='input_text'					,			summary_column='input_summary'	)
							self.assertDictEqual({'input_text': 'text', 'input_summary': 'summary'}					,			task.column_mapping	)





					def      __a    (		self    :    Tuple	):
							lowerCamelCase_  :    Optional[int]   	=			Features({'text': Value('string'	)}	)
							lowerCamelCase_  :    Union[str, Any]   	=			Features({'summary': Value('string'	)}	)
							lowerCamelCase_  :    str   	=			{'text_column': 'input_text', 'summary_column': 'input_summary'}
							lowerCamelCase_  :    Optional[Any]   	=			Summarization.from_dict(lowerCamelCase	)
							self.assertEqual('summarization'					,			task.task	)
							self.assertEqual(lowerCamelCase					,			task.input_schema	)
							self.assertEqual(lowerCamelCase					,			task.label_schema	)






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    List[str]	):
							lowerCamelCase_  :    Any   	=			AutomaticSpeechRecognition(audio_column='input_audio'					,			transcription_column='input_transcription'	)
							self.assertDictEqual({'input_audio': 'audio', 'input_transcription': 'transcription'}					,			task.column_mapping	)





					def      __a    (		self    :    Dict	):
							lowerCamelCase_  :    List[Any]   	=			Features({'audio': Audio()}	)
							lowerCamelCase_  :    Tuple   	=			Features({'transcription': Value('string'	)}	)
							lowerCamelCase_  :    Optional[Any]   	=			{
							    'audio_column': 'input_audio',
							    'transcription_column': 'input_transcription',
							}
							lowerCamelCase_  :    Any   	=			AutomaticSpeechRecognition.from_dict(lowerCamelCase	)
							self.assertEqual('automatic-speech-recognition'					,			task.task	)
							self.assertEqual(lowerCamelCase					,			task.input_schema	)
							self.assertEqual(lowerCamelCase					,			task.label_schema	)






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    Optional[int]	):
							lowerCamelCase_  :    Optional[Any]   	=			sorted(['pos', 'neg']	)



					def      __a    (		self    :    Optional[int]	):
							lowerCamelCase_  :    List[str]   	=			AudioClassification(audio_column='input_audio'					,			label_column='input_label'	)
							self.assertDictEqual({'input_audio': 'audio', 'input_label': 'labels'}					,			task.column_mapping	)



					def      __a    (		self    :    Tuple	):
							lowerCamelCase_  :    Union[str, Any]   	=			Features({'audio': Audio()}	)
							lowerCamelCase_  :    Any   	=			Features({'labels': ClassLabel}	)
							lowerCamelCase_  :    Dict   	=			{
							    'audio_column': 'input_image',
							    'label_column': 'input_label',
							}
							lowerCamelCase_  :    Dict   	=			AudioClassification.from_dict(lowerCamelCase	)
							self.assertEqual('audio-classification'					,			task.task	)
							self.assertEqual(lowerCamelCase					,			task.input_schema	)
							self.assertEqual(lowerCamelCase					,			task.label_schema	)





					def      __a    (		self    :    Any	):
							lowerCamelCase_  :    str   	=			AudioClassification(audio_column='input_audio'					,			label_column='input_label'	)
							self.assertEqual(task.label_schema['labels']					,			lowerCamelCase	)
							lowerCamelCase_  :    Dict   	=			task.align_with_features(Features({'input_label': ClassLabel(names=self.labels	)}	)	)
							self.assertEqual(task.label_schema['labels']					,			ClassLabel(names=self.labels	)	)






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    int	):
							lowerCamelCase_  :    Optional[Any]   	=			sorted(['pos', 'neg']	)



					def      __a    (		self    :    List[str]	):
							lowerCamelCase_  :    Union[str, Any]   	=			ImageClassification(image_column='input_image'					,			label_column='input_label'	)
							self.assertDictEqual({'input_image': 'image', 'input_label': 'labels'}					,			task.column_mapping	)



					def      __a    (		self    :    List[str]	):
							lowerCamelCase_  :    int   	=			Features({'image': Image()}	)
							lowerCamelCase_  :    List[Any]   	=			Features({'labels': ClassLabel}	)
							lowerCamelCase_  :    List[str]   	=			{
							    'image_column': 'input_image',
							    'label_column': 'input_label',
							}
							lowerCamelCase_  :    Dict   	=			ImageClassification.from_dict(lowerCamelCase	)
							self.assertEqual('image-classification'					,			task.task	)
							self.assertEqual(lowerCamelCase					,			task.input_schema	)
							self.assertEqual(lowerCamelCase					,			task.label_schema	)





					def      __a    (		self    :    Optional[Any]	):
							lowerCamelCase_  :    Any   	=			ImageClassification(image_column='input_image'					,			label_column='input_label'	)
							self.assertEqual(task.label_schema['labels']					,			lowerCamelCase	)
							lowerCamelCase_  :    Dict   	=			task.align_with_features(Features({'input_label': ClassLabel(names=self.labels	)}	)	)
							self.assertEqual(task.label_schema['labels']					,			ClassLabel(names=self.labels	)	)






class 	UpperCamelCase_     (     snake_case__       ):



					def      __a    (		self    :    int	):
							lowerCamelCase_  :    Optional[Any]   	=			DatasetInfo(task_templates=QuestionAnsweringExtractive()	)
							lowerCamelCase_  :    Any   	=			Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}					,			info=lowerCamelCase	)
							assert isinstance(dataset.info.task_templates					,			lowerCamelCase	)
							assert len(dataset.info.task_templates	) == 1

							def keep_task(lowerCamelCase    :    List[Any]	):
									return x

							def dont_keep_task(lowerCamelCase    :    int	):
									lowerCamelCase_  :    Dict   	=			deepcopy(lowerCamelCase	)
									lowerCamelCase_  :    Dict   	=			0
									return out

							lowerCamelCase_  :    Tuple   	=			dataset.map(lowerCamelCase	)
							assert mapped_dataset.info.task_templates == dataset.info.task_templates
							# reload from cache
							lowerCamelCase_  :    int   	=			dataset.map(lowerCamelCase	)
							assert mapped_dataset.info.task_templates == dataset.info.task_templates

							lowerCamelCase_  :    List[str]   	=			dataset.map(lowerCamelCase	)
							assert mapped_dataset.info.task_templates == []
							# reload from cache
							lowerCamelCase_  :    List[Any]   	=			dataset.map(lowerCamelCase	)
							assert mapped_dataset.info.task_templates == []





					def      __a    (		self    :    int	):
							lowerCamelCase_  :    List[Any]   	=			Features({'text': Value('string'	), 'label': ClassLabel(names=('pos', 'neg')	)}	)
							lowerCamelCase_  :    Union[str, Any]   	=			TextClassification(text_column='text'					,			label_column='label'	)
							lowerCamelCase_  :    str   	=			DatasetInfo(features=lowerCamelCase					,			task_templates=lowerCamelCase	)
							lowerCamelCase_  :    str   	=			Dataset.from_dict({'text': ['A sentence.'], 'label': ['pos']}					,			info=lowerCamelCase	)

							def process(lowerCamelCase    :    List[Any]	):
									return example

							lowerCamelCase_  :    List[str]   	=			dataset.remove_columns('label'	)
							lowerCamelCase_  :    List[str]   	=			modified_dataset.map(lowerCamelCase	)
							assert mapped_dataset.info.task_templates == []







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 	UpperCamelCase_     (     snake_case__     ,    unittest.TestCase       ):
					_a			:	int							=				SpectrogramDiffusionPipeline
					_a			:	Dict							=				PipelineTesterMixin.required_optional_params - {
					    'callback',
					    'latents',
					    'callback_steps',
					    'output_type',
					    'num_images_per_prompt',
					}
					_a			:	str							=				False
					_a			:	Union[str, Any]							=				False
					_a			:	Optional[int]							=				TOKENS_TO_AUDIO_GENERATION_PARAMS
					_a			:	Optional[Any]							=				TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS



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

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

							lowerCamelCase_  :    Union[str, Any]   	=			TaFilmDecoder(
							    input_dims=1_28					,			targets_length=2_56					,			max_decoder_noise_time=20_000.0					,			d_model=7_68					,			num_layers=1					,			num_heads=1					,			d_kv=4					,			d_ff=20_48					,			dropout_rate=0.1					,			)

							lowerCamelCase_  :    Any   	=			DDPMScheduler()

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



					def      __a    (		self    :    Any					,			lowerCamelCase    :    Any					,			lowerCamelCase    :    int=0	):
							if str(lowerCamelCase	).startswith('mps'	):
									lowerCamelCase_  :    Optional[int]   	=			torch.manual_seed(lowerCamelCase	)
							else:
									lowerCamelCase_  :    Dict   	=			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)
							lowerCamelCase_  :    str   	=			{
							    '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      __a    (		self    :    Dict	):
							lowerCamelCase_  :    str   	=			'cpu'  # ensure determinism for the device-dependent torch.Generator
							lowerCamelCase_  :    Dict   	=			self.get_dummy_components()
							lowerCamelCase_  :    Tuple   	=			SpectrogramDiffusionPipeline(**lowerCamelCase	)
							lowerCamelCase_  :    List[str]   	=			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							lowerCamelCase_  :    Optional[Any]   	=			self.get_dummy_inputs(lowerCamelCase	)
							lowerCamelCase_  :    str   	=			pipe(**lowerCamelCase	)
							lowerCamelCase_  :    Tuple   	=			output.audios

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

							assert mel_slice.shape == (3, 3)
							lowerCamelCase_  :    List[str]   	=			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      __a    (		self    :    Any	):
							return super().test_save_load_local()



					@skip_mps
					def      __a    (		self    :    Tuple	):
							return super().test_dict_tuple_outputs_equivalent()



					@skip_mps
					def      __a    (		self    :    Dict	):
							return super().test_save_load_optional_components()



					@skip_mps
					def      __a    (		self    :    str	):
							return super().test_attention_slicing_forward_pass()



					def      __a    (		self    :    Any	):
							pass



					def      __a    (		self    :    Optional[int]	):
							pass





					@skip_mps
					def      __a    (		self    :    Optional[Any]	):
							return super().test_progress_bar()






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



					def      __a    (		self    :    Optional[int]	):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



					def      __a    (		self    :    str	):
							# TODO - test that pipeline can decode tokens in a callback
							# so that music can be played live
							lowerCamelCase_  :    Optional[Any]   	=			torch_device

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

							lowerCamelCase_  :    str   	=			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							def callback(lowerCamelCase    :    int					,			lowerCamelCase    :    int	):
									# decode mel to audio
									lowerCamelCase_  :    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

							lowerCamelCase_  :    Any   	=			MidiProcessor()
							lowerCamelCase_  :    str   	=			processor(lowerCamelCase	)

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



					def      __a    (		self    :    str	):
							lowerCamelCase_  :    List[str]   	=			torch_device

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

							lowerCamelCase_  :    Dict   	=			processor(lowerCamelCase	)
							# just run two denoising loops
							lowerCamelCase_  :    Optional[Any]   	=			input_tokens[:2]

							lowerCamelCase_  :    List[Any]   	=			torch.manual_seed(0	)
							lowerCamelCase_  :    str   	=			pipe(lowerCamelCase					,			num_inference_steps=2					,			generator=lowerCamelCase	)

							lowerCamelCase_  :    Dict   	=			output.audios[0]

							assert abs(np.abs(lowerCamelCase	).sum() - 3_612.841	) < 1E-1





					def      __a    (		self    :    List[Any]	):
							lowerCamelCase_  :    int   	=			torch_device

							lowerCamelCase_  :    str   	=			SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'	)
							lowerCamelCase_  :    Optional[int]   	=			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)

							lowerCamelCase_  :    Tuple   	=			MidiProcessor()

							lowerCamelCase_  :    int   	=			processor(lowerCamelCase	)

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

							lowerCamelCase_  :    List[Any]   	=			torch.manual_seed(0	)
							lowerCamelCase_  :    int   	=			pipe(lowerCamelCase					,			num_inference_steps=1_00					,			generator=lowerCamelCase	)

							lowerCamelCase_  :    List[Any]   	=			output.audios[0]
							assert abs(np.abs(lowerCamelCase	).sum() - 9_389.1_111	) < 5E-2
