


"""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 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





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


class 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





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







								'''simple docstring'''




								super().__init__()

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




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								if latents is None:
									snake_case__  :						str		=      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__  :						Union[str, Any]		=      latents.to(lowerCamelCase__)

								snake_case__  :						Optional[int]		=      latents * scheduler.init_noise_sigma
								return latents




							def        UpperCAmelCase (						self	,					lowerCamelCase__=0)   ->	Optional[int]:







								'''simple docstring'''




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

								snake_case__  :						str		=      torch.device(f"""cuda:{gpu_id}""")

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




							def        UpperCAmelCase (						self	,					lowerCamelCase__=0)   ->	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.")

								snake_case__  :						Dict		=      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__  :						int		=      None
								for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
									snake_case__,					snake_case__  :						str		=      cpu_offload_with_hook(lowerCamelCase__	,					lowerCamelCase__	,					prev_module_hook=lowerCamelCase__)

								if self.safety_checker is not None:
									snake_case__,					snake_case__  :						Union[str, Any]		=      cpu_offload_with_hook(self.safety_checker	,					lowerCamelCase__	,					prev_module_hook=lowerCamelCase__)

								# We'll offload the last model manually.
								snake_case__  :						List[Any]		=      hook




							@property
							def        UpperCAmelCase (						self)   ->	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        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					)   ->	Optional[Any]:







								'''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__  :						Tuple		=      0
								# get prompt text embeddings
								snake_case__  :						Tuple		=      self.tokenizer(
								    lowerCamelCase__	,					padding="max_length"	,					max_length=self.tokenizer.model_max_length	,					truncation=lowerCamelCase__	,					return_tensors="pt"	,					)
								snake_case__  :						str		=      text_inputs.input_ids
								snake_case__  :						Union[str, Any]		=      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__  :						int		=      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__  :						str		=      self.text_encoder(text_input_ids.to(lowerCamelCase__))
								snake_case__  :						Optional[int]		=      text_encoder_output.text_embeds

								snake_case__  :						str		=      prompt_embeds.repeat_interleave(lowerCamelCase__	,					dim=0)
								# in Shap-E it normalize the prompt_embeds and then later rescale it
								snake_case__  :						Optional[int]		=      prompt_embeds / torch.linalg.norm(lowerCamelCase__	,					dim=-1	,					keepdim=lowerCamelCase__)

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

								# Rescale the features to have unit variance
								snake_case__  :						int		=      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	,					)   ->	Any:







								'''simple docstring'''




								if isinstance(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						Optional[int]		=      1
								elif isinstance(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						Optional[Any]		=      len(lowerCamelCase__)
								else:
									raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase__)}""")

								snake_case__  :						Optional[Any]		=      self._execution_device

								snake_case__  :						int		=      batch_size * num_images_per_prompt

								snake_case__  :						int		=      guidance_scale > 1.0
								snake_case__  :						Tuple		=      self._encode_prompt(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)

								# prior

								self.scheduler.set_timesteps(lowerCamelCase__	,					device=lowerCamelCase__)
								snake_case__  :						Dict		=      self.scheduler.timesteps

								snake_case__  :						str		=      self.prior.config.num_embeddings
								snake_case__  :						Optional[Any]		=      self.prior.config.embedding_dim

								snake_case__  :						Union[str, Any]		=      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__  :						str		=      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__  :						Union[str, Any]		=      torch.cat([latents] * 2) if do_classifier_free_guidance else latents
									snake_case__  :						List[str]		=      self.scheduler.scale_model_input(lowerCamelCase__	,					lowerCamelCase__)

									snake_case__  :						Union[str, Any]		=      self.prior(
									    lowerCamelCase__	,					timestep=lowerCamelCase__	,					proj_embedding=lowerCamelCase__	,					).predicted_image_embedding

									# remove the variance
									snake_case__,					snake_case__  :						List[str]		=      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__  :						int		=      noise_pred.chunk(2)
										snake_case__  :						Union[str, Any]		=      noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

									snake_case__  :						int		=      self.scheduler.step(
									    lowerCamelCase__	,					timestep=lowerCamelCase__	,					sample=lowerCamelCase__	,					).prev_sample

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

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

								snake_case__  :						Dict		=      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__  :						Any		=      images.cpu().numpy()

								if output_type == "pil":
									snake_case__  :						Dict		=      [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"""
# Lint as: python3

import hashlib
from typing import Union






def 				__lowerCAmelCase					(					__lowerCAmelCase			:		Union[str, int, bytes]						)    ->       bytes:
 if isinstance(__lowerCAmelCase  ,	__lowerCAmelCase						):
  # Data already in bytes, returns as it as
  return hash_data
 elif isinstance(__lowerCAmelCase  ,	__lowerCAmelCase						):
  # We keep the data as it as for it ot be later encoded to UTF-8
  # However replace `\\` with `/` for Windows compatibility
  _UpperCamelCase      :	int					      =  hash_data.replace("\\"  ,	"/"						)
 elif isinstance(__lowerCAmelCase  ,	__lowerCAmelCase						):
  _UpperCamelCase      :	Union[str, Any]					      =  str(__lowerCAmelCase						)
 else:
  # If data is not of the required type, raise error
  raise InvalidKeyError(__lowerCAmelCase						)

 return hash_data.encode("utf-8"						)







class  _SCREAMING_SNAKE_CASE       (     SCREAMING_SNAKE_CASE__				):



 '''simple docstring'''





 def __init__(self					,     lowerCAmelCase__   ):

  '''simple docstring'''







  _UpperCamelCase      :	int					      =  "\nFAILURE TO GENERATE DATASET: Invalid key type detected"
  _UpperCamelCase      :	Tuple					      =  F"\nFound Key {hash_data} of type {type(lowerCAmelCase__   )}"
  _UpperCamelCase      :	str					      =  "\nKeys should be either str, int or bytes type"
  super().__init__(F"{self.prefix}{self.err_msg}{self.suffix}"   )







class  _SCREAMING_SNAKE_CASE       (     SCREAMING_SNAKE_CASE__				):



 '''simple docstring'''





 def __init__(self					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__=""   ):

  '''simple docstring'''







  _UpperCamelCase      :	Optional[int]					      =  key
  _UpperCamelCase      :	Tuple					      =  duplicate_key_indices
  _UpperCamelCase      :	int					      =  fix_msg
  _UpperCamelCase      :	List[Any]					      =  "Found multiple examples generated with the same key"
  if len(lowerCAmelCase__   ) <= 20:
   _UpperCamelCase      :	Optional[Any]					      =  F"\nThe examples at index {', '.join(lowerCAmelCase__   )} have the key {key}"
  else:
   _UpperCamelCase      :	Union[str, Any]					      =  F"\nThe examples at index {', '.join(duplicate_key_indices[:20]   )}... ({len(lowerCAmelCase__   ) - 20} more) have the key {key}"
  _UpperCamelCase      :	List[Any]					      =  "\n" + fix_msg if fix_msg else ""
  super().__init__(F"{self.prefix}{self.err_msg}{self.suffix}"   )







class  _SCREAMING_SNAKE_CASE       :



 '''simple docstring'''





 def __init__(self					,     lowerCAmelCase__   ):

  '''simple docstring'''







  _UpperCamelCase      :	Union[str, Any]					      =  hashlib.mda(_as_bytes(lowerCAmelCase__   )   )






 def lowercase_      (self					,     lowerCAmelCase__   ):

  '''simple docstring'''







  _UpperCamelCase      :	Any					      =  self._split_mda.copy()
  _UpperCamelCase      :	List[str]					      =  _as_bytes(lowerCAmelCase__   )
  mda.update(lowerCAmelCase__   )
  # Convert to integer with hexadecimal conversion
  return int(mda.hexdigest()					,     16   )



