

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


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

A_							:     List[Any]     =	"\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  (A__     ):
			lowerCamelCase__				:						Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]





class 				lowerCamelCase  (A__     ):

			def __init__(   self			:  Any      ,			__UpperCAmelCase			:  PriorTransformer      ,			__UpperCAmelCase			:  CLIPTextModelWithProjection      ,			__UpperCAmelCase			:  CLIPTokenizer      ,			__UpperCAmelCase			:  HeunDiscreteScheduler      ,			__UpperCAmelCase			:  ShapERenderer      ,			)				->      List[Any]:
						super().__init__()

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

			def    SCREAMING_SNAKE_CASE			(   self			:  Optional[Any]      ,			__UpperCAmelCase			:  Optional[int]      ,			__UpperCAmelCase			:  int      ,			__UpperCAmelCase			:  Dict      ,			__UpperCAmelCase			:  int      ,			__UpperCAmelCase			:  int      ,			__UpperCAmelCase			:  str    )				->      str:
						if latents is None:
									SCREAMING_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}"""    )
									SCREAMING_SNAKE_CASE__									= latents.to(__UpperCAmelCase    )

						SCREAMING_SNAKE_CASE__									= latents * scheduler.init_noise_sigma
						return latents

			def    SCREAMING_SNAKE_CASE			(   self			:  Optional[Any]      ,			__UpperCAmelCase			:  List[str]=0    )				->      Any:
						if is_accelerate_available():
									from accelerate import cpu_offload
						else:
									raise ImportError("""Please install accelerate via `pip install accelerate`"""    )

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

						SCREAMING_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			:  List[Any]      ,			__UpperCAmelCase			:  str=0    )				->      Optional[Any]:
						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."""    )

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

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

						if self.safety_checker is not None:
									SCREAMING_SNAKE_CASE__							,						SCREAMING_SNAKE_CASE__									= cpu_offload_with_hook(self.safety_checker      ,			__UpperCAmelCase      ,			prev_module_hook=__UpperCAmelCase    )

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

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  Optional[int]    )				->      List[Any]:
						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			:  Union[str, Any]      ,			__UpperCAmelCase			:  Any      ,			__UpperCAmelCase			:  Union[str, Any]      ,			__UpperCAmelCase			:  str      ,			__UpperCAmelCase			:  Union[str, Any]      ,			)				->      List[str]:
						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
						SCREAMING_SNAKE_CASE__									= 0
						# get prompt text embeddings
						SCREAMING_SNAKE_CASE__									= self.tokenizer(
						    __UpperCAmelCase      ,			padding="""max_length"""      ,			max_length=self.tokenizer.model_max_length      ,			truncation=__UpperCAmelCase      ,			return_tensors="""pt"""      ,			)
						SCREAMING_SNAKE_CASE__									= text_inputs.input_ids
						SCREAMING_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    ):
									SCREAMING_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}"""    )

						SCREAMING_SNAKE_CASE__									= self.text_encoder(text_input_ids.to(__UpperCAmelCase    )    )
						SCREAMING_SNAKE_CASE__									= text_encoder_output.text_embeds

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

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

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

						return prompt_embeds





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

						if isinstance(__UpperCAmelCase      ,			__UpperCAmelCase    ):
									SCREAMING_SNAKE_CASE__									= 1
						elif isinstance(__UpperCAmelCase      ,			__UpperCAmelCase    ):
									SCREAMING_SNAKE_CASE__									= len(__UpperCAmelCase    )
						else:
									raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(__UpperCAmelCase    )}"""    )

						SCREAMING_SNAKE_CASE__									= self._execution_device

						SCREAMING_SNAKE_CASE__									= batch_size * num_images_per_prompt

						SCREAMING_SNAKE_CASE__									= guidance_scale > 1.0
						SCREAMING_SNAKE_CASE__									= self._encode_prompt(__UpperCAmelCase      ,			__UpperCAmelCase      ,			__UpperCAmelCase      ,			__UpperCAmelCase    )

						# prior

						self.scheduler.set_timesteps(__UpperCAmelCase      ,			device=__UpperCAmelCase    )
						SCREAMING_SNAKE_CASE__									= self.scheduler.timesteps

						SCREAMING_SNAKE_CASE__									= self.prior.config.num_embeddings
						SCREAMING_SNAKE_CASE__									= self.prior.config.embedding_dim

						SCREAMING_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
						SCREAMING_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
									SCREAMING_SNAKE_CASE__									= torch.cat([latents] * 2    ) if do_classifier_free_guidance else latents
									SCREAMING_SNAKE_CASE__									= self.scheduler.scale_model_input(__UpperCAmelCase      ,			__UpperCAmelCase    )

									SCREAMING_SNAKE_CASE__									= self.prior(
									    __UpperCAmelCase      ,			timestep=__UpperCAmelCase      ,			proj_embedding=__UpperCAmelCase      ,			).predicted_image_embedding

									# remove the variance
									SCREAMING_SNAKE_CASE__							,						SCREAMING_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:
												SCREAMING_SNAKE_CASE__							,						SCREAMING_SNAKE_CASE__									= noise_pred.chunk(2    )
												SCREAMING_SNAKE_CASE__									= noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

									SCREAMING_SNAKE_CASE__									= self.scheduler.step(
									    __UpperCAmelCase      ,			timestep=__UpperCAmelCase      ,			sample=__UpperCAmelCase      ,			).prev_sample

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

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

						SCREAMING_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}"""    )

						SCREAMING_SNAKE_CASE__									= images.cpu().numpy()

						if output_type == "pil":
									SCREAMING_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"""




import importlib.metadata
import subprocess
import sys

def 		A    (       snake_case__ = False      ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__									= False
			if "IPython" in sys.modules:
						SCREAMING_SNAKE_CASE__									= """google.colab""" in str(sys.modules["""IPython"""].get_ipython()      )

			if in_colab:
						if upgrade:
									SCREAMING_SNAKE_CASE__									= ["""pip""", """install""", """-U""", """torch"""]
									subprocess.run(snake_case__						,			check=snake_case__      )
						# get the current version of torch
						SCREAMING_SNAKE_CASE__									= importlib.metadata.version("""torch"""      )
						SCREAMING_SNAKE_CASE__									= torch_version[: torch_version.rindex("""."""      )]
						SCREAMING_SNAKE_CASE__									= f"""https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl"""
						SCREAMING_SNAKE_CASE__									= ["""pip""", """install""", xla_wheel]
						subprocess.run(snake_case__						,			check=snake_case__      )
			else:
						raise RuntimeError("""`install_xla` utility works only on google colab."""      )


