


'''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


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

lowerCamelCase							:   Dict  						=	'\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'
@dataclass
class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






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






class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      def __init__(self    :    Union[str, Any]   ,						UpperCamelCase    :    PriorTransformer   ,						UpperCamelCase    :    CLIPVisionModel   ,						UpperCamelCase    :    CLIPImageProcessor   ,						UpperCamelCase    :    HeunDiscreteScheduler   ,						UpperCamelCase    :    ShapERenderer   ,						):

             '''simple docstring'''







             super().__init__()

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



      def       UpperCamelCase__		(self    :    str   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    Dict   ,						UpperCamelCase    :    int   ,						UpperCamelCase    :    Tuple   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    Any ):

             '''simple docstring'''







             if latents is None:
                    lowercase__      			= 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}" )
                    lowercase__      			= latents.to(UpperCamelCase )

             lowercase__      			= latents * scheduler.init_noise_sigma
             return latents



      def       UpperCamelCase__		(self    :    Union[str, Any]   ,						UpperCamelCase    :    Any=0 ):

             '''simple docstring'''







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

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

             lowercase__      			= [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    :    str ):

             '''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(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    :    Tuple   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    Union[str, Any]   ,						UpperCamelCase    :    Any   ,						):

             '''simple docstring'''







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

             if not isinstance(UpperCamelCase   ,						torch.Tensor ):
                    lowercase__      			= self.image_processor(UpperCamelCase   ,						return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 )

             lowercase__      			= image.to(dtype=self.image_encoder.dtype   ,						device=UpperCamelCase )

             lowercase__      			= self.image_encoder(UpperCamelCase )['''last_hidden_state''']
             lowercase__      			= image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

             lowercase__      			= image_embeds.repeat_interleave(UpperCamelCase   ,						dim=0 )

             if do_classifier_free_guidance:
                    lowercase__      			= 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
                    lowercase__      			= torch.cat([negative_image_embeds, image_embeds] )

             return image_embeds






      @torch.no_grad()
      @replace_example_docstring(UpperCamelCase )
      def __call__(self    :    str   ,						UpperCamelCase    :    Union[PIL.Image.Image, List[PIL.Image.Image]]   ,						UpperCamelCase    :    int = 1   ,						UpperCamelCase    :    int = 25   ,						UpperCamelCase    :    Optional[Union[torch.Generator, List[torch.Generator]]] = None   ,						UpperCamelCase    :    Optional[torch.FloatTensor] = None   ,						UpperCamelCase    :    float = 4.0   ,						UpperCamelCase    :    int = 64   ,						UpperCamelCase    :    Optional[str] = "pil"   ,						UpperCamelCase    :    bool = True   ,						):

             '''simple docstring'''







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

             lowercase__      			= self._execution_device

             lowercase__      			= batch_size * num_images_per_prompt

             lowercase__      			= guidance_scale > 1.0
             lowercase__      			= self._encode_image(UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase )

             # prior

             self.scheduler.set_timesteps(UpperCamelCase   ,						device=UpperCamelCase )
             lowercase__      			= self.scheduler.timesteps

             lowercase__      			= self.prior.config.num_embeddings
             lowercase__      			= self.prior.config.embedding_dim

             lowercase__      			= 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
             lowercase__      			= 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
                    lowercase__      			= torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
                    lowercase__      			= self.scheduler.scale_model_input(UpperCamelCase   ,						UpperCamelCase )

                    lowercase__      			= self.prior(
                        UpperCamelCase   ,						timestep=UpperCamelCase   ,						proj_embedding=UpperCamelCase   ,						).predicted_image_embedding

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

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

                    lowercase__      			= self.scheduler.step(
                        UpperCamelCase   ,						timestep=UpperCamelCase   ,						sample=UpperCamelCase   ,						).prev_sample

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

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

                    images.append(UpperCamelCase )

             lowercase__      			= 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}" )

             lowercase__      			= images.cpu().numpy()

             if output_type == "pil":
                    lowercase__      			= [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 )










import os
import shutil
from pathlib import Path
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging


if is_onnx_available():
       import onnxruntime as ort


UpperCAmelCase_									=	logging.get_logger(__name__)

UpperCAmelCase_									=	{
    'tensor(bool)': np.bool_,
    'tensor(int8)': np.inta,
    'tensor(uint8)': np.uinta,
    'tensor(int16)': np.intaa,
    'tensor(uint16)': np.uintaa,
    'tensor(int32)': np.intaa,
    'tensor(uint32)': np.uintaa,
    'tensor(int64)': np.intaa,
    'tensor(uint64)': np.uintaa,
    'tensor(float16)': np.floataa,
    'tensor(float)': np.floataa,
    'tensor(double)': np.floataa,
}





class     lowerCamelCase__:
      def __init__(				self: str    ,       UpperCamelCase_: List[Any]=None    ,       **UpperCamelCase_: str   ):
             logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future."""   )
             __lowerCamelCase   =						model
             __lowerCamelCase   =						kwargs.get("""model_save_dir"""    ,       UpperCamelCase_   )
             __lowerCamelCase   =						kwargs.get("""latest_model_name"""    ,       UpperCamelCase_   )
      def __call__(				self: Dict    ,       **UpperCamelCase_: Any   ):
             __lowerCamelCase   =						{k: np.array(UpperCamelCase_   ) for k, v in kwargs.items()}
             return self.model.run(UpperCamelCase_    ,       UpperCamelCase_   )
      @staticmethod
      def 			lowerCAmelCase__						(				UpperCamelCase_: Union[str, Path]    ,       UpperCamelCase_: Tuple=None    ,       UpperCamelCase_: Tuple=None   ):
             if provider is None:
                    logger.info("""No onnxruntime provider specified, using CPUExecutionProvider"""   )
                    __lowerCamelCase   =						"""CPUExecutionProvider"""

             return ort.InferenceSession(UpperCamelCase_    ,       providers=[provider]    ,       sess_options=UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: int    ,       UpperCamelCase_: Union[str, Path]    ,       UpperCamelCase_: Optional[str] = None    ,       **UpperCamelCase_: Optional[int]   ):
             __lowerCamelCase   =						file_name if file_name is not None else ONNX_WEIGHTS_NAME

             __lowerCamelCase   =						self.model_save_dir.joinpath(self.latest_model_name   )
             __lowerCamelCase   =						Path(UpperCamelCase_   ).joinpath(UpperCamelCase_   )
             try:
                    shutil.copyfile(UpperCamelCase_    ,       UpperCamelCase_   )
             except shutil.SameFileError:
                    pass

             # copy external weights (for models >2GB)
             __lowerCamelCase   =						self.model_save_dir.joinpath(UpperCamelCase_   )
             if src_path.exists():
                    __lowerCamelCase   =						Path(UpperCamelCase_   ).joinpath(UpperCamelCase_   )
                    try:
                           shutil.copyfile(UpperCamelCase_    ,       UpperCamelCase_   )
                    except shutil.SameFileError:
                           pass
      def 			lowerCAmelCase__						(				self: List[Any]    ,       UpperCamelCase_: Union[str, os.PathLike]    ,       **UpperCamelCase_: Optional[Any]    ,       ):
             if os.path.isfile(UpperCamelCase_   ):
                    logger.error(F'Provided path ({save_directory}) should be a directory, not a file'   )
                    return

             os.makedirs(UpperCamelCase_    ,       exist_ok=UpperCamelCase_   )

             # saving model weights/files
             self._save_pretrained(UpperCamelCase_    ,       **UpperCamelCase_   )
      @classmethod
      def 			lowerCAmelCase__						(				cls: str    ,       UpperCamelCase_: Union[str, Path]    ,       UpperCamelCase_: Optional[Union[bool, str, None]] = None    ,       UpperCamelCase_: Optional[Union[str, None]] = None    ,       UpperCamelCase_: bool = False    ,       UpperCamelCase_: Optional[str] = None    ,       UpperCamelCase_: Optional[str] = None    ,       UpperCamelCase_: Optional[str] = None    ,       UpperCamelCase_: Optional["ort.SessionOptions"] = None    ,       **UpperCamelCase_: int    ,       ):
             __lowerCamelCase   =						file_name if file_name is not None else ONNX_WEIGHTS_NAME
             # load model from local directory
             if os.path.isdir(UpperCamelCase_   ):
                    __lowerCamelCase   =						OnnxRuntimeModel.load_model(
                        os.path.join(UpperCamelCase_    ,       UpperCamelCase_   )    ,       provider=UpperCamelCase_    ,       sess_options=UpperCamelCase_   )
                    __lowerCamelCase   =						Path(UpperCamelCase_   )
             # load model from hub
             else:
                    # download model
                    __lowerCamelCase   =						hf_hub_download(
                        repo_id=UpperCamelCase_    ,       filename=UpperCamelCase_    ,       use_auth_token=UpperCamelCase_    ,       revision=UpperCamelCase_    ,       cache_dir=UpperCamelCase_    ,       force_download=UpperCamelCase_    ,       )
                    __lowerCamelCase   =						Path(UpperCamelCase_   ).parent
                    __lowerCamelCase   =						Path(UpperCamelCase_   ).name
                    __lowerCamelCase   =						OnnxRuntimeModel.load_model(UpperCamelCase_    ,       provider=UpperCamelCase_    ,       sess_options=UpperCamelCase_   )
             return cls(model=UpperCamelCase_    ,       **UpperCamelCase_   )




      @classmethod
      def 			lowerCAmelCase__						(				cls: Optional[int]    ,       UpperCamelCase_: Union[str, Path]    ,       UpperCamelCase_: bool = True    ,       UpperCamelCase_: Optional[str] = None    ,       UpperCamelCase_: Optional[str] = None    ,       **UpperCamelCase_: int    ,       ):
             __lowerCamelCase   =						None
             if len(str(UpperCamelCase_   ).split("""@"""   )   ) == 2:
                    __lowerCamelCase,   __lowerCamelCase   =						model_id.split("""@"""   )

             return cls._from_pretrained(
                 model_id=UpperCamelCase_    ,       revision=UpperCamelCase_    ,       cache_dir=UpperCamelCase_    ,       force_download=UpperCamelCase_    ,       use_auth_token=UpperCamelCase_    ,       **UpperCamelCase_    ,       )

