






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


_snake_case							:   Optional[Any]	  =       logging.get_logger(__name__)  # pylint: disable=invalid-name

_snake_case							:   Optional[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 							__lowercase(							_UpperCamelCase	):
						lowerCAmelCase_		:				Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]




class 							__lowercase(							_UpperCamelCase	):






						def __init__(       self     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    )      ->	Optional[int]:




											"""simple docstring"""





											super().__init__()

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






						def 		lowerCAmelCase (       self     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)      ->	Optional[Any]:




											"""simple docstring"""





											if latents is None:
																lowerCamelCase__					=randn_tensor(_SCREAMING_SNAKE_CASE     ,    generator=_SCREAMING_SNAKE_CASE     ,    device=_SCREAMING_SNAKE_CASE     ,    dtype=_SCREAMING_SNAKE_CASE)
											else:
																if latents.shape != shape:
																					raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}")
																lowerCamelCase__					=latents.to(_SCREAMING_SNAKE_CASE)

											lowerCamelCase__					=latents * scheduler.init_noise_sigma
											return latents






						def 		lowerCAmelCase (       self     ,    _SCREAMING_SNAKE_CASE=0)      ->	Optional[int]:




											"""simple docstring"""





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

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

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






						def 		lowerCAmelCase (       self     ,    _SCREAMING_SNAKE_CASE=0)      ->	int:




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

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

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

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

											if self.safety_checker is not None:
																lowerCamelCase__					,  lowerCamelCase__					=cpu_offload_with_hook(self.safety_checker     ,    _SCREAMING_SNAKE_CASE     ,    prev_module_hook=_SCREAMING_SNAKE_CASE)

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






						@property
						def 		lowerCAmelCase (       self)      ->	Tuple:




											"""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(_SCREAMING_SNAKE_CASE     ,    '_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 		lowerCAmelCase (       self     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    )      ->	Union[str, Any]:




											"""simple docstring"""





											len(_SCREAMING_SNAKE_CASE) if isinstance(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE) else 1

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

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

											lowerCamelCase__					=self.text_encoder(text_input_ids.to(_SCREAMING_SNAKE_CASE))
											lowerCamelCase__					=text_encoder_output.text_embeds

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

											if do_classifier_free_guidance:
																lowerCamelCase__					=torch.zeros_like(_SCREAMING_SNAKE_CASE)

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

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

											return prompt_embeds






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




											"""simple docstring"""





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

											lowerCamelCase__					=self._execution_device

											lowerCamelCase__					=batch_size * num_images_per_prompt

											lowerCamelCase__					=guidance_scale > 1.0
											lowerCamelCase__					=self._encode_prompt(_SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE     ,    _SCREAMING_SNAKE_CASE)

											# prior

											self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE     ,    device=_SCREAMING_SNAKE_CASE)
											lowerCamelCase__					=self.scheduler.timesteps

											lowerCamelCase__					=self.prior.config.num_embeddings
											lowerCamelCase__					=self.prior.config.embedding_dim

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

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

																lowerCamelCase__					=self.prior(
																    _SCREAMING_SNAKE_CASE     ,    timestep=_SCREAMING_SNAKE_CASE     ,    proj_embedding=_SCREAMING_SNAKE_CASE     ,    ).predicted_image_embedding

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

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

																lowerCamelCase__					=self.scheduler.step(
																    _SCREAMING_SNAKE_CASE     ,    timestep=_SCREAMING_SNAKE_CASE     ,    sample=_SCREAMING_SNAKE_CASE     ,    ).prev_sample

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

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

											lowerCamelCase__					=torch.stack(_SCREAMING_SNAKE_CASE)

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

											lowerCamelCase__					=images.cpu().numpy()

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







"""simple docstring"""



import warnings

from ...utils import logging
from .image_processing_vit import ViTImageProcessor


_snake_case							:   Tuple	  =       logging.get_logger(__name__)




class 							__lowercase(							_UpperCamelCase	):






						def __init__(       self     ,    *_SCREAMING_SNAKE_CASE     ,    **_SCREAMING_SNAKE_CASE)      ->	None:




											"""simple docstring"""





											warnings.warn(
											    'The class ViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
											    ' use ViTImageProcessor instead.'     ,    _SCREAMING_SNAKE_CASE     ,    )
											super().__init__(*_SCREAMING_SNAKE_CASE     ,    **_SCREAMING_SNAKE_CASE)