


import gc
import random
import unittest

import numpy as np
import torch

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()


class 	_a							(      __snake_case					,     unittest.TestCase      ):
							_lowercase     :      Any  				=			KandinskyVaaControlnetPipeline
							_lowercase     :      Any  				=			["""image_embeds""", """negative_image_embeds""", """hint"""]
							_lowercase     :      int  				=			["""image_embeds""", """negative_image_embeds""", """hint"""]
							_lowercase     :      Any  				=			[
							    """generator""",
							    """height""",
							    """width""",
							    """latents""",
							    """guidance_scale""",
							    """num_inference_steps""",
							    """return_dict""",
							    """guidance_scale""",
							    """num_images_per_prompt""",
							    """output_type""",
							    """return_dict""",
							]
							_lowercase     :      str  				=			False

							@property
							def 				lowerCamelCase_			(							self:     Any							)      ->       Union[str, Any]:





									"""simple docstring"""







									return 32

							@property
							def 				lowerCamelCase_			(							self:     int							)      ->       List[Any]:





									"""simple docstring"""







									return 32

							@property
							def 				lowerCamelCase_			(							self:     Any							)      ->       int:





									"""simple docstring"""







									return self.time_input_dim

							@property
							def 				lowerCamelCase_			(							self:     List[str]							)      ->       Tuple:





									"""simple docstring"""







									return self.time_input_dim * 4

							@property
							def 				lowerCamelCase_			(							self:     int							)      ->       Optional[int]:





									"""simple docstring"""







									return 100

							@property
							def 				lowerCamelCase_			(							self:     Dict							)      ->       Optional[int]:





									"""simple docstring"""







									torch.manual_seed(0							)

									lowercase__						=				{
									    "in_channels": 8,
									    # Out channels is double in channels because predicts mean and variance
									    "out_channels": 8,
									    "addition_embed_type": "image_hint",
									    "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
									    "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
									    "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
									    "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
									    "layers_per_block": 1,
									    "encoder_hid_dim": self.text_embedder_hidden_size,
									    "encoder_hid_dim_type": "image_proj",
									    "cross_attention_dim": self.cross_attention_dim,
									    "attention_head_dim": 4,
									    "resnet_time_scale_shift": "scale_shift",
									    "class_embed_type": None,
									}

									lowercase__						=				UNetaDConditionModel(**UpperCamelCase__							)
									return model

							@property
							def 				lowerCamelCase_			(							self:     List[Any]							)      ->       Optional[Any]:





									"""simple docstring"""







									return {
									    "block_out_channels": [32, 32, 64, 64],
									    "down_block_types": [
									        "DownEncoderBlock2D",
									        "DownEncoderBlock2D",
									        "DownEncoderBlock2D",
									        "AttnDownEncoderBlock2D",
									    ],
									    "in_channels": 3,
									    "latent_channels": 4,
									    "layers_per_block": 1,
									    "norm_num_groups": 8,
									    "norm_type": "spatial",
									    "num_vq_embeddings": 12,
									    "out_channels": 3,
									    "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
									    "vq_embed_dim": 4,
									}

							@property
							def 				lowerCamelCase_			(							self:     Dict							)      ->       Tuple:





									"""simple docstring"""







									torch.manual_seed(0							)
									lowercase__						=				VQModel(**self.dummy_movq_kwargs							)
									return model

							def 				lowerCamelCase_			(							self:     List[str]							)      ->       Optional[int]:





									"""simple docstring"""







									lowercase__						=				self.dummy_unet
									lowercase__						=				self.dummy_movq

									lowercase__						=				DDIMScheduler(
									    num_train_timesteps=1_000   ,						beta_schedule='''linear'''   ,						beta_start=0.00085   ,						beta_end=0.012   ,						clip_sample=UpperCamelCase__   ,						set_alpha_to_one=UpperCamelCase__   ,						steps_offset=1   ,						prediction_type='''epsilon'''   ,						thresholding=UpperCamelCase__   ,						)

									lowercase__						=				{
									    "unet": unet,
									    "scheduler": scheduler,
									    "movq": movq,
									}
									return components

							def 				lowerCamelCase_			(							self:     str   ,						UpperCamelCase_:     Tuple   ,						UpperCamelCase_:     int=0							)      ->       str:





									"""simple docstring"""







									lowercase__						=				floats_tensor((1, self.text_embedder_hidden_size)   ,						rng=random.Random(UpperCamelCase__							)							).to(UpperCamelCase__							)
									lowercase__						=				floats_tensor((1, self.text_embedder_hidden_size)   ,						rng=random.Random(seed + 1							)							).to(
									    UpperCamelCase__							)

									# create hint
									lowercase__						=				floats_tensor((1, 3, 64, 64)   ,						rng=random.Random(UpperCamelCase__							)							).to(UpperCamelCase__							)

									if str(UpperCamelCase__							).startswith('''mps'''							):
											lowercase__						=				torch.manual_seed(UpperCamelCase__							)
									else:
											lowercase__						=				torch.Generator(device=UpperCamelCase__							).manual_seed(UpperCamelCase__							)
									lowercase__						=				{
									    "image_embeds": image_embeds,
									    "negative_image_embeds": negative_image_embeds,
									    "hint": hint,
									    "generator": generator,
									    "height": 64,
									    "width": 64,
									    "guidance_scale": 4.0,
									    "num_inference_steps": 2,
									    "output_type": "np",
									}
									return inputs


							def 				lowerCamelCase_			(							self:     int							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				"cpu"

									lowercase__						=				self.get_dummy_components()

									lowercase__						=				self.pipeline_class(**UpperCamelCase__							)
									lowercase__						=				pipe.to(UpperCamelCase__							)

									pipe.set_progress_bar_config(disable=UpperCamelCase__							)

									lowercase__						=				pipe(**self.get_dummy_inputs(UpperCamelCase__							)							)
									lowercase__						=				output.images

									lowercase__						=				pipe(
									    **self.get_dummy_inputs(UpperCamelCase__							)   ,						return_dict=UpperCamelCase__   ,						)[0]

									lowercase__						=				image[0, -3:, -3:, -1]
									lowercase__						=				image_from_tuple[0, -3:, -3:, -1]

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

									lowercase__						=				np.array(
									    [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595]							)

									assert (
									    np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
									), f' expected_slice {expected_slice}, but got {image_slice.flatten()}'

									assert (
									    np.abs(image_from_tuple_slice.flatten() - expected_slice							).max() < 1E-2
									), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'


@slow
@require_torch_gpu
class 	_a							(      unittest.TestCase      ):

							def 				lowerCamelCase_			(							self:     List[Any]							)      ->       str:





									"""simple docstring"""







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


							def 				lowerCamelCase_			(							self:     Optional[int]							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				load_numpy(
									    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
									    '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy'''							)

									lowercase__						=				load_image(
									    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
									    '''/kandinskyv22/hint_image_cat.png'''							)
									lowercase__						=				torch.from_numpy(np.array(UpperCamelCase__							)							).float() / 255.0
									lowercase__						=				hint.permute(2   ,						0   ,						1							).unsqueeze(0							)

									lowercase__						=				KandinskyVaaPriorPipeline.from_pretrained(
									    '''kandinsky-community/kandinsky-2-2-prior'''   ,						torch_dtype=torch.floataa							)
									pipe_prior.to(UpperCamelCase__							)

									lowercase__						=				KandinskyVaaControlnetPipeline.from_pretrained(
									    '''kandinsky-community/kandinsky-2-2-controlnet-depth'''   ,						torch_dtype=torch.floataa							)
									lowercase__						=				pipeline.to(UpperCamelCase__							)
									pipeline.set_progress_bar_config(disable=UpperCamelCase__							)

									lowercase__						=				"A robot, 4k photo"

									lowercase__						=				torch.Generator(device='''cuda'''							).manual_seed(0							)
									lowercase__						=				pipe_prior(
									    UpperCamelCase__   ,						generator=UpperCamelCase__   ,						num_inference_steps=5   ,						negative_prompt=''''''   ,						).to_tuple()

									lowercase__						=				torch.Generator(device='''cuda'''							).manual_seed(0							)
									lowercase__						=				pipeline(
									    image_embeds=UpperCamelCase__   ,						negative_image_embeds=UpperCamelCase__   ,						hint=UpperCamelCase__   ,						generator=UpperCamelCase__   ,						num_inference_steps=100   ,						output_type='''np'''   ,						)

									lowercase__						=				output.images[0]

									assert image.shape == (512, 512, 3)

									assert_mean_pixel_difference(UpperCamelCase__   ,						UpperCamelCase__							)





import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase	=							version.parse(importlib_metadata.version('nltk'))
if NLTK_VERSION >= version.Version('3.6.4'):
			from nltk import word_tokenize


lowerCAmelCase	=							'\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n'

lowerCAmelCase	=							'\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n'

lowerCAmelCase	=							'\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    \'meteor\': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric(\'meteor\')\n    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results["meteor"], 4))\n    0.6944\n'


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

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





									"""simple docstring"""







									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'''							),
									        }							)   ,						codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py''']   ,						reference_urls=[
									        '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''',
									        '''https://en.wikipedia.org/wiki/METEOR''',
									    ]   ,						)

							def 				lowerCamelCase_			(							self:     Union[str, Any]   ,						UpperCamelCase_:     List[str]							)      ->       Union[str, Any]:





									"""simple docstring"""







									import nltk

									nltk.download('''wordnet'''							)
									if NLTK_VERSION >= version.Version('''3.6.5'''							):
											nltk.download('''punkt'''							)
									if NLTK_VERSION >= version.Version('''3.6.6'''							):
											nltk.download('''omw-1.4'''							)


							def 				lowerCamelCase_			(							self:     Any   ,						UpperCamelCase_:     Union[str, Any]   ,						UpperCamelCase_:     Tuple   ,						UpperCamelCase_:     Dict=0.9   ,						UpperCamelCase_:     Union[str, Any]=3   ,						UpperCamelCase_:     Optional[int]=0.5							)      ->       Dict:





									"""simple docstring"""







									if NLTK_VERSION >= version.Version('''3.6.5'''							):
											lowercase__						=				[
											    meteor_score.single_meteor_score(
											        word_tokenize(UpperCamelCase_							)   ,						word_tokenize(UpperCamelCase_							)   ,						alpha=UpperCamelCase_   ,						beta=UpperCamelCase_   ,						gamma=UpperCamelCase_							)
											    for ref, pred in zip(UpperCamelCase_   ,						UpperCamelCase_							)
											]
									else:
											lowercase__						=				[
											    meteor_score.single_meteor_score(UpperCamelCase_   ,						UpperCamelCase_   ,						alpha=UpperCamelCase_   ,						beta=UpperCamelCase_   ,						gamma=UpperCamelCase_							)
											    for ref, pred in zip(UpperCamelCase_   ,						UpperCamelCase_							)
											]

									return {"meteor": np.mean(UpperCamelCase_							)}


