


"""simple docstring"""







from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

__lowercase    					=      """
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""






@dataclass
class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase       :							Union[PIL.Image.Image, np.ndarray]






class 						_A  (  _a  ):







    """simple docstring"""




    def __init__(					self				:    List[str]				, __UpperCAmelCase				:    PriorTransformer				, __UpperCAmelCase				:    CLIPVisionModel				, __UpperCAmelCase				:    CLIPImageProcessor				, __UpperCAmelCase				:    HeunDiscreteScheduler				, __UpperCAmelCase				:    ShapERenderer				, ):
      super().__init__()

      self.register_modules(
          prior=__UpperCAmelCase				, image_encoder=__UpperCAmelCase				, image_processor=__UpperCAmelCase				, scheduler=__UpperCAmelCase				, renderer=__UpperCAmelCase				, )






    def 	__snake_case							(					self				:    int				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    Dict				, __UpperCAmelCase				:    Optional[int]):
      if latents is None:
        a						:		Any      							=			randn_tensor(__UpperCAmelCase				, generator=__UpperCAmelCase				, device=__UpperCAmelCase				, dtype=__UpperCAmelCase)
      else:
        if latents.shape != shape:
          raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''')
        a						:		Union[str, Any]      							=			latents.to(__UpperCAmelCase)

      a						:		Any      							=			latents * scheduler.init_noise_sigma
      return latents






    def 	__snake_case							(					self				:    Any				, __UpperCAmelCase				:    str=0):
      if is_accelerate_available():
        from accelerate import cpu_offload
      else:
        raise ImportError("Please install accelerate via `pip install accelerate`")

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

      a						:		Tuple      							=			[self.image_encoder, self.prior]
      for cpu_offloaded_model in models:
        if cpu_offloaded_model is not None:
          cpu_offload(__UpperCAmelCase				, __UpperCAmelCase)






    @property
    def 	__snake_case							(					self				:    int):
      if self.device != torch.device("meta") or not hasattr(self.image_encoder				, "_hf_hook"):
        return self.device
      for module in self.image_encoder.modules():
        if (
            hasattr(__UpperCAmelCase				, "_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				:    List[str]				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    List[Any]				, ):
      if isinstance(__UpperCAmelCase				, __UpperCAmelCase) and isinstance(image[0]				, torch.Tensor):
        a						:		List[Any]      							=			torch.cat(__UpperCAmelCase				, axis=0) if image[0].ndim == 4 else torch.stack(__UpperCAmelCase				, axis=0)

      if not isinstance(__UpperCAmelCase				, torch.Tensor):
        a						:		Any      							=			self.image_processor(__UpperCAmelCase				, return_tensors="pt").pixel_values[0].unsqueeze(0)

      a						:		Union[str, Any]      							=			image.to(dtype=self.image_encoder.dtype				, device=__UpperCAmelCase)

      a						:		List[Any]      							=			self.image_encoder(__UpperCAmelCase)["last_hidden_state"]
      a						:		List[str]      							=			image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

      a						:		str      							=			image_embeds.repeat_interleave(__UpperCAmelCase				, dim=0)

      if do_classifier_free_guidance:
        a						:		Dict      							=			torch.zeros_like(__UpperCAmelCase)

        # 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
        a						:		int      							=			torch.cat([negative_image_embeds, image_embeds])

      return image_embeds






    @torch.no_grad()
    @replace_example_docstring(__UpperCAmelCase)
    def __call__(					self				:    Any				, __UpperCAmelCase				:    Union[PIL.Image.Image, List[PIL.Image.Image]]				, __UpperCAmelCase				:    int = 1				, __UpperCAmelCase				:    int = 25				, __UpperCAmelCase				:    Optional[Union[torch.Generator, List[torch.Generator]]] = None				, __UpperCAmelCase				:    Optional[torch.FloatTensor] = None				, __UpperCAmelCase				:    float = 4.0				, __UpperCAmelCase				:    int = 64				, __UpperCAmelCase				:    Optional[str] = "pil"				, __UpperCAmelCase				:    bool = True				, ):

      if isinstance(__UpperCAmelCase				, PIL.Image.Image):
        a						:		Tuple      							=			1
      elif isinstance(__UpperCAmelCase				, torch.Tensor):
        a						:		Optional[Any]      							=			image.shape[0]
      elif isinstance(__UpperCAmelCase				, __UpperCAmelCase) and isinstance(image[0]				, (torch.Tensor, PIL.Image.Image)):
        a						:		int      							=			len(__UpperCAmelCase)
      else:
        raise ValueError(
            f'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__UpperCAmelCase)}''')

      a						:		List[Any]      							=			self._execution_device

      a						:		Optional[Any]      							=			batch_size * num_images_per_prompt

      a						:		Union[str, Any]      							=			guidance_scale > 1.0
      a						:		Optional[int]      							=			self._encode_image(__UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase)

      # prior

      self.scheduler.set_timesteps(__UpperCAmelCase				, device=__UpperCAmelCase)
      a						:		str      							=			self.scheduler.timesteps

      a						:		Optional[int]      							=			self.prior.config.num_embeddings
      a						:		Optional[int]      							=			self.prior.config.embedding_dim

      a						:		List[str]      							=			self.prepare_latents(
          (batch_size, num_embeddings * embedding_dim)				, image_embeds.dtype				, __UpperCAmelCase				, __UpperCAmelCase				, __UpperCAmelCase				, 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
      a						:		List[str]      							=			latents.reshape(latents.shape[0]				, __UpperCAmelCase				, __UpperCAmelCase)

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

        a						:		Optional[int]      							=			self.prior(
            __UpperCAmelCase				, timestep=__UpperCAmelCase				, proj_embedding=__UpperCAmelCase				, ).predicted_image_embedding

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

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

        a						:		Any      							=			self.scheduler.step(
            __UpperCAmelCase				, timestep=__UpperCAmelCase				, sample=__UpperCAmelCase				, ).prev_sample

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

      a						:		Optional[int]      							=			[]
      for i, latent in enumerate(__UpperCAmelCase):
        print()
        a						:		Tuple      							=			self.renderer.decode(
            latent[None, :]				, __UpperCAmelCase				, size=__UpperCAmelCase				, ray_batch_size=4096				, n_coarse_samples=64				, n_fine_samples=128				, )

        images.append(__UpperCAmelCase)

      a						:		List[str]      							=			torch.stack(__UpperCAmelCase)

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

      a						:		Union[str, Any]      							=			images.cpu().numpy()

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










"""simple docstring"""







from typing import TYPE_CHECKING

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


__lowercase    					=      {
    """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""],
    """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowercase    					=      ["""BertTokenizerFast"""]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowercase    					=      [
     """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """BertForMaskedLM""",
     """BertForMultipleChoice""",
     """BertForNextSentencePrediction""",
     """BertForPreTraining""",
     """BertForQuestionAnswering""",
     """BertForSequenceClassification""",
     """BertForTokenClassification""",
     """BertLayer""",
     """BertLMHeadModel""",
     """BertModel""",
     """BertPreTrainedModel""",
     """load_tf_weights_in_bert""",
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowercase    					=      [
     """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """TFBertEmbeddings""",
     """TFBertForMaskedLM""",
     """TFBertForMultipleChoice""",
     """TFBertForNextSentencePrediction""",
     """TFBertForPreTraining""",
     """TFBertForQuestionAnswering""",
     """TFBertForSequenceClassification""",
     """TFBertForTokenClassification""",
     """TFBertLMHeadModel""",
     """TFBertMainLayer""",
     """TFBertModel""",
     """TFBertPreTrainedModel""",
 ]
try:
 if not is_tensorflow_text_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowercase    					=      ["""TFBertTokenizer"""]

try:
 if not is_flax_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowercase    					=      [
     """FlaxBertForCausalLM""",
     """FlaxBertForMaskedLM""",
     """FlaxBertForMultipleChoice""",
     """FlaxBertForNextSentencePrediction""",
     """FlaxBertForPreTraining""",
     """FlaxBertForQuestionAnswering""",
     """FlaxBertForSequenceClassification""",
     """FlaxBertForTokenClassification""",
     """FlaxBertModel""",
     """FlaxBertPreTrainedModel""",
 ]

if TYPE_CHECKING:
 from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig
 from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_bert_fast import BertTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_bert import (
      BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      BertForMaskedLM,
      BertForMultipleChoice,
      BertForNextSentencePrediction,
      BertForPreTraining,
      BertForQuestionAnswering,
      BertForSequenceClassification,
      BertForTokenClassification,
      BertLayer,
      BertLMHeadModel,
      BertModel,
      BertPreTrainedModel,
      load_tf_weights_in_bert,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_bert import (
      TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFBertEmbeddings,
      TFBertForMaskedLM,
      TFBertForMultipleChoice,
      TFBertForNextSentencePrediction,
      TFBertForPreTraining,
      TFBertForQuestionAnswering,
      TFBertForSequenceClassification,
      TFBertForTokenClassification,
      TFBertLMHeadModel,
      TFBertMainLayer,
      TFBertModel,
      TFBertPreTrainedModel,
  )

 try:
  if not is_tensorflow_text_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_bert_tf import TFBertTokenizer

 try:
  if not is_flax_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_flax_bert import (
      FlaxBertForCausalLM,
      FlaxBertForMaskedLM,
      FlaxBertForMultipleChoice,
      FlaxBertForNextSentencePrediction,
      FlaxBertForPreTraining,
      FlaxBertForQuestionAnswering,
      FlaxBertForSequenceClassification,
      FlaxBertForTokenClassification,
      FlaxBertModel,
      FlaxBertPreTrainedModel,
  )

else:
 import sys

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






