



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


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

a      :  List[str]			     =			'\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'







@dataclass
class 				_a				(   _lowerCAmelCase					):
			A      		=	42







class 				_a				(   _lowerCAmelCase					):

			def __init__(self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   )       ->   List[str]:
						super().__init__()

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

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   int:
						if latents is None:
									UpperCAmelCase_:		List[str]							      =     randn_tensor(SCREAMING_SNAKE_CASE_,   generator=SCREAMING_SNAKE_CASE_,   device=SCREAMING_SNAKE_CASE_,   dtype=SCREAMING_SNAKE_CASE_					)
						else:
									if latents.shape != shape:
												raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'					)
									UpperCAmelCase_:		int							      =     latents.to(SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		List[Any]							      =     latents * scheduler.init_noise_sigma
						return latents

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_=0					)       ->   Optional[int]:
						if is_accelerate_available():
									from accelerate import cpu_offload
						else:
									raise ImportError("""Please install accelerate via `pip install accelerate`"""					)

						UpperCAmelCase_:		Dict							      =     torch.device(f'cuda:{gpu_id}'					)

						UpperCAmelCase_:		Optional[Any]							      =     [self.image_encoder, self.prior]
						for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
												cpu_offload(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)

			@property
			def      __snake_case       (self					)       ->   str:
						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(SCREAMING_SNAKE_CASE_,   """_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      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   )       ->   Union[str, Any]:
						if isinstance(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					) and isinstance(image[0],   torch.Tensor					):
									UpperCAmelCase_:		List[Any]							      =     torch.cat(SCREAMING_SNAKE_CASE_,   axis=0					) if image[0].ndim == 4 else torch.stack(SCREAMING_SNAKE_CASE_,   axis=0					)

						if not isinstance(SCREAMING_SNAKE_CASE_,   torch.Tensor					):
									UpperCAmelCase_:		Optional[int]							      =     self.image_processor(SCREAMING_SNAKE_CASE_,   return_tensors="""pt"""					).pixel_values[0].unsqueeze(0					)

						UpperCAmelCase_:		Union[str, Any]							      =     image.to(dtype=self.image_encoder.dtype,   device=SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Dict							      =     self.image_encoder(SCREAMING_SNAKE_CASE_					)["""last_hidden_state"""]
						UpperCAmelCase_:		Any							      =     image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

						UpperCAmelCase_:		Union[str, Any]							      =     image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE_,   dim=0					)

						if do_classifier_free_guidance:
									UpperCAmelCase_:		int							      =     torch.zeros_like(SCREAMING_SNAKE_CASE_					)

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

						return image_embeds

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

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

						UpperCAmelCase_:		Optional[Any]							      =     self._execution_device

						UpperCAmelCase_:		List[Any]							      =     batch_size * num_images_per_prompt

						UpperCAmelCase_:		Optional[Any]							      =     guidance_scale > 1.0
						UpperCAmelCase_:		Dict							      =     self._encode_image(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)

						# prior

						self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_,   device=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		int							      =     self.scheduler.timesteps

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

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

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

									UpperCAmelCase_:		Optional[Any]							      =     self.prior(
									    SCREAMING_SNAKE_CASE_,   timestep=SCREAMING_SNAKE_CASE_,   proj_embedding=SCREAMING_SNAKE_CASE_,   ).predicted_image_embedding

									# remove the variance
									UpperCAmelCase_      ,							UpperCAmelCase_:		Union[str, Any]							      =     noise_pred.split(
									    scaled_model_input.shape[2],   dim=2					)  # batch_size, num_embeddings, embedding_dim

									if do_classifier_free_guidance is not None:
												UpperCAmelCase_      ,							UpperCAmelCase_:		Any							      =     noise_pred.chunk(2					)
												UpperCAmelCase_:		Tuple							      =     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

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

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

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

									images.append(SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		List[Any]							      =     torch.stack(SCREAMING_SNAKE_CASE_					)

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

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

						if output_type == "pil":
									UpperCAmelCase_:		Dict							      =     [self.numpy_to_pil(SCREAMING_SNAKE_CASE_					) 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=SCREAMING_SNAKE_CASE_					)











from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
	import PIL


a      :  Dict			     =			logging.get_logger(__name__)







class 				_a				(   _lowerCAmelCase					):
			A      		=	['''pixel_values''']

			def __init__(self,   SCREAMING_SNAKE_CASE_ = True,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = PIL.Image.BICUBIC,   SCREAMING_SNAKE_CASE_ = True,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = 1 / 255,   SCREAMING_SNAKE_CASE_ = True,   SCREAMING_SNAKE_CASE_ = True,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   **SCREAMING_SNAKE_CASE_,   )       ->   None:
						super().__init__(**SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Optional[Any]							      =     size if size is not None else {"""height""": 256, """width""": 256}
						UpperCAmelCase_:		Optional[Any]							      =     get_size_dict(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		int							      =     crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
						UpperCAmelCase_:		Dict							      =     get_size_dict(SCREAMING_SNAKE_CASE_,   param_name="""crop_size"""					)

						UpperCAmelCase_:		int							      =     do_resize
						UpperCAmelCase_:		Any							      =     size
						UpperCAmelCase_:		List[Any]							      =     resample
						UpperCAmelCase_:		int							      =     do_center_crop
						UpperCAmelCase_:		Dict							      =     crop_size
						UpperCAmelCase_:		Tuple							      =     do_rescale
						UpperCAmelCase_:		Tuple							      =     rescale_factor
						UpperCAmelCase_:		Dict							      =     do_normalize
						UpperCAmelCase_:		Dict							      =     image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						UpperCAmelCase_:		int							      =     image_std if image_std is not None else IMAGENET_STANDARD_STD

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = PIL.Image.BICUBIC,   SCREAMING_SNAKE_CASE_ = None,   **SCREAMING_SNAKE_CASE_,   )       ->   np.ndarray:
						UpperCAmelCase_:		Tuple							      =     get_size_dict(SCREAMING_SNAKE_CASE_					)
						if "height" not in size or "width" not in size:
									raise ValueError(f'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'					)
						return resize(
						    SCREAMING_SNAKE_CASE_,   size=(size["""height"""], size["""width"""]),   resample=SCREAMING_SNAKE_CASE_,   data_format=SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = None,   **SCREAMING_SNAKE_CASE_,   )       ->   np.ndarray:
						UpperCAmelCase_:		Optional[int]							      =     get_size_dict(SCREAMING_SNAKE_CASE_					)
						if "height" not in size or "width" not in size:
									raise ValueError(f'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'					)
						return center_crop(SCREAMING_SNAKE_CASE_,   size=(size["""height"""], size["""width"""]),   data_format=SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = None,   **SCREAMING_SNAKE_CASE_,   )       ->   int:
						return rescale(SCREAMING_SNAKE_CASE_,   scale=SCREAMING_SNAKE_CASE_,   data_format=SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = None,   **SCREAMING_SNAKE_CASE_,   )       ->   np.ndarray:
						return normalize(SCREAMING_SNAKE_CASE_,   mean=SCREAMING_SNAKE_CASE_,   std=SCREAMING_SNAKE_CASE_,   data_format=SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_=None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST,   **SCREAMING_SNAKE_CASE_,   )       ->   PIL.Image.Image:
						UpperCAmelCase_:		Any							      =     do_resize if do_resize is not None else self.do_resize
						UpperCAmelCase_:		Dict							      =     resample if resample is not None else self.resample
						UpperCAmelCase_:		Tuple							      =     do_center_crop if do_center_crop is not None else self.do_center_crop
						UpperCAmelCase_:		str							      =     do_rescale if do_rescale is not None else self.do_rescale
						UpperCAmelCase_:		List[Any]							      =     rescale_factor if rescale_factor is not None else self.rescale_factor
						UpperCAmelCase_:		List[Any]							      =     do_normalize if do_normalize is not None else self.do_normalize
						UpperCAmelCase_:		Optional[Any]							      =     image_mean if image_mean is not None else self.image_mean
						UpperCAmelCase_:		Dict							      =     image_std if image_std is not None else self.image_std

						UpperCAmelCase_:		Any							      =     size if size is not None else self.size
						UpperCAmelCase_:		Optional[Any]							      =     get_size_dict(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Tuple							      =     crop_size if crop_size is not None else self.crop_size
						UpperCAmelCase_:		Optional[int]							      =     get_size_dict(SCREAMING_SNAKE_CASE_,   param_name="""crop_size"""					)

						UpperCAmelCase_:		str							      =     make_list_of_images(SCREAMING_SNAKE_CASE_					)

						if not valid_images(SCREAMING_SNAKE_CASE_					):
									raise ValueError(
									    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
									    """torch.Tensor, tf.Tensor or jax.ndarray."""					)

						if do_resize and size is None or resample is None:
									raise ValueError("""Size and resample must be specified if do_resize is True."""					)

						if do_center_crop and crop_size is None:
									raise ValueError("""Crop size must be specified if do_center_crop is True."""					)

						if do_rescale and rescale_factor is None:
									raise ValueError("""Rescale factor must be specified if do_rescale is True."""					)

						if do_normalize and (image_mean is None or image_std is None):
									raise ValueError("""Image mean and std must be specified if do_normalize is True."""					)

						# All transformations expect numpy arrays.
						UpperCAmelCase_:		Tuple							      =     [to_numpy_array(SCREAMING_SNAKE_CASE_					) for image in images]

						if do_resize:
									UpperCAmelCase_:		int							      =     [self.resize(image=SCREAMING_SNAKE_CASE_,   size=SCREAMING_SNAKE_CASE_,   resample=SCREAMING_SNAKE_CASE_					) for image in images]

						if do_center_crop:
									UpperCAmelCase_:		Dict							      =     [self.center_crop(image=SCREAMING_SNAKE_CASE_,   size=SCREAMING_SNAKE_CASE_					) for image in images]

						if do_rescale:
									UpperCAmelCase_:		Optional[int]							      =     [self.rescale(image=SCREAMING_SNAKE_CASE_,   scale=SCREAMING_SNAKE_CASE_					) for image in images]

						if do_normalize:
									UpperCAmelCase_:		int							      =     [self.normalize(image=SCREAMING_SNAKE_CASE_,   mean=SCREAMING_SNAKE_CASE_,   std=SCREAMING_SNAKE_CASE_					) for image in images]

						UpperCAmelCase_:		Optional[Any]							      =     [to_channel_dimension_format(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					) for image in images]

						UpperCAmelCase_:		Optional[Any]							      =     {"""pixel_values""": images}
						return BatchFeature(data=SCREAMING_SNAKE_CASE_,   tensor_type=SCREAMING_SNAKE_CASE_					)






