

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_									=   '\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  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE							):
  _a									=  42





class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE							):




  def __init__(				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   )  -> int:
        '''simple docstring'''






        super().__init__()

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




  def   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)  -> Optional[int]:
        '''simple docstring'''






        if latents is None:
              _lowercase	       =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}'''					)
              _lowercase	       =latents.to(lowerCAmelCase					)

        _lowercase	       =latents * scheduler.init_noise_sigma
        return latents




  def   A__     (				self							,   lowerCAmelCase=0					)  -> int:
        '''simple docstring'''






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

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

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




  @property
  def   A__     (				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(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   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   )  -> Union[str, Any]:
        '''simple docstring'''






        if isinstance(lowerCAmelCase							,   lowerCAmelCase					) and isinstance(image[0]							,   torch.Tensor					):
              _lowercase	       =torch.cat(lowerCAmelCase							,   axis=0					) if image[0].ndim == 4 else torch.stack(lowerCAmelCase							,   axis=0					)

        if not isinstance(lowerCAmelCase							,   torch.Tensor					):
              _lowercase	       =self.image_processor(lowerCAmelCase							,   return_tensors='pt'					).pixel_values[0].unsqueeze(0					)

        _lowercase	       =image.to(dtype=self.image_encoder.dtype							,   device=lowerCAmelCase					)

        _lowercase	       =self.image_encoder(lowerCAmelCase					)['last_hidden_state']
        _lowercase	       =image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

        _lowercase	       =image_embeds.repeat_interleave(lowerCAmelCase							,   dim=0					)

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

        return image_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							,   )  -> Dict:
        '''simple docstring'''






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

        _lowercase	       =self._execution_device

        _lowercase	       =batch_size * num_images_per_prompt

        _lowercase	       =guidance_scale > 1.0
        _lowercase	       =self._encode_image(lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)

        # prior

        self.scheduler.set_timesteps(lowerCAmelCase							,   device=lowerCAmelCase					)
        _lowercase	       =self.scheduler.timesteps

        _lowercase	       =self.prior.config.num_embeddings
        _lowercase	       =self.prior.config.embedding_dim

        _lowercase	       =self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)							,   image_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
        _lowercase	       =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
              _lowercase	       =torch.cat([latents] * 2					) if do_classifier_free_guidance else latents
              _lowercase	       =self.scheduler.scale_model_input(lowerCAmelCase							,   lowerCAmelCase					)

              _lowercase	       =self.prior(
                  lowerCAmelCase							,   timestep=lowerCAmelCase							,   proj_embedding=lowerCAmelCase							,   ).predicted_image_embedding

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

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

              _lowercase	       =self.scheduler.step(
                  lowerCAmelCase							,   timestep=lowerCAmelCase							,   sample=lowerCAmelCase							,   ).prev_sample

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

        _lowercase	       =[]
        for i, latent in enumerate(lowerCAmelCase					):
              print()
              _lowercase	       =self.renderer.decode(
                  latent[None, :]							,   lowerCAmelCase							,   size=lowerCAmelCase							,   ray_batch_size=4_096							,   n_coarse_samples=64							,   n_fine_samples=128							,   )

              images.append(lowerCAmelCase					)

        _lowercase	       =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}'''					)

        _lowercase	       =images.cpu().numpy()

        if output_type == "pil":
              _lowercase	       =[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					)





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
  import torch





class  __lowerCAmelCase     (					TensorFormatter[Mapping, """torch.Tensor""", Mapping]							):




  def __init__(				self							,   lowerCAmelCase=None							,   **lowerCAmelCase					)  -> Optional[Any]:
        '''simple docstring'''






        super().__init__(features=lowerCAmelCase					)
        _lowercase	       =torch_tensor_kwargs
        import torch  # noqa import torch at initialization




  def   A__     (				self							,   lowerCAmelCase					)  -> int:
        '''simple docstring'''






        import torch

        if isinstance(lowerCAmelCase							,   lowerCAmelCase					) and column:
              if all(
                  isinstance(lowerCAmelCase							,   torch.Tensor					) and x.shape == column[0].shape and x.dtype == column[0].dtype
                  for x in column					):
                    return torch.stack(lowerCAmelCase					)
        return column




  def   A__     (				self							,   lowerCAmelCase					)  -> str:
        '''simple docstring'''






        import torch

        if isinstance(lowerCAmelCase							,   (str, bytes, type(lowerCAmelCase					))					):
              return value
        elif isinstance(lowerCAmelCase							,   (np.character, np.ndarray)					) and np.issubdtype(value.dtype							,   np.character					):
              return value.tolist()

        _lowercase	       ={}

        if isinstance(lowerCAmelCase							,   (np.number, np.ndarray)					) and np.issubdtype(value.dtype							,   np.integer					):
              _lowercase	       ={'dtype': torch.intaa}
        elif isinstance(lowerCAmelCase							,   (np.number, np.ndarray)					) and np.issubdtype(value.dtype							,   np.floating					):
              _lowercase	       ={'dtype': torch.floataa}
        elif config.PIL_AVAILABLE and "PIL" in sys.modules:
              import PIL.Image

              if isinstance(lowerCAmelCase							,   PIL.Image.Image					):
                    _lowercase	       =np.asarray(lowerCAmelCase					)
        return torch.tensor(lowerCAmelCase							,   **{**default_dtype, **self.torch_tensor_kwargs}					)




  def   A__     (				self							,   lowerCAmelCase					)  -> str:
        '''simple docstring'''






        import torch

        # support for torch, tf, jax etc.
        if hasattr(lowerCAmelCase							,   '__array__'					) and not isinstance(lowerCAmelCase							,   torch.Tensor					):
              _lowercase	       =data_struct.__array__()
        # support for nested types like struct of list of struct
        if isinstance(lowerCAmelCase							,   np.ndarray					):
              if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                    return self._consolidate([self.recursive_tensorize(lowerCAmelCase					) for substruct in data_struct]					)
        elif isinstance(lowerCAmelCase							,   (list, tuple)					):
              return self._consolidate([self.recursive_tensorize(lowerCAmelCase					) for substruct in data_struct]					)
        return self._tensorize(lowerCAmelCase					)




  def   A__     (				self							,   lowerCAmelCase					)  -> Tuple:
        '''simple docstring'''






        return map_nested(self._recursive_tensorize							,   lowerCAmelCase							,   map_list=lowerCAmelCase					)




  def   A__     (				self							,   lowerCAmelCase					)  -> Mapping:
        '''simple docstring'''






        _lowercase	       =self.numpy_arrow_extractor().extract_row(lowerCAmelCase					)
        _lowercase	       =self.python_features_decoder.decode_row(lowerCAmelCase					)
        return self.recursive_tensorize(lowerCAmelCase					)




  def   A__     (				self							,   lowerCAmelCase					)  -> "torch.Tensor":
        '''simple docstring'''






        _lowercase	       =self.numpy_arrow_extractor().extract_column(lowerCAmelCase					)
        _lowercase	       =self.python_features_decoder.decode_column(lowerCAmelCase							,   pa_table.column_names[0]					)
        _lowercase	       =self.recursive_tensorize(lowerCAmelCase					)
        _lowercase	       =self._consolidate(lowerCAmelCase					)
        return column




  def   A__     (				self							,   lowerCAmelCase					)  -> Mapping:
        '''simple docstring'''






        _lowercase	       =self.numpy_arrow_extractor().extract_batch(lowerCAmelCase					)
        _lowercase	       =self.python_features_decoder.decode_batch(lowerCAmelCase					)
        _lowercase	       =self.recursive_tensorize(lowerCAmelCase					)
        for column_name in batch:
              _lowercase	       =self._consolidate(batch[column_name]					)
        return batch


