



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


A:   List[str]								=		logging.get_logger(__name__)  # pylint: disable=invalid-name

A:   List[str]								=		"\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       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   Union[PIL.Image.Image, np.ndarray]



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     )  ->      Optional[Any]:





    '''simple docstring'''




    super().__init__()

    self.register_modules(
        prior=_SCREAMING_SNAKE_CASE      ,     image_encoder=_SCREAMING_SNAKE_CASE      ,     image_processor=_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						)  ->      int:





    '''simple docstring'''




    if latents is None:
     UpperCAmelCase	:					Union[str, Any]	=	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}"						)
     UpperCAmelCase	:					List[str]	=	latents.to(_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Any	=	latents * scheduler.init_noise_sigma
    return latents

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE=0						)  ->      List[str]:





    '''simple docstring'''




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

    UpperCAmelCase	:					List[str]	=	torch.device(F"cuda:{gpu_id}"						)

    UpperCAmelCase	:					Optional[Any]	=	[self.image_encoder, self.prior]
    for cpu_offloaded_model in models:
     if cpu_offloaded_model is not None:
      cpu_offload(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      List[Any]:





    '''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(_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      ,     )  ->      Any:





    '''simple docstring'''




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

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

    UpperCAmelCase	:					Optional[Any]	=	image.to(dtype=self.image_encoder.dtype      ,     device=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					str	=	self.image_encoder(_SCREAMING_SNAKE_CASE						)["""last_hidden_state"""]
    UpperCAmelCase	:					int	=	image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

    UpperCAmelCase	:					Optional[Any]	=	image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE      ,     dim=0						)

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

    return image_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      ,     )  ->      Optional[Any]:





    '''simple docstring'''




    if isinstance(_SCREAMING_SNAKE_CASE      ,     PIL.Image.Image						):
     UpperCAmelCase	:					List[str]	=	1
    elif isinstance(_SCREAMING_SNAKE_CASE      ,     torch.Tensor						):
     UpperCAmelCase	:					str	=	image.shape[0]
    elif isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) and isinstance(image[0]      ,     (torch.Tensor, PIL.Image.Image)						):
     UpperCAmelCase	:					Optional[int]	=	len(_SCREAMING_SNAKE_CASE						)
    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(_SCREAMING_SNAKE_CASE						)}"						)

    UpperCAmelCase	:					str	=	self._execution_device

    UpperCAmelCase	:					List[Any]	=	batch_size * num_images_per_prompt

    UpperCAmelCase	:					List[Any]	=	guidance_scale > 1.0
    UpperCAmelCase	:					Dict	=	self._encode_image(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

    # prior

    self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE      ,     device=_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					str	=	self.scheduler.timesteps

    UpperCAmelCase	:					Optional[int]	=	self.prior.config.num_embeddings
    UpperCAmelCase	:					int	=	self.prior.config.embedding_dim

    UpperCAmelCase	:					Tuple	=	self.prepare_latents(
        (batch_size, num_embeddings * embedding_dim)      ,     image_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
    UpperCAmelCase	:					List[Any]	=	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
     UpperCAmelCase	:					Dict	=	torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
     UpperCAmelCase	:					Optional[Any]	=	self.scheduler.scale_model_input(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

     UpperCAmelCase	:					List[str]	=	self.prior(
         _SCREAMING_SNAKE_CASE      ,     timestep=_SCREAMING_SNAKE_CASE      ,     proj_embedding=_SCREAMING_SNAKE_CASE      ,     ).predicted_image_embedding

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

     if do_classifier_free_guidance is not None:
      UpperCAmelCase	,		UpperCAmelCase	:					Dict	=	noise_pred.chunk(2						)
      UpperCAmelCase	:					Optional[Any]	=	noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

     UpperCAmelCase	:					Optional[Any]	=	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						)

    UpperCAmelCase	:					Optional[Any]	=	[]
    for i, latent in enumerate(_SCREAMING_SNAKE_CASE						):
     print()
     UpperCAmelCase	:					int	=	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						)

    UpperCAmelCase	:					Any	=	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}"						)

    UpperCAmelCase	:					List[Any]	=	images.cpu().numpy()

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




'''simple docstring'''


UpperCAmelCase_		:   Dict							   =		[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

UpperCAmelCase_		:   Any							   =		[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

UpperCAmelCase_		:   Tuple							   =		[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

UpperCAmelCase_		:   Dict							   =		[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

UpperCAmelCase_		:   Tuple							   =		[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

UpperCAmelCase_		:   Union[str, Any]							   =		[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

UpperCAmelCase_		:   Tuple							   =		[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

UpperCAmelCase_		:   int							   =		[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]




