





"""simple docstring"""


import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig

from diffusers import AutoencoderKL, PaintByExamplePipeline, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class        lowercase_			(       __lowerCAmelCase			,unittest.TestCase							):
       snake_case__			:							Tuple										=       PaintByExamplePipeline
       snake_case__			:							List[str]										=       IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
       snake_case__			:							List[str]										=       IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
       snake_case__			:							List[str]										=       frozenset([]							)  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess

       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        torch.manual_seed(0       )
        snake_case__      							=			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				,   )
        snake_case__      							=			PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE       )
        torch.manual_seed(0       )
        snake_case__      							=			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				,   )
        torch.manual_seed(0       )
        snake_case__      							=			CLIPVisionConfig(
            hidden_size=32				,   projection_dim=32				,   intermediate_size=37				,   layer_norm_eps=1e-05				,   num_attention_heads=4				,   num_hidden_layers=5				,   image_size=32				,   patch_size=4				,   )
        snake_case__      							=			PaintByExampleImageEncoder(__SCREAMING_SNAKE_CASE				,   proj_size=32       )
        snake_case__      							=			CLIPImageProcessor(crop_size=32				,   size=32       )

        snake_case__      							=			{
            "unet": unet,
            "scheduler": scheduler,
            "vae": vae,
            "image_encoder": image_encoder,
            "safety_checker": None,
            "feature_extractor": feature_extractor,
        }
        return components

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE       ):






        '''simple docstring'''

        snake_case__      							=			np.array(image.convert("RGB"       )       )
        snake_case__      							=			image[None].transpose(0				,   3				,   1				,   2       )
        snake_case__      							=			torch.from_numpy(__SCREAMING_SNAKE_CASE       ).to(dtype=torch.floataa       ) / 127.5 - 1.0
        return image

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE="cpu"				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

        snake_case__      							=			floats_tensor((1, 3, 32, 32)				,   rng=random.Random(__SCREAMING_SNAKE_CASE       )       ).to(__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			image.cpu().permute(0				,   2				,   3				,   1       )[0]
        snake_case__      							=			Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE       )       ).convert("RGB"       ).resize((64, 64)       )
        snake_case__      							=			Image.fromarray(np.uinta(image + 4       )       ).convert("RGB"       ).resize((64, 64)       )
        snake_case__      							=			Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE       )       ).convert("RGB"       ).resize((32, 32)       )

        if str(__SCREAMING_SNAKE_CASE       ).startswith("mps"       ):
         snake_case__      							=			torch.manual_seed(__SCREAMING_SNAKE_CASE       )
        else:
         snake_case__      							=			torch.Generator(device=__SCREAMING_SNAKE_CASE       ).manual_seed(__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			{
            "example_image": example_image,
            "image": init_image,
            "mask_image": mask_image,
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 6.0,
            "output_type": "numpy",
        }
        return inputs

       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        snake_case__      							=			self.get_dummy_components()

        # make sure here that pndm scheduler skips prk
        snake_case__      							=			PaintByExamplePipeline(**__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			pipe.to("cpu"       )
        pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			self.get_dummy_inputs()
        snake_case__      							=			pipe(**__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			output.images

        snake_case__      							=			image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        snake_case__      							=			np.array([0.4686, 0.5687, 0.4007, 0.5218, 0.5741, 0.4482, 0.4940, 0.4629, 0.4503]       )

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

       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        snake_case__      							=			"cpu"
        snake_case__      							=			self.get_dummy_inputs()
        inputs.pop("mask_image"       )
        snake_case__      							=			self.convert_to_pt(inputs.pop("image"       )       )
        snake_case__      							=			image.clamp(0				,   1       ) / 2

        # make sure here that pndm scheduler skips prk
        snake_case__      							=			PaintByExamplePipeline(**self.get_dummy_components()       )
        snake_case__      							=			pipe.to(__SCREAMING_SNAKE_CASE       )
        pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			pipe(image=__SCREAMING_SNAKE_CASE				,   mask_image=mask_image[:, 0]				,   **__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			output.images

        snake_case__      							=			image.cpu().permute(0				,   2				,   3				,   1       )[0]
        snake_case__      							=			mask_image.cpu().permute(0				,   2				,   3				,   1       )[0]

        snake_case__      							=			Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE       )       ).convert("RGB"       )
        snake_case__      							=			Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE       )       ).convert("RGB"       )

        snake_case__      							=			pipe(**self.get_dummy_inputs()       )
        snake_case__      							=			output.images

        assert out_a.shape == (1, 64, 64, 3)
        assert np.abs(out_a.flatten() - out_a.flatten()       ).max() < 5e-2

       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

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



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

       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

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

       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        snake_case__      							=			load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/paint_by_example/dog_in_bucket.png"       )
        snake_case__      							=			load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/paint_by_example/mask.png"       )
        snake_case__      							=			load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/paint_by_example/panda.jpg"       )

        snake_case__      							=			PaintByExamplePipeline.from_pretrained("Fantasy-Studio/Paint-by-Example"       )
        snake_case__      							=			pipe.to(__SCREAMING_SNAKE_CASE       )
        pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			torch.manual_seed(321       )
        snake_case__      							=			pipe(
            image=__SCREAMING_SNAKE_CASE				,   mask_image=__SCREAMING_SNAKE_CASE				,   example_image=__SCREAMING_SNAKE_CASE				,   generator=__SCREAMING_SNAKE_CASE				,   guidance_scale=5.0				,   num_inference_steps=50				,   output_type="np"				,   )

        snake_case__      							=			output.images

        snake_case__      							=			image[0, -3:, -3:, -1]

        assert image.shape == (1, 512, 512, 3)
        snake_case__      							=			np.array([0.4834, 0.4811, 0.4874, 0.5122, 0.5081, 0.5144, 0.5291, 0.5290, 0.5374]       )

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








"""simple docstring"""


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

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

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


a__   :       Optional[Any]   						=			logging.get_logger(__name__)  # pylint: disable=invalid-name

a__   :       Tuple   						=			"""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

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

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

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

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

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""



@dataclass
class        lowercase_			(       __lowerCAmelCase							):
       snake_case__			:							Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]



class        lowercase_			(       __lowerCAmelCase							):

       def __init__(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   ):






        '''simple docstring'''

        super().__init__()

        self.register_modules(
            prior=__SCREAMING_SNAKE_CASE				,   text_encoder=__SCREAMING_SNAKE_CASE				,   tokenizer=__SCREAMING_SNAKE_CASE				,   scheduler=__SCREAMING_SNAKE_CASE				,   renderer=__SCREAMING_SNAKE_CASE				,   )

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):






        '''simple docstring'''

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

        snake_case__      							=			latents * scheduler.init_noise_sigma
        return latents

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

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

        snake_case__      							=			torch.device(F"cuda:{gpu_id}"       )

        snake_case__      							=			[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
         if cpu_offloaded_model is not None:
          cpu_offload(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

        if is_accelerate_available() and is_accelerate_version(">="				,   "0.17.0.dev0"       ):
         from accelerate import cpu_offload_with_hook
        else:
         raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."       )

        snake_case__      							=			torch.device(F"cuda:{gpu_id}"       )

        if self.device.type != "cpu":
         self.to("cpu"				,   silence_dtype_warnings=__SCREAMING_SNAKE_CASE       )
         torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        snake_case__      							=			None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
         snake_case__							,				snake_case__      							=			cpu_offload_with_hook(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   prev_module_hook=__SCREAMING_SNAKE_CASE       )

        if self.safety_checker is not None:
         snake_case__							,				snake_case__      							=			cpu_offload_with_hook(self.safety_checker				,   __SCREAMING_SNAKE_CASE				,   prev_module_hook=__SCREAMING_SNAKE_CASE       )

        # We'll offload the last model manually.
        snake_case__      							=			hook

       @property
       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        if self.device != torch.device("meta"       ) or not hasattr(self.text_encoder				,   "_hf_hook"       ):
         return self.device
        for module in self.text_encoder.modules():
         if (
             hasattr(__SCREAMING_SNAKE_CASE				,   "_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 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   ):






        '''simple docstring'''

        len(__SCREAMING_SNAKE_CASE       ) if isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        snake_case__      							=			0
        # get prompt text embeddings
        snake_case__      							=			self.tokenizer(
            __SCREAMING_SNAKE_CASE				,   padding="max_length"				,   max_length=self.tokenizer.model_max_length				,   truncation=__SCREAMING_SNAKE_CASE				,   return_tensors="pt"				,   )
        snake_case__      							=			text_inputs.input_ids
        snake_case__      							=			self.tokenizer(__SCREAMING_SNAKE_CASE				,   padding="longest"				,   return_tensors="pt"       ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]       )
         logger.warning(
             "The following part of your input was truncated because CLIP can only handle sequences up to"
             F" {self.tokenizer.model_max_length} tokens: {removed_text}"       )

        snake_case__      							=			self.text_encoder(text_input_ids.to(__SCREAMING_SNAKE_CASE       )       )
        snake_case__      							=			text_encoder_output.text_embeds

        snake_case__      							=			prompt_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE				,   dim=0       )
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        snake_case__      							=			prompt_embeds / torch.linalg.norm(__SCREAMING_SNAKE_CASE				,   dim=-1				,   keepdim=__SCREAMING_SNAKE_CASE       )

        if do_classifier_free_guidance:
         snake_case__      							=			torch.zeros_like(__SCREAMING_SNAKE_CASE       )

         # 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
         snake_case__      							=			torch.cat([negative_prompt_embeds, prompt_embeds]       )

        # Rescale the features to have unit variance
        snake_case__      							=			math.sqrt(prompt_embeds.shape[1]       ) * prompt_embeds

        return prompt_embeds

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






        '''simple docstring'''

        if isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			1
        elif isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			len(__SCREAMING_SNAKE_CASE       )
        else:
         raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__SCREAMING_SNAKE_CASE       )}"       )

        snake_case__      							=			self._execution_device

        snake_case__      							=			batch_size * num_images_per_prompt

        snake_case__      							=			guidance_scale > 1.0
        snake_case__      							=			self._encode_prompt(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

        # prior

        self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE				,   device=__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			self.scheduler.timesteps

        snake_case__      							=			self.prior.config.num_embeddings
        snake_case__      							=			self.prior.config.embedding_dim

        snake_case__      							=			self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)				,   prompt_embeds.dtype				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   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
        snake_case__      							=			latents.reshape(latents.shape[0]				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

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

         snake_case__      							=			self.prior(
             __SCREAMING_SNAKE_CASE				,   timestep=__SCREAMING_SNAKE_CASE				,   proj_embedding=__SCREAMING_SNAKE_CASE				,   ).predicted_image_embedding

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

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

         snake_case__      							=			self.scheduler.step(
             __SCREAMING_SNAKE_CASE				,   timestep=__SCREAMING_SNAKE_CASE				,   sample=__SCREAMING_SNAKE_CASE				,   ).prev_sample

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

        snake_case__      							=			[]
        for i, latent in enumerate(__SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			self.renderer.decode(
             latent[None, :]				,   __SCREAMING_SNAKE_CASE				,   size=__SCREAMING_SNAKE_CASE				,   ray_batch_size=4096				,   n_coarse_samples=64				,   n_fine_samples=128				,   )
         images.append(__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			torch.stack(__SCREAMING_SNAKE_CASE       )

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

        snake_case__      							=			images.cpu().numpy()

        if output_type == "pil":
         snake_case__      							=			[self.numpy_to_pil(__SCREAMING_SNAKE_CASE       ) 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=__SCREAMING_SNAKE_CASE       )

