



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


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

snake_case_			:     Optional[int]  	=  '\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 							lowercase__     (							lowercase       ):
	lowercase__      =      42






class 							lowercase__     (							lowercase       ):





	def __init__(			self :    Dict			,lowerCamelCase__ :    PriorTransformer			,lowerCamelCase__ :    CLIPVisionModel			,lowerCamelCase__ :    CLIPImageProcessor			,lowerCamelCase__ :    HeunDiscreteScheduler			,lowerCamelCase__ :    ShapERenderer			,):







							'''simple docstring'''
							super().__init__()

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





	def      UpperCamelCase_  (			self :    List[Any]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    List[Any]			,lowerCamelCase__ :    Union[str, Any]			):







							'''simple docstring'''


							if latents is None:
													_UpperCamelCase :		Dict			    =       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}'			)
													_UpperCamelCase :		List[str]			    =       latents.to(__UpperCAmelCase			)

							_UpperCamelCase :		str			    =       latents * scheduler.init_noise_sigma
							return latents





	def      UpperCamelCase_  (			self :    List[str]			,lowerCamelCase__ :    List[str]=0			):







							'''simple docstring'''


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

							_UpperCamelCase :		Optional[Any]			    =       torch.device(F'cuda:{gpu_id}'			)

							_UpperCamelCase :		Dict			    =       [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 :    Optional[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(__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 :    Any			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    Dict			,):







							'''simple docstring'''


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

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

							_UpperCamelCase :		Optional[int]			    =       image.to(dtype=self.image_encoder.dtype			,device=__UpperCAmelCase			)

							_UpperCamelCase :		List[str]			    =       self.image_encoder(__UpperCAmelCase			)['last_hidden_state']
							_UpperCamelCase :		str			    =       image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

							_UpperCamelCase :		Tuple			    =       image_embeds.repeat_interleave(__UpperCAmelCase			,dim=0			)

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

							return image_embeds





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







							'''simple docstring'''


							if isinstance(__UpperCAmelCase			,PIL.Image.Image			):
													_UpperCamelCase :		List[Any]			    =       1
							elif isinstance(__UpperCAmelCase			,torch.Tensor			):
													_UpperCamelCase :		int			    =       image.shape[0]
							elif isinstance(__UpperCAmelCase			,__UpperCAmelCase			) and isinstance(image[0]			,(torch.Tensor, PIL.Image.Image)			):
													_UpperCamelCase :		int			    =       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			)}'			)

							_UpperCamelCase :		int			    =       self._execution_device

							_UpperCamelCase :		List[Any]			    =       batch_size * num_images_per_prompt

							_UpperCamelCase :		Optional[int]			    =       guidance_scale > 1.0
							_UpperCamelCase :		List[str]			    =       self._encode_image(__UpperCAmelCase			,__UpperCAmelCase			,__UpperCAmelCase			,__UpperCAmelCase			)

							# prior

							self.scheduler.set_timesteps(__UpperCAmelCase			,device=__UpperCAmelCase			)
							_UpperCamelCase :		List[Any]			    =       self.scheduler.timesteps

							_UpperCamelCase :		Any			    =       self.prior.config.num_embeddings
							_UpperCamelCase :		Dict			    =       self.prior.config.embedding_dim

							_UpperCamelCase :		Dict			    =       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
							_UpperCamelCase :		Any			    =       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
													_UpperCamelCase :		List[Any]			    =       torch.cat([latents] * 2			) if do_classifier_free_guidance else latents
													_UpperCamelCase :		Optional[int]			    =       self.scheduler.scale_model_input(__UpperCAmelCase			,__UpperCAmelCase			)

													_UpperCamelCase :		Optional[Any]			    =       self.prior(
													    __UpperCAmelCase			,timestep=__UpperCAmelCase			,proj_embedding=__UpperCAmelCase			,).predicted_image_embedding

													# remove the variance
													_UpperCamelCase    ,      _UpperCamelCase :		int			    =       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 :		List[Any]			    =       noise_pred.chunk(2			)
																			_UpperCamelCase :		Optional[Any]			    =       noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

													_UpperCamelCase :		Any			    =       self.scheduler.step(
													    __UpperCAmelCase			,timestep=__UpperCAmelCase			,sample=__UpperCAmelCase			,).prev_sample

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

							_UpperCamelCase :		List[str]			    =       []
							for i, latent in enumerate(__UpperCAmelCase			):
													print()
													_UpperCamelCase :		List[Any]			    =       self.renderer.decode(
													    latent[None, :]			,__UpperCAmelCase			,size=__UpperCAmelCase			,ray_batch_size=4096			,n_coarse_samples=64			,n_fine_samples=128			,)

													images.append(__UpperCAmelCase			)

							_UpperCamelCase :		int			    =       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}'			)

							_UpperCamelCase :		str			    =       images.cpu().numpy()

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







'''simple docstring'''
from torch import nn






def A__   (					UpperCAmelCase_							):
						if act_fn in ["swish", "silu"]:
												return nn.SiLU()
						elif act_fn == "mish":
												return nn.Mish()
						elif act_fn == "gelu":
												return nn.GELU()
						else:
												raise ValueError(f'Unsupported activation function: {act_fn}'							)


