


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': [515]},
}

@pytest.mark.parametrize(
    '''task_cls'''    ,     [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]    ,     )
def   UpperCamelCase__   (    UpperCAmelCase_			)						->							Any:




       '''simple docstring'''






       _lowercase					:				str           =			task_cls()
       _lowercase					:				Optional[Any]           =			asdict(UpperCAmelCase_			)
       _lowercase					:				Any           =			task_template_from_dict(UpperCAmelCase_			)
       assert task == reloaded

class 					UpperCAmelCase__   :



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       Dict		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       Tuple		):





            """simple docstring"""



            _lowercase					:				Optional[Any]           =			Features({'''text''': Value('''string'''		)}		)
            _lowercase					:				Any           =			{'''text_column''': '''input_text'''}
            _lowercase					:				Any           =			LanguageModeling.from_dict(UpperCamelCase		)
            assert "language-modeling" == task.task
            assert input_schema == task.input_schema




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       Optional[Any]		):





            """simple docstring"""



            _lowercase					:				Any           =			sorted(['''pos''', '''neg''']		)




     def   lowerCAmelCase_   ( self       :       List[Any]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       Union[str, Any]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       List[Any]		):





            """simple docstring"""



            _lowercase					:				Union[str, Any]           =			TextClassification(text_column='''input_text'''	,      label_column='''input_label'''		)
            self.assertEqual(task.label_schema['''labels''']	,      UpperCamelCase		)
            _lowercase					:				Any           =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels		)}		)		)
            self.assertEqual(task.label_schema['''labels''']	,      ClassLabel(names=self.labels		)		)




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       str		):





            """simple docstring"""



            _lowercase					:				str           =			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   lowerCAmelCase_   ( self       :       Dict		):





            """simple docstring"""



            _lowercase					:				Optional[int]           =			Features({'''question''': Value('''string'''		), '''context''': Value('''string'''		)}		)
            _lowercase					:				Optional[int]           =			Features(
                {
                    '''answers''': Sequence(
                        {
                            '''text''': Value('''string'''		),
                            '''answer_start''': Value('''int32'''		),
                        }		)
                }		)
            _lowercase					:				Tuple           =			{
                '''context_column''': '''input_input_context''',
                '''question_column''': '''input_question''',
                '''answers_column''': '''input_answers''',
            }
            _lowercase					:				int           =			QuestionAnsweringExtractive.from_dict(UpperCamelCase		)
            self.assertEqual('''question-answering-extractive'''	,      task.task		)
            self.assertEqual(UpperCamelCase	,      task.input_schema		)
            self.assertEqual(UpperCamelCase	,      task.label_schema		)




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       Optional[Any]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       Tuple		):





            """simple docstring"""



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




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       List[str]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       Dict		):





            """simple docstring"""



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




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       Tuple		):





            """simple docstring"""



            _lowercase					:				Any           =			sorted(['''pos''', '''neg''']		)




     def   lowerCAmelCase_   ( self       :       List[Any]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       Optional[Any]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       str		):





            """simple docstring"""



            _lowercase					:				str           =			AudioClassification(audio_column='''input_audio'''	,      label_column='''input_label'''		)
            self.assertEqual(task.label_schema['''labels''']	,      UpperCamelCase		)
            _lowercase					:				Optional[Any]           =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels		)}		)		)
            self.assertEqual(task.label_schema['''labels''']	,      ClassLabel(names=self.labels		)		)




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       Union[str, Any]		):





            """simple docstring"""



            _lowercase					:				List[Any]           =			sorted(['''pos''', '''neg''']		)




     def   lowerCAmelCase_   ( self       :       Optional[Any]		):





            """simple docstring"""



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




     def   lowerCAmelCase_   ( self       :       Union[str, Any]		):





            """simple docstring"""



            _lowercase					:				int           =			Features({'''image''': Image()}		)
            _lowercase					:				Optional[int]           =			Features({'''labels''': ClassLabel}		)
            _lowercase					:				int           =			{
                '''image_column''': '''input_image''',
                '''label_column''': '''input_label''',
            }
            _lowercase					:				Tuple           =			ImageClassification.from_dict(UpperCamelCase		)
            self.assertEqual('''image-classification'''	,      task.task		)
            self.assertEqual(UpperCamelCase	,      task.input_schema		)
            self.assertEqual(UpperCamelCase	,      task.label_schema		)




     def   lowerCAmelCase_   ( self       :       List[Any]		):





            """simple docstring"""



            _lowercase					:				int           =			ImageClassification(image_column='''input_image'''	,      label_column='''input_label'''		)
            self.assertEqual(task.label_schema['''labels''']	,      UpperCamelCase		)
            _lowercase					:				List[Any]           =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels		)}		)		)
            self.assertEqual(task.label_schema['''labels''']	,      ClassLabel(names=self.labels		)		)




class 					UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def   lowerCAmelCase_   ( self       :       Tuple		):





            """simple docstring"""



            _lowercase					:				List[Any]           =			DatasetInfo(task_templates=QuestionAnsweringExtractive()		)
            _lowercase					:				Dict           =			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       :       List[str]		):
                   return x

            def dont_keep_task(UpperCamelCase       :       Optional[int]		):
                   _lowercase					:				Union[str, Any]           =			deepcopy(UpperCamelCase		)
                   _lowercase					:				Dict           =			0
                   return out

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

            _lowercase					:				str           =			dataset.map(UpperCamelCase		)
            assert mapped_dataset.info.task_templates == []
            # reload from cache
            _lowercase					:				Any           =			dataset.map(UpperCamelCase		)
            assert mapped_dataset.info.task_templates == []




     def   lowerCAmelCase_   ( self       :       str		):





            """simple docstring"""



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

            def process(UpperCamelCase       :       str		):
                   return example

            _lowercase					:				Tuple           =			dataset.remove_columns('''label'''		)
            _lowercase					:				Any           =			modified_dataset.map(UpperCamelCase		)
            assert mapped_dataset.info.task_templates == []



# limitations under the License.


from typing import Optional, Tuple, Union

import torch

from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput

class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def __init__( self       :       List[str]	,      UpperCamelCase       :       Union[str, Any]	,      UpperCamelCase       :       int		):





            """simple docstring"""



            super().__init__()
            self.register_modules(unet=UpperCamelCase	,      scheduler=UpperCamelCase		)




     @torch.no_grad()
     def __call__( self       :       Any	,      UpperCamelCase       :       int = 1	,      UpperCamelCase       :       Optional[torch.Generator] = None	,      UpperCamelCase       :       int = 50	,      UpperCamelCase       :       Optional[str] = "pil"	,      UpperCamelCase       :       bool = True	,      **UpperCamelCase       :       int	,      ):





            """simple docstring"""



            _lowercase					:				Optional[int]           =			torch.randn(
                (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size)	,      generator=UpperCamelCase	,      )
            _lowercase					:				Dict           =			image.to(self.device		)

            # set step values
            self.scheduler.set_timesteps(UpperCamelCase		)

            for t in self.progress_bar(self.scheduler.timesteps		):
                   # 1. predict noise model_output
                   _lowercase					:				Dict           =			self.unet(UpperCamelCase	,      UpperCamelCase		).sample

                   # 2. predict previous mean of image x_t-1 and add variance depending on eta
                   # eta corresponds to η in paper and should be between [0, 1]
                   # do x_t -> x_t-1
                   _lowercase					:				Tuple           =			self.scheduler.step(UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase		).prev_sample

            _lowercase					:				Optional[int]           =			(image / 2 + 0.5).clamp(0	,      1		)
            _lowercase					:				int           =			image.cpu().permute(0	,      2	,      3	,      1		).numpy()
            if output_type == "pil":
                   _lowercase					:				List[Any]           =			self.numpy_to_pil(UpperCamelCase		)

            if not return_dict:
                   return (image,), "This is a local test"

            return ImagePipelineOutput(images=UpperCamelCase		), "This is a local test"