






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


lowerCamelCase			:					str         =	logging.get_logger(__name__)



class 							_UpperCamelCase			(__UpperCAmelCase			):
      snake_case_	  =							["""pixel_values"""]


      def __init__(	self					,						__UpperCamelCase = True					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = PILImageResampling.BILINEAR					,						__UpperCamelCase = True					,						__UpperCamelCase = 1 / 2_5_5					,						__UpperCamelCase = True					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						**__UpperCamelCase					,						)->	str:
           super().__init__(**lowerCAmelCase_	)
           __lowerCAmelCase								=					size if size is not None else {"shortest_edge": 3_8_4}
           __lowerCAmelCase								=					get_size_dict(lowerCAmelCase_					,						default_to_square=lowerCAmelCase_	)

           __lowerCAmelCase								=					do_resize
           __lowerCAmelCase								=					size
           # Default value set here for backwards compatibility where the value in config is None
           __lowerCAmelCase								=					crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
           __lowerCAmelCase								=					resample
           __lowerCAmelCase								=					do_rescale
           __lowerCAmelCase								=					rescale_factor
           __lowerCAmelCase								=					do_normalize
           __lowerCAmelCase								=					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
           __lowerCAmelCase								=					image_std if image_std is not None else IMAGENET_STANDARD_STD


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase = PILImageResampling.BICUBIC					,						__UpperCamelCase = None					,						**__UpperCamelCase					,						)->	Union[str, Any]:
           __lowerCAmelCase								=					get_size_dict(lowerCAmelCase_					,						default_to_square=lowerCAmelCase_	)
           if "shortest_edge" not in size:
                raise ValueError(F"""Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}"""	)
           __lowerCAmelCase								=					size["shortest_edge"]

           if shortest_edge < 3_8_4:
                # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
                __lowerCAmelCase								=					int(shortest_edge / crop_pct	)
                __lowerCAmelCase								=					get_resize_output_image_size(lowerCAmelCase_					,						size=lowerCAmelCase_					,						default_to_square=lowerCAmelCase_	)
                __lowerCAmelCase								=					resize(image=lowerCAmelCase_					,						size=lowerCAmelCase_					,						resample=lowerCAmelCase_					,						data_format=lowerCAmelCase_					,						**lowerCAmelCase_	)
                # then crop to (shortest_edge, shortest_edge)
                return center_crop(image=lowerCAmelCase_					,						size=(shortest_edge, shortest_edge)					,						data_format=lowerCAmelCase_					,						**lowerCAmelCase_	)
           else:
                # warping (no cropping) when evaluated at 384 or larger
                return resize(
                    lowerCAmelCase_					,						size=(shortest_edge, shortest_edge)					,						resample=lowerCAmelCase_					,						data_format=lowerCAmelCase_					,						**lowerCAmelCase_	)


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase = None					,						**__UpperCamelCase					,						)->	Union[str, Any]:
           return rescale(lowerCAmelCase_					,						scale=lowerCAmelCase_					,						data_format=lowerCAmelCase_					,						**lowerCAmelCase_	)


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase = None					,						**__UpperCamelCase					,						)->	Dict:
           return normalize(lowerCAmelCase_					,						mean=lowerCAmelCase_					,						std=lowerCAmelCase_					,						data_format=lowerCAmelCase_					,						**lowerCAmelCase_	)


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = ChannelDimension.FIRST					,						**__UpperCamelCase					,						)->	Tuple:
           __lowerCAmelCase								=					do_resize if do_resize is not None else self.do_resize
           __lowerCAmelCase								=					crop_pct if crop_pct is not None else self.crop_pct
           __lowerCAmelCase								=					resample if resample is not None else self.resample
           __lowerCAmelCase								=					do_rescale if do_rescale is not None else self.do_rescale
           __lowerCAmelCase								=					rescale_factor if rescale_factor is not None else self.rescale_factor
           __lowerCAmelCase								=					do_normalize if do_normalize is not None else self.do_normalize
           __lowerCAmelCase								=					image_mean if image_mean is not None else self.image_mean
           __lowerCAmelCase								=					image_std if image_std is not None else self.image_std

           __lowerCAmelCase								=					size if size is not None else self.size
           __lowerCAmelCase								=					get_size_dict(lowerCAmelCase_					,						default_to_square=lowerCAmelCase_	)

           __lowerCAmelCase								=					make_list_of_images(lowerCAmelCase_	)

           if not valid_images(lowerCAmelCase_	):
                raise ValueError(
                    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                    "torch.Tensor, tf.Tensor or jax.ndarray."	)

           if do_resize and size is None or resample is None:
                raise ValueError("Size and resample must be specified if do_resize is True."	)

           if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
                raise ValueError("crop_pct must be specified if size < 384."	)

           if do_rescale and rescale_factor is None:
                raise ValueError("Rescale factor must be specified if do_rescale is True."	)

           if do_normalize and (image_mean is None or image_std is None):
                raise ValueError("Image mean and std must be specified if do_normalize is True."	)

           # All transformations expect numpy arrays.
           __lowerCAmelCase								=					[to_numpy_array(lowerCAmelCase_	) for image in images]

           if do_resize:
                __lowerCAmelCase								=					[self.resize(image=lowerCAmelCase_					,						size=lowerCAmelCase_					,						crop_pct=lowerCAmelCase_					,						resample=lowerCAmelCase_	) for image in images]

           if do_rescale:
                __lowerCAmelCase								=					[self.rescale(image=lowerCAmelCase_					,						scale=lowerCAmelCase_	) for image in images]

           if do_normalize:
                __lowerCAmelCase								=					[self.normalize(image=lowerCAmelCase_					,						mean=lowerCAmelCase_					,						std=lowerCAmelCase_	) for image in images]

           __lowerCAmelCase								=					[to_channel_dimension_format(lowerCAmelCase_					,						lowerCAmelCase_	) for image in images]

           __lowerCAmelCase								=					{"pixel_values": images}
           return BatchFeature(data=lowerCAmelCase_					,						tensor_type=lowerCAmelCase_	)














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


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

lowerCamelCase			:					str         =	'''
    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 							_UpperCamelCase			(a_			):
      snake_case_  =							42



class 							_UpperCamelCase			(a_			):


      def __init__(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						)->	Dict:
           super().__init__()

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


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)->	Union[str, Any]:
           if latents is None:
                __lowerCAmelCase								=					randn_tensor(__UpperCamelCase					,						generator=__UpperCamelCase					,						device=__UpperCamelCase					,						dtype=__UpperCamelCase	)
           else:
                if latents.shape != shape:
                     raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""	)
                __lowerCAmelCase								=					latents.to(__UpperCamelCase	)

           __lowerCAmelCase								=					latents * scheduler.init_noise_sigma
           return latents


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase=0	)->	str:
           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(__UpperCamelCase					,						__UpperCamelCase	)


      @property
      def  __UpperCAmelCase		(	self	)->	List[str]:
           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(__UpperCamelCase					,						"_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  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						)->	Union[str, Any]:
           if isinstance(__UpperCamelCase					,						__UpperCamelCase	) and isinstance(image[0]					,						torch.Tensor	):
                __lowerCAmelCase								=					torch.cat(__UpperCamelCase					,						axis=0	) if image[0].ndim == 4 else torch.stack(__UpperCamelCase					,						axis=0	)

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

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

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

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

           if do_classifier_free_guidance:
                __lowerCAmelCase								=					torch.zeros_like(__UpperCamelCase	)

                # 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(__UpperCamelCase	)
      def __call__(	self					,						__UpperCamelCase					,						__UpperCamelCase = 1					,						__UpperCamelCase = 2_5					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = 4.0					,						__UpperCamelCase = 6_4					,						__UpperCamelCase = "pil"					,						__UpperCamelCase = True					,						)->	Dict:

           if isinstance(__UpperCamelCase					,						PIL.Image.Image	):
                __lowerCAmelCase								=					1
           elif isinstance(__UpperCamelCase					,						torch.Tensor	):
                __lowerCAmelCase								=					image.shape[0]
           elif isinstance(__UpperCamelCase					,						__UpperCamelCase	) and isinstance(image[0]					,						(torch.Tensor, PIL.Image.Image)	):
                __lowerCAmelCase								=					len(__UpperCamelCase	)
           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(__UpperCamelCase	)}"""	)

           __lowerCAmelCase								=					self._execution_device

           __lowerCAmelCase								=					batch_size * num_images_per_prompt

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

           # prior

           self.scheduler.set_timesteps(__UpperCamelCase					,						device=__UpperCamelCase	)
           __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					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						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]					,						__UpperCamelCase					,						__UpperCamelCase	)

           for i, t in enumerate(self.progress_bar(__UpperCamelCase	)	):
                # 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(__UpperCamelCase					,						__UpperCamelCase	)

                __lowerCAmelCase								=					self.prior(
                    __UpperCamelCase					,						timestep=__UpperCamelCase					,						proj_embedding=__UpperCamelCase					,						).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(
                    __UpperCamelCase					,						timestep=__UpperCamelCase					,						sample=__UpperCamelCase					,						).prev_sample

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

           __lowerCAmelCase								=					[]
           for i, latent in enumerate(__UpperCamelCase	):
                print()
                __lowerCAmelCase								=					self.renderer.decode(
                    latent[None, :]					,						__UpperCamelCase					,						size=__UpperCamelCase					,						ray_batch_size=4_0_9_6					,						n_coarse_samples=6_4					,						n_fine_samples=1_2_8					,						)

                images.append(__UpperCamelCase	)

           __lowerCAmelCase								=					torch.stack(__UpperCamelCase	)

           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(__UpperCamelCase	) 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=__UpperCamelCase	)






