





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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 	UpperCamelCase__				(   lowerCAmelCase_							,   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			Optional[Any]				=    KandinskyImgaImgPipeline
     __snake_case					:			int				=    ["prompt", "image_embeds", "negative_image_embeds", "image"]
     __snake_case					:			str				=    [
         "prompt",
         "negative_prompt",
         "image_embeds",
         "negative_image_embeds",
         "image",
     ]
     __snake_case					:			Dict				=    [
         "generator",
         "height",
         "width",
         "strength",
         "guidance_scale",
         "negative_prompt",
         "num_inference_steps",
         "return_dict",
         "guidance_scale",
         "num_images_per_prompt",
         "output_type",
         "return_dict",
     ]
     __snake_case					:			List[Any]				=    False






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




           '''simple docstring'''


           return 32






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




           '''simple docstring'''


           return 32






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




           '''simple docstring'''


           return self.time_input_dim






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




           '''simple docstring'''


           return self.time_input_dim * 4






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	List[str]:




           '''simple docstring'''


           return 100






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" )
           return tokenizer






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




           '''simple docstring'''


           torch.manual_seed(0 )
           SCREAMING_SNAKE_CASE	=		MCLIPConfig(
               numDims=self.cross_attention_dim		,transformerDimensions=self.text_embedder_hidden_size		,hidden_size=self.text_embedder_hidden_size		,intermediate_size=37		,num_attention_heads=4		,num_hidden_layers=5		,vocab_size=1005		,)

           SCREAMING_SNAKE_CASE	=		MultilingualCLIP(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		text_encoder.eval()

           return text_encoder






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Dict:




           '''simple docstring'''


           torch.manual_seed(0 )

           SCREAMING_SNAKE_CASE	=		{
               """in_channels""": 4,
               # Out channels is double in channels because predicts mean and variance
               """out_channels""": 8,
               """addition_embed_type""": """text_image""",
               """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""": """text_image_proj""",
               """cross_attention_dim""": self.cross_attention_dim,
               """attention_head_dim""": 4,
               """resnet_time_scale_shift""": """scale_shift""",
               """class_embed_type""": None,
           }

           SCREAMING_SNAKE_CASE	=		UNetaDConditionModel(**lowerCamelCase__ )
           return model






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	Dict:




           '''simple docstring'''


           return {
               "block_out_channels": [32, 64],
               "down_block_types": ["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",
               ],
               "vq_embed_dim": 4,
           }






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




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.dummy_text_encoder
           SCREAMING_SNAKE_CASE	=		self.dummy_tokenizer
           SCREAMING_SNAKE_CASE	=		self.dummy_unet
           SCREAMING_SNAKE_CASE	=		self.dummy_movq

           SCREAMING_SNAKE_CASE	=		{
               """num_train_timesteps""": 1000,
               """beta_schedule""": """linear""",
               """beta_start""": 0.00085,
               """beta_end""": 0.012,
               """clip_sample""": False,
               """set_alpha_to_one""": False,
               """steps_offset""": 0,
               """prediction_type""": """epsilon""",
               """thresholding""": False,
           }

           SCREAMING_SNAKE_CASE	=		DDIMScheduler(**lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		{
               """text_encoder""": text_encoder,
               """tokenizer""": tokenizer,
               """unet""": unet,
               """scheduler""": scheduler,
               """movq""": movq,
           }

           return components






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int]		,lowerCamelCase__		:					Union[str, Any]		,lowerCamelCase__		:					int=0 )  ->	Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		floats_tensor((1, self.cross_attention_dim)		,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		floats_tensor((1, self.cross_attention_dim)		,rng=random.Random(seed + 1 ) ).to(lowerCamelCase__ )
           # create init_image
           SCREAMING_SNAKE_CASE	=		floats_tensor((1, 3, 64, 64)		,rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		image.cpu().permute(0		,2		,3		,1 )[0]
           SCREAMING_SNAKE_CASE	=		Image.fromarray(np.uinta(lowerCamelCase__ ) ).convert("""RGB""" ).resize((256, 256) )

           if str(lowerCamelCase__ ).startswith("""mps""" ):
                 SCREAMING_SNAKE_CASE	=		torch.manual_seed(lowerCamelCase__ )
           else:
                 SCREAMING_SNAKE_CASE	=		torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		{
               """prompt""": """horse""",
               """image""": init_image,
               """image_embeds""": image_embeds,
               """negative_image_embeds""": negative_image_embeds,
               """generator""": generator,
               """height""": 64,
               """width""": 64,
               """num_inference_steps""": 10,
               """guidance_scale""": 7.0,
               """strength""": 0.2,
               """output_type""": """np""",
           }
           return inputs






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		"""cpu"""

           SCREAMING_SNAKE_CASE	=		self.get_dummy_components()

           SCREAMING_SNAKE_CASE	=		self.pipeline_class(**lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		pipe.to(lowerCamelCase__ )

           pipe.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		pipe(**self.get_dummy_inputs(lowerCamelCase__ ) )
           SCREAMING_SNAKE_CASE	=		output.images

           SCREAMING_SNAKE_CASE	=		pipe(
               **self.get_dummy_inputs(lowerCamelCase__ )		,return_dict=lowerCamelCase__		,)[0]

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

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

           SCREAMING_SNAKE_CASE	=		np.array(
               [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233] )
           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 	UpperCamelCase__				(   unittest.TestCase     ):



     '''simple docstring'''

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




           '''simple docstring'''


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






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/kandinsky/kandinsky_img2img_frog.npy""" )

           SCREAMING_SNAKE_CASE	=		load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" )
           SCREAMING_SNAKE_CASE	=		"""A red cartoon frog, 4k"""

           SCREAMING_SNAKE_CASE	=		KandinskyPriorPipeline.from_pretrained(
               """kandinsky-community/kandinsky-2-1-prior"""		,torch_dtype=torch.floataa )
           pipe_prior.to(lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		KandinskyImgaImgPipeline.from_pretrained(
               """kandinsky-community/kandinsky-2-1"""		,torch_dtype=torch.floataa )
           SCREAMING_SNAKE_CASE	=		pipeline.to(lowerCamelCase__ )

           pipeline.set_progress_bar_config(disable=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		torch.Generator(device="""cpu""" ).manual_seed(0 )
           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		pipe_prior(
               lowerCamelCase__		,generator=lowerCamelCase__		,num_inference_steps=5		,negative_prompt=""""""		,).to_tuple()

           SCREAMING_SNAKE_CASE	=		pipeline(
               lowerCamelCase__		,image=lowerCamelCase__		,image_embeds=lowerCamelCase__		,negative_image_embeds=lowerCamelCase__		,generator=lowerCamelCase__		,num_inference_steps=100		,height=768		,width=768		,strength=0.2		,output_type="""np"""		,)

           SCREAMING_SNAKE_CASE	=		output.images[0]

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

           assert_mean_pixel_difference(lowerCamelCase__		,lowerCamelCase__ )









from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


SCREAMING_SNAKE_CASE_		     = """\
@misc{wu2016googles,
      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""

SCREAMING_SNAKE_CASE_		     = """\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

SCREAMING_SNAKE_CASE_		     = """\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""

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



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	MetricInfo:




           '''simple docstring'''


           return datasets.MetricInfo(
               description=_DESCRIPTION		,citation=_CITATION		,inputs_description=_KWARGS_DESCRIPTION		,features=datasets.Features(
                   {
                       """predictions""": datasets.Sequence(datasets.Value("""string"""		,id="""token""" )		,id="""sequence""" ),
                       """references""": datasets.Sequence(
                           datasets.Sequence(datasets.Value("""string"""		,id="""token""" )		,id="""sequence""" )		,id="""references""" ),
                   } )		,)






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					List[List[List[str]]]		,lowerCamelCase__		:					List[List[str]]		,lowerCamelCase__		:					int = 1		,lowerCamelCase__		:					int = 4		,)  ->	Dict[str, float]:




           '''simple docstring'''


           return {
               "google_bleu": gleu_score.corpus_gleu(
                   list_of_references=lowerCamelCase__		,hypotheses=lowerCamelCase__		,min_len=lowerCamelCase__		,max_len=lowerCamelCase__ )
           }


