




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


snake_case__          =						{
    """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 						snake_case__    ( lowerCamelCase__				:   str			)   ->   str:
					A_ :     Tuple =							task_cls()
					A_ :     Dict =							asdict(lowerCAmelCase__			)
					A_ :     Any =							task_template_from_dict(lowerCAmelCase__			)
					assert task == reloaded






class     UpperCamelCase_     :







						"""simple docstring"""


						def       _a    (     self      :       List[Any]    ):





											"""simple docstring"""







											A_ :     Optional[int] =							LanguageModeling(text_column='''input_text'''    )
											assert {"input_text": "text"} == task.column_mapping







						def       _a    (     self      :       int    ):





											"""simple docstring"""







											A_ :     Union[str, Any] =							Features({'''text''': Value('''string'''    )}    )
											A_ :     List[Any] =							{'text_column': 'input_text'}
											A_ :     List[Any] =							LanguageModeling.from_dict(_lowerCamelCase    )
											assert "language-modeling" == task.task
											assert input_schema == task.input_schema






class     UpperCamelCase_     (snake_case__    ):







						"""simple docstring"""


						def       _a    (     self      :       Optional[int]    ):





											"""simple docstring"""







											A_ :     List[str] =							sorted(['''pos''', '''neg''']    )







						def       _a    (     self      :       Dict    ):





											"""simple docstring"""







											A_ :     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]    ):





											"""simple docstring"""







											A_ :     List[Any] =							Features({'''text''': Value('''string'''    )}    )
											# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
											A_ :     int =							Features({'''labels''': ClassLabel}    )
											A_ :     int =							{'text_column': 'input_text', 'label_column': 'input_labels'}
											A_ :     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    ):





											"""simple docstring"""







											A_ :     Any =							TextClassification(text_column='''input_text'''							, label_column='''input_label'''    )
											self.assertEqual(task.label_schema['''labels''']							, _lowerCamelCase    )
											A_ :     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__    ):







						"""simple docstring"""


						def       _a    (     self      :       Optional[Any]    ):





											"""simple docstring"""







											A_ :     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    ):





											"""simple docstring"""







											A_ :     Union[str, Any] =							Features({'''question''': Value('''string'''    ), '''context''': Value('''string'''    )}    )
											A_ :     Union[str, Any] =							Features(
											    {
											        '''answers''': Sequence(
											            {
											                '''text''': Value('''string'''    ),
											                '''answer_start''': Value('''int32'''    ),
											            }    )
											    }    )
											A_ :     List[Any] =							{
											    'context_column': 'input_input_context',
											    'question_column': 'input_question',
											    'answers_column': 'input_answers',
											}
											A_ :     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__    ):







						"""simple docstring"""


						def       _a    (     self      :       List[Any]    ):





											"""simple docstring"""







											A_ :     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    ):





											"""simple docstring"""







											A_ :     Optional[int] =							Features({'''text''': Value('''string'''    )}    )
											A_ :     Union[str, Any] =							Features({'''summary''': Value('''string'''    )}    )
											A_ :     str =							{'text_column': 'input_text', 'summary_column': 'input_summary'}
											A_ :     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__    ):







						"""simple docstring"""


						def       _a    (     self      :       List[str]    ):





											"""simple docstring"""







											A_ :     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    ):





											"""simple docstring"""







											A_ :     List[Any] =							Features({'''audio''': Audio()}    )
											A_ :     Tuple =							Features({'''transcription''': Value('''string'''    )}    )
											A_ :     Optional[Any] =							{
											    'audio_column': 'input_audio',
											    'transcription_column': 'input_transcription',
											}
											A_ :     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__    ):







						"""simple docstring"""


						def       _a    (     self      :       Optional[int]    ):





											"""simple docstring"""







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







						def       _a    (     self      :       Optional[int]    ):





											"""simple docstring"""







											A_ :     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    ):





											"""simple docstring"""







											A_ :     Union[str, Any] =							Features({'''audio''': Audio()}    )
											A_ :     Any =							Features({'''labels''': ClassLabel}    )
											A_ :     Dict =							{
											    'audio_column': 'input_image',
											    'label_column': 'input_label',
											}
											A_ :     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    ):





											"""simple docstring"""







											A_ :     str =							AudioClassification(audio_column='''input_audio'''							, label_column='''input_label'''    )
											self.assertEqual(task.label_schema['''labels''']							, _lowerCamelCase    )
											A_ :     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__    ):







						"""simple docstring"""


						def       _a    (     self      :       int    ):





											"""simple docstring"""







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







						def       _a    (     self      :       List[str]    ):





											"""simple docstring"""







											A_ :     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]    ):





											"""simple docstring"""







											A_ :     int =							Features({'''image''': Image()}    )
											A_ :     List[Any] =							Features({'''labels''': ClassLabel}    )
											A_ :     List[str] =							{
											    'image_column': 'input_image',
											    'label_column': 'input_label',
											}
											A_ :     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]    ):





											"""simple docstring"""







											A_ :     Any =							ImageClassification(image_column='''input_image'''							, label_column='''input_label'''    )
											self.assertEqual(task.label_schema['''labels''']							, _lowerCamelCase    )
											A_ :     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__    ):







						"""simple docstring"""


						def       _a    (     self      :       int    ):





											"""simple docstring"""







											A_ :     Optional[Any] =							DatasetInfo(task_templates=QuestionAnsweringExtractive()    )
											A_ :     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    ):
																A_ :     Dict =							deepcopy(_lowerCamelCase    )
																A_ :     Dict =							0
																return out

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

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







						def       _a    (     self      :       int    ):





											"""simple docstring"""







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

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

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









'''simple docstring'''




import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()






class     UpperCamelCase_     (unittest.TestCase     ):







						"""simple docstring"""


						@property
						def       _a    (     self      :       int    ):





											"""simple docstring"""







											A_ :     Dict =							1
											A_ :     Any =							3
											A_ :     Any =							(32, 32)

											A_ :     Dict =							floats_tensor((batch_size, num_channels) + sizes							, rng=random.Random(0    )    ).to(_lowerCamelCase    )
											return image







						@property
						def       _a    (     self      :       Dict    ):





											"""simple docstring"""







											torch.manual_seed(0    )
											A_ :     Optional[int] =							UNetaDModel(
											    block_out_channels=(32, 64)							, layers_per_block=2							, sample_size=32							, in_channels=6							, out_channels=3							, down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')							, up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')							, )
											return model







						@property
						def       _a    (     self      :       Any    ):





											"""simple docstring"""







											torch.manual_seed(0    )
											A_ :     Dict =							VQModel(
											    block_out_channels=[32, 64]							, in_channels=3							, out_channels=3							, down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']							, up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']							, latent_channels=3							, )
											return model







						def       _a    (     self      :       List[Any]    ):





											"""simple docstring"""







											A_ :     Any =							'''cpu'''
											A_ :     Optional[Any] =							self.dummy_uncond_unet
											A_ :     str =							DDIMScheduler()
											A_ :     Optional[int] =							self.dummy_vq_model

											A_ :     Optional[Any] =							LDMSuperResolutionPipeline(unet=_lowerCamelCase							, vqvae=_lowerCamelCase							, scheduler=_lowerCamelCase    )
											ldm.to(_lowerCamelCase    )
											ldm.set_progress_bar_config(disable=_lowerCamelCase    )

											A_ :     Any =							self.dummy_image.to(_lowerCamelCase    )

											A_ :     str =							torch.Generator(device=_lowerCamelCase    ).manual_seed(0    )
											A_ :     List[Any] =							ldm(image=_lowerCamelCase							, generator=_lowerCamelCase							, num_inference_steps=2							, output_type='''numpy'''    ).images

											A_ :     str =							image[0, -3:, -3:, -1]

											assert image.shape == (1, 64, 64, 3)
											A_ :     List[Any] =							np.array([0.86_78, 0.82_45, 0.63_81, 0.68_30, 0.43_85, 0.55_99, 0.46_41, 0.62_01, 0.51_50]    )

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







						@unittest.skipIf(torch_device != '''cuda'''							, '''This test requires a GPU'''    )
						def       _a    (     self      :       Optional[int]    ):





											"""simple docstring"""







											A_ :     Tuple =							self.dummy_uncond_unet
											A_ :     List[str] =							DDIMScheduler()
											A_ :     str =							self.dummy_vq_model

											# put models in fp16
											A_ :     List[Any] =							unet.half()
											A_ :     Optional[int] =							vqvae.half()

											A_ :     Optional[Any] =							LDMSuperResolutionPipeline(unet=_lowerCamelCase							, vqvae=_lowerCamelCase							, scheduler=_lowerCamelCase    )
											ldm.to(_lowerCamelCase    )
											ldm.set_progress_bar_config(disable=_lowerCamelCase    )

											A_ :     Optional[Any] =							self.dummy_image.to(_lowerCamelCase    )

											A_ :     Optional[Any] =							ldm(_lowerCamelCase							, num_inference_steps=2							, output_type='''numpy'''    ).images

											assert image.shape == (1, 64, 64, 3)






@slow
@require_torch
class     UpperCamelCase_     (unittest.TestCase     ):







						"""simple docstring"""


						def       _a    (     self      :       int    ):





											"""simple docstring"""







											A_ :     Optional[int] =							load_image(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											    '''/vq_diffusion/teddy_bear_pool.png'''    )
											A_ :     List[str] =							init_image.resize((64, 64)							, resample=PIL_INTERPOLATION['''lanczos''']    )

											A_ :     List[str] =							LDMSuperResolutionPipeline.from_pretrained('''duongna/ldm-super-resolution'''							, device_map='''auto'''    )
											ldm.set_progress_bar_config(disable=_lowerCamelCase    )

											A_ :     List[str] =							torch.manual_seed(0    )
											A_ :     str =							ldm(image=_lowerCamelCase							, generator=_lowerCamelCase							, num_inference_steps=20							, output_type='''numpy'''    ).images

											A_ :     str =							image[0, -3:, -3:, -1]

											assert image.shape == (1, 256, 256, 3)
											A_ :     Optional[Any] =							np.array([0.76_44, 0.76_79, 0.76_42, 0.76_33, 0.76_66, 0.75_60, 0.74_25, 0.72_57, 0.69_07]    )

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



