


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


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

__UpperCAmelCase    				=      "\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_  ( a_						):
      __magic_name__     :							Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]

class  lowercase_  ( a_						):







      def __init__(      self :							Tuple		,  _lowercase :							PriorTransformer		,  _lowercase :							CLIPTextModelWithProjection		,  _lowercase :							CLIPTokenizer		,  _lowercase :							HeunDiscreteScheduler		,  _lowercase :							ShapERenderer		,  ):
        super().__init__()

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







      def 				_lowerCAmelCase       (      self :							Union[str, Any]		,  _lowercase :							List[Any]		,  _lowercase :							str		,  _lowercase :							Any		,  _lowercase :							Any		,  _lowercase :							Any		,  _lowercase :							List[str]    ):
        if latents is None:
          lowerCAmelCase__    :    List[Any]								=					randn_tensor(_lowercase		,  generator=_lowercase		,  device=_lowercase		,  dtype=_lowercase    )
        else:
          if latents.shape != shape:
            raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"    )
          lowerCAmelCase__    :    List[Any]								=					latents.to(_lowercase    )

        lowerCAmelCase__    :    Dict								=					latents * scheduler.init_noise_sigma
        return latents







      def 				_lowerCAmelCase       (      self :							int		,  _lowercase :							List[Any]=0    ):
        if is_accelerate_available():
          from accelerate import cpu_offload
        else:
          raise ImportError("Please install accelerate via `pip install accelerate`"    )

        lowerCAmelCase__    :    Any								=					torch.device(f"cuda:{gpu_id}"    )

        lowerCAmelCase__    :    Optional[int]								=					[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
            cpu_offload(_lowercase		,  _lowercase    )







      def 				_lowerCAmelCase       (      self :							Optional[Any]		,  _lowercase :							Dict=0    ):
        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__    :    Dict								=					torch.device(f"cuda:{gpu_id}"    )

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

        lowerCAmelCase__    :    Tuple								=					None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
          lowerCAmelCase__    :    Dict								=					cpu_offload_with_hook(_lowercase		,  _lowercase		,  prev_module_hook=_lowercase    )

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

        # We'll offload the last model manually.
        lowerCAmelCase__    :    Optional[int]								=					hook







      @property
      def 				_lowerCAmelCase       (      self :							Optional[int]    ):
        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(_lowercase		,  "_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 :							Union[str, Any]		,  _lowercase :							Optional[int]		,  _lowercase :							List[Any]		,  _lowercase :							Any		,  _lowercase :							Optional[Any]		,  ):
        len(_lowercase    ) if isinstance(_lowercase		,  _lowercase    ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        lowerCAmelCase__    :    Union[str, Any]								=					0
        # get prompt text embeddings
        lowerCAmelCase__    :    List[Any]								=					self.tokenizer(
            _lowercase		,  padding="max_length"		,  max_length=self.tokenizer.model_max_length		,  truncation=_lowercase		,  return_tensors="pt"		,  )
        lowerCAmelCase__    :    int								=					text_inputs.input_ids
        lowerCAmelCase__    :    Optional[Any]								=					self.tokenizer(_lowercase		,  padding="longest"		,  return_tensors="pt"    ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_lowercase		,  _lowercase    ):
          lowerCAmelCase__    :    Optional[Any]								=					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__    :    int								=					self.text_encoder(text_input_ids.to(_lowercase    )    )
        lowerCAmelCase__    :    Optional[Any]								=					text_encoder_output.text_embeds

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

        if do_classifier_free_guidance:
          lowerCAmelCase__    :    int								=					torch.zeros_like(_lowercase    )

          # 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__    :    Union[str, Any]								=					torch.cat([negative_prompt_embeds, prompt_embeds]    )

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

        return prompt_embeds







      @torch.no_grad()
      @replace_example_docstring(_lowercase    )
      def __call__(      self :							Tuple		,  _lowercase :							str		,  _lowercase :							int = 1		,  _lowercase :							int = 2_5		,  _lowercase :							Optional[Union[torch.Generator, List[torch.Generator]]] = None		,  _lowercase :							Optional[torch.FloatTensor] = None		,  _lowercase :							float = 4.0		,  _lowercase :							int = 6_4		,  _lowercase :							Optional[str] = "pil"		,  _lowercase :							bool = True		,  ):

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

        lowerCAmelCase__    :    Any								=					self._execution_device

        lowerCAmelCase__    :    Optional[int]								=					batch_size * num_images_per_prompt

        lowerCAmelCase__    :    List[Any]								=					guidance_scale > 1.0
        lowerCAmelCase__    :    int								=					self._encode_prompt(_lowercase		,  _lowercase		,  _lowercase		,  _lowercase    )

        # prior

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

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

        lowerCAmelCase__    :    Any								=					self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)		,  prompt_embeds.dtype		,  _lowercase		,  _lowercase		,  _lowercase		,  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__    :    Any								=					latents.reshape(latents.shape[0]		,  _lowercase		,  _lowercase    )

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

          lowerCAmelCase__    :    Optional[int]								=					self.prior(
              _lowercase		,  timestep=_lowercase		,  proj_embedding=_lowercase		,  ).predicted_image_embedding

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

          lowerCAmelCase__    :    List[Any]								=					self.scheduler.step(
              _lowercase		,  timestep=_lowercase		,  sample=_lowercase		,  ).prev_sample

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

        lowerCAmelCase__    :    Optional[Any]								=					[]
        for i, latent in enumerate(_lowercase    ):
          lowerCAmelCase__    :    str								=					self.renderer.decode(
              latent[None, :]		,  _lowercase		,  size=_lowercase		,  ray_batch_size=4_0_9_6		,  n_coarse_samples=6_4		,  n_fine_samples=1_2_8		,  )
          images.append(_lowercase    )

        lowerCAmelCase__    :    Union[str, Any]								=					torch.stack(_lowercase    )

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

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




"""simple docstring"""





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__UpperCAmelCase    				=      {"configuration_sew_d": ["SEW_D_PRETRAINED_CONFIG_ARCHIVE_MAP", "SEWDConfig"]}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   __UpperCAmelCase    				=      [
       "SEW_D_PRETRAINED_MODEL_ARCHIVE_LIST",
       "SEWDForCTC",
       "SEWDForSequenceClassification",
       "SEWDModel",
       "SEWDPreTrainedModel",
   ]

if TYPE_CHECKING:
   from .configuration_sew_d import SEW_D_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWDConfig

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_sew_d import (
          SEW_D_PRETRAINED_MODEL_ARCHIVE_LIST,
          SEWDForCTC,
          SEWDForSequenceClassification,
          SEWDModel,
          SEWDPreTrainedModel,
      )


else:
   import sys

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