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


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

_lowercase							 =							'''
    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 				__a    (   __a					):



							'''simple docstring'''







							_lowerCamelCase				: Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]





class 				__a    (   __a					):



							'''simple docstring'''







							def __init__(    self     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						) ->       List[Any]:




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

										self.register_modules(
										    prior=_lowerCamelCase     ,						text_encoder=_lowerCamelCase     ,						tokenizer=_lowerCamelCase     ,						scheduler=_lowerCamelCase     ,						renderer=_lowerCamelCase     ,						)
							def      SCREAMING_SNAKE_CASE	(    self     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase					) ->       Union[str, Any]:




										'''simple docstring'''
										if latents is None:
													__lowercase						      =					randn_tensor(_lowerCamelCase     ,						generator=_lowerCamelCase     ,						device=_lowerCamelCase     ,						dtype=_lowerCamelCase					)
										else:
													if latents.shape != shape:
																raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''					)
													__lowercase						      =					latents.to(_lowerCamelCase					)

										__lowercase						      =					latents * scheduler.init_noise_sigma
										return latents
							def      SCREAMING_SNAKE_CASE	(    self     ,						_lowerCamelCase=0					) ->       List[Any]:




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

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

										__lowercase						      =					[self.text_encoder, self.prior]
										for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																cpu_offload(_lowerCamelCase     ,						_lowerCamelCase					)
							def      SCREAMING_SNAKE_CASE	(    self     ,						_lowerCamelCase=0					) ->       Optional[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."					)

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

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

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

										if self.safety_checker is not None:
													__lowercase      ,				__lowercase						      =					cpu_offload_with_hook(self.safety_checker     ,						_lowerCamelCase     ,						prev_module_hook=_lowerCamelCase					)

										# We'll offload the last model manually.
										__lowercase						      =					hook
							@property
							def      SCREAMING_SNAKE_CASE	(    self					) ->       Optional[Any]:




										'''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(_lowerCamelCase     ,						"_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     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						) ->       List[str]:




										'''simple docstring'''
										len(_lowerCamelCase					) if isinstance(_lowerCamelCase     ,						_lowerCamelCase					) else 1

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

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

										__lowercase						      =					self.text_encoder(text_input_ids.to(_lowerCamelCase					)					)
										__lowercase						      =					text_encoder_output.text_embeds

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

										if do_classifier_free_guidance:
													__lowercase						      =					torch.zeros_like(_lowerCamelCase					)

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

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

										return prompt_embeds





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




										'''simple docstring'''

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

										__lowercase						      =					self._execution_device

										__lowercase						      =					batch_size * num_images_per_prompt

										__lowercase						      =					guidance_scale > 1.0
										__lowercase						      =					self._encode_prompt(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase					)

										# prior

										self.scheduler.set_timesteps(_lowerCamelCase     ,						device=_lowerCamelCase					)
										__lowercase						      =					self.scheduler.timesteps

										__lowercase						      =					self.prior.config.num_embeddings
										__lowercase						      =					self.prior.config.embedding_dim

										__lowercase						      =					self.prepare_latents(
										    (batch_size, num_embeddings * embedding_dim)     ,						prompt_embeds.dtype     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						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
										__lowercase						      =					latents.reshape(latents.shape[0]     ,						_lowerCamelCase     ,						_lowerCamelCase					)

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

													__lowercase						      =					self.prior(
													    _lowerCamelCase     ,						timestep=_lowerCamelCase     ,						proj_embedding=_lowerCamelCase     ,						).predicted_image_embedding

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

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

													__lowercase						      =					self.scheduler.step(
													    _lowerCamelCase     ,						timestep=_lowerCamelCase     ,						sample=_lowerCamelCase     ,						).prev_sample

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

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

										__lowercase						      =					torch.stack(_lowerCamelCase					)

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

										__lowercase						      =					images.cpu().numpy()

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







"""simple docstring"""






from scipy.constants import g



def     lowerCAmelCase__ (		__magic_name__ ,      __magic_name__			)	->float:
			if mass < 0:
						# handling of negative values of mass
						raise ValueError("The mass of a body cannot be negative"			)
			if height < 0:
						# handling of negative values of height
						raise ValueError("The height above the ground cannot be negative"			)
			return mass * g * height


if __name__ == "__main__":
					from doctest import testmod

					testmod(name='''potential_energy''')





