

"""simple docstring"""


import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

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


enable_full_determinism()





class    snake_case     (    __snake_case,							__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_       :				Any       				=  StableDiffusionDiffEditPipeline
				SCREAMING_SNAKE_CASE_       :				Dict       				=  TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""}
				SCREAMING_SNAKE_CASE_       :				str       				=  TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""}
				SCREAMING_SNAKE_CASE_       :				List[str]       				=  frozenset(
				    []  )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
				SCREAMING_SNAKE_CASE_       :				List[Any]       				=  frozenset([]  )

				def 							lowercase_					(     self							:    Tuple)->       Optional[int]:



						'''simple docstring'''


						torch.manual_seed(0)
						__lowerCAmelCase:	str   				=      UNetaDConditionModel(
						    block_out_channels=(3_2, 6_4)					,  layers_per_block=2					,  sample_size=3_2					,  in_channels=4					,  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:	Union[str, Any]   				=      DDIMScheduler(
						    beta_start=0.00085					,  beta_end=0.012					,  beta_schedule="scaled_linear"					,  clip_sample=UpperCamelCase__					,  set_alpha_to_one=UpperCamelCase__					,  )
						__lowerCAmelCase:	Dict   				=      DDIMInverseScheduler(
						    beta_start=0.00085					,  beta_end=0.012					,  beta_schedule="scaled_linear"					,  clip_sample=UpperCamelCase__					,  set_alpha_to_zero=UpperCamelCase__					,  )
						torch.manual_seed(0)
						__lowerCAmelCase:	List[Any]   				=      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:	Any   				=      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:	Optional[int]   				=      CLIPTextModel(UpperCamelCase__)
						__lowerCAmelCase:	Optional[int]   				=      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

						__lowerCAmelCase:	Optional[int]   				=      {
						    "unet": unet,
						    "scheduler": scheduler,
						    "inverse_scheduler": inverse_scheduler,
						    "vae": vae,
						    "text_encoder": text_encoder,
						    "tokenizer": tokenizer,
						    "safety_checker": None,
						    "feature_extractor": None,
						}

						return components

				def 							lowercase_					(     self							:    Optional[Any]					,  UpperCamelCase__							:    List[str]					,  UpperCamelCase__							:    str=0)->       str:



						'''simple docstring'''


						__lowerCAmelCase:	List[str]   				=      floats_tensor((1, 1_6, 1_6)					,  rng=random.Random(UpperCamelCase__)).to(UpperCamelCase__)
						__lowerCAmelCase:	Any   				=      floats_tensor((1, 2, 4, 1_6, 1_6)					,  rng=random.Random(UpperCamelCase__)).to(UpperCamelCase__)
						if str(UpperCamelCase__).startswith("mps"):
								__lowerCAmelCase:	Optional[int]   				=      torch.manual_seed(UpperCamelCase__)
						else:
								__lowerCAmelCase:	List[Any]   				=      torch.Generator(device=UpperCamelCase__).manual_seed(UpperCamelCase__)
						__lowerCAmelCase:	str   				=      {
						    "prompt": "a dog and a newt",
						    "mask_image": mask,
						    "image_latents": latents,
						    "generator": generator,
						    "num_inference_steps": 2,
						    "inpaint_strength": 1.0,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}

						return inputs

				def 							lowercase_					(     self							:    Optional[int]					,  UpperCamelCase__							:    Optional[int]					,  UpperCamelCase__							:    List[str]=0)->       str:



						'''simple docstring'''


						__lowerCAmelCase:	Union[str, Any]   				=      floats_tensor((1, 3, 3_2, 3_2)					,  rng=random.Random(UpperCamelCase__)).to(UpperCamelCase__)
						__lowerCAmelCase:	Dict   				=      image.cpu().permute(0					,  2					,  3					,  1)[0]
						__lowerCAmelCase:	List[Any]   				=      Image.fromarray(np.uinta(UpperCamelCase__)).convert("RGB")
						if str(UpperCamelCase__).startswith("mps"):
								__lowerCAmelCase:	Optional[int]   				=      torch.manual_seed(UpperCamelCase__)
						else:
								__lowerCAmelCase:	Optional[int]   				=      torch.Generator(device=UpperCamelCase__).manual_seed(UpperCamelCase__)
						__lowerCAmelCase:	int   				=      {
						    "image": image,
						    "source_prompt": "a cat and a frog",
						    "target_prompt": "a dog and a newt",
						    "generator": generator,
						    "num_inference_steps": 2,
						    "num_maps_per_mask": 2,
						    "mask_encode_strength": 1.0,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}

						return inputs

				def 							lowercase_					(     self							:    Any					,  UpperCamelCase__							:    Any					,  UpperCamelCase__							:    int=0)->       int:



						'''simple docstring'''


						__lowerCAmelCase:	List[str]   				=      floats_tensor((1, 3, 3_2, 3_2)					,  rng=random.Random(UpperCamelCase__)).to(UpperCamelCase__)
						__lowerCAmelCase:	Optional[int]   				=      image.cpu().permute(0					,  2					,  3					,  1)[0]
						__lowerCAmelCase:	Optional[Any]   				=      Image.fromarray(np.uinta(UpperCamelCase__)).convert("RGB")
						if str(UpperCamelCase__).startswith("mps"):
								__lowerCAmelCase:	List[str]   				=      torch.manual_seed(UpperCamelCase__)
						else:
								__lowerCAmelCase:	str   				=      torch.Generator(device=UpperCamelCase__).manual_seed(UpperCamelCase__)
						__lowerCAmelCase:	Optional[Any]   				=      {
						    "image": image,
						    "prompt": "a cat and a frog",
						    "generator": generator,
						    "num_inference_steps": 2,
						    "inpaint_strength": 1.0,
						    "guidance_scale": 6.0,
						    "decode_latents": True,
						    "output_type": "numpy",
						}
						return inputs

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



						'''simple docstring'''


						if not hasattr(self.pipeline_class					,  "_optional_components"):
								return

						__lowerCAmelCase:	Union[str, Any]   				=      self.get_dummy_components()
						__lowerCAmelCase:	Tuple   				=      self.pipeline_class(**UpperCamelCase__)
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						# set all optional components to None and update pipeline config accordingly
						for optional_component in pipe._optional_components:
								setattr(UpperCamelCase__					,  UpperCamelCase__					,  UpperCamelCase__)
						pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components})

						__lowerCAmelCase:	Any   				=      self.get_dummy_inputs(UpperCamelCase__)
						__lowerCAmelCase:	Union[str, Any]   				=      pipe(**UpperCamelCase__)[0]

						with tempfile.TemporaryDirectory() as tmpdir:
								pipe.save_pretrained(UpperCamelCase__)
								__lowerCAmelCase:	Optional[Any]   				=      self.pipeline_class.from_pretrained(UpperCamelCase__)
								pipe_loaded.to(UpperCamelCase__)
								pipe_loaded.set_progress_bar_config(disable=UpperCamelCase__)

						for optional_component in pipe._optional_components:
								self.assertTrue(
								    getattr(UpperCamelCase__					,  UpperCamelCase__) is None					,  f"`{optional_component}` did not stay set to None after loading."					,  )

						__lowerCAmelCase:	Dict   				=      self.get_dummy_inputs(UpperCamelCase__)
						__lowerCAmelCase:	Any   				=      pipe_loaded(**UpperCamelCase__)[0]

						__lowerCAmelCase:	Any   				=      np.abs(output - output_loaded).max()
						self.assertLess(UpperCamelCase__					,  1e-4)

				def 							lowercase_					(     self							:    int)->       str:



						'''simple docstring'''


						__lowerCAmelCase:	List[Any]   				=      "cpu"

						__lowerCAmelCase:	Optional[int]   				=      self.get_dummy_components()
						__lowerCAmelCase:	Any   				=      self.pipeline_class(**UpperCamelCase__)
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	Union[str, Any]   				=      self.get_dummy_mask_inputs(UpperCamelCase__)
						__lowerCAmelCase:	Optional[Any]   				=      pipe.generate_mask(**UpperCamelCase__)
						__lowerCAmelCase:	List[str]   				=      mask[0, -3:, -3:]

						self.assertEqual(mask.shape					,  (1, 1_6, 1_6))
						__lowerCAmelCase:	int   				=      np.array([0] * 9)
						__lowerCAmelCase:	Dict   				=      np.abs(mask_slice.flatten() - expected_slice).max()
						self.assertLessEqual(UpperCamelCase__					,  1e-3)
						self.assertEqual(mask[0, -3, -4]					,  0)

				def 							lowercase_					(     self							:    Tuple)->       Tuple:



						'''simple docstring'''


						__lowerCAmelCase:	int   				=      "cpu"

						__lowerCAmelCase:	Tuple   				=      self.get_dummy_components()
						__lowerCAmelCase:	Optional[int]   				=      self.pipeline_class(**UpperCamelCase__)
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	Optional[Any]   				=      self.get_dummy_inversion_inputs(UpperCamelCase__)
						__lowerCAmelCase:	List[Any]   				=      pipe.invert(**UpperCamelCase__).images
						__lowerCAmelCase:	Tuple   				=      image[0, -1, -3:, -3:]

						self.assertEqual(image.shape					,  (2, 3_2, 3_2, 3))
						__lowerCAmelCase:	List[Any]   				=      np.array(
						    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]					,  )
						__lowerCAmelCase:	Dict   				=      np.abs(image_slice.flatten() - expected_slice).max()
						self.assertLessEqual(UpperCamelCase__					,  1e-3)

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



						'''simple docstring'''


						super().test_inference_batch_single_identical(expected_max_diff=5e-3)




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



						'''simple docstring'''


						__lowerCAmelCase:	List[str]   				=      "cpu"

						__lowerCAmelCase:	Any   				=      self.get_dummy_components()

						__lowerCAmelCase:	Tuple   				=      {"beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear"}
						__lowerCAmelCase:	List[str]   				=      DPMSolverMultistepScheduler(**UpperCamelCase__)
						__lowerCAmelCase:	List[Any]   				=      DPMSolverMultistepInverseScheduler(**UpperCamelCase__)

						__lowerCAmelCase:	Dict   				=      self.pipeline_class(**UpperCamelCase__)
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	Dict   				=      self.get_dummy_inversion_inputs(UpperCamelCase__)
						__lowerCAmelCase:	Optional[Any]   				=      pipe.invert(**UpperCamelCase__).images
						__lowerCAmelCase:	List[str]   				=      image[0, -1, -3:, -3:]

						self.assertEqual(image.shape					,  (2, 3_2, 3_2, 3))
						__lowerCAmelCase:	int   				=      np.array(
						    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]					,  )
						__lowerCAmelCase:	Dict   				=      np.abs(image_slice.flatten() - expected_slice).max()
						self.assertLessEqual(UpperCamelCase__					,  1e-3)





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

				def 							lowercase_					(     self							:    Optional[int])->       Any:



						'''simple docstring'''


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

				@classmethod
				def 							lowercase_					(     cls							:    int)->       Dict:



						'''simple docstring'''


						__lowerCAmelCase:	Optional[int]   				=      load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png")

						__lowerCAmelCase:	List[str]   				=      raw_image.convert("RGB").resize((7_6_8, 7_6_8))

						__lowerCAmelCase:	Union[str, Any]   				=      raw_image

				def 							lowercase_					(     self							:    Dict)->       Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:	List[Any]   				=      torch.manual_seed(0)

						__lowerCAmelCase:	List[Any]   				=      StableDiffusionDiffEditPipeline.from_pretrained(
						    "stabilityai/stable-diffusion-2-1"					,  safety_checker=UpperCamelCase__					,  torch_dtype=torch.floataa)
						__lowerCAmelCase:	List[Any]   				=      DDIMScheduler.from_config(pipe.scheduler.config)
						__lowerCAmelCase:	Dict   				=      DDIMInverseScheduler.from_config(pipe.scheduler.config)
						pipe.enable_model_cpu_offload()
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	List[Any]   				=      "a bowl of fruit"
						__lowerCAmelCase:	Union[str, Any]   				=      "a bowl of pears"

						__lowerCAmelCase:	Tuple   				=      pipe.generate_mask(
						    image=self.raw_image					,  source_prompt=UpperCamelCase__					,  target_prompt=UpperCamelCase__					,  generator=UpperCamelCase__					,  )

						__lowerCAmelCase:	Optional[Any]   				=      pipe.invert(
						    prompt=UpperCamelCase__					,  image=self.raw_image					,  inpaint_strength=0.7					,  generator=UpperCamelCase__).latents

						__lowerCAmelCase:	Any   				=      pipe(
						    prompt=UpperCamelCase__					,  mask_image=UpperCamelCase__					,  image_latents=UpperCamelCase__					,  generator=UpperCamelCase__					,  negative_prompt=UpperCamelCase__					,  inpaint_strength=0.7					,  output_type="numpy"					,  ).images[0]

						__lowerCAmelCase:	Any   				=      (
						    np.array(
						        load_image(
						            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						            "/diffedit/pears.png").resize((7_6_8, 7_6_8)))
						    / 2_5_5
						)
						assert np.abs((expected_image - image).max()) < 5e-1




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



						'''simple docstring'''


						__lowerCAmelCase:	int   				=      torch.manual_seed(0)

						__lowerCAmelCase:	Tuple   				=      StableDiffusionDiffEditPipeline.from_pretrained(
						    "stabilityai/stable-diffusion-2-1"					,  safety_checker=UpperCamelCase__					,  torch_dtype=torch.floataa)
						__lowerCAmelCase:	Dict   				=      DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
						__lowerCAmelCase:	Optional[Any]   				=      DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config)
						pipe.enable_model_cpu_offload()
						pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:	int   				=      "a bowl of fruit"
						__lowerCAmelCase:	Optional[Any]   				=      "a bowl of pears"

						__lowerCAmelCase:	Any   				=      pipe.generate_mask(
						    image=self.raw_image					,  source_prompt=UpperCamelCase__					,  target_prompt=UpperCamelCase__					,  generator=UpperCamelCase__					,  )

						__lowerCAmelCase:	List[str]   				=      pipe.invert(
						    prompt=UpperCamelCase__					,  image=self.raw_image					,  inpaint_strength=0.7					,  generator=UpperCamelCase__					,  num_inference_steps=2_5					,  ).latents

						__lowerCAmelCase:	List[Any]   				=      pipe(
						    prompt=UpperCamelCase__					,  mask_image=UpperCamelCase__					,  image_latents=UpperCamelCase__					,  generator=UpperCamelCase__					,  negative_prompt=UpperCamelCase__					,  inpaint_strength=0.7					,  num_inference_steps=2_5					,  output_type="numpy"					,  ).images[0]

						__lowerCAmelCase:	Tuple   				=      (
						    np.array(
						        load_image(
						            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						            "/diffedit/pears.png").resize((7_6_8, 7_6_8)))
						    / 2_5_5
						)
						assert np.abs((expected_image - image).max()) < 5e-1





"""simple docstring"""


import os

from bleurt import score  # From: git+https://github.com/google-research/bleurt.git

import datasets


__A						       =      datasets.logging.get_logger(__name__)


__A						       =      "\\n@inproceedings{bleurt,\n  title={BLEURT: Learning Robust Metrics for Text Generation},\n  author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n  booktitle={ACL},\n  year={2020},\n  url={https://arxiv.org/abs/2004.04696}\n}\n"

__A						       =      "\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project's README at https://github.com/google-research/bleurt#readme for more information.\n"

__A						       =      "\nBLEURT score.\n\nArgs:\n    `predictions` (list of str): prediction/candidate sentences\n    `references` (list of str): reference sentences\n    `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n    'scores': List of scores.\nExamples:\n\n    >>> predictions = [\"hello there\", \"general kenobi\"]\n    >>> references = [\"hello there\", \"general kenobi\"]\n    >>> bleurt = datasets.load_metric(\"bleurt\")\n    >>> results = bleurt.compute(predictions=predictions, references=references)\n    >>> print([round(v, 2) for v in results[\"scores\"]])\n    [1.03, 1.04]\n"

__A						       =      {
    "bleurt-tiny-128": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip",
    "bleurt-tiny-512": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip",
    "bleurt-base-128": "https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip",
    "bleurt-base-512": "https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip",
    "bleurt-large-128": "https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip",
    "bleurt-large-512": "https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip",
    "BLEURT-20-D3": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip",
    "BLEURT-20-D6": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip",
    "BLEURT-20-D12": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip",
    "BLEURT-20": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip",
}





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

				def 							lowercase_					(     self							:    Optional[int])->       Any:



						'''simple docstring'''


						return datasets.MetricInfo(
						    description=_DESCRIPTION					,  citation=_CITATION					,  homepage="https://github.com/google-research/bleurt"					,  inputs_description=_KWARGS_DESCRIPTION					,  features=datasets.Features(
						        {
						            "predictions": datasets.Value("string"					,  id="sequence"),
						            "references": datasets.Value("string"					,  id="sequence"),
						        })					,  codebase_urls=["https://github.com/google-research/bleurt"]					,  reference_urls=["https://github.com/google-research/bleurt", "https://arxiv.org/abs/2004.04696"]					,  )

				def 							lowercase_					(     self							:    int					,  UpperCamelCase__							:    Dict)->       List[str]:



						'''simple docstring'''


						if self.config_name == "default":
								logger.warning(
								    "Using default BLEURT-Base checkpoint for sequence maximum length 128. "
								    "You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').")
								__lowerCAmelCase:	List[str]   				=      "bleurt-base-128"

						if self.config_name.lower() in CHECKPOINT_URLS:
								__lowerCAmelCase:	Optional[int]   				=      self.config_name.lower()

						elif self.config_name.upper() in CHECKPOINT_URLS:
								__lowerCAmelCase:	Tuple   				=      self.config_name.upper()

						else:
								raise KeyError(
								    f"{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}")

						# download the model checkpoint specified by self.config_name and set up the scorer
						__lowerCAmelCase:	Union[str, Any]   				=      dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name])
						__lowerCAmelCase:	Dict   				=      score.BleurtScorer(os.path.join(UpperCamelCase__					,  UpperCamelCase__))




				def 							lowercase_					(     self							:    Optional[int]					,  UpperCamelCase__							:    Tuple					,  UpperCamelCase__							:    int)->       str:



						'''simple docstring'''


						__lowerCAmelCase:	str   				=      self.scorer.score(references=UpperCamelCase__					,  candidates=UpperCamelCase__)
						return {"scores": scores}


