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


a		:					List[str]    	=					{
    '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_15]},
}



@pytest.mark.parametrize(
    'task_cls'       ,		[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]       ,		)
def 						__magic_name__		(				UpperCamelCase    :		Any    )    ->	List[Any]:
    a__    = task_cls()
    a__    = asdict(UpperCamelCase    )
    a__    = task_template_from_dict(UpperCamelCase    )
    assert task == reloaded







class 						lowercase:



     def  lowercase__     (       self      )		->    Dict:







         """simple docstring"""



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




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







         """simple docstring"""



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







class 						lowercase(_lowercase					):



     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



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



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



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



     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



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




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







         """simple docstring"""



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







class 						lowercase(_lowercase					):



     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



         a__    = 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  lowercase__     (       self      )		->    List[Any]:







         """simple docstring"""



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







class 						lowercase(_lowercase					):



     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



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




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







         """simple docstring"""



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







class 						lowercase(_lowercase					):



     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



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




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







         """simple docstring"""



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







class 						lowercase(_lowercase					):



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







         """simple docstring"""



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



     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



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



     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



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




     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



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







class 						lowercase(_lowercase					):



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







         """simple docstring"""



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



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







         """simple docstring"""



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



     def  lowercase__     (       self      )		->    Any:







         """simple docstring"""



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




     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



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







class 						lowercase(_lowercase					):



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







         """simple docstring"""



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

         def keep_task(__SCREAMING_SNAKE_CASE      ):
             return x

         def dont_keep_task(__SCREAMING_SNAKE_CASE      ):
             a__    = deepcopy(__SCREAMING_SNAKE_CASE      )
             a__    = 0
             return out

         a__    = dataset.map(__SCREAMING_SNAKE_CASE      )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         a__    = dataset.map(__SCREAMING_SNAKE_CASE      )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

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




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







         """simple docstring"""



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

         def process(__SCREAMING_SNAKE_CASE      ):
             return example

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




"""simple docstring"""




import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


a		:					str    	=					False







@nightly
@require_torch_gpu
class 						lowercase(unittest.TestCase					):



     def  lowercase__     (       self      )		->    Any:







         """simple docstring"""



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



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







         """simple docstring"""



         a__    = VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'      )
         # remove text_unet
         pipe.remove_unused_weights()
         pipe.to(__SCREAMING_SNAKE_CASE      )
         pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

         a__    = load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'      )

         a__    = torch.manual_seed(0      )
         a__    = pipe(
             prompt='first prompt'    ,							image=__SCREAMING_SNAKE_CASE    ,							text_to_image_strength=0.75    ,							generator=__SCREAMING_SNAKE_CASE    ,							guidance_scale=7.5    ,							num_inference_steps=2    ,							output_type='numpy'    ,							).images

         with tempfile.TemporaryDirectory() as tmpdirname:
             pipe.save_pretrained(__SCREAMING_SNAKE_CASE      )
             a__    = VersatileDiffusionDualGuidedPipeline.from_pretrained(__SCREAMING_SNAKE_CASE      )

         pipe.to(__SCREAMING_SNAKE_CASE      )
         pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

         a__    = generator.manual_seed(0      )
         a__    = pipe(
             prompt='first prompt'    ,							image=__SCREAMING_SNAKE_CASE    ,							text_to_image_strength=0.75    ,							generator=__SCREAMING_SNAKE_CASE    ,							guidance_scale=7.5    ,							num_inference_steps=2    ,							output_type='numpy'    ,							).images

         assert np.abs(image - new_image      ).sum() < 1e-5, "Models don't have the same forward pass"




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







         """simple docstring"""



         a__    = VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'      )
         pipe.remove_unused_weights()
         pipe.to(__SCREAMING_SNAKE_CASE      )
         pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE      )

         a__    = 'cyberpunk 2077'
         a__    = load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'      )
         a__    = torch.manual_seed(0      )
         a__    = pipe(
             prompt=__SCREAMING_SNAKE_CASE    ,							image=__SCREAMING_SNAKE_CASE    ,							text_to_image_strength=0.75    ,							generator=__SCREAMING_SNAKE_CASE    ,							guidance_scale=7.5    ,							num_inference_steps=5_0    ,							output_type='numpy'    ,							).images

         a__    = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         a__    = np.array([0.07_87, 0.08_49, 0.08_26, 0.08_12, 0.08_07, 0.07_95, 0.08_18, 0.07_98, 0.07_79]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2


