

"""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__				:  Optional[Any]													=  logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase__				:  Optional[Any]													=  '''
    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     _UpperCAmelCase			(		__a):
			__a :       Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class     _UpperCAmelCase			(		__a):
			def __init__(		self      ,		_A      ,		_A      ,		_A      ,		_A      ,		_A      ,		)    ->    Dict:






				'''simple docstring'''







				super().__init__()

				self.register_modules(
				    prior=_A      ,		text_encoder=_A      ,		tokenizer=_A      ,		scheduler=_A      ,		renderer=_A      ,		)
			def 							__snake_case (		self      ,		_A      ,		_A      ,		_A      ,		_A      ,		_A      ,		_A     )    ->    List[Any]:






				'''simple docstring'''







				if latents is None:
					_UpperCAmelCase    :							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}'''     )
					_UpperCAmelCase    :							List[Any]									=					latents.to(_A     )

				_UpperCAmelCase    :							Union[str, Any]									=					latents * scheduler.init_noise_sigma
				return latents
			def 							__snake_case (		self      ,		_A=0     )    ->    int:






				'''simple docstring'''







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

				_UpperCAmelCase    :							List[Any]									=					torch.device(f'''cuda:{gpu_id}'''     )

				_UpperCAmelCase    :							Union[str, Any]									=					[self.text_encoder, self.prior]
				for cpu_offloaded_model in models:
					if cpu_offloaded_model is not None:
						cpu_offload(_A      ,		_A     )
			def 							__snake_case (		self      ,		_A=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."""     )

				_UpperCAmelCase    :							Any									=					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)

				_UpperCAmelCase    :							Optional[Any]									=					None
				for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
					_UpperCAmelCase						,   _UpperCAmelCase    :							Union[str, Any]									=					cpu_offload_with_hook(_A      ,		_A      ,		prev_module_hook=_A     )

				if self.safety_checker is not None:
					_UpperCAmelCase						,   _UpperCAmelCase    :							Optional[int]									=					cpu_offload_with_hook(self.safety_checker      ,		_A      ,		prev_module_hook=_A     )

				# We'll offload the last model manually.
				_UpperCAmelCase    :							str									=					hook
			@property
			def 							__snake_case (		self     )    ->    Union[str, 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(_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 							__snake_case (		self      ,		_A      ,		_A      ,		_A      ,		_A      ,		)    ->    List[str]:






				'''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
				_UpperCAmelCase    :							str									=					0
				# get prompt text embeddings
				_UpperCAmelCase    :							str									=					self.tokenizer(
				    _A      ,		padding="""max_length"""      ,		max_length=self.tokenizer.model_max_length      ,		truncation=_A      ,		return_tensors="""pt"""      ,		)
				_UpperCAmelCase    :							Optional[Any]									=					text_inputs.input_ids
				_UpperCAmelCase    :							List[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     ):
					_UpperCAmelCase    :							Dict									=					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}'''     )

				_UpperCAmelCase    :							Any									=					self.text_encoder(text_input_ids.to(_A     )     )
				_UpperCAmelCase    :							int									=					text_encoder_output.text_embeds

				_UpperCAmelCase    :							Tuple									=					prompt_embeds.repeat_interleave(_A      ,		dim=0     )
				# in Shap-E it normalize the prompt_embeds and then later rescale it
				_UpperCAmelCase    :							List[Any]									=					prompt_embeds / torch.linalg.norm(_A      ,		dim=-1      ,		keepdim=_A     )

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

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

				return prompt_embeds
			@torch.no_grad()
			@replace_example_docstring(_A     )
			def __call__(		self      ,		_A      ,		_A = 1      ,		_A = 25      ,		_A = None      ,		_A = None      ,		_A = 4.0      ,		_A = 64      ,		_A = "pil"      ,		_A = True      ,		)    ->    str:






				'''simple docstring'''







				if isinstance(_A      ,		_A     ):
					_UpperCAmelCase    :							List[Any]									=					1
				elif isinstance(_A      ,		_A     ):
					_UpperCAmelCase    :							Union[str, Any]									=					len(_A     )
				else:
					raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(_A     )}'''     )

				_UpperCAmelCase    :							Optional[int]									=					self._execution_device

				_UpperCAmelCase    :							str									=					batch_size * num_images_per_prompt

				_UpperCAmelCase    :							Any									=					guidance_scale > 1.0
				_UpperCAmelCase    :							List[Any]									=					self._encode_prompt(_A      ,		_A      ,		_A      ,		_A     )

				# prior

				self.scheduler.set_timesteps(_A      ,		device=_A     )
				_UpperCAmelCase    :							List[Any]									=					self.scheduler.timesteps

				_UpperCAmelCase    :							Dict									=					self.prior.config.num_embeddings
				_UpperCAmelCase    :							str									=					self.prior.config.embedding_dim

				_UpperCAmelCase    :							Tuple									=					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
				_UpperCAmelCase    :							str									=					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
					_UpperCAmelCase    :							Optional[Any]									=					torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
					_UpperCAmelCase    :							Optional[Any]									=					self.scheduler.scale_model_input(_A      ,		_A     )

					_UpperCAmelCase    :							Any									=					self.prior(
					    _A      ,		timestep=_A      ,		proj_embedding=_A      ,		).predicted_image_embedding

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

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

					_UpperCAmelCase    :							Dict									=					self.scheduler.step(
					    _A      ,		timestep=_A      ,		sample=_A      ,		).prev_sample

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

				_UpperCAmelCase    :							str									=					[]
				for i, latent in enumerate(_A     ):
					_UpperCAmelCase    :							Optional[Any]									=					self.renderer.decode(
					    latent[None, :]      ,		_A      ,		size=_A      ,		ray_batch_size=40_96      ,		n_coarse_samples=64      ,		n_fine_samples=1_28      ,		)
					images.append(_A     )

				_UpperCAmelCase    :							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}'''     )

				_UpperCAmelCase    :							str									=					images.cpu().numpy()

				if output_type == "pil":
					_UpperCAmelCase    :							List[str]									=					[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"""






def       UpperCamelCase					(			_lowerCAmelCase     :						float,  _lowerCAmelCase     :						float )				->			float:
	_UpperCAmelCase    :							List[Any]									=					float()
	try:
		_UpperCAmelCase    :							Optional[Any]									=					mass * acceleration
	except Exception:
		return -0.0
	return force


if __name__ == "__main__":
						import doctest

						# run doctest
						doctest.testmod()

						# demo
						lowerCamelCase__				:  Any													=  12.5
						lowerCamelCase__				:  Union[str, Any]													=  10
						lowerCamelCase__				:  Optional[Any]													=  newtons_second_law_of_motion(mass, acceleration)
						print('''The force is ''', force, '''N''')





