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


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

SCREAMING_SNAKE_CASE__       =	"\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_     (      lowerCAmelCase       ):



				"""simple docstring"""
				_lowerCAmelCase  :     Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]





class 	lowerCAmelCase_     (      lowerCAmelCase       ):



				"""simple docstring"""

				def __init__(					self		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     ):






										"""simple docstring"""

										super().__init__()

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

				def 		snake_case			(					self		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase     ):






										"""simple docstring"""

										if latents is None:
																snake_case             =      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}"""     )
																snake_case             =      latents.to(lowerCAmelCase     )

										snake_case             =      latents * scheduler.init_noise_sigma
										return latents

				def 		snake_case			(					self		,     lowerCAmelCase=0     ):






										"""simple docstring"""

										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(lowerCAmelCase		,     lowerCAmelCase     )

				def 		snake_case			(					self		,     lowerCAmelCase=0     ):






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

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

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

										if self.safety_checker is not None:
																snake_case       ,snake_case             =      cpu_offload_with_hook(self.safety_checker		,     lowerCAmelCase		,     prev_module_hook=lowerCAmelCase     )

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

				@property
				def 		snake_case			(					self     ):






										"""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 		snake_case			(					self		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     ):






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

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

										if do_classifier_free_guidance:
																snake_case             =      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
																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(lowerCAmelCase     )
				def __call__(					self		,     lowerCAmelCase		,     lowerCAmelCase = 1		,     lowerCAmelCase = 25		,     lowerCAmelCase = None		,     lowerCAmelCase = None		,     lowerCAmelCase = 4.0		,     lowerCAmelCase = 64		,     lowerCAmelCase = "pil"		,     lowerCAmelCase = True		,     ):






										"""simple docstring"""

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

										snake_case             =      self._execution_device

										snake_case             =      batch_size * num_images_per_prompt

										snake_case             =      guidance_scale > 1.0
										snake_case             =      self._encode_prompt(lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase		,     lowerCAmelCase     )

										# prior

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

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

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

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

										snake_case             =      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}"""     )

										snake_case             =      images.cpu().numpy()

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

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


SCREAMING_SNAKE_CASE__       =	{
    "configuration_marian": ["MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "MarianConfig", "MarianOnnxConfig"],
}

try:
					if not is_sentencepiece_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__       =	["MarianTokenizer"]

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__       =	[
					    "MARIAN_PRETRAINED_MODEL_ARCHIVE_LIST",
					    "MarianForCausalLM",
					    "MarianModel",
					    "MarianMTModel",
					    "MarianPreTrainedModel",
					]

try:
					if not is_tf_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__       =	["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"]

try:
					if not is_flax_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__       =	["FlaxMarianModel", "FlaxMarianMTModel", "FlaxMarianPreTrainedModel"]

if TYPE_CHECKING:
					from .configuration_marian import MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP, MarianConfig, MarianOnnxConfig

					try:
										if not is_sentencepiece_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_marian import MarianTokenizer

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_marian import (
										    MARIAN_PRETRAINED_MODEL_ARCHIVE_LIST,
										    MarianForCausalLM,
										    MarianModel,
										    MarianMTModel,
										    MarianPreTrainedModel,
										)

					try:
										if not is_tf_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_tf_marian import TFMarianModel, TFMarianMTModel, TFMarianPreTrainedModel

					try:
										if not is_flax_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, FlaxMarianPreTrainedModel

else:
					import sys

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


