

"""simple docstring"""






import gc
import random
import unittest

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

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

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


enable_full_determinism()







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







			def       __lowerCAmelCase					(      self      :			Dict	):





								'''simple docstring'''



								torch.manual_seed(0	)
								UpperCAmelCase      : int   =					UNetaDConditionModel(
								    block_out_channels=(32, 64)      ,	layers_per_block=2      ,	sample_size=32      ,	in_channels=9      ,	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      ,	)
								UpperCAmelCase      : int   =					PNDMScheduler(skip_prk_steps=_lowerCAmelCase	)
								torch.manual_seed(0	)
								UpperCAmelCase      : Optional[Any]   =					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	)
								UpperCAmelCase      : str   =					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      ,	)
								UpperCAmelCase      : Union[str, Any]   =					CLIPTextModel(_lowerCAmelCase	)
								UpperCAmelCase      : int   =					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

								UpperCAmelCase      : int   =					{
								    '''unet''': unet,
								    '''scheduler''': scheduler,
								    '''vae''': vae,
								    '''text_encoder''': text_encoder,
								    '''tokenizer''': tokenizer,
								    '''safety_checker''': None,
								    '''feature_extractor''': None,
								}
								return components







			def       __lowerCAmelCase					(      self      :			List[Any]      ,	lowercase      :			Any      ,	lowercase      :			List[Any]=0	):





								'''simple docstring'''



								UpperCAmelCase      : Optional[Any]   =					floats_tensor((1, 3, 32, 32)      ,	rng=random.Random(_lowerCAmelCase	)	).to(_lowerCAmelCase	)
								UpperCAmelCase      : List[Any]   =					image.cpu().permute(0      ,	2      ,	3      ,	1	)[0]
								UpperCAmelCase      : int   =					Image.fromarray(np.uinta(_lowerCAmelCase	)	).convert("RGB"	).resize((64, 64)	)
								UpperCAmelCase      : List[Any]   =					Image.fromarray(np.uinta(image + 4	)	).convert("RGB"	).resize((64, 64)	)
								if str(_lowerCAmelCase	).startswith("mps"	):
													UpperCAmelCase      : Tuple   =					torch.manual_seed(_lowerCAmelCase	)
								else:
													UpperCAmelCase      : Optional[int]   =					torch.Generator(device=_lowerCAmelCase	).manual_seed(_lowerCAmelCase	)
								UpperCAmelCase      : Dict   =					{
								    '''prompt''': '''A painting of a squirrel eating a burger''',
								    '''image''': init_image,
								    '''mask_image''': mask_image,
								    '''generator''': generator,
								    '''num_inference_steps''': 2,
								    '''guidance_scale''': 6.0,
								    '''output_type''': '''numpy''',
								}
								return inputs







			def       __lowerCAmelCase					(      self      :			Optional[Any]	):





								'''simple docstring'''



								UpperCAmelCase      : Any   =					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
								UpperCAmelCase      : Optional[Any]   =					self.get_dummy_components()
								UpperCAmelCase      : str   =					StableDiffusionInpaintPipeline(**_lowerCAmelCase	)
								UpperCAmelCase      : Dict   =					sd_pipe.to(_lowerCAmelCase	)
								sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase	)

								UpperCAmelCase      : Optional[Any]   =					self.get_dummy_inputs(_lowerCAmelCase	)
								UpperCAmelCase      : int   =					sd_pipe(**_lowerCAmelCase	).images
								UpperCAmelCase      : List[Any]   =					image[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								UpperCAmelCase      : Dict   =					np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6]	)

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







			def       __lowerCAmelCase					(      self      :			Tuple	):





								'''simple docstring'''



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







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







			def       __lowerCAmelCase					(      self      :			Dict	):





								'''simple docstring'''



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







			def       __lowerCAmelCase					(      self      :			Tuple	):





								'''simple docstring'''



								UpperCAmelCase      : Dict   =					load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/sd2-inpaint/init_image.png"	)
								UpperCAmelCase      : Dict   =					load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"	)
								UpperCAmelCase      : str   =					load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
								    "/yellow_cat_sitting_on_a_park_bench.npy"	)

								UpperCAmelCase      : Union[str, Any]   =					'''stabilityai/stable-diffusion-2-inpainting'''
								UpperCAmelCase      : int   =					StableDiffusionInpaintPipeline.from_pretrained(_lowerCAmelCase      ,	safety_checker=_lowerCAmelCase	)
								pipe.to(_lowerCAmelCase	)
								pipe.set_progress_bar_config(disable=_lowerCAmelCase	)
								pipe.enable_attention_slicing()

								UpperCAmelCase      : Any   =					'''Face of a yellow cat, high resolution, sitting on a park bench'''

								UpperCAmelCase      : Tuple   =					torch.manual_seed(0	)
								UpperCAmelCase      : Tuple   =					pipe(
								    prompt=_lowerCAmelCase      ,	image=_lowerCAmelCase      ,	mask_image=_lowerCAmelCase      ,	generator=_lowerCAmelCase      ,	output_type="np"      ,	)
								UpperCAmelCase      : List[Any]   =					output.images[0]

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







			def       __lowerCAmelCase					(      self      :			List[str]	):





								'''simple docstring'''



								UpperCAmelCase      : int   =					load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/sd2-inpaint/init_image.png"	)
								UpperCAmelCase      : Any   =					load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"	)
								UpperCAmelCase      : str   =					load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
								    "/yellow_cat_sitting_on_a_park_bench_fp16.npy"	)

								UpperCAmelCase      : Dict   =					'''stabilityai/stable-diffusion-2-inpainting'''
								UpperCAmelCase      : Any   =					StableDiffusionInpaintPipeline.from_pretrained(
								    _lowerCAmelCase      ,	torch_dtype=torch.floataa      ,	safety_checker=_lowerCAmelCase      ,	)
								pipe.to(_lowerCAmelCase	)
								pipe.set_progress_bar_config(disable=_lowerCAmelCase	)
								pipe.enable_attention_slicing()

								UpperCAmelCase      : Union[str, Any]   =					'''Face of a yellow cat, high resolution, sitting on a park bench'''

								UpperCAmelCase      : Any   =					torch.manual_seed(0	)
								UpperCAmelCase      : Optional[int]   =					pipe(
								    prompt=_lowerCAmelCase      ,	image=_lowerCAmelCase      ,	mask_image=_lowerCAmelCase      ,	generator=_lowerCAmelCase      ,	output_type="np"      ,	)
								UpperCAmelCase      : str   =					output.images[0]

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







			def       __lowerCAmelCase					(      self      :			str	):





								'''simple docstring'''



								torch.cuda.empty_cache()
								torch.cuda.reset_max_memory_allocated()
								torch.cuda.reset_peak_memory_stats()

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

								UpperCAmelCase      : Union[str, Any]   =					'''stabilityai/stable-diffusion-2-inpainting'''
								UpperCAmelCase      : Any   =					PNDMScheduler.from_pretrained(_lowerCAmelCase      ,	subfolder="scheduler"	)
								UpperCAmelCase      : int   =					StableDiffusionInpaintPipeline.from_pretrained(
								    _lowerCAmelCase      ,	safety_checker=_lowerCAmelCase      ,	scheduler=_lowerCAmelCase      ,	torch_dtype=torch.floataa      ,	)
								pipe.to(_lowerCAmelCase	)
								pipe.set_progress_bar_config(disable=_lowerCAmelCase	)
								pipe.enable_attention_slicing(1	)
								pipe.enable_sequential_cpu_offload()

								UpperCAmelCase      : Union[str, Any]   =					'''Face of a yellow cat, high resolution, sitting on a park bench'''

								UpperCAmelCase      : List[Any]   =					torch.manual_seed(0	)
								UpperCAmelCase      : List[Any]   =					pipe(
								    prompt=_lowerCAmelCase      ,	image=_lowerCAmelCase      ,	mask_image=_lowerCAmelCase      ,	generator=_lowerCAmelCase      ,	num_inference_steps=2      ,	output_type="np"      ,	)

								UpperCAmelCase      : List[str]   =					torch.cuda.max_memory_allocated()
								# make sure that less than 2.65 GB is allocated
								assert mem_bytes < 2.6_5 * 10**9









import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class 				a			(      unittest.TestCase			):






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[int]           =   0






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				List[str]           =   AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''					)
										self.assertIsInstance(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with tempfile.TemporaryDirectory() as tmpdirname:
																__SCREAMING_SNAKE_CASE:				Optional[Any]           =   Path(_lowerCAmelCase					) / '''preprocessor_config.json'''
																__SCREAMING_SNAKE_CASE:				List[str]           =   Path(_lowerCAmelCase					) / '''config.json'''
																json.dump(
																    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			, open(_lowerCAmelCase			, '''w'''					)			, )
																json.dump({'''model_type''': '''clip'''}			, open(_lowerCAmelCase			, '''w'''					)					)

																__SCREAMING_SNAKE_CASE:				Dict           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase					)
																self.assertIsInstance(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with tempfile.TemporaryDirectory() as tmpdirname:
																__SCREAMING_SNAKE_CASE:				int           =   Path(_lowerCAmelCase					) / '''preprocessor_config.json'''
																__SCREAMING_SNAKE_CASE:				Tuple           =   Path(_lowerCAmelCase					) / '''config.json'''
																json.dump(
																    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			, open(_lowerCAmelCase			, '''w'''					)			, )
																json.dump({'''model_type''': '''clip'''}			, open(_lowerCAmelCase			, '''w'''					)					)

																__SCREAMING_SNAKE_CASE:				str           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase					)
																self.assertIsInstance(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with tempfile.TemporaryDirectory() as tmpdirname:
																__SCREAMING_SNAKE_CASE:				int           =   CLIPConfig()

																# Create a dummy config file with image_proceesor_type
																__SCREAMING_SNAKE_CASE:				Any           =   Path(_lowerCAmelCase					) / '''preprocessor_config.json'''
																__SCREAMING_SNAKE_CASE:				Optional[Any]           =   Path(_lowerCAmelCase					) / '''config.json'''
																json.dump(
																    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			, open(_lowerCAmelCase			, '''w'''					)			, )
																json.dump({'''model_type''': '''clip'''}			, open(_lowerCAmelCase			, '''w'''					)					)

																# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																__SCREAMING_SNAKE_CASE:				Any           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase					).to_dict()

																config_dict.pop('''image_processor_type'''					)
																__SCREAMING_SNAKE_CASE:				List[str]           =   CLIPImageProcessor(**_lowerCAmelCase					)

																# save in new folder
																model_config.save_pretrained(_lowerCAmelCase					)
																config.save_pretrained(_lowerCAmelCase					)

																__SCREAMING_SNAKE_CASE:				Dict           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase					)

																# make sure private variable is not incorrectly saved
																__SCREAMING_SNAKE_CASE:				int           =   json.loads(config.to_json_string()					)
																self.assertTrue('''_processor_class''' not in dict_as_saved					)

										self.assertIsInstance(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with tempfile.TemporaryDirectory() as tmpdirname:
																__SCREAMING_SNAKE_CASE:				Optional[int]           =   Path(_lowerCAmelCase					) / '''preprocessor_config.json'''
																json.dump(
																    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			, open(_lowerCAmelCase			, '''w'''					)			, )

																__SCREAMING_SNAKE_CASE:				int           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase					)
																self.assertIsInstance(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with self.assertRaisesRegex(
										    _lowerCAmelCase			, '''clip-base is not a local folder and is not a valid model identifier'''					):
																__SCREAMING_SNAKE_CASE:				Tuple           =   AutoImageProcessor.from_pretrained('''clip-base'''					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with self.assertRaisesRegex(
										    _lowerCAmelCase			, R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''					):
																__SCREAMING_SNAKE_CASE:				Dict           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase			, revision='''aaaaaa'''					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with self.assertRaisesRegex(
										    _lowerCAmelCase			, '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''			, ):
																__SCREAMING_SNAKE_CASE:				int           =   AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										with self.assertRaises(_lowerCAmelCase					):
																__SCREAMING_SNAKE_CASE:				Optional[Any]           =   AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''					)
										# If remote code is disabled, we can't load this config.
										with self.assertRaises(_lowerCAmelCase					):
																__SCREAMING_SNAKE_CASE:				Any           =   AutoImageProcessor.from_pretrained(
																    '''hf-internal-testing/test_dynamic_image_processor'''			, trust_remote_code=_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   AutoImageProcessor.from_pretrained(
										    '''hf-internal-testing/test_dynamic_image_processor'''			, trust_remote_code=_lowerCAmelCase					)
										self.assertEqual(image_processor.__class__.__name__			, '''NewImageProcessor'''					)

										# Test image processor can be reloaded.
										with tempfile.TemporaryDirectory() as tmp_dir:
																image_processor.save_pretrained(_lowerCAmelCase					)
																__SCREAMING_SNAKE_CASE:				List[str]           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase			, trust_remote_code=_lowerCAmelCase					)
										self.assertEqual(reloaded_image_processor.__class__.__name__			, '''NewImageProcessor'''					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										try:
																AutoConfig.register('''custom'''			, _lowerCAmelCase					)
																AutoImageProcessor.register(_lowerCAmelCase			, _lowerCAmelCase					)
																# Trying to register something existing in the Transformers library will raise an error
																with self.assertRaises(_lowerCAmelCase					):
																						AutoImageProcessor.register(_lowerCAmelCase			, _lowerCAmelCase					)

																with tempfile.TemporaryDirectory() as tmpdirname:
																						__SCREAMING_SNAKE_CASE:				Optional[int]           =   Path(_lowerCAmelCase					) / '''preprocessor_config.json'''
																						__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   Path(_lowerCAmelCase					) / '''config.json'''
																						json.dump(
																						    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			, open(_lowerCAmelCase			, '''w'''					)			, )
																						json.dump({'''model_type''': '''clip'''}			, open(_lowerCAmelCase			, '''w'''					)					)

																						__SCREAMING_SNAKE_CASE:				List[str]           =   CustomImageProcessor.from_pretrained(_lowerCAmelCase					)

																# Now that the config is registered, it can be used as any other config with the auto-API
																with tempfile.TemporaryDirectory() as tmp_dir:
																						image_processor.save_pretrained(_lowerCAmelCase					)
																						__SCREAMING_SNAKE_CASE:				int           =   AutoImageProcessor.from_pretrained(_lowerCAmelCase					)
																						self.assertIsInstance(_lowerCAmelCase			, _lowerCAmelCase					)

										finally:
																if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]
																if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																						del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]






				def 			snake_case_    (  self					):

										"""simple docstring"""




										class 				a			(      __lowercase			):
														SCREAMING_SNAKE_CASE__     :   Tuple		      =     True

										try:
																AutoConfig.register('''custom'''			, _lowerCAmelCase					)
																AutoImageProcessor.register(_lowerCAmelCase			, _lowerCAmelCase					)
																# If remote code is not set, the default is to use local
																__SCREAMING_SNAKE_CASE:				str           =   AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''					)
																self.assertEqual(image_processor.__class__.__name__			, '''NewImageProcessor'''					)
																self.assertTrue(image_processor.is_local					)

																# If remote code is disabled, we load the local one.
																__SCREAMING_SNAKE_CASE:				Tuple           =   AutoImageProcessor.from_pretrained(
																    '''hf-internal-testing/test_dynamic_image_processor'''			, trust_remote_code=_lowerCAmelCase					)
																self.assertEqual(image_processor.__class__.__name__			, '''NewImageProcessor'''					)
																self.assertTrue(image_processor.is_local					)

																# If remote is enabled, we load from the Hub
																__SCREAMING_SNAKE_CASE:				Any           =   AutoImageProcessor.from_pretrained(
																    '''hf-internal-testing/test_dynamic_image_processor'''			, trust_remote_code=_lowerCAmelCase					)
																self.assertEqual(image_processor.__class__.__name__			, '''NewImageProcessor'''					)
																self.assertTrue(not hasattr(_lowerCAmelCase			, '''is_local'''					)					)

										finally:
																if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]
																if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																						del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



