



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


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

__UpperCAmelCase      =    '''
    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 	__snake_case	(     __snake_case):
  snake_case__    :       Union[PIL.Image.Image, np.ndarray]






class 	__snake_case	(     __snake_case):




  def __init__(			self					:						Union[str, Any]						, __lowerCAmelCase					:						PriorTransformer						, __lowerCAmelCase					:						CLIPVisionModel						, __lowerCAmelCase					:						CLIPImageProcessor						, __lowerCAmelCase					:						HeunDiscreteScheduler						, __lowerCAmelCase					:						ShapERenderer						, ):






         """simple docstring"""






         super().__init__()

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




  def 						SCREAMING_SNAKE_CASE    (			self					:						Tuple						, __lowerCAmelCase					:						Optional[int]						, __lowerCAmelCase					:						Dict						, __lowerCAmelCase					:						Optional[int]						, __lowerCAmelCase					:						Optional[Any]						, __lowerCAmelCase					:						Optional[int]						, __lowerCAmelCase					:						Optional[int]		):






         """simple docstring"""






         if latents is None:
                _lowerCamelCase						:    Dict         =			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}'''		)
                _lowerCamelCase						:    int         =			latents.to(lowerCamelCase_		)

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




  def 						SCREAMING_SNAKE_CASE    (			self					:						Dict						, __lowerCAmelCase					:						Tuple=0		):






         """simple docstring"""






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

         _lowerCamelCase						:    Optional[int]         =			torch.device(f'''cuda:{gpu_id}'''		)

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




  @property
  def 						SCREAMING_SNAKE_CASE    (			self					:						List[Any]		):






         """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 						SCREAMING_SNAKE_CASE    (			self					:						List[Any]						, __lowerCAmelCase					:						int						, __lowerCAmelCase					:						Dict						, __lowerCAmelCase					:						int						, __lowerCAmelCase					:						Any						, ):






         """simple docstring"""






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

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

         _lowerCamelCase						:    Any         =			image.to(dtype=self.image_encoder.dtype						, device=lowerCamelCase_		)

         _lowerCamelCase						:    Dict         =			self.image_encoder(lowerCamelCase_		)["""last_hidden_state"""]
         _lowerCamelCase						:    Union[str, Any]         =			image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

         _lowerCamelCase						:    Dict         =			image_embeds.repeat_interleave(lowerCamelCase_						, dim=0		)

         if do_classifier_free_guidance:
                _lowerCamelCase						:    Optional[Any]         =			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
                _lowerCamelCase						:    Union[str, Any]         =			torch.cat([negative_image_embeds, image_embeds]		)

         return image_embeds




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






         """simple docstring"""






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

         _lowerCamelCase						:    Union[str, Any]         =			self._execution_device

         _lowerCamelCase						:    Optional[Any]         =			batch_size * num_images_per_prompt

         _lowerCamelCase						:    Tuple         =			guidance_scale > 1.0
         _lowerCamelCase						:    Union[str, Any]         =			self._encode_image(lowerCamelCase_						, lowerCamelCase_						, lowerCamelCase_						, lowerCamelCase_		)

         # prior

         self.scheduler.set_timesteps(lowerCamelCase_						, device=lowerCamelCase_		)
         _lowerCamelCase						:    Dict         =			self.scheduler.timesteps

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

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

                _lowerCamelCase						:    Dict         =			self.prior(
                    lowerCamelCase_						, timestep=lowerCamelCase_						, proj_embedding=lowerCamelCase_						, ).predicted_image_embedding

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

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

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

         _lowerCamelCase						:    Optional[int]         =			[]
         for i, latent in enumerate(lowerCamelCase_		):
                print()
                _lowerCamelCase						:    List[Any]         =			self.renderer.decode(
                    latent[None, :]						, lowerCamelCase_						, size=lowerCamelCase_						, ray_batch_size=4_0_9_6						, n_coarse_samples=6_4						, n_fine_samples=1_2_8						, )

                images.append(lowerCamelCase_		)

         _lowerCamelCase						:    Union[str, Any]         =			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}'''		)

         _lowerCamelCase						:    List[Any]         =			images.cpu().numpy()

         if output_type == "pil":
                _lowerCamelCase						:    Optional[Any]         =			[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"""






from torch import nn






class 	__snake_case	(     nn.Module):




  def __init__(			self					:						Optional[Any]						, __lowerCAmelCase					:						Dict						, __lowerCAmelCase					:						str		):






         """simple docstring"""






         super().__init__()
         _lowerCamelCase						:    List[str]         =			class_size
         _lowerCamelCase						:    List[str]         =			embed_size
         # self.mlp1 = nn.Linear(embed_size, embed_size)
         # self.mlp2 = (nn.Linear(embed_size, class_size))
         _lowerCamelCase						:    Optional[int]         =			nn.Linear(__lowerCAmelCase						, __lowerCAmelCase		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						List[Any]						, __lowerCAmelCase					:						Tuple		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[Any]         =			self.mlp(__lowerCAmelCase		)
         return logits


