
"""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        _UpperCAmelCase(       lowerCamelCase ,	lowerCamelCase ,	lowerCamelCase ,	unittest.TestCase      ):
		lowercase__         = StableDiffusionInpaintPipeline
		lowercase__         = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
		lowercase__         = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
		lowercase__         = frozenset(
		    []      )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
		lowercase__         = frozenset([]      )



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							torch.manual_seed(0)
							_UpperCamelCase									=    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=__a							,						)
							_UpperCamelCase									=    PNDMScheduler(skip_prk_steps=__a)
							torch.manual_seed(0)
							_UpperCamelCase									=    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									=    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									=    CLIPTextModel(__a)
							_UpperCamelCase									=    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

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



		def 		UpperCAmelCase				(   self							,						__a							,						__a=0)			->			Optional[int]:






							'''simple docstring'''
							# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
							_UpperCamelCase									=    floats_tensor((1, 3, 32, 32)							,						rng=random.Random(__a)).to(__a)
							_UpperCamelCase									=    image.cpu().permute(0							,						2							,						3							,						1)[0]
							_UpperCamelCase									=    Image.fromarray(np.uinta(__a)).convert('''RGB''').resize((64, 64))
							_UpperCamelCase									=    Image.fromarray(np.uinta(image + 4)).convert('''RGB''').resize((64, 64))
							if str(__a).startswith('''mps'''):
												_UpperCamelCase									=    torch.manual_seed(__a)
							else:
												_UpperCamelCase									=    torch.Generator(device=__a).manual_seed(__a)
							_UpperCamelCase									=    {
							    '''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 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCamelCase									=    self.get_dummy_components()
							_UpperCamelCase									=    StableDiffusionInpaintPipeline(**__a)
							_UpperCamelCase									=    sd_pipe.to(__a)
							sd_pipe.set_progress_bar_config(disable=__a)

							_UpperCamelCase									=    self.get_dummy_inputs(__a)
							_UpperCamelCase									=    sd_pipe(**__a).images
							_UpperCamelCase									=    image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							_UpperCamelCase									=    np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476])

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




		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							super().test_inference_batch_single_identical(expected_max_diff=3e-3)






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



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							_UpperCamelCase									=    load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/sd2-inpaint/init_image.png''')
							_UpperCamelCase									=    load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''')
							_UpperCamelCase									=    load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
							    '''/yellow_cat_sitting_on_a_park_bench.npy''')

							_UpperCamelCase									=    '''stabilityai/stable-diffusion-2-inpainting'''
							_UpperCamelCase									=    StableDiffusionInpaintPipeline.from_pretrained(__a							,						safety_checker=__a)
							pipe.to(__a)
							pipe.set_progress_bar_config(disable=__a)
							pipe.enable_attention_slicing()

							_UpperCamelCase									=    '''Face of a yellow cat, high resolution, sitting on a park bench'''

							_UpperCamelCase									=    torch.manual_seed(0)
							_UpperCamelCase									=    pipe(
							    prompt=__a							,						image=__a							,						mask_image=__a							,						generator=__a							,						output_type='''np'''							,						)
							_UpperCamelCase									=    output.images[0]

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



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/sd2-inpaint/init_image.png''')
							_UpperCamelCase									=    load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''')
							_UpperCamelCase									=    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									=    '''stabilityai/stable-diffusion-2-inpainting'''
							_UpperCamelCase									=    StableDiffusionInpaintPipeline.from_pretrained(
							    __a							,						torch_dtype=torch.floataa							,						safety_checker=__a							,						)
							pipe.to(__a)
							pipe.set_progress_bar_config(disable=__a)
							pipe.enable_attention_slicing()

							_UpperCamelCase									=    '''Face of a yellow cat, high resolution, sitting on a park bench'''

							_UpperCamelCase									=    torch.manual_seed(0)
							_UpperCamelCase									=    pipe(
							    prompt=__a							,						image=__a							,						mask_image=__a							,						generator=__a							,						output_type='''np'''							,						)
							_UpperCamelCase									=    output.images[0]

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




		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

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

							_UpperCamelCase									=    '''stabilityai/stable-diffusion-2-inpainting'''
							_UpperCamelCase									=    PNDMScheduler.from_pretrained(__a							,						subfolder='''scheduler''')
							_UpperCamelCase									=    StableDiffusionInpaintPipeline.from_pretrained(
							    __a							,						safety_checker=__a							,						scheduler=__a							,						torch_dtype=torch.floataa							,						)
							pipe.to(__a)
							pipe.set_progress_bar_config(disable=__a)
							pipe.enable_attention_slicing(1)
							pipe.enable_sequential_cpu_offload()

							_UpperCamelCase									=    '''Face of a yellow cat, high resolution, sitting on a park bench'''

							_UpperCamelCase									=    torch.manual_seed(0)
							_UpperCamelCase									=    pipe(
							    prompt=__a							,						image=__a							,						mask_image=__a							,						generator=__a							,						num_inference_steps=2							,						output_type='''np'''							,						)

							_UpperCamelCase									=    torch.cuda.max_memory_allocated()
							# make sure that less than 2.65 GB is allocated
							assert mem_bytes < 2.65 * 10**9








"""simple docstring"""





# Imports
import numpy as np






class        _UpperCAmelCase:



		def __init__(   self							,						__a=None							,						__a=None							,						__a=None							,						__a=None							,						__a=None)			->			Dict:






							'''simple docstring'''
							self.set_matricies(red=__a							,						green=__a							,						blue=__a							,						red_edge=__a							,						nir=__a)



		def 		UpperCAmelCase				(   self							,						__a=None							,						__a=None							,						__a=None							,						__a=None							,						__a=None)			->			Dict:






							'''simple docstring'''
							if red is not None:
												_UpperCamelCase									=    red
							if green is not None:
												_UpperCamelCase									=    green
							if blue is not None:
												_UpperCamelCase									=    blue
							if red_edge is not None:
												_UpperCamelCase									=    red_edge
							if nir is not None:
												_UpperCamelCase									=    nir
							return True



		def 		UpperCAmelCase				(   self							,						__a=""							,						__a=None							,						__a=None							,						__a=None							,						__a=None							,						__a=None)			->			List[str]:






							'''simple docstring'''
							self.set_matricies(red=__a							,						green=__a							,						blue=__a							,						red_edge=__a							,						nir=__a)
							_UpperCamelCase									=    {
							    '''ARVI2''': self.arvaa,
							    '''CCCI''': self.ccci,
							    '''CVI''': self.cvi,
							    '''GLI''': self.gli,
							    '''NDVI''': self.ndvi,
							    '''BNDVI''': self.bndvi,
							    '''redEdgeNDVI''': self.red_edge_ndvi,
							    '''GNDVI''': self.gndvi,
							    '''GBNDVI''': self.gbndvi,
							    '''GRNDVI''': self.grndvi,
							    '''RBNDVI''': self.rbndvi,
							    '''PNDVI''': self.pndvi,
							    '''ATSAVI''': self.atsavi,
							    '''BWDRVI''': self.bwdrvi,
							    '''CIgreen''': self.ci_green,
							    '''CIrededge''': self.ci_rededge,
							    '''CI''': self.ci,
							    '''CTVI''': self.ctvi,
							    '''GDVI''': self.gdvi,
							    '''EVI''': self.evi,
							    '''GEMI''': self.gemi,
							    '''GOSAVI''': self.gosavi,
							    '''GSAVI''': self.gsavi,
							    '''Hue''': self.hue,
							    '''IVI''': self.ivi,
							    '''IPVI''': self.ipvi,
							    '''I''': self.i,
							    '''RVI''': self.rvi,
							    '''MRVI''': self.mrvi,
							    '''MSAVI''': self.m_savi,
							    '''NormG''': self.norm_g,
							    '''NormNIR''': self.norm_nir,
							    '''NormR''': self.norm_r,
							    '''NGRDI''': self.ngrdi,
							    '''RI''': self.ri,
							    '''S''': self.s,
							    '''IF''': self._if,
							    '''DVI''': self.dvi,
							    '''TVI''': self.tvi,
							    '''NDRE''': self.ndre,
							}

							try:
												return funcs[index]()
							except KeyError:
												print('''Index not in the list!''')
												return False



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red)))



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
							    (self.nir - self.red) / (self.nir + self.red)
							)



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






							'''simple docstring'''
							return self.nir * (self.red / (self.green**2))



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							return (2 * self.green - self.red - self.blue) / (
							    2 * self.green + self.red + self.blue
							)



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






							'''simple docstring'''
							return (self.nir - self.red) / (self.nir + self.red)



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							return (self.nir - self.blue) / (self.nir + self.blue)



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return (self.redEdge - self.red) / (self.redEdge + self.red)



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






							'''simple docstring'''
							return (self.nir - self.green) / (self.nir + self.green)



		def 		UpperCAmelCase				(   self)			->			Optional[Any]:






							'''simple docstring'''
							return (self.nir - (self.green + self.blue)) / (
							    self.nir + (self.green + self.blue)
							)



		def 		UpperCAmelCase				(   self)			->			Tuple:






							'''simple docstring'''
							return (self.nir - (self.green + self.red)) / (
							    self.nir + (self.green + self.red)
							)



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))



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






							'''simple docstring'''
							return (self.nir - (self.green + self.red + self.blue)) / (
							    self.nir + (self.green + self.red + self.blue)
							)



		def 		UpperCAmelCase				(   self							,						__a=0.08							,						__a=1.22							,						__a=0.03)			->			Optional[Any]:






							'''simple docstring'''
							return a * (
							    (self.nir - a * self.red - b)
							    / (a * self.nir + self.red - a * b + x * (1 + a**2))
							)



		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)



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






							'''simple docstring'''
							return (self.nir / self.green) - 1



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return (self.nir / self.redEdge) - 1



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






							'''simple docstring'''
							return (self.red - self.blue) / self.red



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






							'''simple docstring'''
							_UpperCamelCase									=    self.ndvi()
							return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2))



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






							'''simple docstring'''
							return self.nir - self.green



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






							'''simple docstring'''
							return 2.5 * (
							    (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
							)



		def 		UpperCAmelCase				(   self)			->			Tuple:






							'''simple docstring'''
							_UpperCamelCase									=    (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / (
							    self.nir + self.red + 0.5
							)
							return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red)



		def 		UpperCAmelCase				(   self							,						__a=0.16)			->			Optional[Any]:






							'''simple docstring'''
							return (self.nir - self.green) / (self.nir + self.green + y)



		def 		UpperCAmelCase				(   self							,						__a=0.5)			->			Dict:






							'''simple docstring'''
							return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n)



		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							return np.arctan(
							    ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue))



		def 		UpperCAmelCase				(   self							,						__a=None							,						__a=None)			->			Any:






							'''simple docstring'''
							return (self.nir - b) / (a * self.red)



		def 		UpperCAmelCase				(   self)			->			Optional[Any]:






							'''simple docstring'''
							return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1)



		def 		UpperCAmelCase				(   self)			->			Optional[Any]:






							'''simple docstring'''
							return (self.red + self.green + self.blue) / 30.5



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							return self.nir / self.red



		def 		UpperCAmelCase				(   self)			->			Tuple:






							'''simple docstring'''
							return (self.rvi() - 1) / (self.rvi() + 1)



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return (
							    (2 * self.nir + 1)
							    - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2)
							) / 2



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






							'''simple docstring'''
							return self.green / (self.nir + self.red + self.green)



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							return self.nir / (self.nir + self.red + self.green)



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






							'''simple docstring'''
							return self.red / (self.nir + self.red + self.green)



		def 		UpperCAmelCase				(   self)			->			Tuple:






							'''simple docstring'''
							return (self.green - self.red) / (self.green + self.red)



		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							return (self.red - self.green) / (self.red + self.green)



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    np.max([np.max(self.red), np.max(self.green), np.max(self.blue)])
							_UpperCamelCase									=    np.min([np.min(self.red), np.min(self.green), np.min(self.blue)])
							return (max_value - min_value) / max_value



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							return (2 * self.red - self.green - self.blue) / (self.green - self.blue)



		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							return self.nir / self.red



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							return (self.ndvi() + 0.5) ** (1 / 2)




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






							'''simple docstring'''
							return (self.nir - self.redEdge) / (self.nir + self.redEdge)






