






import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class 							_UpperCamelCase			(a_							,		a_							,		a_							,		unittest.TestCase			):
      snake_case_  =							StableDiffusionInpaintPipeline
      snake_case_  =							TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
      snake_case_  =							TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
      snake_case_  =							frozenset(
          []			)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
      snake_case_  =							frozenset([]			)


      def  __UpperCAmelCase		(	self	)->	List[Any]:
           torch.manual_seed(0	)
           __lowerCAmelCase								=					UNetaDConditionModel(
               block_out_channels=(3_2, 6_4)					,						layers_per_block=2					,						sample_size=3_2					,						in_channels=9					,						out_channels=4					,						down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")					,						up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")					,						cross_attention_dim=3_2					,						attention_head_dim=(2, 4)					,						use_linear_projection=__UpperCamelCase					,						)
           __lowerCAmelCase								=					PNDMScheduler(skip_prk_steps=__UpperCamelCase	)
           torch.manual_seed(0	)
           __lowerCAmelCase								=					AutoencoderKL(
               block_out_channels=[3_2, 6_4]					,						in_channels=3					,						out_channels=3					,						down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]					,						up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]					,						latent_channels=4					,						sample_size=1_2_8					,						)
           torch.manual_seed(0	)
           __lowerCAmelCase								=					CLIPTextConfig(
               bos_token_id=0					,						eos_token_id=2					,						hidden_size=3_2					,						intermediate_size=3_7					,						layer_norm_eps=1e-05					,						num_attention_heads=4					,						num_hidden_layers=5					,						pad_token_id=1					,						vocab_size=1_0_0_0					,						hidden_act="gelu"					,						projection_dim=5_1_2					,						)
           __lowerCAmelCase								=					CLIPTextModel(__UpperCamelCase	)
           __lowerCAmelCase								=					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

           __lowerCAmelCase								=					{
               "unet": unet,
               "scheduler": scheduler,
               "vae": vae,
               "text_encoder": text_encoder,
               "tokenizer": tokenizer,
               "safety_checker": None,
               "feature_extractor": None,
           }
           return components


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase=0	)->	str:
           # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
           __lowerCAmelCase								=					floats_tensor((1, 3, 3_2, 3_2)					,						rng=random.Random(__UpperCamelCase	)	).to(__UpperCamelCase	)
           __lowerCAmelCase								=					image.cpu().permute(0					,						2					,						3					,						1	)[0]
           __lowerCAmelCase								=					Image.fromarray(np.uinta(__UpperCamelCase	)	).convert("RGB"	).resize((6_4, 6_4)	)
           __lowerCAmelCase								=					Image.fromarray(np.uinta(image + 4	)	).convert("RGB"	).resize((6_4, 6_4)	)
           if str(__UpperCamelCase	).startswith("mps"	):
                __lowerCAmelCase								=					torch.manual_seed(__UpperCamelCase	)
           else:
                __lowerCAmelCase								=					torch.Generator(device=__UpperCamelCase	).manual_seed(__UpperCamelCase	)
           __lowerCAmelCase								=					{
               "prompt": "A painting of a squirrel eating a burger",
               "image": init_image,
               "mask_image": mask_image,
               "generator": generator,
               "num_inference_steps": 2,
               "guidance_scale": 6.0,
               "output_type": "numpy",
           }
           return inputs


      def  __UpperCAmelCase		(	self	)->	Optional[Any]:
           __lowerCAmelCase								=					"cpu"  # ensure determinism for the device-dependent torch.Generator
           __lowerCAmelCase								=					self.get_dummy_components()
           __lowerCAmelCase								=					StableDiffusionInpaintPipeline(**__UpperCamelCase	)
           __lowerCAmelCase								=					sd_pipe.to(__UpperCamelCase	)
           sd_pipe.set_progress_bar_config(disable=__UpperCamelCase	)

           __lowerCAmelCase								=					self.get_dummy_inputs(__UpperCamelCase	)
           __lowerCAmelCase								=					sd_pipe(**__UpperCamelCase	).images
           __lowerCAmelCase								=					image[0, -3:, -3:, -1]

           assert image.shape == (1, 6_4, 6_4, 3)
           __lowerCAmelCase								=					np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6]	)

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


      def  __UpperCAmelCase		(	self	)->	Optional[int]:
           super().test_inference_batch_single_identical(expected_max_diff=3e-3	)



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


      def  __UpperCAmelCase		(	self	)->	List[Any]:
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()


      def  __UpperCAmelCase		(	self	)->	List[str]:
           __lowerCAmelCase								=					load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-inpaint/init_image.png"	)
           __lowerCAmelCase								=					load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"	)
           __lowerCAmelCase								=					load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
               "/yellow_cat_sitting_on_a_park_bench.npy"	)

           __lowerCAmelCase								=					"stabilityai/stable-diffusion-2-inpainting"
           __lowerCAmelCase								=					StableDiffusionInpaintPipeline.from_pretrained(__UpperCamelCase					,						safety_checker=__UpperCamelCase	)
           pipe.to(__UpperCamelCase	)
           pipe.set_progress_bar_config(disable=__UpperCamelCase	)
           pipe.enable_attention_slicing()

           __lowerCAmelCase								=					"Face of a yellow cat, high resolution, sitting on a park bench"

           __lowerCAmelCase								=					torch.manual_seed(0	)
           __lowerCAmelCase								=					pipe(
               prompt=__UpperCamelCase					,						image=__UpperCamelCase					,						mask_image=__UpperCamelCase					,						generator=__UpperCamelCase					,						output_type="np"					,						)
           __lowerCAmelCase								=					output.images[0]

           assert image.shape == (5_1_2, 5_1_2, 3)
           assert np.abs(expected_image - image	).max() < 9e-3


      def  __UpperCAmelCase		(	self	)->	Optional[int]:
           __lowerCAmelCase								=					load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-inpaint/init_image.png"	)
           __lowerCAmelCase								=					load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"	)
           __lowerCAmelCase								=					load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
               "/yellow_cat_sitting_on_a_park_bench_fp16.npy"	)

           __lowerCAmelCase								=					"stabilityai/stable-diffusion-2-inpainting"
           __lowerCAmelCase								=					StableDiffusionInpaintPipeline.from_pretrained(
               __UpperCamelCase					,						torch_dtype=torch.floataa					,						safety_checker=__UpperCamelCase					,						)
           pipe.to(__UpperCamelCase	)
           pipe.set_progress_bar_config(disable=__UpperCamelCase	)
           pipe.enable_attention_slicing()

           __lowerCAmelCase								=					"Face of a yellow cat, high resolution, sitting on a park bench"

           __lowerCAmelCase								=					torch.manual_seed(0	)
           __lowerCAmelCase								=					pipe(
               prompt=__UpperCamelCase					,						image=__UpperCamelCase					,						mask_image=__UpperCamelCase					,						generator=__UpperCamelCase					,						output_type="np"					,						)
           __lowerCAmelCase								=					output.images[0]

           assert image.shape == (5_1_2, 5_1_2, 3)
           assert np.abs(expected_image - image	).max() < 5e-1


      def  __UpperCAmelCase		(	self	)->	Dict:
           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           __lowerCAmelCase								=					load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-inpaint/init_image.png"	)
           __lowerCAmelCase								=					load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"	)

           __lowerCAmelCase								=					"stabilityai/stable-diffusion-2-inpainting"
           __lowerCAmelCase								=					PNDMScheduler.from_pretrained(__UpperCamelCase					,						subfolder="scheduler"	)
           __lowerCAmelCase								=					StableDiffusionInpaintPipeline.from_pretrained(
               __UpperCamelCase					,						safety_checker=__UpperCamelCase					,						scheduler=__UpperCamelCase					,						torch_dtype=torch.floataa					,						)
           pipe.to(__UpperCamelCase	)
           pipe.set_progress_bar_config(disable=__UpperCamelCase	)
           pipe.enable_attention_slicing(1	)
           pipe.enable_sequential_cpu_offload()

           __lowerCAmelCase								=					"Face of a yellow cat, high resolution, sitting on a park bench"

           __lowerCAmelCase								=					torch.manual_seed(0	)
           __lowerCAmelCase								=					pipe(
               prompt=__UpperCamelCase					,						image=__UpperCamelCase					,						mask_image=__UpperCamelCase					,						generator=__UpperCamelCase					,						num_inference_steps=2					,						output_type="np"					,						)

           __lowerCAmelCase								=					torch.cuda.max_memory_allocated()
           # make sure that less than 2.65 GB is allocated
           assert mem_bytes < 2.6_5 * 1_0**9














from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


lowerCamelCase			:					Tuple         =	'''\
@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}
}
'''

lowerCamelCase			:					int         =	'''\
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.
'''

lowerCamelCase			:					List[str]         =	'''\
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			):


      def  __UpperCAmelCase		(	self	)->	MetricInfo:
           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  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase = 1					,						__UpperCamelCase = 4					,						)->	Dict[str, float]:
           return {
               "google_bleu": gleu_score.corpus_gleu(
                   list_of_references=__UpperCamelCase					,						hypotheses=__UpperCamelCase					,						min_len=__UpperCamelCase					,						max_len=__UpperCamelCase	)
           }






