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


UpperCAmelCase							=       {
    "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": [5_1_5]},
}






@pytest.mark.parametrize(
    "task_cls" ,	[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ] ,	)
def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: Optional[Any]     ):
      snake_case_     :			List[str]       =       task_cls()
      snake_case_     :			str       =       asdict(lowerCAmelCase_     )
      snake_case_     :			Tuple       =       task_template_from_dict(lowerCAmelCase_     )
      assert task == reloaded



class 					snake_case__       :



   def 					UpperCAmelCase__       (				self   :   int   )							->     List[str]:




         '''simple docstring'''




         snake_case_     :			Any       =       LanguageModeling(text_column="input_text"   )
         assert {"input_text": "text"} == task.column_mapping



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




         '''simple docstring'''




         snake_case_     :			Dict       =       Features({"text": Value("string"   )}   )
         snake_case_     :			Optional[Any]       =       {"text_column": "input_text"}
         snake_case_     :			str       =       LanguageModeling.from_dict(A__   )
         assert "language-modeling" == task.task
         assert input_schema == task.input_schema



class 					snake_case__       (				_UpperCamelCase							):



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     str:




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       sorted(["pos", "neg"]   )



   def 					UpperCAmelCase__       (				self   :   Tuple   )							->     Optional[Any]:




         '''simple docstring'''




         snake_case_     :			Optional[int]       =       TextClassification(text_column="input_text"			,	label_column="input_label"   )
         self.assertDictEqual({"input_text": "text", "input_label": "labels"}			,	task.column_mapping   )



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




         '''simple docstring'''




         snake_case_     :			str       =       Features({"text": Value("string"   )}   )
         # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
         snake_case_     :			Union[str, Any]       =       Features({"labels": ClassLabel}   )
         snake_case_     :			Tuple       =       {"text_column": "input_text", "label_column": "input_labels"}
         snake_case_     :			str       =       TextClassification.from_dict(A__   )
         self.assertEqual("text-classification"			,	task.task   )
         self.assertEqual(A__			,	task.input_schema   )
         self.assertEqual(A__			,	task.label_schema   )



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




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       TextClassification(text_column="input_text"			,	label_column="input_label"   )
         self.assertEqual(task.label_schema["labels"]			,	A__   )
         snake_case_     :			Dict       =       task.align_with_features(Features({"input_label": ClassLabel(names=self.labels   )}   )   )
         self.assertEqual(task.label_schema["labels"]			,	ClassLabel(names=self.labels   )   )



class 					snake_case__       (				_UpperCamelCase							):



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




         '''simple docstring'''




         snake_case_     :			Optional[Any]       =       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   :   List[str]   )							->     Optional[Any]:




         '''simple docstring'''




         snake_case_     :			List[str]       =       Features({"question": Value("string"   ), "context": Value("string"   )}   )
         snake_case_     :			int       =       Features(
             {
                 "answers": Sequence(
                     {
                         "text": Value("string"   ),
                         "answer_start": Value("int32"   ),
                     }   )
             }   )
         snake_case_     :			List[Any]       =       {
             "context_column": "input_input_context",
             "question_column": "input_question",
             "answers_column": "input_answers",
         }
         snake_case_     :			Optional[int]       =       QuestionAnsweringExtractive.from_dict(A__   )
         self.assertEqual("question-answering-extractive"			,	task.task   )
         self.assertEqual(A__			,	task.input_schema   )
         self.assertEqual(A__			,	task.label_schema   )



class 					snake_case__       (				_UpperCamelCase							):



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




         '''simple docstring'''




         snake_case_     :			Tuple       =       Summarization(text_column="input_text"			,	summary_column="input_summary"   )
         self.assertDictEqual({"input_text": "text", "input_summary": "summary"}			,	task.column_mapping   )



   def 					UpperCAmelCase__       (				self   :   Union[str, Any]   )							->     List[Any]:




         '''simple docstring'''




         snake_case_     :			int       =       Features({"text": Value("string"   )}   )
         snake_case_     :			Dict       =       Features({"summary": Value("string"   )}   )
         snake_case_     :			int       =       {"text_column": "input_text", "summary_column": "input_summary"}
         snake_case_     :			Union[str, Any]       =       Summarization.from_dict(A__   )
         self.assertEqual("summarization"			,	task.task   )
         self.assertEqual(A__			,	task.input_schema   )
         self.assertEqual(A__			,	task.label_schema   )



class 					snake_case__       (				_UpperCamelCase							):



   def 					UpperCAmelCase__       (				self   :   Any   )							->     int:




         '''simple docstring'''




         snake_case_     :			Optional[Any]       =       AutomaticSpeechRecognition(audio_column="input_audio"			,	transcription_column="input_transcription"   )
         self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}			,	task.column_mapping   )



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     Tuple:




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       Features({"audio": Audio()}   )
         snake_case_     :			List[Any]       =       Features({"transcription": Value("string"   )}   )
         snake_case_     :			List[Any]       =       {
             "audio_column": "input_audio",
             "transcription_column": "input_transcription",
         }
         snake_case_     :			Optional[Any]       =       AutomaticSpeechRecognition.from_dict(A__   )
         self.assertEqual("automatic-speech-recognition"			,	task.task   )
         self.assertEqual(A__			,	task.input_schema   )
         self.assertEqual(A__			,	task.label_schema   )



class 					snake_case__       (				_UpperCamelCase							):



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




         '''simple docstring'''




         snake_case_     :			Tuple       =       sorted(["pos", "neg"]   )



   def 					UpperCAmelCase__       (				self   :   Optional[Any]   )							->     Any:




         '''simple docstring'''




         snake_case_     :			List[str]       =       AudioClassification(audio_column="input_audio"			,	label_column="input_label"   )
         self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}			,	task.column_mapping   )



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




         '''simple docstring'''




         snake_case_     :			Optional[Any]       =       Features({"audio": Audio()}   )
         snake_case_     :			str       =       Features({"labels": ClassLabel}   )
         snake_case_     :			int       =       {
             "audio_column": "input_image",
             "label_column": "input_label",
         }
         snake_case_     :			Union[str, Any]       =       AudioClassification.from_dict(A__   )
         self.assertEqual("audio-classification"			,	task.task   )
         self.assertEqual(A__			,	task.input_schema   )
         self.assertEqual(A__			,	task.label_schema   )



   def 					UpperCAmelCase__       (				self   :   int   )							->     Any:




         '''simple docstring'''




         snake_case_     :			str       =       AudioClassification(audio_column="input_audio"			,	label_column="input_label"   )
         self.assertEqual(task.label_schema["labels"]			,	A__   )
         snake_case_     :			Optional[int]       =       task.align_with_features(Features({"input_label": ClassLabel(names=self.labels   )}   )   )
         self.assertEqual(task.label_schema["labels"]			,	ClassLabel(names=self.labels   )   )



class 					snake_case__       (				_UpperCamelCase							):



   def 					UpperCAmelCase__       (				self   :   str   )							->     Optional[int]:




         '''simple docstring'''




         snake_case_     :			Any       =       sorted(["pos", "neg"]   )



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




         '''simple docstring'''




         snake_case_     :			List[str]       =       ImageClassification(image_column="input_image"			,	label_column="input_label"   )
         self.assertDictEqual({"input_image": "image", "input_label": "labels"}			,	task.column_mapping   )



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     Optional[int]:




         '''simple docstring'''




         snake_case_     :			Optional[int]       =       Features({"image": Image()}   )
         snake_case_     :			str       =       Features({"labels": ClassLabel}   )
         snake_case_     :			int       =       {
             "image_column": "input_image",
             "label_column": "input_label",
         }
         snake_case_     :			Dict       =       ImageClassification.from_dict(A__   )
         self.assertEqual("image-classification"			,	task.task   )
         self.assertEqual(A__			,	task.input_schema   )
         self.assertEqual(A__			,	task.label_schema   )



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




         '''simple docstring'''




         snake_case_     :			Optional[Any]       =       ImageClassification(image_column="input_image"			,	label_column="input_label"   )
         self.assertEqual(task.label_schema["labels"]			,	A__   )
         snake_case_     :			Any       =       task.align_with_features(Features({"input_label": ClassLabel(names=self.labels   )}   )   )
         self.assertEqual(task.label_schema["labels"]			,	ClassLabel(names=self.labels   )   )



class 					snake_case__       (				_UpperCamelCase							):



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     Optional[Any]:




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       DatasetInfo(task_templates=QuestionAnsweringExtractive()   )
         snake_case_     :			Tuple       =       Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}			,	info=A__   )
         assert isinstance(dataset.info.task_templates			,	A__   )
         assert len(dataset.info.task_templates   ) == 1

         def keep_task(A__   :   Optional[Any]   ):
               return x

         def dont_keep_task(A__   :   Dict   ):
               snake_case_     :			Any       =       deepcopy(A__   )
               snake_case_     :			Any       =       0
               return out

         snake_case_     :			List[str]       =       dataset.map(A__   )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         snake_case_     :			int       =       dataset.map(A__   )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

         snake_case_     :			Union[str, Any]       =       dataset.map(A__   )
         assert mapped_dataset.info.task_templates == []
         # reload from cache
         snake_case_     :			Tuple       =       dataset.map(A__   )
         assert mapped_dataset.info.task_templates == []



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     Union[str, Any]:




         '''simple docstring'''




         snake_case_     :			Any       =       Features({"text": Value("string"   ), "label": ClassLabel(names=("pos", "neg")   )}   )
         snake_case_     :			Optional[Any]       =       TextClassification(text_column="text"			,	label_column="label"   )
         snake_case_     :			Optional[int]       =       DatasetInfo(features=A__			,	task_templates=A__   )
         snake_case_     :			int       =       Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}			,	info=A__   )

         def process(A__   :   Optional[int]   ):
               return example

         snake_case_     :			str       =       dataset.remove_columns("label"   )
         snake_case_     :			int       =       modified_dataset.map(A__   )
         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()


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



@unittest.skip("The note-seq package currently throws an error on import"							)
class 					snake_case__       (				_UpperCamelCase					,						unittest.TestCase							):
   _SCREAMING_SNAKE_CASE	: str						    =      SpectrogramDiffusionPipeline
   _SCREAMING_SNAKE_CASE	: List[str]						    =      PipelineTesterMixin.required_optional_params - {
       "callback",
       "latents",
       "callback_steps",
       "output_type",
       "num_images_per_prompt",
   }
   _SCREAMING_SNAKE_CASE	: Dict						    =      False
   _SCREAMING_SNAKE_CASE	: int						    =      False
   _SCREAMING_SNAKE_CASE	: List[str]						    =      TOKENS_TO_AUDIO_GENERATION_PARAMS
   _SCREAMING_SNAKE_CASE	: Any						    =      TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS



   def 					UpperCAmelCase__       (				self   :   Tuple   )							->     Optional[Any]:




         '''simple docstring'''




         torch.manual_seed(0   )
         snake_case_     :			List[Any]       =       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"			,	)

         snake_case_     :			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"			,	)

         snake_case_     :			Any       =       TaFilmDecoder(
             input_dims=1_28			,	targets_length=2_56			,	max_decoder_noise_time=2_0000.0			,	d_model=7_68			,	num_layers=1			,	num_heads=1			,	d_kv=4			,	d_ff=20_48			,	dropout_rate=0.1			,	)

         snake_case_     :			List[Any]       =       DDPMScheduler()

         snake_case_     :			List[Any]       =       {
             "notes_encoder": notes_encoder.eval(),
             "continuous_encoder": continuous_encoder.eval(),
             "decoder": decoder.eval(),
             "scheduler": scheduler,
             "melgan": None,
         }
         return components



   def 					UpperCAmelCase__       (				self   :   Dict			,	A__   :   int			,	A__   :   Dict=0   )							->     Tuple:




         '''simple docstring'''




         if str(A__   ).startswith("mps"   ):
               snake_case_     :			List[Any]       =       torch.manual_seed(A__   )
         else:
               snake_case_     :			List[Any]       =       torch.Generator(device=A__   ).manual_seed(A__   )
         snake_case_     :			Optional[int]       =       {
             "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 					UpperCAmelCase__       (				self   :   Union[str, Any]   )							->     str:




         '''simple docstring'''




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

         snake_case_     :			List[Any]       =       self.get_dummy_inputs(A__   )
         snake_case_     :			Union[str, Any]       =       pipe(**A__   )
         snake_case_     :			str       =       output.audios

         snake_case_     :			List[Any]       =       mel[0, -3:, -3:]

         assert mel_slice.shape == (3, 3)
         snake_case_     :			Any       =       np.array(
             [-11.51_2925, -4.78_8215, -0.4617_2905, -2.05_1715, -10.53_9147, -10.97_0963, -9.09_1634, 4.0, 4.0]   )
         assert np.abs(mel_slice.flatten() - expected_slice   ).max() < 1E-2



   @skip_mps
   def 					UpperCAmelCase__       (				self   :   Any   )							->     Tuple:




         '''simple docstring'''




         return super().test_save_load_local()



   @skip_mps
   def 					UpperCAmelCase__       (				self   :   Union[str, Any]   )							->     List[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   :   Optional[int]   )							->     List[str]:




         '''simple docstring'''




         return super().test_attention_slicing_forward_pass()



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




         '''simple docstring'''




         pass



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     str:




         '''simple docstring'''




         pass



   @skip_mps
   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     Any:




         '''simple docstring'''




         return super().test_progress_bar()



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



   def 					UpperCAmelCase__       (				self   :   Union[str, Any]   )							->     List[Any]:




         '''simple docstring'''




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



   def 					UpperCAmelCase__       (				self   :   int   )							->     Dict:




         '''simple docstring'''




         snake_case_     :			Optional[int]       =       torch_device

         snake_case_     :			List[str]       =       SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"   )
         snake_case_     :			Dict       =       pipe.melgan
         snake_case_     :			Optional[Any]       =       None

         snake_case_     :			int       =       pipe.to(A__   )
         pipe.set_progress_bar_config(disable=A__   )

         def callback(A__   :   Dict			,	A__   :   Optional[Any]   ):
               # decode mel to audio
               snake_case_     :			str       =       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

         snake_case_     :			List[str]       =       MidiProcessor()
         snake_case_     :			Dict       =       processor(A__   )

         snake_case_     :			Optional[Any]       =       input_tokens[:3]
         snake_case_     :			Dict       =       torch.manual_seed(0   )
         pipe(A__			,	num_inference_steps=5			,	generator=A__			,	callback=A__			,	output_type="mel"   )



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




         '''simple docstring'''




         snake_case_     :			Any       =       torch_device

         snake_case_     :			List[Any]       =       SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"   )
         snake_case_     :			Any       =       pipe.to(A__   )
         pipe.set_progress_bar_config(disable=A__   )
         snake_case_     :			Any       =       MidiProcessor()

         snake_case_     :			List[Any]       =       processor(A__   )
         # just run two denoising loops
         snake_case_     :			str       =       input_tokens[:2]

         snake_case_     :			Tuple       =       torch.manual_seed(0   )
         snake_case_     :			int       =       pipe(A__			,	num_inference_steps=2			,	generator=A__   )

         snake_case_     :			int       =       output.audios[0]

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



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     List[str]:




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       torch_device

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

         snake_case_     :			int       =       MidiProcessor()

         snake_case_     :			int       =       processor(A__   )

         # just run 4 denoising loops
         snake_case_     :			Union[str, Any]       =       input_tokens[:4]

         snake_case_     :			Optional[Any]       =       torch.manual_seed(0   )
         snake_case_     :			Optional[Any]       =       pipe(A__			,	num_inference_steps=1_00			,	generator=A__   )

         snake_case_     :			List[str]       =       output.audios[0]
         assert abs(np.abs(A__   ).sum() - 9389.1111   ) < 5E-2



