'''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 							a__(   lowerCAmelCase__					,		lowerCAmelCase__					,		lowerCAmelCase__					,		unittest.TestCase      ):


			'''simple docstring'''






			UpperCAmelCase_     :	Any						=			StableDiffusionInpaintPipeline
			UpperCAmelCase_     :	int						=			TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
			UpperCAmelCase_     :	Dict						=			TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
			UpperCAmelCase_     :	Dict						=			frozenset(
			    []      )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
			UpperCAmelCase_     :	List[str]						=			frozenset([]      )



			def 				a_			(  self):




					"""simple docstring"""


					torch.manual_seed(0)
					lowerCAmelCase     =    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			,       )
					lowerCAmelCase     =    PNDMScheduler(skip_prk_steps=__lowerCAmelCase)
					torch.manual_seed(0)
					lowerCAmelCase     =    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)
					lowerCAmelCase     =    CLIPTextConfig(
					    bos_token_id=0			,       eos_token_id=2			,       hidden_size=32			,       intermediate_size=37			,       layer_norm_eps=1E-0_5			,       num_attention_heads=4			,       num_hidden_layers=5			,       pad_token_id=1			,       vocab_size=1000			,       hidden_act="""gelu"""			,       projection_dim=512			,       )
					lowerCAmelCase     =    CLIPTextModel(__lowerCAmelCase)
					lowerCAmelCase     =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

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



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase=0):




					"""simple docstring"""


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




					"""simple docstring"""


					lowerCAmelCase     =    """cpu"""  # ensure determinism for the device-dependent torch.Generator
					lowerCAmelCase     =    self.get_dummy_components()
					lowerCAmelCase     =    StableDiffusionInpaintPipeline(**__lowerCAmelCase)
					lowerCAmelCase     =    sd_pipe.to(__lowerCAmelCase)
					sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase)

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

					assert image.shape == (1, 64, 64, 3)
					lowerCAmelCase     =    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 				a_			(  self):




					"""simple docstring"""


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







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


			'''simple docstring'''






			def 				a_			(  self):




					"""simple docstring"""


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



			def 				a_			(  self):




					"""simple docstring"""


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

					lowerCAmelCase     =    """stabilityai/stable-diffusion-2-inpainting"""
					lowerCAmelCase     =    StableDiffusionInpaintPipeline.from_pretrained(__lowerCAmelCase			,       safety_checker=__lowerCAmelCase)
					pipe.to(__lowerCAmelCase)
					pipe.set_progress_bar_config(disable=__lowerCAmelCase)
					pipe.enable_attention_slicing()

					lowerCAmelCase     =    """Face of a yellow cat, high resolution, sitting on a park bench"""

					lowerCAmelCase     =    torch.manual_seed(0)
					lowerCAmelCase     =    pipe(
					    prompt=__lowerCAmelCase			,       image=__lowerCAmelCase			,       mask_image=__lowerCAmelCase			,       generator=__lowerCAmelCase			,       output_type="""np"""			,       )
					lowerCAmelCase     =    output.images[0]

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



			def 				a_			(  self):




					"""simple docstring"""


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

					lowerCAmelCase     =    """stabilityai/stable-diffusion-2-inpainting"""
					lowerCAmelCase     =    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()

					lowerCAmelCase     =    """Face of a yellow cat, high resolution, sitting on a park bench"""

					lowerCAmelCase     =    torch.manual_seed(0)
					lowerCAmelCase     =    pipe(
					    prompt=__lowerCAmelCase			,       image=__lowerCAmelCase			,       mask_image=__lowerCAmelCase			,       generator=__lowerCAmelCase			,       output_type="""np"""			,       )
					lowerCAmelCase     =    output.images[0]

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







			def 				a_			(  self):




					"""simple docstring"""


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

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

					lowerCAmelCase     =    """stabilityai/stable-diffusion-2-inpainting"""
					lowerCAmelCase     =    PNDMScheduler.from_pretrained(__lowerCAmelCase			,       subfolder="""scheduler""")
					lowerCAmelCase     =    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()

					lowerCAmelCase     =    """Face of a yellow cat, high resolution, sitting on a park bench"""

					lowerCAmelCase     =    torch.manual_seed(0)
					lowerCAmelCase     =    pipe(
					    prompt=__lowerCAmelCase			,       image=__lowerCAmelCase			,       mask_image=__lowerCAmelCase			,       generator=__lowerCAmelCase			,       num_inference_steps=2			,       output_type="""np"""			,       )

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





'''simple docstring'''




from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

__lowercase        =    '''
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e-img2img"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"
        >>> image = load_image(image_url).convert("RGB")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")
        ```
'''






@dataclass
class 							a__(   lowerCAmelCase__      ):


			'''simple docstring'''






			UpperCAmelCase_     :	Union[PIL.Image.Image, np.ndarray]







class 							a__(   lowerCAmelCase__      ):


			'''simple docstring'''






			def __init__(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       ):




					"""simple docstring"""


					super().__init__()

					self.register_modules(
					    prior=__lowerCAmelCase			,       image_encoder=__lowerCAmelCase			,       image_processor=__lowerCAmelCase			,       scheduler=__lowerCAmelCase			,       renderer=__lowerCAmelCase			,       )



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase):




					"""simple docstring"""


					if latents is None:
							lowerCAmelCase     =    randn_tensor(__lowerCAmelCase			,       generator=__lowerCAmelCase			,       device=__lowerCAmelCase			,       dtype=__lowerCAmelCase)
					else:
							if latents.shape != shape:
									raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
							lowerCAmelCase     =    latents.to(__lowerCAmelCase)

					lowerCAmelCase     =    latents * scheduler.init_noise_sigma
					return latents



			def 				a_			(  self			,       __lowerCAmelCase=0):




					"""simple docstring"""


					if is_accelerate_available():
							from accelerate import cpu_offload
					else:
							raise ImportError("""Please install accelerate via `pip install accelerate`""")

					lowerCAmelCase     =    torch.device(f"cuda:{gpu_id}")

					lowerCAmelCase     =    [self.image_encoder, self.prior]
					for cpu_offloaded_model in models:
							if cpu_offloaded_model is not None:
									cpu_offload(__lowerCAmelCase			,       __lowerCAmelCase)



			@property
			def 				a_			(  self):




					"""simple docstring"""


					if self.device != torch.device("""meta""") or not hasattr(self.image_encoder			,       """_hf_hook"""):
							return self.device
					for module in self.image_encoder.modules():
							if (
							    hasattr(__lowerCAmelCase			,       """_hf_hook""")
							    and hasattr(module._hf_hook			,       """execution_device""")
							    and module._hf_hook.execution_device is not None
							):
									return torch.device(module._hf_hook.execution_device)
					return self.device



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       ):




					"""simple docstring"""


					if isinstance(__lowerCAmelCase			,       __lowerCAmelCase) and isinstance(image[0]			,       torch.Tensor):
							lowerCAmelCase     =    torch.cat(__lowerCAmelCase			,       axis=0) if image[0].ndim == 4 else torch.stack(__lowerCAmelCase			,       axis=0)

					if not isinstance(__lowerCAmelCase			,       torch.Tensor):
							lowerCAmelCase     =    self.image_processor(__lowerCAmelCase			,       return_tensors="""pt""").pixel_values[0].unsqueeze(0)

					lowerCAmelCase     =    image.to(dtype=self.image_encoder.dtype			,       device=__lowerCAmelCase)

					lowerCAmelCase     =    self.image_encoder(__lowerCAmelCase)["""last_hidden_state"""]
					lowerCAmelCase     =    image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

					lowerCAmelCase     =    image_embeds.repeat_interleave(__lowerCAmelCase			,       dim=0)

					if do_classifier_free_guidance:
							lowerCAmelCase     =    torch.zeros_like(__lowerCAmelCase)

							# 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
							lowerCAmelCase     =    torch.cat([negative_image_embeds, image_embeds])

					return image_embeds







			@torch.no_grad()
			@replace_example_docstring(__lowerCAmelCase)
			def __call__(  self			,       __lowerCAmelCase			,       __lowerCAmelCase = 1			,       __lowerCAmelCase = 25			,       __lowerCAmelCase = None			,       __lowerCAmelCase = None			,       __lowerCAmelCase = 4.0			,       __lowerCAmelCase = 64			,       __lowerCAmelCase = "pil"			,       __lowerCAmelCase = True			,       ):




					"""simple docstring"""


					if isinstance(__lowerCAmelCase			,       PIL.Image.Image):
							lowerCAmelCase     =    1
					elif isinstance(__lowerCAmelCase			,       torch.Tensor):
							lowerCAmelCase     =    image.shape[0]
					elif isinstance(__lowerCAmelCase			,       __lowerCAmelCase) and isinstance(image[0]			,       (torch.Tensor, PIL.Image.Image)):
							lowerCAmelCase     =    len(__lowerCAmelCase)
					else:
							raise ValueError(
							    f"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__lowerCAmelCase)}")

					lowerCAmelCase     =    self._execution_device

					lowerCAmelCase     =    batch_size * num_images_per_prompt

					lowerCAmelCase     =    guidance_scale > 1.0
					lowerCAmelCase     =    self._encode_image(__lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase)

					# prior

					self.scheduler.set_timesteps(__lowerCAmelCase			,       device=__lowerCAmelCase)
					lowerCAmelCase     =    self.scheduler.timesteps

					lowerCAmelCase     =    self.prior.config.num_embeddings
					lowerCAmelCase     =    self.prior.config.embedding_dim

					lowerCAmelCase     =    self.prepare_latents(
					    (batch_size, num_embeddings * embedding_dim)			,       image_embeds.dtype			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       self.scheduler			,       )

					# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
					lowerCAmelCase     =    latents.reshape(latents.shape[0]			,       __lowerCAmelCase			,       __lowerCAmelCase)

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

							lowerCAmelCase     =    self.prior(
							    __lowerCAmelCase			,       timestep=__lowerCAmelCase			,       proj_embedding=__lowerCAmelCase			,       ).predicted_image_embedding

							# remove the variance
							lowerCAmelCase   ,	lowerCAmelCase     =    noise_pred.split(
							    scaled_model_input.shape[2]			,       dim=2)  # batch_size, num_embeddings, embedding_dim

							if do_classifier_free_guidance is not None:
									lowerCAmelCase   ,	lowerCAmelCase     =    noise_pred.chunk(2)
									lowerCAmelCase     =    noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							lowerCAmelCase     =    self.scheduler.step(
							    __lowerCAmelCase			,       timestep=__lowerCAmelCase			,       sample=__lowerCAmelCase			,       ).prev_sample

					if output_type == "latent":
							return ShapEPipelineOutput(images=__lowerCAmelCase)

					lowerCAmelCase     =    []
					for i, latent in enumerate(__lowerCAmelCase):
							print()
							lowerCAmelCase     =    self.renderer.decode(
							    latent[None, :]			,       __lowerCAmelCase			,       size=__lowerCAmelCase			,       ray_batch_size=4096			,       n_coarse_samples=64			,       n_fine_samples=128			,       )

							images.append(__lowerCAmelCase)

					lowerCAmelCase     =    torch.stack(__lowerCAmelCase)

					if output_type not in ["np", "pil"]:
							raise ValueError(f"Only the output types `pil` and `np` are supported not output_type={output_type}")

					lowerCAmelCase     =    images.cpu().numpy()

					if output_type == "pil":
							lowerCAmelCase     =    [self.numpy_to_pil(__lowerCAmelCase) for image in images]

					# Offload last model to CPU
					if hasattr(self			,       """final_offload_hook""") and self.final_offload_hook is not None:
							self.final_offload_hook.offload()

					if not return_dict:
							return (images,)

					return ShapEPipelineOutput(images=__lowerCAmelCase)




