






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 							SCREAMING_SNAKE_CASE__		(       UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_				,     unittest.TestCase		):





					"""simple docstring"""






					a_			=	StableDiffusionInpaintPipeline
					a_			=	TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
					a_			=	TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
					a_			=	frozenset(
					    []		)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
					a_			=	frozenset([]		)



					def  _lowercase  (      self  :						str ):
						torch.manual_seed(0 )
						snake_case__				:   Optional[Any]     =						UNetaDConditionModel(
						    block_out_channels=(3_2, 6_4)							,	layers_per_block=2							,	sample_size=3_2							,	in_channels=9							,	out_channels=4							,	down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")							,	up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")							,	cross_attention_dim=3_2							,	attention_head_dim=(2, 4)							,	use_linear_projection=__A							,	)
						snake_case__				:   int     =						PNDMScheduler(skip_prk_steps=__A )
						torch.manual_seed(0 )
						snake_case__				:   Union[str, Any]     =						AutoencoderKL(
						    block_out_channels=[3_2, 6_4]							,	in_channels=3							,	out_channels=3							,	down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]							,	up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]							,	latent_channels=4							,	sample_size=1_2_8							,	)
						torch.manual_seed(0 )
						snake_case__				:   List[Any]     =						CLIPTextConfig(
						    bos_token_id=0							,	eos_token_id=2							,	hidden_size=3_2							,	intermediate_size=3_7							,	layer_norm_eps=1e-0_5							,	num_attention_heads=4							,	num_hidden_layers=5							,	pad_token_id=1							,	vocab_size=1_0_0_0							,	hidden_act="gelu"							,	projection_dim=5_1_2							,	)
						snake_case__				:   Tuple     =						CLIPTextModel(__A )
						snake_case__				:   Optional[int]     =						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

						snake_case__				:   Dict     =						{
						    "unet": unet,
						    "scheduler": scheduler,
						    "vae": vae,
						    "text_encoder": text_encoder,
						    "tokenizer": tokenizer,
						    "safety_checker": None,
						    "feature_extractor": None,
						}
						return components



					def  _lowercase  (      self  :						Tuple							,	__A  :						Optional[int]							,	__A  :						str=0 ):
						# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
						snake_case__				:   str     =						floats_tensor((1, 3, 3_2, 3_2)							,	rng=random.Random(__A ) ).to(__A )
						snake_case__				:   str     =						image.cpu().permute(0							,	2							,	3							,	1 )[0]
						snake_case__				:   int     =						Image.fromarray(np.uinta(__A ) ).convert("RGB" ).resize((6_4, 6_4) )
						snake_case__				:   Optional[int]     =						Image.fromarray(np.uinta(image + 4 ) ).convert("RGB" ).resize((6_4, 6_4) )
						if str(__A ).startswith("mps" ):
							snake_case__				:   str     =						torch.manual_seed(__A )
						else:
							snake_case__				:   Any     =						torch.Generator(device=__A ).manual_seed(__A )
						snake_case__				:   List[Any]     =						{
						    "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  _lowercase  (      self  :						List[Any] ):
						snake_case__				:   str     =						"cpu"  # ensure determinism for the device-dependent torch.Generator
						snake_case__				:   Tuple     =						self.get_dummy_components()
						snake_case__				:   str     =						StableDiffusionInpaintPipeline(**__A )
						snake_case__				:   int     =						sd_pipe.to(__A )
						sd_pipe.set_progress_bar_config(disable=__A )

						snake_case__				:   str     =						self.get_dummy_inputs(__A )
						snake_case__				:   int     =						sd_pipe(**__A ).images
						snake_case__				:   List[Any]     =						image[0, -3:, -3:, -1]

						assert image.shape == (1, 6_4, 6_4, 3)
						snake_case__				:   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  _lowercase  (      self  :						int ):
						super().test_inference_batch_single_identical(expected_max_diff=3e-3 )



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





					"""simple docstring"""






					def  _lowercase  (      self  :						Union[str, Any] ):
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



					def  _lowercase  (      self  :						List[Any] ):
						snake_case__				:   Optional[Any]     =						load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-inpaint/init_image.png" )
						snake_case__				:   Tuple     =						load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" )
						snake_case__				:   List[Any]     =						load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
						    "/yellow_cat_sitting_on_a_park_bench.npy" )

						snake_case__				:   str     =						"stabilityai/stable-diffusion-2-inpainting"
						snake_case__				:   Union[str, Any]     =						StableDiffusionInpaintPipeline.from_pretrained(__A							,	safety_checker=__A )
						pipe.to(__A )
						pipe.set_progress_bar_config(disable=__A )
						pipe.enable_attention_slicing()

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

						snake_case__				:   Tuple     =						torch.manual_seed(0 )
						snake_case__				:   int     =						pipe(
						    prompt=__A							,	image=__A							,	mask_image=__A							,	generator=__A							,	output_type="np"							,	)
						snake_case__				:   Dict     =						output.images[0]

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



					def  _lowercase  (      self  :						Dict ):
						snake_case__				:   Any     =						load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-inpaint/init_image.png" )
						snake_case__				:   List[str]     =						load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" )
						snake_case__				:   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" )

						snake_case__				:   int     =						"stabilityai/stable-diffusion-2-inpainting"
						snake_case__				:   List[Any]     =						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()

						snake_case__				:   List[str]     =						"Face of a yellow cat, high resolution, sitting on a park bench"

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

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






					def  _lowercase  (      self  :						List[Any] ):
						torch.cuda.empty_cache()
						torch.cuda.reset_max_memory_allocated()
						torch.cuda.reset_peak_memory_stats()

						snake_case__				:   Optional[int]     =						load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-inpaint/init_image.png" )
						snake_case__				:   Any     =						load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" )

						snake_case__				:   Union[str, Any]     =						"stabilityai/stable-diffusion-2-inpainting"
						snake_case__				:   List[str]     =						PNDMScheduler.from_pretrained(__A							,	subfolder="scheduler" )
						snake_case__				:   Tuple     =						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()

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

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

						snake_case__				:   Tuple     =						torch.cuda.max_memory_allocated()
						# make sure that less than 2.65 GB is allocated
						assert mem_bytes < 2.6_5 * 1_0**9









# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
	import jax
	import jaxlib

__lowerCamelCase      :    Optional[int]   		=   get_logger()

__lowerCamelCase      :    Optional[dict]   		=   None



class 							SCREAMING_SNAKE_CASE__		(       TensorFormatter[Mapping, "jax.Array", Mapping]		):





					"""simple docstring"""






					def __init__(      self  :						Optional[Any]							,	__A  :						Dict=None							,	__A  :						List[str]=None							,	**__A  :						str ):
						super().__init__(features=__A )
						import jax
						from jaxlib.xla_client import Device

						if isinstance(__A							,	__A ):
							raise ValueError(
							    f'''Expected {device} to be a `str` not {type(__A )}, as `jaxlib.xla_extension.Device` '''
							    "is not serializable neither with `pickle` nor with `dill`. Instead you can surround "
							    "the device with `str()` to get its string identifier that will be internally mapped "
							    "to the actual `jaxlib.xla_extension.Device`." )
						snake_case__				:   List[Any]     =						device if isinstance(__A							,	__A ) else str(jax.devices()[0] )
						# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
						# with `pickle` nor with `dill`, so we need to use a global variable instead
						global DEVICE_MAPPING
						if DEVICE_MAPPING is None:
							snake_case__				:   Any     =						self._map_devices_to_str()
						if self.device not in list(DEVICE_MAPPING.keys() ):
							logger.warning(
							    f'''Device with string identifier {self.device} not listed among the available '''
							    f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default '''
							    f'''device: {str(jax.devices()[0] )}.''' )
							snake_case__				:   str     =						str(jax.devices()[0] )
						snake_case__				:   str     =						jnp_array_kwargs



					@staticmethod
					def  _lowercase  (      ):
						import jax

						return {str(__A ): device for device in jax.devices()}



					def  _lowercase  (      self  :						Optional[Any]							,	__A  :						str ):
						import jax
						import jax.numpy as jnp

						if isinstance(__A							,	__A ) and column:
							if all(
							    isinstance(__A							,	jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ):
								return jnp.stack(__A							,	axis=0 )
						return column



					def  _lowercase  (      self  :						int							,	__A  :						Tuple ):
						import jax
						import jax.numpy as jnp

						if isinstance(__A							,	(str, bytes, type(__A )) ):
							return value
						elif isinstance(__A							,	(np.character, np.ndarray) ) and np.issubdtype(value.dtype							,	np.character ):
							return value.tolist()

						snake_case__				:   Optional[int]     =						{}

						if isinstance(__A							,	(np.number, np.ndarray) ) and np.issubdtype(value.dtype							,	np.integer ):
							# the default int precision depends on the jax config
							# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
							if jax.config.jax_enable_xaa:
								snake_case__				:   Any     =						{"dtype": jnp.intaa}
							else:
								snake_case__				:   Tuple     =						{"dtype": jnp.intaa}
						elif isinstance(__A							,	(np.number, np.ndarray) ) and np.issubdtype(value.dtype							,	np.floating ):
							snake_case__				:   str     =						{"dtype": jnp.floataa}
						elif config.PIL_AVAILABLE and "PIL" in sys.modules:
							import PIL.Image

							if isinstance(__A							,	PIL.Image.Image ):
								snake_case__				:   Optional[Any]     =						np.asarray(__A )

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
						global DEVICE_MAPPING
						if DEVICE_MAPPING is None:
							snake_case__				:   int     =						self._map_devices_to_str()

						with jax.default_device(DEVICE_MAPPING[self.device] ):
							# calling jnp.array on a np.ndarray does copy the data
							# see https://github.com/google/jax/issues/4486
							return jnp.array(__A							,	**{**default_dtype, **self.jnp_array_kwargs} )



					def  _lowercase  (      self  :						Union[str, Any]							,	__A  :						Optional[int] ):
						import jax

						# support for torch, tf, jax etc.
						if config.TORCH_AVAILABLE and "torch" in sys.modules:
							import torch

							if isinstance(__A							,	torch.Tensor ):
								return self._tensorize(data_struct.detach().cpu().numpy()[()] )
						if hasattr(__A							,	"__array__" ) and not isinstance(__A							,	jax.Array ):
							snake_case__				:   Union[str, Any]     =						data_struct.__array__()
						# support for nested types like struct of list of struct
						if isinstance(__A							,	np.ndarray ):
							if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
								return self._consolidate([self.recursive_tensorize(__A ) for substruct in data_struct] )
						elif isinstance(__A							,	(list, tuple) ):
							return self._consolidate([self.recursive_tensorize(__A ) for substruct in data_struct] )
						return self._tensorize(__A )



					def  _lowercase  (      self  :						Tuple							,	__A  :						dict ):
						return map_nested(self._recursive_tensorize							,	__A							,	map_list=__A )



					def  _lowercase  (      self  :						Optional[int]							,	__A  :						pa.Table ):
						snake_case__				:   int     =						self.numpy_arrow_extractor().extract_row(__A )
						snake_case__				:   Tuple     =						self.python_features_decoder.decode_row(__A )
						return self.recursive_tensorize(__A )



					def  _lowercase  (      self  :						Optional[Any]							,	__A  :						pa.Table ):
						snake_case__				:   Any     =						self.numpy_arrow_extractor().extract_column(__A )
						snake_case__				:   Optional[int]     =						self.python_features_decoder.decode_column(__A							,	pa_table.column_names[0] )
						snake_case__				:   List[Any]     =						self.recursive_tensorize(__A )
						snake_case__				:   Dict     =						self._consolidate(__A )
						return column






					def  _lowercase  (      self  :						str							,	__A  :						pa.Table ):
						snake_case__				:   Any     =						self.numpy_arrow_extractor().extract_batch(__A )
						snake_case__				:   int     =						self.python_features_decoder.decode_batch(__A )
						snake_case__				:   List[Any]     =						self.recursive_tensorize(__A )
						for column_name in batch:
							snake_case__				:   Any     =						self._consolidate(batch[column_name] )
						return batch



