






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


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

lowerCamelCase     :							Dict    ='''\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n'''





@dataclass
class       __a  (   _UpperCAmelCase	):
 _lowerCAmelCase	:	Union[PIL.Image.Image, np.ndarray]







class       __a  (   _UpperCAmelCase	):







 def __init__(		self :       int							,       SCREAMING_SNAKE_CASE :       Dict							,       SCREAMING_SNAKE_CASE :       Any							,       SCREAMING_SNAKE_CASE :       Union[str, Any]							,       SCREAMING_SNAKE_CASE :       Dict							,       SCREAMING_SNAKE_CASE :       Optional[int]							,       ):


      '''simple docstring'''






      super().__init__()

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







 def  __lowercase (		self :       List[Any]							,       SCREAMING_SNAKE_CASE :       Tuple							,       SCREAMING_SNAKE_CASE :       Any							,       SCREAMING_SNAKE_CASE :       Any							,       SCREAMING_SNAKE_CASE :       Tuple							,       SCREAMING_SNAKE_CASE :       Optional[int]							,       SCREAMING_SNAKE_CASE :       Optional[Any]						):


      '''simple docstring'''






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

      UpperCamelCase__      :       Dict	    =  latents * scheduler.init_noise_sigma
      return latents







 def  __lowercase (		self :       Tuple							,       SCREAMING_SNAKE_CASE :       Optional[Any]=0						):


      '''simple docstring'''






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

      UpperCamelCase__      :       str	    =  torch.device(F'cuda:{gpu_id}'						)

      UpperCamelCase__      :       List[Any]	    =  [self.image_encoder, self.prior]
      for cpu_offloaded_model in models:
           if cpu_offloaded_model is not None:
                cpu_offload(_UpperCAmelCase							,       _UpperCAmelCase						)







 @property
 def  __lowercase (		self :       List[str]						):


      '''simple docstring'''






      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  __lowercase (		self :       List[str]							,       SCREAMING_SNAKE_CASE :       List[Any]							,       SCREAMING_SNAKE_CASE :       Any							,       SCREAMING_SNAKE_CASE :       Tuple							,       SCREAMING_SNAKE_CASE :       Optional[int]							,       ):


      '''simple docstring'''






      if isinstance(_UpperCAmelCase							,       _UpperCAmelCase						) and isinstance(image[0]							,       torch.Tensor						):
           UpperCamelCase__      :       List[Any]	    =  torch.cat(_UpperCAmelCase							,       axis=0						) if image[0].ndim == 4 else torch.stack(_UpperCAmelCase							,       axis=0						)

      if not isinstance(_UpperCAmelCase							,       torch.Tensor						):
           UpperCamelCase__      :       Optional[int]	    =  self.image_processor(_UpperCAmelCase							,       return_tensors="pt"						).pixel_values[0].unsqueeze(0						)

      UpperCamelCase__      :       str	    =  image.to(dtype=self.image_encoder.dtype							,       device=_UpperCAmelCase						)

      UpperCamelCase__      :       str	    =  self.image_encoder(_UpperCAmelCase						)['''last_hidden_state''']
      UpperCamelCase__      :       Tuple	    =  image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

      UpperCamelCase__      :       Any	    =  image_embeds.repeat_interleave(_UpperCAmelCase							,       dim=0						)

      if do_classifier_free_guidance:
           UpperCamelCase__      :       str	    =  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
           UpperCamelCase__      :       Dict	    =  torch.cat([negative_image_embeds, image_embeds]						)

      return image_embeds







 @torch.no_grad()
 @replace_example_docstring(_UpperCAmelCase						)
 def __call__(		self :       Union[str, Any]							,       SCREAMING_SNAKE_CASE :       str							,       SCREAMING_SNAKE_CASE :       int = 1							,       SCREAMING_SNAKE_CASE :       int = 25							,       SCREAMING_SNAKE_CASE :       str = None							,       SCREAMING_SNAKE_CASE :       str = None							,       SCREAMING_SNAKE_CASE :       List[str] = 4.0							,       SCREAMING_SNAKE_CASE :       List[Any] = 64							,       SCREAMING_SNAKE_CASE :       Optional[Any] = "pil"							,       SCREAMING_SNAKE_CASE :       Union[str, Any] = True							,       ):


      '''simple docstring'''






      if isinstance(_UpperCAmelCase							,       PIL.Image.Image						):
           UpperCamelCase__      :       str	    =  1
      elif isinstance(_UpperCAmelCase							,       torch.Tensor						):
           UpperCamelCase__      :       int	    =  image.shape[0]
      elif isinstance(_UpperCAmelCase							,       _UpperCAmelCase						) and isinstance(image[0]							,       (torch.Tensor, PIL.Image.Image)						):
           UpperCamelCase__      :       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						)}'						)

      UpperCamelCase__      :       Optional[Any]	    =  self._execution_device

      UpperCamelCase__      :       Dict	    =  batch_size * num_images_per_prompt

      UpperCamelCase__      :       str	    =  guidance_scale > 1.0
      UpperCamelCase__      :       List[Any]	    =  self._encode_image(_UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase						)

      # prior

      self.scheduler.set_timesteps(_UpperCAmelCase							,       device=_UpperCAmelCase						)
      UpperCamelCase__      :       Union[str, Any]	    =  self.scheduler.timesteps

      UpperCamelCase__      :       List[Any]	    =  self.prior.config.num_embeddings
      UpperCamelCase__      :       List[str]	    =  self.prior.config.embedding_dim

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

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

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

           UpperCamelCase__      :       Optional[int]	    =  self.scheduler.step(
               _UpperCAmelCase							,       timestep=_UpperCAmelCase							,       sample=_UpperCAmelCase							,       ).prev_sample

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

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

           images.append(_UpperCAmelCase						)

      UpperCamelCase__      :       Tuple	    =  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}'						)

      UpperCamelCase__      :       Tuple	    =  images.cpu().numpy()

      if output_type == "pil":
           UpperCamelCase__      :       List[Any]	    =  [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						)








from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
 from ..tf_utils import stable_softmax

lowerCamelCase     :							str    =logging.get_logger(__name__)





@add_end_docstrings(A__	)
class       __a  (   A__	):







 def __init__(		self :       List[str]							,       **SCREAMING_SNAKE_CASE :       Tuple						):


      '''simple docstring'''






      super().__init__(**SCREAMING_SNAKE_CASE						)

      requires_backends(self							,       "vision"						)
      self.check_model_type(
          TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
          if self.framework == "tf"
          else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING						)







 def __call__(		self :       Dict							,       SCREAMING_SNAKE_CASE :       Union[str, List[str], "Image", List["Image"]]							,       **SCREAMING_SNAKE_CASE :       str						):


      '''simple docstring'''






      return super().__call__(SCREAMING_SNAKE_CASE							,       **SCREAMING_SNAKE_CASE						)







 def  __lowercase (		self :       List[str]							,       **SCREAMING_SNAKE_CASE :       List[str]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[Any]	    =  {}
      if "candidate_labels" in kwargs:
           UpperCamelCase__      :       Optional[Any]	    =  kwargs["candidate_labels"]
      if "hypothesis_template" in kwargs:
           UpperCamelCase__      :       int	    =  kwargs["hypothesis_template"]

      return preprocess_params, {}, {}







 def  __lowercase (		self :       List[Any]							,       SCREAMING_SNAKE_CASE :       List[Any]							,       SCREAMING_SNAKE_CASE :       Tuple=None							,       SCREAMING_SNAKE_CASE :       Optional[int]="This is a photo of {}."						):


      '''simple docstring'''






      UpperCamelCase__      :       Dict	    =  load_image(SCREAMING_SNAKE_CASE						)
      UpperCamelCase__      :       List[Any]	    =  self.image_processor(images=[image]							,       return_tensors=self.framework						)
      UpperCamelCase__      :       Any	    =  candidate_labels
      UpperCamelCase__      :       Dict	    =  [hypothesis_template.format(SCREAMING_SNAKE_CASE						) for x in candidate_labels]
      UpperCamelCase__      :       Optional[Any]	    =  self.tokenizer(SCREAMING_SNAKE_CASE							,       return_tensors=self.framework							,       padding=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__      :       List[Any]	    =  [text_inputs]
      return inputs







 def  __lowercase (		self :       int							,       SCREAMING_SNAKE_CASE :       Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__      :       Tuple	    =  model_inputs.pop("candidate_labels"						)
      UpperCamelCase__      :       List[str]	    =  model_inputs.pop("text_inputs"						)
      if isinstance(text_inputs[0]							,       SCREAMING_SNAKE_CASE						):
           UpperCamelCase__      :       Dict	    =  text_inputs[0]
      else:
           # Batching case.
           UpperCamelCase__      :       Union[str, Any]	    =  text_inputs[0][0]

      UpperCamelCase__      :       Any	    =  self.model(**SCREAMING_SNAKE_CASE							,       **SCREAMING_SNAKE_CASE						)

      UpperCamelCase__      :       Dict	    =  {
          "candidate_labels": candidate_labels,
          "logits": outputs.logits_per_image,
      }
      return model_outputs







 def  __lowercase (		self :       Any							,       SCREAMING_SNAKE_CASE :       List[str]						):


      '''simple docstring'''






      UpperCamelCase__      :       Optional[int]	    =  model_outputs.pop("candidate_labels"						)
      UpperCamelCase__      :       int	    =  model_outputs["logits"][0]
      if self.framework == "pt":
           UpperCamelCase__      :       Dict	    =  logits.softmax(dim=-1						).squeeze(-1						)
           UpperCamelCase__      :       Optional[Any]	    =  probs.tolist()
           if not isinstance(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						):
                UpperCamelCase__      :       List[Any]	    =  [scores]
      elif self.framework == "tf":
           UpperCamelCase__      :       Optional[Any]	    =  stable_softmax(SCREAMING_SNAKE_CASE							,       axis=-1						)
           UpperCamelCase__      :       Optional[int]	    =  probs.numpy().tolist()
      else:
           raise ValueError(F'Unsupported framework: {self.framework}'						)

      UpperCamelCase__      :       Optional[int]	    =  [
          {"score": score, "label": candidate_label}
          for score, candidate_label in sorted(zip(SCREAMING_SNAKE_CASE							,       SCREAMING_SNAKE_CASE						)							,       key=lambda SCREAMING_SNAKE_CASE						: -x[0]						)
      ]
      return result