






'''simple docstring'''





import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf
class 				lowercase       (							enum.Enum      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							0
    lowerCAmelCase__      				=							1
    lowerCAmelCase__      				=							2


@add_end_docstrings(_lowerCamelCase      )
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							"\n    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n    begging for his blessing. <eod> </s> <eos>\n    "

    def __init__(					self     :     List[Any]				,     *__lowerCamelCase     :     Union[str, Any]				,     **__lowerCamelCase     :     List[Any]     )							->							Optional[int]:

     '''simple docstring'''




     super().__init__(*__lowerCAmelCase				,     **__lowerCAmelCase     )
     self.check_model_type(
         TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING     )
     if "prefix" not in self._preprocess_params:
      # This is very specific. The logic is quite complex and needs to be done
      # as a "default".
      # It also defines both some preprocess_kwargs and generate_kwargs
      # which is why we cannot put them in their respective methods.
      lowerCamelCase__  =     None
      if self.model.config.prefix is not None:
       lowerCamelCase__  =     self.model.config.prefix
      if prefix is None and self.model.__class__.__name__ in [
          "XLNetLMHeadModel",
          "TransfoXLLMHeadModel",
          "TFXLNetLMHeadModel",
          "TFTransfoXLLMHeadModel",
      ]:
       # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
       lowerCamelCase__  =     self.XL_PREFIX
      if prefix is not None:
       # Recalculate some generate_kwargs linked to prefix.
       lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     self._sanitize_parameters(prefix=__lowerCAmelCase				,     **self._forward_params     )
       lowerCamelCase__  =     {**self._preprocess_params, **preprocess_params}
       lowerCamelCase__  =     {**self._forward_params, **forward_params}

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     str=None				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     str=None				,     __lowerCamelCase     :     Optional[int]=None				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     Any=None				,     **__lowerCamelCase     :     Dict				,     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     {}
     if prefix is not None:
      lowerCamelCase__  =     prefix
     if prefix:
      lowerCamelCase__  =     self.tokenizer(
          __lowerCAmelCase				,     padding=__lowerCAmelCase				,     add_special_tokens=__lowerCAmelCase				,     return_tensors=self.framework     )
      lowerCamelCase__  =     prefix_inputs["input_ids"].shape[-1]

     if handle_long_generation is not None:
      if handle_long_generation not in {"hole"}:
       raise ValueError(
           f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'''
           " [None, \'hole\']"     )
      lowerCamelCase__  =     handle_long_generation

     preprocess_params.update(__lowerCAmelCase     )
     lowerCamelCase__  =     generate_kwargs

     lowerCamelCase__  =     {}
     if return_full_text is not None and return_type is None:
      if return_text is not None:
       raise ValueError("`return_text` is mutually exclusive with `return_full_text`"     )
      if return_tensors is not None:
       raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`"     )
      lowerCamelCase__  =     ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
     if return_tensors is not None and return_type is None:
      if return_text is not None:
       raise ValueError("`return_text` is mutually exclusive with `return_tensors`"     )
      lowerCamelCase__  =     ReturnType.TENSORS
     if return_type is not None:
      lowerCamelCase__  =     return_type
     if clean_up_tokenization_spaces is not None:
      lowerCamelCase__  =     clean_up_tokenization_spaces

     if stop_sequence is not None:
      lowerCamelCase__  =     self.tokenizer.encode(__lowerCAmelCase				,     add_special_tokens=__lowerCAmelCase     )
      if len(__lowerCAmelCase     ) > 1:
       warnings.warn(
           "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
           " the stop sequence will be used as the stop sequence string in the interim."     )
      lowerCamelCase__  =     stop_sequence_ids[0]

     return preprocess_params, forward_params, postprocess_params

    def    a__				(					self     :     Tuple				,     *__lowerCamelCase     :     List[str]				,     **__lowerCamelCase     :     List[Any]     )							->							str:

     '''simple docstring'''




     if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
      kwargs.update({"add_space_before_punct_symbol": True}     )

     return super()._parse_and_tokenize(*__lowerCAmelCase				,     **__lowerCAmelCase     )

    def __call__(					self     :     int				,     __lowerCamelCase     :     Tuple				,     **__lowerCamelCase     :     int     )							->							Dict:

     '''simple docstring'''




     return super().__call__(__lowerCAmelCase				,     **__lowerCAmelCase     )

    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     Tuple=""				,     __lowerCamelCase     :     List[str]=None				,     **__lowerCamelCase     :     List[str]     )							->							int:

     '''simple docstring'''




     lowerCamelCase__  =     self.tokenizer(
         prefix + prompt_text				,     padding=__lowerCAmelCase				,     add_special_tokens=__lowerCAmelCase				,     return_tensors=self.framework     )
     lowerCamelCase__  =     prompt_text

     if handle_long_generation == "hole":
      lowerCamelCase__  =     inputs["input_ids"].shape[-1]
      if "max_new_tokens" in generate_kwargs:
       lowerCamelCase__  =     generate_kwargs["max_new_tokens"]
      else:
       lowerCamelCase__  =     generate_kwargs.get("max_length"				,     self.model.config.max_length     ) - cur_len
       if new_tokens < 0:
        raise ValueError("We cannot infer how many new tokens are expected"     )
      if cur_len + new_tokens > self.tokenizer.model_max_length:
       lowerCamelCase__  =     self.tokenizer.model_max_length - new_tokens
       if keep_length <= 0:
        raise ValueError(
            "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
            " models max length"     )

       lowerCamelCase__  =     inputs["input_ids"][:, -keep_length:]
       if "attention_mask" in inputs:
        lowerCamelCase__  =     inputs["attention_mask"][:, -keep_length:]

     return inputs

    def    a__				(					self     :     str				,     __lowerCamelCase     :     List[Any]				,     **__lowerCamelCase     :     Optional[Any]     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     model_inputs["input_ids"]
     lowerCamelCase__  =     model_inputs.get("attention_mask"				,     __lowerCAmelCase     )
     # Allow empty prompts
     if input_ids.shape[1] == 0:
      lowerCamelCase__  =     None
      lowerCamelCase__  =     None
      lowerCamelCase__  =     1
     else:
      lowerCamelCase__  =     input_ids.shape[0]
     lowerCamelCase__  =     model_inputs.pop("prompt_text"     )

     # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
     # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
     lowerCamelCase__  =     generate_kwargs.pop("prefix_length"				,     0     )
     if prefix_length > 0:
      lowerCamelCase__  =     "max_new_tokens" in generate_kwargs or (
          "generation_config" in generate_kwargs
          and generate_kwargs["generation_config"].max_new_tokens is not None
      )
      if not has_max_new_tokens:
       lowerCamelCase__  =     generate_kwargs.get("max_length"     ) or self.model.config.max_length
       generate_kwargs["max_length"] += prefix_length
      lowerCamelCase__  =     "min_new_tokens" in generate_kwargs or (
          "generation_config" in generate_kwargs
          and generate_kwargs["generation_config"].min_new_tokens is not None
      )
      if not has_min_new_tokens and "min_length" in generate_kwargs:
       generate_kwargs["min_length"] += prefix_length

        # BS x SL
     lowerCamelCase__  =     self.model.generate(input_ids=__lowerCAmelCase				,     attention_mask=__lowerCAmelCase				,     **__lowerCAmelCase     )
     lowerCamelCase__  =     generated_sequence.shape[0]
     if self.framework == "pt":
      lowerCamelCase__  =     generated_sequence.reshape(__lowerCAmelCase				,     out_b // in_b				,     *generated_sequence.shape[1:]     )
     elif self.framework == "tf":
      lowerCamelCase__  =     tf.reshape(__lowerCAmelCase				,     (in_b, out_b // in_b, *generated_sequence.shape[1:])     )
     return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}




    def    a__				(					self     :     Dict				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     List[str]=ReturnType.FULL_TEXT				,     __lowerCamelCase     :     Dict=True     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     model_outputs["generated_sequence"][0]
     lowerCamelCase__  =     model_outputs["input_ids"]
     lowerCamelCase__  =     model_outputs["prompt_text"]
     lowerCamelCase__  =     generated_sequence.numpy().tolist()
     lowerCamelCase__  =     []
     for sequence in generated_sequence:
      if return_type == ReturnType.TENSORS:
       lowerCamelCase__  =     {"generated_token_ids": sequence}
      elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
       # Decode text
       lowerCamelCase__  =     self.tokenizer.decode(
           __lowerCAmelCase				,     skip_special_tokens=__lowerCAmelCase				,     clean_up_tokenization_spaces=__lowerCAmelCase				,     )

       # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
       if input_ids is None:
        lowerCamelCase__  =     0
       else:
        lowerCamelCase__  =     len(
            self.tokenizer.decode(
                input_ids[0]				,     skip_special_tokens=__lowerCAmelCase				,     clean_up_tokenization_spaces=__lowerCAmelCase				,     )     )

       if return_type == ReturnType.FULL_TEXT:
        lowerCamelCase__  =     prompt_text + text[prompt_length:]
       else:
        lowerCamelCase__  =     text[prompt_length:]

       lowerCamelCase__  =     {"generated_text": all_text}
      records.append(__lowerCAmelCase     )

     return records









'''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 				lowercase       (							_lowerCamelCase ,       _lowerCamelCase ,       unittest.TestCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							StableDiffusionDiffEditPipeline
    lowerCAmelCase__      				=							TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
    lowerCAmelCase__      				=							TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
    lowerCAmelCase__      				=							frozenset(
        []      )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    lowerCAmelCase__      				=							frozenset([]      )

    def    a__				(					self     :     int     )							->							Dict:

     '''simple docstring'''




     torch.manual_seed(0     )
     lowerCamelCase__  =     UNetaDConditionModel(
         block_out_channels=(32, 64)				,     layers_per_block=2				,     sample_size=32				,     in_channels=4				,     out_channels=4				,     down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")				,     up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")				,     cross_attention_dim=32				,     attention_head_dim=(2, 4)				,     use_linear_projection=__lowerCamelCase				,     )
     lowerCamelCase__  =     DDIMScheduler(
         beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     beta_schedule="scaled_linear"				,     clip_sample=__lowerCamelCase				,     set_alpha_to_one=__lowerCamelCase				,     )
     lowerCamelCase__  =     DDIMInverseScheduler(
         beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     beta_schedule="scaled_linear"				,     clip_sample=__lowerCamelCase				,     set_alpha_to_zero=__lowerCamelCase				,     )
     torch.manual_seed(0     )
     lowerCamelCase__  =     AutoencoderKL(
         block_out_channels=[32, 64]				,     in_channels=3				,     out_channels=3				,     down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]				,     up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]				,     latent_channels=4				,     sample_size=128				,     )
     torch.manual_seed(0     )
     lowerCamelCase__  =     CLIPTextConfig(
         bos_token_id=0				,     eos_token_id=2				,     hidden_size=32				,     intermediate_size=37				,     layer_norm_eps=1E-05				,     num_attention_heads=4				,     num_hidden_layers=5				,     pad_token_id=1				,     vocab_size=1000				,     hidden_act="gelu"				,     projection_dim=512				,     )
     lowerCamelCase__  =     CLIPTextModel(__lowerCamelCase     )
     lowerCamelCase__  =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

     lowerCamelCase__  =     {
         "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    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Any=0     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor((1, 16, 16)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     lowerCamelCase__  =     floats_tensor((1, 2, 4, 16, 16)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     lowerCamelCase__  =     {
         "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    a__				(					self     :     str				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Optional[int]=0     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor((1, 3, 32, 32)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     lowerCamelCase__  =     image.cpu().permute(0				,     2				,     3				,     1     )[0]
     lowerCamelCase__  =     Image.fromarray(np.uinta(__lowerCamelCase     )     ).convert("RGB"     )
     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     lowerCamelCase__  =     {
         "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    a__				(					self     :     Optional[int]				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     List[str]=0     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor((1, 3, 32, 32)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     lowerCamelCase__  =     image.cpu().permute(0				,     2				,     3				,     1     )[0]
     lowerCamelCase__  =     Image.fromarray(np.uinta(__lowerCamelCase     )     ).convert("RGB"     )
     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     lowerCamelCase__  =     {
         "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    a__				(					self     :     Tuple     )							->							str:

     '''simple docstring'''




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

     lowerCamelCase__  =     self.get_dummy_components()
     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

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

     lowerCamelCase__  =     self.get_dummy_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe(**__lowerCamelCase     )[0]

     with tempfile.TemporaryDirectory() as tmpdir:
      pipe.save_pretrained(__lowerCamelCase     )
      lowerCamelCase__  =     self.pipeline_class.from_pretrained(__lowerCamelCase     )
      pipe_loaded.to(__lowerCamelCase     )
      pipe_loaded.set_progress_bar_config(disable=__lowerCamelCase     )

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

     lowerCamelCase__  =     self.get_dummy_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe_loaded(**__lowerCamelCase     )[0]

     lowerCamelCase__  =     np.abs(output - output_loaded     ).max()
     self.assertLess(__lowerCamelCase				,     1E-4     )

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

     '''simple docstring'''




     lowerCamelCase__  =     "cpu"

     lowerCamelCase__  =     self.get_dummy_components()
     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     self.get_dummy_mask_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe.generate_mask(**__lowerCamelCase     )
     lowerCamelCase__  =     mask[0, -3:, -3:]

     self.assertEqual(mask.shape				,     (1, 16, 16)     )
     lowerCamelCase__  =     np.array([0] * 9     )
     lowerCamelCase__  =     np.abs(mask_slice.flatten() - expected_slice     ).max()
     self.assertLessEqual(__lowerCamelCase				,     1E-3     )
     self.assertEqual(mask[0, -3, -4]				,     0     )

    def    a__				(					self     :     List[str]     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     "cpu"

     lowerCamelCase__  =     self.get_dummy_components()
     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     self.get_dummy_inversion_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe.invert(**__lowerCamelCase     ).images
     lowerCamelCase__  =     image[0, -1, -3:, -3:]

     self.assertEqual(image.shape				,     (2, 32, 32, 3)     )
     lowerCamelCase__  =     np.array(
         [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]				,     )
     lowerCamelCase__  =     np.abs(image_slice.flatten() - expected_slice     ).max()
     self.assertLessEqual(__lowerCamelCase				,     1E-3     )

    def    a__				(					self     :     Tuple     )							->							Tuple:

     '''simple docstring'''




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




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

     '''simple docstring'''




     lowerCamelCase__  =     "cpu"

     lowerCamelCase__  =     self.get_dummy_components()

     lowerCamelCase__  =     {"beta_start": 0.0_0_0_8_5, "beta_end": 0.0_1_2, "beta_schedule": "scaled_linear"}
     lowerCamelCase__  =     DPMSolverMultistepScheduler(**__lowerCamelCase     )
     lowerCamelCase__  =     DPMSolverMultistepInverseScheduler(**__lowerCamelCase     )

     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     self.get_dummy_inversion_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe.invert(**__lowerCamelCase     ).images
     lowerCamelCase__  =     image[0, -1, -3:, -3:]

     self.assertEqual(image.shape				,     (2, 32, 32, 3)     )
     lowerCamelCase__  =     np.array(
         [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]				,     )
     lowerCamelCase__  =     np.abs(image_slice.flatten() - expected_slice     ).max()
     self.assertLessEqual(__lowerCamelCase				,     1E-3     )
@require_torch_gpu
@slow
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    def    a__				(					self     :     Optional[int]     )							->							int:

     '''simple docstring'''




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

    @classmethod
    def    a__				(					cls     :     int     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     load_image(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"     )

     lowerCamelCase__  =     raw_image.convert("RGB"     ).resize((768, 768)     )

     lowerCamelCase__  =     raw_image

    def    a__				(					self     :     Optional[Any]     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     torch.manual_seed(0     )

     lowerCamelCase__  =     StableDiffusionDiffEditPipeline.from_pretrained(
         "stabilityai/stable-diffusion-2-1"				,     safety_checker=__lowerCamelCase				,     torch_dtype=torch.floataa     )
     lowerCamelCase__  =     DDIMScheduler.from_config(pipe.scheduler.config     )
     lowerCamelCase__  =     DDIMInverseScheduler.from_config(pipe.scheduler.config     )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     "a bowl of fruit"
     lowerCamelCase__  =     "a bowl of pears"

     lowerCamelCase__  =     pipe.generate_mask(
         image=self.raw_image				,     source_prompt=__lowerCamelCase				,     target_prompt=__lowerCamelCase				,     generator=__lowerCamelCase				,     )

     lowerCamelCase__  =     pipe.invert(
         prompt=__lowerCamelCase				,     image=self.raw_image				,     inpaint_strength=0.7				,     generator=__lowerCamelCase     ).latents

     lowerCamelCase__  =     pipe(
         prompt=__lowerCamelCase				,     mask_image=__lowerCamelCase				,     image_latents=__lowerCamelCase				,     generator=__lowerCamelCase				,     negative_prompt=__lowerCamelCase				,     inpaint_strength=0.7				,     output_type="numpy"				,     ).images[0]

     lowerCamelCase__  =     (
         np.array(
             load_image(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/diffedit/pears.png"     ).resize((768, 768)     )     )
         / 255
     )
     assert np.abs((expected_image - image).max()     ) < 5E-1




    def    a__				(					self     :     List[str]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     torch.manual_seed(0     )

     lowerCamelCase__  =     StableDiffusionDiffEditPipeline.from_pretrained(
         "stabilityai/stable-diffusion-2-1"				,     safety_checker=__lowerCamelCase				,     torch_dtype=torch.floataa     )
     lowerCamelCase__  =     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config     )
     lowerCamelCase__  =     DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config     )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     "a bowl of fruit"
     lowerCamelCase__  =     "a bowl of pears"

     lowerCamelCase__  =     pipe.generate_mask(
         image=self.raw_image				,     source_prompt=__lowerCamelCase				,     target_prompt=__lowerCamelCase				,     generator=__lowerCamelCase				,     )

     lowerCamelCase__  =     pipe.invert(
         prompt=__lowerCamelCase				,     image=self.raw_image				,     inpaint_strength=0.7				,     generator=__lowerCamelCase				,     num_inference_steps=25				,     ).latents

     lowerCamelCase__  =     pipe(
         prompt=__lowerCamelCase				,     mask_image=__lowerCamelCase				,     image_latents=__lowerCamelCase				,     generator=__lowerCamelCase				,     negative_prompt=__lowerCamelCase				,     inpaint_strength=0.7				,     num_inference_steps=25				,     output_type="numpy"				,     ).images[0]

     lowerCamelCase__  =     (
         np.array(
             load_image(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/diffedit/pears.png"     ).resize((768, 768)     )     )
         / 255
     )
     assert np.abs((expected_image - image).max()     ) < 5E-1

