






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__							=     logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase__							=     """
    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__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				Union[PIL.Image.Image, np.ndarray]




class 			snake_case__   (							lowercase_):

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__			,						a__			,						a__			,						a__			,						) ->      str:






            '''simple docstring'''





            super().__init__()

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



       def 					__lowercase						(							self			,						a__			,						a__			,						a__			,						a__			,						a__			,						a__    ) ->      str:






            '''simple docstring'''





            if latents is None:
                 __snake_case			:int          =						randn_tensor(a__			,						generator=a__			,						device=a__			,						dtype=a__    )
            else:
                 if latents.shape != shape:
                      raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''    )
                 __snake_case			:Union[str, Any]          =						latents.to(a__    )

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



       def 					__lowercase						(							self			,						a__=0    ) ->      Any:






            '''simple docstring'''





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

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

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



       @property
       def 					__lowercase						(							self    ) ->      Union[str, 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(a__			,						"""_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			,						a__			,						a__			,						a__			,						a__			,						) ->      Any:






            '''simple docstring'''





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

            if not isinstance(a__			,						torch.Tensor    ):
                 __snake_case			:Tuple          =						self.image_processor(a__			,						return_tensors="""pt"""    ).pixel_values[0].unsqueeze(0    )

            __snake_case			:Optional[int]          =						image.to(dtype=self.image_encoder.dtype			,						device=a__    )

            __snake_case			:int          =						self.image_encoder(a__    )["""last_hidden_state"""]
            __snake_case			:List[Any]          =						image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

            __snake_case			:Optional[Any]          =						image_embeds.repeat_interleave(a__			,						dim=0    )

            if do_classifier_free_guidance:
                 __snake_case			:int          =						torch.zeros_like(a__    )

                 # 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
                 __snake_case			:Optional[Any]          =						torch.cat([negative_image_embeds, image_embeds]    )

            return image_embeds



       @torch.no_grad()
       @replace_example_docstring(a__    )
       def __call__(							self			,						a__			,						a__ = 1			,						a__ = 25			,						a__ = None			,						a__ = None			,						a__ = 4.0			,						a__ = 64			,						a__ = "pil"			,						a__ = True			,						) ->      Optional[Any]:






            '''simple docstring'''





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

            __snake_case			:List[str]          =						self._execution_device

            __snake_case			:Tuple          =						batch_size * num_images_per_prompt

            __snake_case			:str          =						guidance_scale > 1.0
            __snake_case			:Union[str, Any]          =						self._encode_image(a__			,						a__			,						a__			,						a__    )

            # prior

            self.scheduler.set_timesteps(a__			,						device=a__    )
            __snake_case			:List[str]          =						self.scheduler.timesteps

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

            __snake_case			:int          =						self.prepare_latents(
                (batch_size, num_embeddings * embedding_dim)			,						image_embeds.dtype			,						a__			,						a__			,						a__			,						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
            __snake_case			:Union[str, Any]          =						latents.reshape(latents.shape[0]			,						a__			,						a__    )

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

                 __snake_case			:List[Any]          =						self.prior(
                     a__			,						timestep=a__			,						proj_embedding=a__			,						).predicted_image_embedding

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

                 if do_classifier_free_guidance is not None:
                      __snake_case       , __snake_case			:Optional[int]          =						noise_pred.chunk(2    )
                      __snake_case			:str          =						noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

                 __snake_case			:Union[str, Any]          =						self.scheduler.step(
                     a__			,						timestep=a__			,						sample=a__			,						).prev_sample

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

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

                 images.append(a__    )

            __snake_case			:Dict          =						torch.stack(a__    )

            if output_type not in ["np", "pil"]:
                 raise ValueError(F'''Only the output types `pil` and `np` are supported not output_type={output_type}'''    )

            __snake_case			:List[str]          =						images.cpu().numpy()

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










from typing import TYPE_CHECKING

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


lowerCamelCase__							=     {
    """configuration_canine""": ["""CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CanineConfig"""],
    """tokenization_canine""": ["""CanineTokenizer"""],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCamelCase__							=     [
         """CANINE_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """CanineForMultipleChoice""",
         """CanineForQuestionAnswering""",
         """CanineForSequenceClassification""",
         """CanineForTokenClassification""",
         """CanineLayer""",
         """CanineModel""",
         """CaninePreTrainedModel""",
         """load_tf_weights_in_canine""",
     ]


if TYPE_CHECKING:
     from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
     from .tokenization_canine import CanineTokenizer

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_canine import (
              CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
              CanineForMultipleChoice,
              CanineForQuestionAnswering,
              CanineForSequenceClassification,
              CanineForTokenClassification,
              CanineLayer,
              CanineModel,
              CaninePreTrainedModel,
              load_tf_weights_in_canine,
          )


else:
     import sys

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


