






import unittest

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

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

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class 				lowerCamelCase__							(       lowerCamelCase__  ,		unittest.TestCase):




	'''simple docstring'''




	_A			=  KandinskyVaaPriorPipeline
	_A			=  ['prompt']
	_A			=  ['prompt', 'negative_prompt']
	_A			=  [
	    'num_images_per_prompt',
	    'generator',
	    'num_inference_steps',
	    'latents',
	    'negative_prompt',
	    'guidance_scale',
	    'output_type',
	    'return_dict',
	]
	_A			=  False







	@property
	def      _lowerCamelCase       (      self	:List[Any]		)	->				List[str]:
								return 3_2







	@property
	def      _lowerCamelCase       (      self	:Tuple		)	->				Optional[int]:
								return 3_2







	@property
	def      _lowerCamelCase       (      self	:str		)	->				List[str]:
								return self.time_input_dim







	@property
	def      _lowerCamelCase       (      self	:int		)	->				str:
								return self.time_input_dim * 4







	@property
	def      _lowerCamelCase       (      self	:str		)	->				List[str]:
								return 1_0_0







	@property
	def      _lowerCamelCase       (      self	:Dict		)	->				Optional[Any]:
								__UpperCamelCase			:     Optional[Any]         =      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)
								return tokenizer







	@property
	def      _lowerCamelCase       (      self	:Optional[int]		)	->				List[str]:
								torch.manual_seed(0		)
								__UpperCamelCase			:     Tuple         =      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=3_7  ,     layer_norm_eps=1E-0_5  ,     num_attention_heads=4  ,     num_hidden_layers=5  ,     pad_token_id=1  ,     vocab_size=1_0_0_0  ,     )
								return CLIPTextModelWithProjection(__lowerCamelCase		)







	@property
	def      _lowerCamelCase       (      self	:Any		)	->				Optional[int]:
								torch.manual_seed(0		)

								__UpperCamelCase			:     List[Any]         =      {
								    '''num_attention_heads''': 2,
								    '''attention_head_dim''': 1_2,
								    '''embedding_dim''': self.text_embedder_hidden_size,
								    '''num_layers''': 1,
								}

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







	@property
	def      _lowerCamelCase       (      self	:List[Any]		)	->				Tuple:
								torch.manual_seed(0		)
								__UpperCamelCase			:     int         =      CLIPVisionConfig(
								    hidden_size=self.text_embedder_hidden_size  ,     image_size=2_2_4  ,     projection_dim=self.text_embedder_hidden_size  ,     intermediate_size=3_7  ,     num_attention_heads=4  ,     num_channels=3  ,     num_hidden_layers=5  ,     patch_size=1_4  ,     )

								__UpperCamelCase			:     str         =      CLIPVisionModelWithProjection(__lowerCamelCase		)
								return model







	@property
	def      _lowerCamelCase       (      self	:Optional[int]		)	->				List[Any]:
								__UpperCamelCase			:     Any         =      CLIPImageProcessor(
								    crop_size=2_2_4  ,     do_center_crop=__lowerCamelCase  ,     do_normalize=__lowerCamelCase  ,     do_resize=__lowerCamelCase  ,     image_mean=[0.48145466, 0.4578275, 0.40821073]  ,     image_std=[0.26862954, 0.26130258, 0.27577711]  ,     resample=3  ,     size=2_2_4  ,     )

								return image_processor







	def      _lowerCamelCase       (      self	:Dict		)	->				Optional[Any]:
								__UpperCamelCase			:     Any         =      self.dummy_prior
								__UpperCamelCase			:     int         =      self.dummy_image_encoder
								__UpperCamelCase			:     Union[str, Any]         =      self.dummy_text_encoder
								__UpperCamelCase			:     Optional[int]         =      self.dummy_tokenizer
								__UpperCamelCase			:     Dict         =      self.dummy_image_processor

								__UpperCamelCase			:     Tuple         =      UnCLIPScheduler(
								    variance_type="fixed_small_log"  ,     prediction_type="sample"  ,     num_train_timesteps=1_0_0_0  ,     clip_sample=__lowerCamelCase  ,     clip_sample_range=10.0  ,     )

								__UpperCamelCase			:     List[Any]         =      {
								    '''prior''': prior,
								    '''image_encoder''': image_encoder,
								    '''text_encoder''': text_encoder,
								    '''tokenizer''': tokenizer,
								    '''scheduler''': scheduler,
								    '''image_processor''': image_processor,
								}

								return components







	def      _lowerCamelCase       (      self	:Dict  ,     a	:Any  ,     a	:int=0		)	->				List[Any]:






								if str(__lowerCamelCase		).startswith("mps"		):
															__UpperCamelCase			:     List[Any]         =      torch.manual_seed(__lowerCamelCase		)
								else:
															__UpperCamelCase			:     int         =      torch.Generator(device=__lowerCamelCase		).manual_seed(__lowerCamelCase		)
								__UpperCamelCase			:     Tuple         =      {
								    '''prompt''': '''horse''',
								    '''generator''': generator,
								    '''guidance_scale''': 4.0,
								    '''num_inference_steps''': 2,
								    '''output_type''': '''np''',
								}
								return inputs







	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Optional[Any]:
								__UpperCamelCase			:     int         =      '''cpu'''

								__UpperCamelCase			:     str         =      self.get_dummy_components()

								__UpperCamelCase			:     List[Any]         =      self.pipeline_class(**__lowerCamelCase		)
								__UpperCamelCase			:     int         =      pipe.to(__lowerCamelCase		)

								pipe.set_progress_bar_config(disable=__lowerCamelCase		)

								__UpperCamelCase			:     Optional[int]         =      pipe(**self.get_dummy_inputs(__lowerCamelCase		)		)
								__UpperCamelCase			:     Optional[int]         =      output.image_embeds

								__UpperCamelCase			:     Optional[Any]         =      pipe(
								    **self.get_dummy_inputs(__lowerCamelCase		)  ,     return_dict=__lowerCamelCase  ,     )[0]

								__UpperCamelCase			:     Optional[int]         =      image[0, -1_0:]
								__UpperCamelCase			:     Tuple         =      image_from_tuple[0, -1_0:]

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

								__UpperCamelCase			:     Dict         =      np.array(
								    [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]		)

								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      _lowerCamelCase       (      self	:List[str]		)	->				int:
								__UpperCamelCase			:     int         =      torch_device == '''cpu'''
								__UpperCamelCase			:     List[str]         =      True
								__UpperCamelCase			:     Optional[int]         =      False

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







	@skip_mps
	def      _lowerCamelCase       (      self	:Optional[int]		)	->				Optional[int]:
								__UpperCamelCase			:     Optional[Any]         =      torch_device == '''cpu'''
								__UpperCamelCase			:     Union[str, Any]         =      False

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

import re
import string

import numpy as np

import datasets


lowercase						:      List[str]									= '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

lowercase						:      List[str]									= '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

lowercase						:      List[str]									= '\n'




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




	'''simple docstring'''




	def      _lowerCamelCase       (      self	:Dict		)	->				Optional[Any]:
								return datasets.MetricInfo(
								    description=_DESCRIPTION  ,     citation=_CITATION  ,     inputs_description=_KWARGS_DESCRIPTION  ,     features=datasets.Features(
								        {
								            "predictions": datasets.Value("string"  ,     id="sequence"		),
								            "references": datasets.Value("string"  ,     id="sequence"		),
								        }		)  ,     reference_urls=[]  ,     )







	def      _lowerCamelCase       (      self	:int  ,     a	:Optional[Any]  ,     a	:Dict  ,     a	:Optional[int]=None  ,     a	:int=False  ,     a	:Tuple=False  ,     a	:Optional[int]=False  ,     )	->				Any:
								if regexes_to_ignore is not None:
															for s in regexes_to_ignore:
																						__UpperCamelCase			:     List[Any]         =      np.array([re.sub(a  ,     ""  ,     a		) for x in predictions]		)
																						__UpperCamelCase			:     Optional[Any]         =      np.array([re.sub(a  ,     ""  ,     a		) for x in references]		)
								else:
															__UpperCamelCase			:     Optional[int]         =      np.asarray(a		)
															__UpperCamelCase			:     List[str]         =      np.asarray(a		)

								if ignore_case:
															__UpperCamelCase			:     Optional[int]         =      np.char.lower(a		)
															__UpperCamelCase			:     str         =      np.char.lower(a		)

								if ignore_punctuation:
															__UpperCamelCase			:     Tuple         =      string.punctuation.maketrans(""  ,     ""  ,     string.punctuation		)
															__UpperCamelCase			:     int         =      np.char.translate(a  ,     table=a		)
															__UpperCamelCase			:     str         =      np.char.translate(a  ,     table=a		)

								if ignore_numbers:
															__UpperCamelCase			:     List[str]         =      string.digits.maketrans(""  ,     ""  ,     string.digits		)
															__UpperCamelCase			:     Tuple         =      np.char.translate(a  ,     table=a		)
															__UpperCamelCase			:     Union[str, Any]         =      np.char.translate(a  ,     table=a		)

								__UpperCamelCase			:     List[Any]         =      predictions == references

								return {"exact_match": np.mean(a		) * 1_0_0}