

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

_lowerCamelCase      :					Dict					    =      """
    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        lowerCAmelCase__  (					_UpperCamelCase			):



       '''simple docstring'''







       lowercase_						=    4_2





class        lowerCAmelCase__  (					_UpperCamelCase			):



       '''simple docstring'''







       def __init__(							self ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   ):







             '''simple docstring'''



             super().__init__()

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

       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__     ):







             '''simple docstring'''



             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 ,   lowercase__=0     ):







             '''simple docstring'''



             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     ):







             '''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     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   ):







             '''simple docstring'''



             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 ,   lowercase__ ,   lowercase__ = 1 ,   lowercase__ = 2_5 ,   lowercase__ = None ,   lowercase__ = None ,   lowercase__ = 4.0 ,   lowercase__ = 6_4 ,   lowercase__ = "pil" ,   lowercase__ = True ,   ):







             '''simple docstring'''



             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    =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    =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=4_0_9_6 ,   n_coarse_samples=6_4 ,   n_fine_samples=1_2_8 ,   )

                   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_     )









# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__UpperCamelCase:	List[Any] = {
    """configuration_efficientnet""": [
        """EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """EfficientNetConfig""",
        """EfficientNetOnnxConfig""",
    ]
}

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			__UpperCamelCase:	Dict = ["""EfficientNetImageProcessor"""]

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			__UpperCamelCase:	Dict = [
			    """EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
			    """EfficientNetForImageClassification""",
			    """EfficientNetModel""",
			    """EfficientNetPreTrainedModel""",
			]

if TYPE_CHECKING:
			from .configuration_efficientnet import (
			    EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
			    EfficientNetConfig,
			    EfficientNetOnnxConfig,
			)

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .image_processing_efficientnet import EfficientNetImageProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_efficientnet import (
						    EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
						    EfficientNetForImageClassification,
						    EfficientNetModel,
						    EfficientNetPreTrainedModel,
						)

else:
			import sys

			__UpperCamelCase:	List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)


