




'''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 	lowerCamelCase_				(			UpperCAmelCase_,			unittest.TestCase				):




					'''simple docstring'''






					lowercase__       =					KandinskyVaaPriorEmbaEmbPipeline
					lowercase__       =					["""prompt""", """image"""]
					lowercase__       =					["""prompt""", """image"""]
					lowercase__       =					[
					    """num_images_per_prompt""",
					    """strength""",
					    """generator""",
					    """num_inference_steps""",
					    """latents""",
					    """negative_prompt""",
					    """guidance_scale""",
					    """output_type""",
					    """return_dict""",
					]
					lowercase__       =					False






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return 32






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return 32






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return self.time_input_dim






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return self.time_input_dim * 4






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return 100






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)
							return tokenizer






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							torch.manual_seed(0					)
							_snake_case      			=			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-05,    num_attention_heads=4,    num_hidden_layers=5,    pad_token_id=1,    vocab_size=1_000,    )
							return CLIPTextModelWithProjection(__UpperCamelCase					)






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							torch.manual_seed(0					)

							_snake_case      			=			{
							    "num_attention_heads": 2,
							    "attention_head_dim": 12,
							    "embedding_dim": self.text_embedder_hidden_size,
							    "num_layers": 1,
							}

							_snake_case      			=			PriorTransformer(**__UpperCamelCase					)
							# 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
							_snake_case      			=			nn.Parameter(torch.ones(model.clip_std.shape					)					)
							return model






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							torch.manual_seed(0					)
							_snake_case      			=			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,    )

							_snake_case      			=			CLIPVisionModelWithProjection(__UpperCamelCase					)
							return model






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			CLIPImageProcessor(
							    crop_size=224,    do_center_crop=__UpperCamelCase,    do_normalize=__UpperCamelCase,    do_resize=__UpperCamelCase,    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 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			self.dummy_prior
							_snake_case      			=			self.dummy_image_encoder
							_snake_case      			=			self.dummy_text_encoder
							_snake_case      			=			self.dummy_tokenizer
							_snake_case      			=			self.dummy_image_processor

							_snake_case      			=			UnCLIPScheduler(
							    variance_type="fixed_small_log",    prediction_type="sample",    num_train_timesteps=1_000,    clip_sample=__UpperCamelCase,    clip_sample_range=10.0,    )

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

							return components






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase=0					):
							if str(__UpperCamelCase					).startswith("mps"					):
									_snake_case      			=			torch.manual_seed(__UpperCamelCase					)
							else:
									_snake_case      			=			torch.Generator(device=__UpperCamelCase					).manual_seed(__UpperCamelCase					)

							_snake_case      			=			floats_tensor((1, 3, 64, 64),    rng=random.Random(__UpperCamelCase					)					).to(__UpperCamelCase					)
							_snake_case      			=			image.cpu().permute(0,    2,    3,    1					)[0]
							_snake_case      			=			Image.fromarray(np.uinta(__UpperCamelCase					)					).convert("RGB"					).resize((256, 256)					)

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






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			"cpu"

							_snake_case      			=			self.get_dummy_components()

							_snake_case      			=			self.pipeline_class(**__UpperCamelCase					)
							_snake_case      			=			pipe.to(__UpperCamelCase					)

							pipe.set_progress_bar_config(disable=__UpperCamelCase					)

							_snake_case      			=			pipe(**self.get_dummy_inputs(__UpperCamelCase					)					)
							_snake_case      			=			output.image_embeds

							_snake_case      			=			pipe(
							    **self.get_dummy_inputs(__UpperCamelCase					),    return_dict=__UpperCamelCase,    )[0]

							_snake_case      			=			image[0, -10:]
							_snake_case      			=			image_from_tuple[0, -10:]

							assert image.shape == (1, 32)

							_snake_case      			=			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 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			torch_device == "cpu"
							_snake_case      			=			True
							_snake_case      			=			False

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






					@skip_mps
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			torch_device == "cpu"
							_snake_case      			=			False

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











'''simple docstring'''







import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


_lowerCamelCase				:		str				      =    '\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n'

_lowerCamelCase				:		Union[str, Any]				      =    '\nThis metric wrap the official scoring script for version 2 of the Stanford Question\nAnswering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n\nSQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions\nwritten adversarially by crowdworkers to look similar to answerable ones.\nTo do well on SQuAD2.0, systems must not only answer questions when possible, but also\ndetermine when no answer is supported by the paragraph and abstain from answering.\n'

_lowerCamelCase				:		List[Any]				      =    '\nComputes SQuAD v2 scores (F1 and EM).\nArgs:\n    predictions: List of triple for question-answers to score with the following elements:\n        - the question-answer \'id\' field as given in the references (see below)\n        - the text of the answer\n        - the probability that the question has no answer\n    references: List of question-answers dictionaries with the following key-values:\n            - \'id\': id of the question-answer pair (see above),\n            - \'answers\': a list of Dict {\'text\': text of the answer as a string}\n    no_answer_threshold: float\n        Probability threshold to decide that a question has no answer.\nReturns:\n    \'exact\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\n    \'total\': Number of score considered\n    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)\n    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer\n    \'HasAns_total\': Number of score considered\n    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)\n    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer\n    \'NoAns_total\': Number of score considered\n    \'best_exact\': Best exact match (with varying threshold)\n    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match\n    \'best_f1\': Best F1 (with varying threshold)\n    \'best_f1_thresh\': No-answer probability threshold associated to the best F1\nExamples:\n\n    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]\n    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n    >>> squad_v2_metric = datasets.load_metric("squad_v2")\n    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact\': 100.0, \'f1\': 100.0, \'total\': 1, \'HasAns_exact\': 100.0, \'HasAns_f1\': 100.0, \'HasAns_total\': 1, \'best_exact\': 100.0, \'best_exact_thresh\': 0.0, \'best_f1\': 100.0, \'best_f1_thresh\': 0.0}\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,			_KWARGS_DESCRIPTION				)
class 	lowerCamelCase_				(			datasets.Metric				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return datasets.MetricInfo(
							    description=_DESCRIPTION,    citation=_CITATION,    inputs_description=_KWARGS_DESCRIPTION,    features=datasets.Features(
							        {
							            "predictions": {
							                "id": datasets.Value("string"					),
							                "prediction_text": datasets.Value("string"					),
							                "no_answer_probability": datasets.Value("float32"					),
							            },
							            "references": {
							                "id": datasets.Value("string"					),
							                "answers": datasets.features.Sequence(
							                    {"text": datasets.Value("string"					), "answer_start": datasets.Value("int32"					)}					),
							            },
							        }					),    codebase_urls=["https://rajpurkar.github.io/SQuAD-explorer/"],    reference_urls=["https://rajpurkar.github.io/SQuAD-explorer/"],    )






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase=1.0					):
							_snake_case      			=			{p["id"]: p["no_answer_probability"] for p in predictions}
							_snake_case      			=			[{"paragraphs": [{"qas": references}]}]
							_snake_case      			=			{p["id"]: p["prediction_text"] for p in predictions}

							_snake_case      			=			make_qid_to_has_ans(__UpperCamelCase					)  # maps qid to True/False
							_snake_case      			=			[k for k, v in qid_to_has_ans.items() if v]
							_snake_case      			=			[k for k, v in qid_to_has_ans.items() if not v]

							_snake_case			,       _snake_case      			=			get_raw_scores(__UpperCamelCase,    __UpperCamelCase					)
							_snake_case      			=			apply_no_ans_threshold(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					)
							_snake_case      			=			apply_no_ans_threshold(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					)
							_snake_case      			=			make_eval_dict(__UpperCamelCase,    __UpperCamelCase					)

							if has_ans_qids:
									_snake_case      			=			make_eval_dict(__UpperCamelCase,    __UpperCamelCase,    qid_list=__UpperCamelCase					)
									merge_eval(__UpperCamelCase,    __UpperCamelCase,    "HasAns"					)
							if no_ans_qids:
									_snake_case      			=			make_eval_dict(__UpperCamelCase,    __UpperCamelCase,    qid_list=__UpperCamelCase					)
									merge_eval(__UpperCamelCase,    __UpperCamelCase,    "NoAns"					)
							find_all_best_thresh(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					)
							return dict(__UpperCamelCase					)





