



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


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

__UpperCAmelCase    	=  '''
    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 						lowerCamelCase__			(		_a ):
						_lowerCAmelCase             =			42


class 						lowerCamelCase__			(		_a ):


						def __init__(			self    :	Optional[int]   ,							_a    :	PriorTransformer   ,							_a    :	CLIPTextModelWithProjection   ,							_a    :	CLIPTokenizer   ,							_a    :	HeunDiscreteScheduler   ,							_a    :	ShapERenderer   ,							):
													super().__init__()

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


						def 	_lowerCamelCase      (			self    :	Dict   ,							_a    :	List[str]   ,							_a    :	Dict   ,							_a    :	Any   ,							_a    :	Optional[Any]   ,							_a    :	Dict   ,							_a    :	int      ):
													if latents is None:
																				a__:							Optional[Any]									=randn_tensor(_a   ,							generator=_a   ,							device=_a   ,							dtype=_a      )
													else:
																				if latents.shape != shape:
																											raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"      )
																				a__:							Tuple									=latents.to(_a      )

													a__:							List[Any]									=latents * scheduler.init_noise_sigma
													return latents


						def 	_lowerCamelCase      (			self    :	Tuple   ,							_a    :	str=0      ):
													if is_accelerate_available():
																				from accelerate import cpu_offload
													else:
																				raise ImportError("Please install accelerate via `pip install accelerate`"      )

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

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


						def 	_lowerCamelCase      (			self    :	int   ,							_a    :	str=0      ):
													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."      )

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

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

													a__:							Any									=None
													for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
																				a__				,      a__:							str									=cpu_offload_with_hook(_a   ,							_a   ,							prev_module_hook=_a      )

													if self.safety_checker is not None:
																				a__				,      a__:							Tuple									=cpu_offload_with_hook(self.safety_checker   ,							_a   ,							prev_module_hook=_a      )

													# We'll offload the last model manually.
													a__:							str									=hook


						@property
						def 	_lowerCamelCase      (			self    :	int      ):
													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(_a   ,							"_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 	_lowerCamelCase      (			self    :	Optional[int]   ,							_a    :	Optional[int]   ,							_a    :	Any   ,							_a    :	int   ,							_a    :	int   ,							):
													len(_a      ) if isinstance(_a   ,							_a      ) else 1

													# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
													a__:							Optional[int]									=0
													# get prompt text embeddings
													a__:							List[Any]									=self.tokenizer(
													    _a   ,							padding="max_length"   ,							max_length=self.tokenizer.model_max_length   ,							truncation=_a   ,							return_tensors="pt"   ,							)
													a__:							int									=text_inputs.input_ids
													a__:							Union[str, Any]									=self.tokenizer(_a   ,							padding="longest"   ,							return_tensors="pt"      ).input_ids

													if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_a   ,							_a      ):
																				a__:							str									=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}"      )

													a__:							Dict									=self.text_encoder(text_input_ids.to(_a      )      )
													a__:							List[str]									=text_encoder_output.text_embeds

													a__:							Optional[int]									=prompt_embeds.repeat_interleave(_a   ,							dim=0      )
													# in Shap-E it normalize the prompt_embeds and then later rescale it
													a__:							Optional[Any]									=prompt_embeds / torch.linalg.norm(_a   ,							dim=-1   ,							keepdim=_a      )

													if do_classifier_free_guidance:
																				a__:							Optional[int]									=torch.zeros_like(_a      )

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

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

													return prompt_embeds







						@torch.no_grad()
						@replace_example_docstring(_a      )
						def __call__(			self    :	Tuple   ,							_a    :	str   ,							_a    :	int = 1   ,							_a    :	int = 2_5   ,							_a    :	Optional[Union[torch.Generator, List[torch.Generator]]] = None   ,							_a    :	Optional[torch.FloatTensor] = None   ,							_a    :	float = 4.0   ,							_a    :	int = 6_4   ,							_a    :	Optional[str] = "pil"   ,							_a    :	bool = True   ,							):

													if isinstance(_a   ,							_a      ):
																				a__:							str									=1
													elif isinstance(_a   ,							_a      ):
																				a__:							Optional[int]									=len(_a      )
													else:
																				raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(_a      )}"      )

													a__:							List[Any]									=self._execution_device

													a__:							Union[str, Any]									=batch_size * num_images_per_prompt

													a__:							List[Any]									=guidance_scale > 1.0
													a__:							List[Any]									=self._encode_prompt(_a   ,							_a   ,							_a   ,							_a      )

													# prior

													self.scheduler.set_timesteps(_a   ,							device=_a      )
													a__:							List[Any]									=self.scheduler.timesteps

													a__:							Optional[Any]									=self.prior.config.num_embeddings
													a__:							List[str]									=self.prior.config.embedding_dim

													a__:							Dict									=self.prepare_latents(
													    (batch_size, num_embeddings * embedding_dim)   ,							prompt_embeds.dtype   ,							_a   ,							_a   ,							_a   ,							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
													a__:							List[Any]									=latents.reshape(latents.shape[0]   ,							_a   ,							_a      )

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

																				a__:							Union[str, Any]									=self.prior(
																				    _a   ,							timestep=_a   ,							proj_embedding=_a   ,							).predicted_image_embedding

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

																				if do_classifier_free_guidance is not None:
																											a__				,      a__:							str									=noise_pred.chunk(2      )
																											a__:							Union[str, Any]									=noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

																				a__:							Optional[Any]									=self.scheduler.step(
																				    _a   ,							timestep=_a   ,							sample=_a   ,							).prev_sample

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

													a__:							Tuple									=[]
													for i, latent in enumerate(_a      ):
																				a__:							Tuple									=self.renderer.decode(
																				    latent[None, :]   ,							_a   ,							size=_a   ,							ray_batch_size=4_0_9_6   ,							n_coarse_samples=6_4   ,							n_fine_samples=1_2_8   ,							)
																				images.append(_a      )

													a__:							List[str]									=torch.stack(_a      )

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

													a__:							Any									=images.cpu().numpy()

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










from typing import Callable





def     __lowerCamelCase							(   __magic_name__						:	Callable    ):

							def wrapper(__magic_name__						:	Optional[Any]    ):
														a__:							List[Any]									=function_with_docstring.__doc__
														return target_function

							return wrapper





