




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


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

_lowerCamelCase				:		Optional[int]				      =    '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = \"a shark\"\n\n        >>> images = pipe(\n        ...     prompt,\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], \"shark_3d.gif\")\n        ```\n'





@dataclass
class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					lowercase__       =					42





class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					def __init__(       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    ):
							super().__init__()

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






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					):

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

							_snake_case      			=			latents * scheduler.init_noise_sigma
							return latents






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase=0					):

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

							_snake_case      			=			torch.device(f'''cuda:{gpu_id}'''					)

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






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase=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."					)

							_snake_case      			=			torch.device(f'''cuda:{gpu_id}'''					)

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

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

							if self.safety_checker is not None:
									_snake_case			,       _snake_case      			=			cpu_offload_with_hook(self.safety_checker,    __UpperCamelCase,    prev_module_hook=__UpperCamelCase					)

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






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):

							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(__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 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    ):
							len(__UpperCamelCase					) if isinstance(__UpperCamelCase,    __UpperCamelCase					) else 1

							# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
							_snake_case      			=			0
							# get prompt text embeddings
							_snake_case      			=			self.tokenizer(
							    __UpperCamelCase,    padding="max_length",    max_length=self.tokenizer.model_max_length,    truncation=__UpperCamelCase,    return_tensors="pt",    )
							_snake_case      			=			text_inputs.input_ids
							_snake_case      			=			self.tokenizer(__UpperCamelCase,    padding="longest",    return_tensors="pt"					).input_ids

							if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__UpperCamelCase,    __UpperCamelCase					):
									_snake_case      			=			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}'''					)

							_snake_case      			=			self.text_encoder(text_input_ids.to(__UpperCamelCase					)					)
							_snake_case      			=			text_encoder_output.text_embeds

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

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

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

							return prompt_embeds






					@torch.no_grad()
					@replace_example_docstring(__UpperCamelCase					)
					def __call__(       self,    __UpperCamelCase,    __UpperCamelCase = 1,    __UpperCamelCase = 25,    __UpperCamelCase = None,    __UpperCamelCase = None,    __UpperCamelCase = 4.0,    __UpperCamelCase = 64,    __UpperCamelCase = "pil",    __UpperCamelCase = True,    ):

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

							_snake_case      			=			self._execution_device

							_snake_case      			=			batch_size * num_images_per_prompt

							_snake_case      			=			guidance_scale > 1.0
							_snake_case      			=			self._encode_prompt(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					)

							# prior

							self.scheduler.set_timesteps(__UpperCamelCase,    device=__UpperCamelCase					)
							_snake_case      			=			self.scheduler.timesteps

							_snake_case      			=			self.prior.config.num_embeddings
							_snake_case      			=			self.prior.config.embedding_dim

							_snake_case      			=			self.prepare_latents(
							    (batch_size, num_embeddings * embedding_dim),    prompt_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
							_snake_case      			=			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
									_snake_case      			=			torch.cat([latents] * 2					) if do_classifier_free_guidance else latents
									_snake_case      			=			self.scheduler.scale_model_input(__UpperCamelCase,    __UpperCamelCase					)

									_snake_case      			=			self.prior(
									    __UpperCamelCase,    timestep=__UpperCamelCase,    proj_embedding=__UpperCamelCase,    ).predicted_image_embedding

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

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

									_snake_case      			=			self.scheduler.step(
									    __UpperCamelCase,    timestep=__UpperCamelCase,    sample=__UpperCamelCase,    ).prev_sample

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

							_snake_case      			=			[]
							for i, latent in enumerate(__UpperCamelCase					):
									_snake_case      			=			self.renderer.decode(
									    latent[None, :],    __UpperCamelCase,    size=__UpperCamelCase,    ray_batch_size=4_096,    n_coarse_samples=64,    n_fine_samples=128,    )
									images.append(__UpperCamelCase					)

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

							_snake_case      			=			images.cpu().numpy()

							if output_type == "pil":
									_snake_case      			=			[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 typing import TYPE_CHECKING

from ...utils import _LazyModule


SCREAMING_SNAKE_CASE__       =	{"tokenization_bert_japanese": ["BertJapaneseTokenizer", "CharacterTokenizer", "MecabTokenizer"]}


if TYPE_CHECKING:
					from .tokenization_bert_japanese import BertJapaneseTokenizer, CharacterTokenizer, MecabTokenizer

else:
					import sys

					SCREAMING_SNAKE_CASE__       =	_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


