



'''simple docstring'''







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				):






	'''simple docstring'''

	A__		=	42





class      lowerCamelCase__     (     _A				):






	'''simple docstring'''

	def __init__(  self		:  Tuple   ,		__A		:  PriorTransformer   ,		__A		:  CLIPTextModelWithProjection   ,		__A		:  CLIPTokenizer   ,		__A		:  HeunDiscreteScheduler   ,		__A		:  ShapERenderer   ,		)     ->			Any:




								'''simple docstring'''





								super().__init__()

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




	def      lowercase__							(  self		:  List[str]   ,		__A		:  Optional[int]   ,		__A		:  List[str]   ,		__A		:  Optional[Any]   ,		__A		:  List[str]   ,		__A		:  Tuple   ,		__A		:  Optional[int]					)     ->			Tuple:




								'''simple docstring'''





								if latents is None:
															lowerCAmelCase__  =   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}'''					)
															lowerCAmelCase__  =   latents.to(__A					)

								lowerCAmelCase__  =   latents * scheduler.init_noise_sigma
								return latents




	def      lowercase__							(  self		:  Union[str, Any]   ,		__A		:  int=0					)     ->			Any:




								'''simple docstring'''





								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.text_encoder, self.prior]
								for cpu_offloaded_model in models:
															if cpu_offloaded_model is not None:
																						cpu_offload(__A   ,		__A					)




	def      lowercase__							(  self		:  Tuple   ,		__A		:  str=0					)     ->			List[Any]:




								'''simple docstring'''





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

								lowerCAmelCase__  =   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)

								lowerCAmelCase__  =   None
								for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
															lowerCAmelCase__  ,lowerCAmelCase__  =   cpu_offload_with_hook(__A   ,		__A   ,		prev_module_hook=__A					)

								if self.safety_checker is not None:
															lowerCAmelCase__  ,lowerCAmelCase__  =   cpu_offload_with_hook(self.safety_checker   ,		__A   ,		prev_module_hook=__A					)

								# We'll offload the last model manually.
								lowerCAmelCase__  =   hook




	@property
	def      lowercase__							(  self		:  Union[str, Any]					)     ->			int:




								'''simple docstring'''





								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      lowercase__							(  self		:  List[Any]   ,		__A		:  List[str]   ,		__A		:  List[str]   ,		__A		:  str   ,		__A		:  Optional[Any]   ,		)     ->			Union[str, Any]:




								'''simple docstring'''





								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
								lowerCAmelCase__  =   0
								# get prompt text embeddings
								lowerCAmelCase__  =   self.tokenizer(
								    __A   ,		padding="""max_length"""   ,		max_length=self.tokenizer.model_max_length   ,		truncation=__A   ,		return_tensors="""pt"""   ,		)
								lowerCAmelCase__  =   text_inputs.input_ids
								lowerCAmelCase__  =   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					):
															lowerCAmelCase__  =   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}'''					)

								lowerCAmelCase__  =   self.text_encoder(text_input_ids.to(__A					)					)
								lowerCAmelCase__  =   text_encoder_output.text_embeds

								lowerCAmelCase__  =   prompt_embeds.repeat_interleave(__A   ,		dim=0					)
								# in Shap-E it normalize the prompt_embeds and then later rescale it
								lowerCAmelCase__  =   prompt_embeds / torch.linalg.norm(__A   ,		dim=-1   ,		keepdim=__A					)

								if do_classifier_free_guidance:
															lowerCAmelCase__  =   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
															lowerCAmelCase__  =   torch.cat([negative_prompt_embeds, prompt_embeds]					)

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

								return prompt_embeds




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




								'''simple docstring'''





								if isinstance(__A   ,		__A					):
															lowerCAmelCase__  =   1
								elif isinstance(__A   ,		__A					):
															lowerCAmelCase__  =   len(__A					)
								else:
															raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(__A					)}'''					)

								lowerCAmelCase__  =   self._execution_device

								lowerCAmelCase__  =   batch_size * num_images_per_prompt

								lowerCAmelCase__  =   guidance_scale > 1.0
								lowerCAmelCase__  =   self._encode_prompt(__A   ,		__A   ,		__A   ,		__A					)

								# prior

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

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

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

								lowerCAmelCase__  =   []
								for i, latent in enumerate(__A					):
															lowerCAmelCase__  =   self.renderer.decode(
															    latent[None, :]   ,		__A   ,		size=__A   ,		ray_batch_size=4096   ,		n_coarse_samples=64   ,		n_fine_samples=128   ,		)
															images.append(__A					)

								lowerCAmelCase__  =   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}'''					)

								lowerCAmelCase__  =   images.cpu().numpy()

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










'''simple docstring'''







from ..utils import DummyObject, requires_backends

class      lowerCamelCase__     (     metaclass=_A				):






	'''simple docstring'''

	A__		=	['''torch''', '''librosa''']




	def __init__(  self		:  Optional[Any]   ,		*__A		:  Tuple   ,		**__A		:  Tuple					)     ->			Union[str, Any]:




								'''simple docstring'''





								requires_backends(self   ,		["""torch""", """librosa"""]					)




	@classmethod
	def      lowercase__							(  cls		:  Dict   ,		*__A		:  List[Any]   ,		**__A		:  List[str]					)     ->			Union[str, Any]:




								'''simple docstring'''





								requires_backends(cls   ,		["""torch""", """librosa"""]					)




	@classmethod
	def      lowercase__							(  cls		:  Optional[int]   ,		*__A		:  List[str]   ,		**__A		:  Tuple					)     ->			Any:




								'''simple docstring'''





								requires_backends(cls   ,		["""torch""", """librosa"""]					)





class      lowerCamelCase__     (     metaclass=_A				):






	'''simple docstring'''

	A__		=	['''torch''', '''librosa''']




	def __init__(  self		:  int   ,		*__A		:  Dict   ,		**__A		:  List[Any]					)     ->			List[Any]:




								'''simple docstring'''





								requires_backends(self   ,		["""torch""", """librosa"""]					)




	@classmethod
	def      lowercase__							(  cls		:  Optional[int]   ,		*__A		:  Optional[int]   ,		**__A		:  List[Any]					)     ->			Union[str, Any]:




								'''simple docstring'''





								requires_backends(cls   ,		["""torch""", """librosa"""]					)




	@classmethod
	def      lowercase__							(  cls		:  List[str]   ,		*__A		:  List[str]   ,		**__A		:  int					)     ->			List[str]:




								'''simple docstring'''





								requires_backends(cls   ,		["""torch""", """librosa"""]					)





