



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 	lowerCamelCase_    ( _A						,_A						,unittest.TestCase						):






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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int] )      ->				List[Any]:
									torch.manual_seed(0 )
									A							:					Tuple              =						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	,	)
									A							:					str              =						DDIMScheduler(
									    beta_start=0.00085	,	beta_end=0.012	,	beta_schedule="scaled_linear"	,	clip_sample=__lowerCamelCase	,	set_alpha_to_one=__lowerCamelCase	,	)
									A							:					List[str]              =						DDIMInverseScheduler(
									    beta_start=0.00085	,	beta_end=0.012	,	beta_schedule="scaled_linear"	,	clip_sample=__lowerCamelCase	,	set_alpha_to_zero=__lowerCamelCase	,	)
									torch.manual_seed(0 )
									A							:					Tuple              =						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=1_28	,	)
									torch.manual_seed(0 )
									A							:					Optional[Any]              =						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=10_00	,	hidden_act="gelu"	,	projection_dim=5_12	,	)
									A							:					Any              =						CLIPTextModel(__lowerCamelCase )
									A							:					int              =						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

									A							:					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 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any]	,	__lowerCamelCase      :			List[Any]	,	__lowerCamelCase      :			Any=0 )      ->				str:
									A							:					List[str]              =						floats_tensor((1, 16, 16)	,	rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
									A							:					Union[str, Any]              =						floats_tensor((1, 2, 4, 16, 16)	,	rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
									if str(__lowerCamelCase ).startswith("mps" ):
												A							:					List[Any]              =						torch.manual_seed(__lowerCamelCase )
									else:
												A							:					str              =						torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
									A							:					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 			SCREAMING_SNAKE_CASE__		(	self      :			Union[str, Any]	,	__lowerCamelCase      :			List[Any]	,	__lowerCamelCase      :			List[Any]=0 )      ->				Dict:
									A							:					str              =						floats_tensor((1, 3, 32, 32)	,	rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
									A							:					Union[str, Any]              =						image.cpu().permute(0	,	2	,	3	,	1 )[0]
									A							:					Tuple              =						Image.fromarray(np.uinta(__lowerCamelCase ) ).convert("RGB" )
									if str(__lowerCamelCase ).startswith("mps" ):
												A							:					str              =						torch.manual_seed(__lowerCamelCase )
									else:
												A							:					List[str]              =						torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
									A							:					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 			SCREAMING_SNAKE_CASE__		(	self      :			int	,	__lowerCamelCase      :			Tuple	,	__lowerCamelCase      :			int=0 )      ->				Union[str, Any]:
									A							:					Dict              =						floats_tensor((1, 3, 32, 32)	,	rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
									A							:					Union[str, Any]              =						image.cpu().permute(0	,	2	,	3	,	1 )[0]
									A							:					List[str]              =						Image.fromarray(np.uinta(__lowerCamelCase ) ).convert("RGB" )
									if str(__lowerCamelCase ).startswith("mps" ):
												A							:					List[Any]              =						torch.manual_seed(__lowerCamelCase )
									else:
												A							:					int              =						torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
									A							:					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 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				Optional[Any]:
									if not hasattr(self.pipeline_class	,	"_optional_components" ):
												return

									A							:					Any              =						self.get_dummy_components()
									A							:					Union[str, Any]              =						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} )

									A							:					List[str]              =						self.get_dummy_inputs(__lowerCamelCase )
									A							:					Union[str, Any]              =						pipe(**__lowerCamelCase )[0]

									with tempfile.TemporaryDirectory() as tmpdir:
												pipe.save_pretrained(__lowerCamelCase )
												A							:					Tuple              =						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."""	,	)

									A							:					Optional[int]              =						self.get_dummy_inputs(__lowerCamelCase )
									A							:					Optional[Any]              =						pipe_loaded(**__lowerCamelCase )[0]

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple )      ->				Optional[Any]:
									A							:					Optional[int]              =						"cpu"

									A							:					int              =						self.get_dummy_components()
									A							:					List[str]              =						self.pipeline_class(**__lowerCamelCase )
									pipe.to(__lowerCamelCase )
									pipe.set_progress_bar_config(disable=__lowerCamelCase )

									A							:					List[Any]              =						self.get_dummy_mask_inputs(__lowerCamelCase )
									A							:					int              =						pipe.generate_mask(**__lowerCamelCase )
									A							:					Optional[int]              =						mask[0, -3:, -3:]

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str )      ->				Dict:
									A							:					Union[str, Any]              =						"cpu"

									A							:					Dict              =						self.get_dummy_components()
									A							:					Dict              =						self.pipeline_class(**__lowerCamelCase )
									pipe.to(__lowerCamelCase )
									pipe.set_progress_bar_config(disable=__lowerCamelCase )

									A							:					Tuple              =						self.get_dummy_inversion_inputs(__lowerCamelCase )
									A							:					Union[str, Any]              =						pipe.invert(**__lowerCamelCase ).images
									A							:					int              =						image[0, -1, -3:, -3:]

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				Any:
									super().test_inference_batch_single_identical(expected_max_diff=5e-3 )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				Dict:
									A							:					Any              =						"cpu"

									A							:					Optional[int]              =						self.get_dummy_components()

									A							:					List[str]              =						{"beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear"}
									A							:					int              =						DPMSolverMultistepScheduler(**__lowerCamelCase )
									A							:					List[str]              =						DPMSolverMultistepInverseScheduler(**__lowerCamelCase )

									A							:					Dict              =						self.pipeline_class(**__lowerCamelCase )
									pipe.to(__lowerCamelCase )
									pipe.set_progress_bar_config(disable=__lowerCamelCase )

									A							:					int              =						self.get_dummy_inversion_inputs(__lowerCamelCase )
									A							:					Optional[Any]              =						pipe.invert(**__lowerCamelCase ).images
									A							:					str              =						image[0, -1, -3:, -3:]

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







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






						'''simple docstring'''







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				List[str]:
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







						@classmethod
						def 			SCREAMING_SNAKE_CASE__		(	cls      :			Any )      ->				Tuple:
									A							:					Tuple              =						load_image(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" )

									A							:					List[Any]              =						raw_image.convert("RGB" ).resize((7_68, 7_68) )

									A							:					Optional[int]              =						raw_image







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				Dict:
									A							:					Any              =						torch.manual_seed(0 )

									A							:					Optional[int]              =						StableDiffusionDiffEditPipeline.from_pretrained(
									    "stabilityai/stable-diffusion-2-1"	,	safety_checker=__lowerCamelCase	,	torch_dtype=torch.floataa )
									A							:					Union[str, Any]              =						DDIMScheduler.from_config(pipe.scheduler.config )
									A							:					List[Any]              =						DDIMInverseScheduler.from_config(pipe.scheduler.config )
									pipe.enable_model_cpu_offload()
									pipe.set_progress_bar_config(disable=__lowerCamelCase )

									A							:					Union[str, Any]              =						"a bowl of fruit"
									A							:					Dict              =						"a bowl of pears"

									A							:					Optional[int]              =						pipe.generate_mask(
									    image=self.raw_image	,	source_prompt=__lowerCamelCase	,	target_prompt=__lowerCamelCase	,	generator=__lowerCamelCase	,	)

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

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

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple )      ->				List[str]:
									A							:					List[Any]              =						torch.manual_seed(0 )

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

									A							:					Tuple              =						"a bowl of fruit"
									A							:					Union[str, Any]              =						"a bowl of pears"

									A							:					Optional[Any]              =						pipe.generate_mask(
									    image=self.raw_image	,	source_prompt=__lowerCamelCase	,	target_prompt=__lowerCamelCase	,	generator=__lowerCamelCase	,	)

									A							:					Union[str, Any]              =						pipe.invert(
									    prompt=__lowerCamelCase	,	image=self.raw_image	,	inpaint_strength=0.7	,	generator=__lowerCamelCase	,	num_inference_steps=25	,	).latents

									A							:					List[str]              =						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]

									A							:					Union[str, Any]              =						(
									    np.array(
									        load_image(
									            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
									            "/diffedit/pears.png" ).resize((7_68, 7_68) ) )
									    / 2_55
									)
									assert np.abs((expected_image - image).max() ) < 5e-1




import os


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
__SCREAMING_SNAKE_CASE           =  """."""


if __name__ == "__main__":
							__SCREAMING_SNAKE_CASE           =  os.path.join(REPO_PATH, """utils/documentation_tests.txt""")
							__SCREAMING_SNAKE_CASE           =  []
							__SCREAMING_SNAKE_CASE           =  []
							with open(doctest_file_path) as fp:
														for line in fp:
																					__SCREAMING_SNAKE_CASE           =  line.strip()
																					__SCREAMING_SNAKE_CASE           =  os.path.join(REPO_PATH, line)
																					if not (os.path.isfile(path) or os.path.isdir(path)):
																												non_existent_paths.append(line)
																					all_paths.append(path)
							if len(non_existent_paths) > 0:
														__SCREAMING_SNAKE_CASE           =  """\n""".join(non_existent_paths)
														raise ValueError(F"""`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}""")
							if all_paths != sorted(all_paths):
														raise ValueError("""Files in `utils/documentation_tests.txt` are not in alphabetical order.""")