


import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


a					  =     logging.get_logger(__name__)  # pylint: disable=invalid-name







class        UpperCamelCase__   (	__magic_name__   ):

					def __init__(     self       :   Optional[Any]							,					UpperCamelCase__       :   WhisperForConditionalGeneration							,					UpperCamelCase__       :   WhisperProcessor							,					UpperCamelCase__       :   AutoencoderKL							,					UpperCamelCase__       :   CLIPTextModel							,					UpperCamelCase__       :   CLIPTokenizer							,					UpperCamelCase__       :   UNetaDConditionModel							,					UpperCamelCase__       :   Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]							,					UpperCamelCase__       :   StableDiffusionSafetyChecker							,					UpperCamelCase__       :   CLIPImageProcessor							,					):






										'''simple docstring'''






										super().__init__()

										if safety_checker is None:
															logger.warning(
															    F'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'''
															    """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
															    """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
															    """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
															    """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
															    """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""       )

										self.register_modules(
										    speech_model=UpperCamelCase__							,					speech_processor=UpperCamelCase__							,					vae=UpperCamelCase__							,					text_encoder=UpperCamelCase__							,					tokenizer=UpperCamelCase__							,					unet=UpperCamelCase__							,					scheduler=UpperCamelCase__							,					feature_extractor=UpperCamelCase__							,					)

					def   UpperCAmelCase__       (     self       :   str							,					UpperCamelCase__       :   Optional[Union[str, int]] = "auto"       ):






										'''simple docstring'''






										if slice_size == "auto":
															lowercase_  							=			self.unet.config.attention_head_dim // 2
										self.unet.set_attention_slice(UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										self.enable_attention_slicing(UpperCamelCase__       )







					@torch.no_grad()
					def __call__(     self       :   Optional[int]							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   Optional[int]=16_000							,					UpperCamelCase__       :   int = 512							,					UpperCamelCase__       :   int = 512							,					UpperCamelCase__       :   int = 50							,					UpperCamelCase__       :   float = 7.5							,					UpperCamelCase__       :   Optional[Union[str, List[str]]] = None							,					UpperCamelCase__       :   Optional[int] = 1							,					UpperCamelCase__       :   float = 0.0							,					UpperCamelCase__       :   Optional[torch.Generator] = None							,					UpperCamelCase__       :   Optional[torch.FloatTensor] = None							,					UpperCamelCase__       :   Optional[str] = "pil"							,					UpperCamelCase__       :   bool = True							,					UpperCamelCase__       :   Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCamelCase__       :   int = 1							,					**UpperCamelCase__       :   Optional[int]							,					):






										'''simple docstring'''






										lowercase_  							=			self.speech_processor.feature_extractor(
										    UpperCamelCase__							,					return_tensors="""pt"""							,					sampling_rate=UpperCamelCase__       ).input_features.to(self.device       )
										lowercase_  							=			self.speech_model.generate(UpperCamelCase__							,					max_length=480_000       )

										lowercase_  							=			self.speech_processor.tokenizer.batch_decode(UpperCamelCase__							,					skip_special_tokens=UpperCamelCase__							,					normalize=UpperCamelCase__       )[
										    0
										]

										if isinstance(UpperCamelCase__							,					UpperCamelCase__       ):
															lowercase_  							=			1
										elif isinstance(UpperCamelCase__							,					UpperCamelCase__       ):
															lowercase_  							=			len(UpperCamelCase__       )
										else:
															raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase__       )}'''       )

										if height % 8 != 0 or width % 8 != 0:
															raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.'''       )

										if (callback_steps is None) or (
										    callback_steps is not None and (not isinstance(UpperCamelCase__							,					UpperCamelCase__       ) or callback_steps <= 0)
										):
															raise ValueError(
															    F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
															    F''' {type(UpperCamelCase__       )}.'''       )

										# get prompt text embeddings
										lowercase_  							=			self.tokenizer(
										    UpperCamelCase__							,					padding="""max_length"""							,					max_length=self.tokenizer.model_max_length							,					return_tensors="""pt"""							,					)
										lowercase_  							=			text_inputs.input_ids

										if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
															lowercase_  							=			self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]       )
															logger.warning(
															    """The following part of your input was truncated because CLIP can only handle sequences up to"""
															    F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''       )
															lowercase_  							=			text_input_ids[:, : self.tokenizer.model_max_length]
										lowercase_  							=			self.text_encoder(text_input_ids.to(self.device       )       )[0]

										# duplicate text embeddings for each generation per prompt, using mps friendly method
										lowercase_							,					lowercase_							,					lowercase_  							=			text_embeddings.shape
										lowercase_  							=			text_embeddings.repeat(1							,					UpperCamelCase__							,					1       )
										lowercase_  							=			text_embeddings.view(bs_embed * num_images_per_prompt							,					UpperCamelCase__							,					-1       )

										# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
										# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
										# corresponds to doing no classifier free guidance.
										lowercase_  							=			guidance_scale > 1.0
										# get unconditional embeddings for classifier free guidance
										if do_classifier_free_guidance:
															lowercase_  							=			42
															if negative_prompt is None:
																				lowercase_  							=			[""""""] * batch_size
															elif type(UpperCamelCase__       ) is not type(UpperCamelCase__       ):
																				raise TypeError(
																				    F'''`negative_prompt` should be the same type to `prompt`, but got {type(UpperCamelCase__       )} !='''
																				    F''' {type(UpperCamelCase__       )}.'''       )
															elif isinstance(UpperCamelCase__							,					UpperCamelCase__       ):
																				lowercase_  							=			[negative_prompt]
															elif batch_size != len(UpperCamelCase__       ):
																				raise ValueError(
																				    F'''`negative_prompt`: {negative_prompt} has batch size {len(UpperCamelCase__       )}, but `prompt`:'''
																				    F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
																				    """ the batch size of `prompt`."""       )
															else:
																				lowercase_  							=			negative_prompt

															lowercase_  							=			text_input_ids.shape[-1]
															lowercase_  							=			self.tokenizer(
															    UpperCamelCase__							,					padding="""max_length"""							,					max_length=UpperCamelCase__							,					truncation=UpperCamelCase__							,					return_tensors="""pt"""							,					)
															lowercase_  							=			self.text_encoder(uncond_input.input_ids.to(self.device       )       )[0]

															# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
															lowercase_  							=			uncond_embeddings.shape[1]
															lowercase_  							=			uncond_embeddings.repeat(1							,					UpperCamelCase__							,					1       )
															lowercase_  							=			uncond_embeddings.view(batch_size * num_images_per_prompt							,					UpperCamelCase__							,					-1       )

															# For classifier free guidance, we need to do two forward passes.
															# Here we concatenate the unconditional and text embeddings into a single batch
															# to avoid doing two forward passes
															lowercase_  							=			torch.cat([uncond_embeddings, text_embeddings]       )

										# get the initial random noise unless the user supplied it

										# Unlike in other pipelines, latents need to be generated in the target device
										# for 1-to-1 results reproducibility with the CompVis implementation.
										# However this currently doesn't work in `mps`.
										lowercase_  							=			(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
										lowercase_  							=			text_embeddings.dtype
										if latents is None:
															if self.device.type == "mps":
																				# randn does not exist on mps
																				lowercase_  							=			torch.randn(UpperCamelCase__							,					generator=UpperCamelCase__							,					device="""cpu"""							,					dtype=UpperCamelCase__       ).to(
																				    self.device       )
															else:
																				lowercase_  							=			torch.randn(UpperCamelCase__							,					generator=UpperCamelCase__							,					device=self.device							,					dtype=UpperCamelCase__       )
										else:
															if latents.shape != latents_shape:
																				raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}'''       )
															lowercase_  							=			latents.to(self.device       )

										# set timesteps
										self.scheduler.set_timesteps(UpperCamelCase__       )

										# Some schedulers like PNDM have timesteps as arrays
										# It's more optimized to move all timesteps to correct device beforehand
										lowercase_  							=			self.scheduler.timesteps.to(self.device       )

										# scale the initial noise by the standard deviation required by the scheduler
										lowercase_  							=			latents * self.scheduler.init_noise_sigma

										# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
										# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
										# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
										# and should be between [0, 1]
										lowercase_  							=			"""eta""" in set(inspect.signature(self.scheduler.step       ).parameters.keys()       )
										lowercase_  							=			{}
										if accepts_eta:
															lowercase_  							=			eta

										for i, t in enumerate(self.progress_bar(UpperCamelCase__       )       ):
															# expand the latents if we are doing classifier free guidance
															lowercase_  							=			torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents
															lowercase_  							=			self.scheduler.scale_model_input(UpperCamelCase__							,					UpperCamelCase__       )

															# predict the noise residual
															lowercase_  							=			self.unet(UpperCamelCase__							,					UpperCamelCase__							,					encoder_hidden_states=UpperCamelCase__       ).sample

															# perform guidance
															if do_classifier_free_guidance:
																				lowercase_							,					lowercase_  							=			noise_pred.chunk(2       )
																				lowercase_  							=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

															# compute the previous noisy sample x_t -> x_t-1
															lowercase_  							=			self.scheduler.step(UpperCamelCase__							,					UpperCamelCase__							,					UpperCamelCase__							,					**UpperCamelCase__       ).prev_sample

															# call the callback, if provided
															if callback is not None and i % callback_steps == 0:
																				callback(UpperCamelCase__							,					UpperCamelCase__							,					UpperCamelCase__       )

										lowercase_  							=			1 / 0.18_215 * latents
										lowercase_  							=			self.vae.decode(UpperCamelCase__       ).sample

										lowercase_  							=			(image / 2 + 0.5).clamp(0							,					1       )

										# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
										lowercase_  							=			image.cpu().permute(0							,					2							,					3							,					1       ).float().numpy()

										if output_type == "pil":
															lowercase_  							=			self.numpy_to_pil(UpperCamelCase__       )

										if not return_dict:
															return image

										return StableDiffusionPipelineOutput(images=UpperCamelCase__							,					nsfw_content_detected=UpperCamelCase__       )






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        UpperCamelCase__   (	__magic_name__							,				__magic_name__							,				unittest.TestCase   ):
					__SCREAMING_SNAKE_CASE       :  Optional[int]						=   StableDiffusionDiffEditPipeline
					__SCREAMING_SNAKE_CASE       :  Optional[Any]						=   TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'}
					__SCREAMING_SNAKE_CASE       :  List[str]						=   TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'}
					__SCREAMING_SNAKE_CASE       :  int						=   frozenset(
					    []   )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
					__SCREAMING_SNAKE_CASE       :  Any						=   frozenset([]   )

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										torch.manual_seed(0       )
										lowercase_  							=			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=UpperCamelCase__							,					)
										lowercase_  							=			DDIMScheduler(
										    beta_start=0.00_085							,					beta_end=0.012							,					beta_schedule="""scaled_linear"""							,					clip_sample=UpperCamelCase__							,					set_alpha_to_one=UpperCamelCase__							,					)
										lowercase_  							=			DDIMInverseScheduler(
										    beta_start=0.00_085							,					beta_end=0.012							,					beta_schedule="""scaled_linear"""							,					clip_sample=UpperCamelCase__							,					set_alpha_to_zero=UpperCamelCase__							,					)
										torch.manual_seed(0       )
										lowercase_  							=			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       )
										lowercase_  							=			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=1_000							,					hidden_act="""gelu"""							,					projection_dim=512							,					)
										lowercase_  							=			CLIPTextModel(UpperCamelCase__       )
										lowercase_  							=			CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       )

										lowercase_  							=			{
										    """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   UpperCAmelCase__       (     self       :   int							,					UpperCamelCase__       :   Any							,					UpperCamelCase__       :   Any=0       ):






										'''simple docstring'''






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






										'''simple docstring'''






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






										'''simple docstring'''






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






										'''simple docstring'''






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

										lowercase_  							=			self.get_dummy_components()
										lowercase_  							=			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}       )

										lowercase_  							=			self.get_dummy_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe(**UpperCamelCase__       )[0]

										with tempfile.TemporaryDirectory() as tmpdir:
															pipe.save_pretrained(UpperCamelCase__       )
															lowercase_  							=			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.'''							,					)

										lowercase_  							=			self.get_dummy_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe_loaded(**UpperCamelCase__       )[0]

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

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			"""cpu"""

										lowercase_  							=			self.get_dummy_components()
										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

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

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

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			"""cpu"""

										lowercase_  							=			self.get_dummy_components()
										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

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

										self.assertEqual(image.shape							,					(2, 32, 32, 3)       )
										lowercase_  							=			np.array(
										    [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799]							,					)
										lowercase_  							=			np.abs(image_slice.flatten() - expected_slice       ).max()
										self.assertLessEqual(UpperCamelCase__							,					1e-3       )

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






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







					def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






										'''simple docstring'''






										lowercase_  							=			"""cpu"""

										lowercase_  							=			self.get_dummy_components()

										lowercase_  							=			{"""beta_start""": 0.00_085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""}
										lowercase_  							=			DPMSolverMultistepScheduler(**UpperCamelCase__       )
										lowercase_  							=			DPMSolverMultistepInverseScheduler(**UpperCamelCase__       )

										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

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

										self.assertEqual(image.shape							,					(2, 32, 32, 3)       )
										lowercase_  							=			np.array(
										    [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799]							,					)
										lowercase_  							=			np.abs(image_slice.flatten() - expected_slice       ).max()
										self.assertLessEqual(UpperCamelCase__							,					1e-3       )







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

					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






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

					@classmethod
					def   UpperCAmelCase__       (     cls       :   Dict       ):






										'''simple docstring'''






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

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

										lowercase_  							=			raw_image

					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										lowercase_  							=			torch.manual_seed(0       )

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

										lowercase_  							=			"""a bowl of fruit"""
										lowercase_  							=			"""a bowl of pears"""

										lowercase_  							=			pipe.generate_mask(
										    image=self.raw_image							,					source_prompt=UpperCamelCase__							,					target_prompt=UpperCamelCase__							,					generator=UpperCamelCase__							,					)

										lowercase_  							=			pipe.invert(
										    prompt=UpperCamelCase__							,					image=self.raw_image							,					inpaint_strength=0.7							,					generator=UpperCamelCase__       ).latents

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

										lowercase_  							=			(
										    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   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			torch.manual_seed(0       )

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

										lowercase_  							=			"""a bowl of fruit"""
										lowercase_  							=			"""a bowl of pears"""

										lowercase_  							=			pipe.generate_mask(
										    image=self.raw_image							,					source_prompt=UpperCamelCase__							,					target_prompt=UpperCamelCase__							,					generator=UpperCamelCase__							,					)

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

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

										lowercase_  							=			(
										    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


