




'''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  __lowercase    (	_a			):
   _a    						=   42





class  __lowercase    (	_a			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				)					->     Tuple:
     super().__init__()

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







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Dict:
     if latents is None:
       __a								=       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}"   )
       __a								=       latents.to(__lowerCamelCase   )

     __a								=       latents * scheduler.init_noise_sigma
     return latents







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase=0   )					->     int:
     if is_accelerate_available():
       from accelerate import cpu_offload
     else:
       raise ImportError('Please install accelerate via `pip install accelerate`'   )

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

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







   @property
   def 		UpperCamelCase__      (						self   )					->     Optional[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(__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 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				)					->     List[str]:
     if isinstance(__lowerCamelCase   ,				__lowerCamelCase   ) and isinstance(image[0]   ,				torch.Tensor   ):
       __a								=       torch.cat(__lowerCamelCase   ,				axis=0   ) if image[0].ndim == 4 else torch.stack(__lowerCamelCase   ,				axis=0   )

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

     __a								=       image.to(dtype=self.image_encoder.dtype   ,				device=__lowerCamelCase   )

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

     __a								=       image_embeds.repeat_interleave(__lowerCamelCase   ,				dim=0   )

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

     return image_embeds







   @torch.no_grad()
   @replace_example_docstring(__lowerCamelCase   )
   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase = 1   ,				UpperCamelCase = 25   ,				UpperCamelCase = None   ,				UpperCamelCase = None   ,				UpperCamelCase = 4.0   ,				UpperCamelCase = 64   ,				UpperCamelCase = "pil"   ,				UpperCamelCase = True   ,				)					->     str:

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

     __a								=       self._execution_device

     __a								=       batch_size * num_images_per_prompt

     __a								=       guidance_scale > 1.0
     __a								=       self._encode_image(__lowerCamelCase   ,				__lowerCamelCase   ,				__lowerCamelCase   ,				__lowerCamelCase   )

     # prior

     self.scheduler.set_timesteps(__lowerCamelCase   ,				device=__lowerCamelCase   )
     __a								=       self.scheduler.timesteps

     __a								=       self.prior.config.num_embeddings
     __a								=       self.prior.config.embedding_dim

     __a								=       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
     __a								=       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
       __a								=       torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
       __a								=       self.scheduler.scale_model_input(__lowerCamelCase   ,				__lowerCamelCase   )

       __a								=       self.prior(
           __lowerCamelCase   ,				timestep=__lowerCamelCase   ,				proj_embedding=__lowerCamelCase   ,				).predicted_image_embedding

       # remove the variance
       __a						,							__a								=       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								=       noise_pred.chunk(2   )
         __a								=       noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

       __a								=       self.scheduler.step(
           __lowerCamelCase   ,				timestep=__lowerCamelCase   ,				sample=__lowerCamelCase   ,				).prev_sample

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

     __a								=       []
     for i, latent in enumerate(__lowerCamelCase   ):
       print()
       __a								=       self.renderer.decode(
           latent[None, :]   ,				__lowerCamelCase   ,				size=__lowerCamelCase   ,				ray_batch_size=4096   ,				n_coarse_samples=64   ,				n_fine_samples=128   ,				)

       images.append(__lowerCamelCase   )

     __a								=       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}"   )

     __a								=       images.cpu().numpy()

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









from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__magic_name__  :  Union[str, Any]					=       {
    """configuration_altclip""": [
        """ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """AltCLIPConfig""",
        """AltCLIPTextConfig""",
        """AltCLIPVisionConfig""",
    ],
    """processing_altclip""": ["""AltCLIPProcessor"""],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  str					=       [
          """ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """AltCLIPPreTrainedModel""",
          """AltCLIPModel""",
          """AltCLIPTextModel""",
          """AltCLIPVisionModel""",
      ]


if TYPE_CHECKING:
      from .configuration_altclip import (
          ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
          AltCLIPConfig,
          AltCLIPTextConfig,
          AltCLIPVisionConfig,
      )
      from .processing_altclip import AltCLIPProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_altclip import (
                ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
                AltCLIPModel,
                AltCLIPPreTrainedModel,
                AltCLIPTextModel,
                AltCLIPVisionModel,
            )


else:
      import sys

      __magic_name__  :  str					=       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

