





'''simple docstring'''


import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class    a_     (       _lowerCAmelCase			,		unittest.TestCase							):
     __A  				=    KandinskyVaaPriorEmbaEmbPipeline
     __A  				=    ["prompt", "image"]
     __A  				=    ["prompt", "image"]
     __A  				=    [
         "num_images_per_prompt",
         "strength",
         "generator",
         "num_inference_steps",
         "latents",
         "negative_prompt",
         "guidance_scale",
         "output_type",
         "return_dict",
     ]
     __A  				=    False





     @property
     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        return 32





     @property
     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        return 32





     @property
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        return self.time_input_dim





     @property
     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        return self.time_input_dim * 4





     @property
     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        return 100





     @property
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :List[str]					    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)
        return tokenizer





     @property
     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        torch.manual_seed(0		)
        lowercase_    :int					    =				CLIPTextConfig(
            bos_token_id=0			,   eos_token_id=2			,   hidden_size=self.text_embedder_hidden_size			,   projection_dim=self.text_embedder_hidden_size			,   intermediate_size=37			,   layer_norm_eps=1e-0_5			,   num_attention_heads=4			,   num_hidden_layers=5			,   pad_token_id=1			,   vocab_size=1_000			,   )
        return CLIPTextModelWithProjection(lowercase		)





     @property
     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        torch.manual_seed(0		)

        lowercase_    :List[Any]					    =				{
            "num_attention_heads": 2,
            "attention_head_dim": 12,
            "embedding_dim": self.text_embedder_hidden_size,
            "num_layers": 1,
        }

        lowercase_    :int					    =				PriorTransformer(**lowercase		)
        # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
        lowercase_    :Optional[int]					    =				nn.Parameter(torch.ones(model.clip_std.shape		)		)
        return model





     @property
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        torch.manual_seed(0		)
        lowercase_    :Tuple					    =				CLIPVisionConfig(
            hidden_size=self.text_embedder_hidden_size			,   image_size=224			,   projection_dim=self.text_embedder_hidden_size			,   intermediate_size=37			,   num_attention_heads=4			,   num_channels=3			,   num_hidden_layers=5			,   patch_size=14			,   )

        lowercase_    :int					    =				CLIPVisionModelWithProjection(lowercase		)
        return model





     @property
     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    :Tuple					    =				CLIPImageProcessor(
            crop_size=224			,   do_center_crop=lowercase			,   do_normalize=lowercase			,   do_resize=lowercase			,   image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]			,   image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]			,   resample=3			,   size=224			,   )

        return image_processor





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    :Any					    =				self.dummy_prior
        lowercase_    :Any					    =				self.dummy_image_encoder
        lowercase_    :Dict					    =				self.dummy_text_encoder
        lowercase_    :Optional[Any]					    =				self.dummy_tokenizer
        lowercase_    :Any					    =				self.dummy_image_processor

        lowercase_    :int					    =				UnCLIPScheduler(
            variance_type="fixed_small_log"			,   prediction_type="sample"			,   num_train_timesteps=1_000			,   clip_sample=lowercase			,   clip_sample_range=10.0			,   )

        lowercase_    :Dict					    =				{
            "prior": prior,
            "image_encoder": image_encoder,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "scheduler": scheduler,
            "image_processor": image_processor,
        }

        return components





     def 							lowercase__   (				self	:      List[Any]			,   lowercase	:      Any			,   lowercase	:      Tuple=0		):





        """simple docstring"""




        if str(lowercase		).startswith("mps"		):
           lowercase_    :Tuple					    =				torch.manual_seed(lowercase		)
        else:
           lowercase_    :Tuple					    =				torch.Generator(device=lowercase		).manual_seed(lowercase		)

        lowercase_    :str					    =				floats_tensor((1, 3, 64, 64)			,   rng=random.Random(lowercase		)		).to(lowercase		)
        lowercase_    :Union[str, Any]					    =				image.cpu().permute(0			,   2			,   3			,   1		)[0]
        lowercase_    :Union[str, Any]					    =				Image.fromarray(np.uinta(lowercase		)		).convert("RGB"		).resize((256, 256)		)

        lowercase_    :str					    =				{
            "prompt": "horse",
            "image": init_image,
            "strength": 0.5,
            "generator": generator,
            "guidance_scale": 4.0,
            "num_inference_steps": 2,
            "output_type": "np",
        }
        return inputs





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





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				"cpu"

        lowercase_    :int					    =				self.get_dummy_components()

        lowercase_    :Optional[Any]					    =				self.pipeline_class(**lowercase		)
        lowercase_    :int					    =				pipe.to(lowercase		)

        pipe.set_progress_bar_config(disable=lowercase		)

        lowercase_    :Union[str, Any]					    =				pipe(**self.get_dummy_inputs(lowercase		)		)
        lowercase_    :List[Any]					    =				output.image_embeds

        lowercase_    :Any					    =				pipe(
            **self.get_dummy_inputs(lowercase		)			,   return_dict=lowercase			,   )[0]

        lowercase_    :str					    =				image[0, -10:]
        lowercase_    :Optional[Any]					    =				image_from_tuple[0, -10:]

        assert image.shape == (1, 32)

        lowercase_    :List[str]					    =				np.array(
            [
                0.1_07_12_84,
                1.3_33_02_71,
                0.61_26_02_23,
                -0.6_69_10_65,
                -0.3_84_68_52,
                -1.0_30_36_61,
                0.22_71_61_11,
                0.03_34_89_01,
                0.30_04_06_75,
                -0.24_80_50_29,
            ]		)

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





     @skip_mps
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :List[str]					    =				torch_device == "cpu"
        lowercase_    :Optional[Any]					    =				True
        lowercase_    :int					    =				False

        self._test_inference_batch_single_identical(
            test_max_difference=lowercase			,   relax_max_difference=lowercase			,   test_mean_pixel_difference=lowercase			,   )







     @skip_mps
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :str					    =				torch_device == "cpu"
        lowercase_    :str					    =				False

        self._test_attention_slicing_forward_pass(
            test_max_difference=lowercase			,   test_mean_pixel_difference=lowercase			,   )









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


lowerCAmelCase      :  Tuple      							={
    '''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_						(		__lowerCamelCase      :      str				):
   lowercase_    :str					    =				task_cls()
   lowercase_    :Tuple					    =				asdict(__lowerCamelCase				)
   lowercase_    :Dict					    =				task_template_from_dict(__lowerCamelCase				)
   assert task == reloaded
class    a_     :





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




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







     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Tuple					    =				Features({"text": Value("string"		)}		)
        lowercase_    :List[Any]					    =				{"text_column": "input_text"}
        lowercase_    :List[str]					    =				LanguageModeling.from_dict(lowercase		)
        assert "language-modeling" == task.task
        assert input_schema == task.input_schema







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :List[str]					    =				sorted(["pos", "neg"]		)





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    :List[str]					    =				TextClassification(text_column="input_text"			,   label_column="input_label"		)
        self.assertDictEqual({"input_text": "text", "input_label": "labels"}			,   task.column_mapping		)





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




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







     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




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







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :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 							lowercase__   (				self	:      Any		):





        """simple docstring"""




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







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




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







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





        """simple docstring"""




        lowercase_    :int					    =				Features({"text": Value("string"		)}		)
        lowercase_    :str					    =				Features({"summary": Value("string"		)}		)
        lowercase_    :Tuple					    =				{"text_column": "input_text", "summary_column": "input_summary"}
        lowercase_    :Optional[int]					    =				Summarization.from_dict(lowercase		)
        self.assertEqual("summarization"			,   task.task		)
        self.assertEqual(lowercase			,   task.input_schema		)
        self.assertEqual(lowercase			,   task.label_schema		)







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




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







     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




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







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    :str					    =				sorted(["pos", "neg"]		)





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				AudioClassification(audio_column="input_audio"			,   label_column="input_label"		)
        self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}			,   task.column_mapping		)





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




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







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





        """simple docstring"""




        lowercase_    :Dict					    =				AudioClassification(audio_column="input_audio"			,   label_column="input_label"		)
        self.assertEqual(task.label_schema["labels"]			,   lowercase		)
        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    a_     (       _lowerCAmelCase							):





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





        """simple docstring"""




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





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				ImageClassification(image_column="input_image"			,   label_column="input_label"		)
        self.assertDictEqual({"input_image": "image", "input_label": "labels"}			,   task.column_mapping		)





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




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







     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




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







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :Dict					    =				DatasetInfo(task_templates=QuestionAnsweringExtractive()		)
        lowercase_    :Optional[Any]					    =				Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}			,   info=lowercase		)
        assert isinstance(dataset.info.task_templates			,   lowercase		)
        assert len(dataset.info.task_templates		) == 1

        def keep_task(lowercase	:      List[str]		):
           return x

        def dont_keep_task(lowercase	:      Any		):
           lowercase_    :Optional[Any]					    =				deepcopy(lowercase		)
           lowercase_    :Dict					    =				0
           return out

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

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







     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




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

        def process(lowercase	:      Dict		):
           return example

        lowercase_    :Tuple					    =				dataset.remove_columns("label"		)
        lowercase_    :Optional[int]					    =				modified_dataset.map(lowercase		)
        assert mapped_dataset.info.task_templates == []


