import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate






class 							_SCREAMING_SNAKE_CASE(   lowercase__	):
   UpperCamelCase_				:						Tuple 			=   CONFIG_NAME
   @register_to_config
   def __init__(    self							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = 8							,     lowerCAmelCase_ = "lanczos"							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = False							,     )	->int:
        super().__init__()
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->PIL.Image.Image:
        if images.ndim == 3:
             a  :    Optional[int]				=						images[None, ...]
        a  :    Dict				=						(images * 2_55).round().astype('''uint8'''    )
        if images.shape[-1] == 1:
             # special case for grayscale (single channel) images
             a  :    Dict				=						[Image.fromarray(image.squeeze()							,     mode='''L'''    ) for image in images]
        else:
             a  :    int				=						[Image.fromarray(_A    ) for image in images]

        return pil_images
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->np.ndarray:
        if not isinstance(_A							,     _A    ):
             a  :    List[str]				=						[images]
        a  :    str				=						[np.array(_A    ).astype(np.floataa    ) / 2_55.0 for image in images]
        a  :    str				=						np.stack(_A							,     axis=0    )

        return images
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->torch.FloatTensor:
        if images.ndim == 3:
             a  :    Tuple				=						images[..., None]

        a  :    List[str]				=						torch.from_numpy(images.transpose(0							,     3							,     1							,     2    )    )
        return images
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->np.ndarray:
        a  :    str				=						images.cpu().permute(0							,     2							,     3							,     1    ).float().numpy()
        return images
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->Union[str, Any]:
        return 2.0 * images - 1.0
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->Union[str, Any]:
        return (images / 2 + 0.5).clamp(0							,     1    )
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->PIL.Image.Image:
        a  :    List[Any]				=						image.convert('''RGB'''    )
        return image
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = None							,     )	->PIL.Image.Image:
        if height is None:
             a  :    Tuple				=						image.height
        if width is None:
             a  :    Optional[int]				=						image.width

        a  :    List[Any]				=						(
            x - x % self.config.vae_scale_factor for x in (width, height)
        )  # resize to integer multiple of vae_scale_factor
        a  :    int				=						image.resize((width, height)							,     resample=PIL_INTERPOLATION[self.config.resample]    )
        return image
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = None							,     )	->torch.Tensor:
        a  :    List[Any]				=						(PIL.Image.Image, np.ndarray, torch.Tensor)
        if isinstance(_A							,     _A    ):
             a  :    Optional[int]				=						[image]
        elif not (isinstance(_A							,     _A    ) and all(isinstance(_A							,     _A    ) for i in image    )):
             raise ValueError(
                 F"""Input is in incorrect format: {[type(_A    ) for i in image]}. Currently, we only support {', '.join(_A    )}"""    )

        if isinstance(image[0]							,     PIL.Image.Image    ):
             if self.config.do_convert_rgb:
                  a  :    Optional[Any]				=						[self.convert_to_rgb(_A    ) for i in image]
             if self.config.do_resize:
                  a  :    int				=						[self.resize(_A							,     _A							,     _A    ) for i in image]
             a  :    Dict				=						self.pil_to_numpy(_A    )  # to np
             a  :    int				=						self.numpy_to_pt(_A    )  # to pt

        elif isinstance(image[0]							,     np.ndarray    ):
             a  :    str				=						np.concatenate(_A							,     axis=0    ) if image[0].ndim == 4 else np.stack(_A							,     axis=0    )
             a  :    Any				=						self.numpy_to_pt(_A    )
             a  :    Tuple				=						image.shape
             if self.config.do_resize and (
                 height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
             ):
                  raise ValueError(
                      F"""Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"""
                      F"""currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"""    )

        elif isinstance(image[0]							,     torch.Tensor    ):
             a  :    Optional[Any]				=						torch.cat(_A							,     axis=0    ) if image[0].ndim == 4 else torch.stack(_A							,     axis=0    )
             a  :    List[Any]				=						image.shape

             # don't need any preprocess if the image is latents
             if channel == 4:
                  return image

             if self.config.do_resize and (
                 height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
             ):
                  raise ValueError(
                      F"""Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"""
                      F"""currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"""    )

        # expected range [0,1], normalize to [-1,1]
        a  :    str				=						self.config.do_normalize
        if image.min() < 0:
             warnings.warn(
                 '''Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] '''
                 F"""when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]"""							,     _A							,     )
             a  :    str				=						False

        if do_normalize:
             a  :    int				=						self.normalize(_A    )

        return image


   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_ = "pil"							,     lowerCAmelCase_ = None							,     )	->Optional[Any]:
        if not isinstance(_A							,     torch.Tensor    ):
             raise ValueError(
                 F"""Input for postprocessing is in incorrect format: {type(_A    )}. We only support pytorch tensor"""    )
        if output_type not in ["latent", "pt", "np", "pil"]:
             a  :    Optional[Any]				=						(
                 F"""the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: """
                 '`pil`, `np`, `pt`, `latent`'
             )
             deprecate('''Unsupported output_type'''							,     '''1.0.0'''							,     _A							,     standard_warn=_A    )
             a  :    Union[str, Any]				=						'np'

        if output_type == "latent":
             return image

        if do_denormalize is None:
             a  :    Any				=						[self.config.do_normalize] * image.shape[0]

        a  :    Optional[int]				=						torch.stack(
            [self.denormalize(image[i]    ) if do_denormalize[i] else image[i] for i in range(image.shape[0]    )]    )

        if output_type == "pt":
             return image

        a  :    Any				=						self.pt_to_numpy(_A    )

        if output_type == "np":
             return image

        if output_type == "pil":
             return self.numpy_to_pil(_A    )






class 							_SCREAMING_SNAKE_CASE(   lowercase__	):
   UpperCamelCase_				:						Optional[int] 			=   CONFIG_NAME
   @register_to_config
   def __init__(    self							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = 8							,     lowerCAmelCase_ = "lanczos"							,     lowerCAmelCase_ = True							,     )	->Tuple:
        super().__init__()
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->Optional[int]:
        if images.ndim == 3:
             a  :    Union[str, Any]				=						images[None, ...]
        a  :    Optional[Any]				=						(images * 2_55).round().astype('''uint8'''    )
        if images.shape[-1] == 1:
             # special case for grayscale (single channel) images
             a  :    Optional[int]				=						[Image.fromarray(image.squeeze()							,     mode='''L'''    ) for image in images]
        else:
             a  :    Optional[Any]				=						[Image.fromarray(image[:, :, :3]    ) for image in images]

        return pil_images
   @staticmethod
   def _lowercase(    lowerCAmelCase_    )	->Optional[Any]:
        return image[:, :, 1] * 2**8 + image[:, :, 2]
   def _lowercase(    self							,     lowerCAmelCase_    )	->Dict:
        if images.ndim == 3:
             a  :    Tuple				=						images[None, ...]
        a  :    Any				=						images[:, :, :, 3:]
        if images.shape[-1] == 6:
             a  :    List[str]				=						(images_depth * 2_55).round().astype('''uint8'''    )
             a  :    Any				=						[
                 Image.fromarray(self.rgblike_to_depthmap(_A    )							,     mode='''I;16'''    ) for image_depth in images_depth
             ]
        elif images.shape[-1] == 4:
             a  :    Optional[Any]				=						(images_depth * 6_55_35.0).astype(np.uintaa    )
             a  :    Any				=						[Image.fromarray(_A							,     mode='''I;16'''    ) for image_depth in images_depth]
        else:
             raise Exception('''Not supported'''    )

        return pil_images


   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_ = "pil"							,     lowerCAmelCase_ = None							,     )	->int:
        if not isinstance(_A							,     torch.Tensor    ):
             raise ValueError(
                 F"""Input for postprocessing is in incorrect format: {type(_A    )}. We only support pytorch tensor"""    )
        if output_type not in ["latent", "pt", "np", "pil"]:
             a  :    List[Any]				=						(
                 F"""the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: """
                 '`pil`, `np`, `pt`, `latent`'
             )
             deprecate('''Unsupported output_type'''							,     '''1.0.0'''							,     _A							,     standard_warn=_A    )
             a  :    List[str]				=						'np'

        if do_denormalize is None:
             a  :    Tuple				=						[self.config.do_normalize] * image.shape[0]

        a  :    Tuple				=						torch.stack(
            [self.denormalize(image[i]    ) if do_denormalize[i] else image[i] for i in range(image.shape[0]    )]    )

        a  :    Optional[int]				=						self.pt_to_numpy(_A    )

        if output_type == "np":
             if image.shape[-1] == 6:
                  a  :    str				=						np.stack([self.rgblike_to_depthmap(im[:, :, 3:]    ) for im in image]							,     axis=0    )
             else:
                  a  :    Tuple				=						image[:, :, :, 3:]
             return image[:, :, :, :3], image_depth

        if output_type == "pil":
             return self.numpy_to_pil(_A    ), self.numpy_to_depth(_A    )
        else:
             raise Exception(F"""This type {output_type} is not supported"""    )
import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

UpperCAmelCase							   =      """
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""






@dataclass
class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   UpperCamelCase_				:						Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   def __init__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->int:
        super().__init__()

        self.register_modules(
            prior=lowerCAmelCase_							,     text_encoder=lowerCAmelCase_							,     tokenizer=lowerCAmelCase_							,     scheduler=lowerCAmelCase_							,     renderer=lowerCAmelCase_							,     )
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )	->str:
        if latents is None:
             a  :    List[str]				=						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  :    str				=						latents.to(lowerCAmelCase_    )

        a  :    Tuple				=						latents * scheduler.init_noise_sigma
        return latents
   def _lowercase(    self							,     lowerCAmelCase_=0    )	->List[Any]:
        if is_accelerate_available():
             from accelerate import cpu_offload
        else:
             raise ImportError('''Please install accelerate via `pip install accelerate`'''    )

        a  :    Dict				=						torch.device(F"""cuda:{gpu_id}"""    )

        a  :    Union[str, Any]				=						[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                  cpu_offload(lowerCAmelCase_							,     lowerCAmelCase_    )
   def _lowercase(    self							,     lowerCAmelCase_=0    )	->str:
        if is_accelerate_available() and is_accelerate_version('''>='''							,     '''0.17.0.dev0'''    ):
             from accelerate import cpu_offload_with_hook
        else:
             raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''    )

        a  :    Union[str, Any]				=						torch.device(F"""cuda:{gpu_id}"""    )

        if self.device.type != "cpu":
             self.to('''cpu'''							,     silence_dtype_warnings=lowerCAmelCase_    )
             torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        a  :    Dict				=						None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
             a			,							a  :    str				=						cpu_offload_with_hook(lowerCAmelCase_							,     lowerCAmelCase_							,     prev_module_hook=lowerCAmelCase_    )

        if self.safety_checker is not None:
             a			,							a  :    Optional[Any]				=						cpu_offload_with_hook(self.safety_checker							,     lowerCAmelCase_							,     prev_module_hook=lowerCAmelCase_    )

        # We'll offload the last model manually.
        a  :    Any				=						hook
   @property
   def _lowercase(    self    )	->Any:
        if self.device != torch.device('''meta'''    ) or not hasattr(self.text_encoder							,     '''_hf_hook'''    ):
             return self.device
        for module in self.text_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 _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->Optional[Any]:
        len(lowerCAmelCase_    ) if isinstance(lowerCAmelCase_							,     lowerCAmelCase_    ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        a  :    Dict				=						0
        # get prompt text embeddings
        a  :    Any				=						self.tokenizer(
            lowerCAmelCase_							,     padding='''max_length'''							,     max_length=self.tokenizer.model_max_length							,     truncation=lowerCAmelCase_							,     return_tensors='''pt'''							,     )
        a  :    List[str]				=						text_inputs.input_ids
        a  :    Union[str, Any]				=						self.tokenizer(lowerCAmelCase_							,     padding='''longest'''							,     return_tensors='''pt'''    ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase_							,     lowerCAmelCase_    ):
             a  :    Union[str, Any]				=						self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]    )
             logger.warning(
                 '''The following part of your input was truncated because CLIP can only handle sequences up to'''
                 F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""    )

        a  :    Optional[int]				=						self.text_encoder(text_input_ids.to(lowerCAmelCase_    )    )
        a  :    Optional[Any]				=						text_encoder_output.text_embeds

        a  :    Any				=						prompt_embeds.repeat_interleave(lowerCAmelCase_							,     dim=0    )
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        a  :    List[str]				=						prompt_embeds / torch.linalg.norm(lowerCAmelCase_							,     dim=-1							,     keepdim=lowerCAmelCase_    )

        if do_classifier_free_guidance:
             a  :    Optional[int]				=						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  :    Dict				=						torch.cat([negative_prompt_embeds, prompt_embeds]    )

        # Rescale the features to have unit variance
        a  :    Union[str, Any]				=						math.sqrt(prompt_embeds.shape[1]    ) * prompt_embeds

        return prompt_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:

        if isinstance(lowerCAmelCase_							,     lowerCAmelCase_    ):
             a  :    Tuple				=						1
        elif isinstance(lowerCAmelCase_							,     lowerCAmelCase_    ):
             a  :    Dict				=						len(lowerCAmelCase_    )
        else:
             raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_    )}"""    )

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

        a  :    List[str]				=						batch_size * num_images_per_prompt

        a  :    Optional[int]				=						guidance_scale > 1.0
        a  :    Union[str, Any]				=						self._encode_prompt(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )

        # prior

        self.scheduler.set_timesteps(lowerCAmelCase_							,     device=lowerCAmelCase_    )
        a  :    str				=						self.scheduler.timesteps

        a  :    Any				=						self.prior.config.num_embeddings
        a  :    Dict				=						self.prior.config.embedding_dim

        a  :    Any				=						self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)							,     prompt_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  :    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
             a  :    int				=						torch.cat([latents] * 2    ) if do_classifier_free_guidance else latents
             a  :    List[str]				=						self.scheduler.scale_model_input(lowerCAmelCase_							,     lowerCAmelCase_    )

             a  :    Union[str, Any]				=						self.prior(
                 lowerCAmelCase_							,     timestep=lowerCAmelCase_							,     proj_embedding=lowerCAmelCase_							,     ).predicted_image_embedding

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

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

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

        a  :    int				=						[]
        for i, latent in enumerate(lowerCAmelCase_    ):
             a  :    Dict				=						self.renderer.decode(
                 latent[None, :]							,     lowerCAmelCase_							,     size=lowerCAmelCase_							,     ray_batch_size=40_96							,     n_coarse_samples=64							,     n_fine_samples=1_28							,     )
             images.append(lowerCAmelCase_    )

        a  :    Optional[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}"""    )

        a  :    Any				=						images.cpu().numpy()

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