




'''simple docstring'''





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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_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


_SCREAMING_SNAKE_CASE							:   Dict      		= logging.get_logger(__name__)




class  _snake_case		(	_snake_case							):
			lowerCAmelCase_     :      Dict						       =    ['''pixel_values''']




			def __init__(					self				,							a__ = True				,							a__ = None				,							a__ = PILImageResampling.BICUBIC				,							a__ = True				,							a__ = 1 / 255				,							a__ = True				,							a__ = None				,							a__ = None				,							a__ = True				,							**a__				,							)				->				None:

										'''simple docstring'''




										super().__init__(**_UpperCamelCase							)
										snake_case_						=      size if size is not None else {'height': 384, 'width': 384}
										snake_case_						=      get_size_dict(_UpperCamelCase				,							default_to_square=_UpperCamelCase							)

										snake_case_						=      do_resize
										snake_case_						=      size
										snake_case_						=      resample
										snake_case_						=      do_rescale
										snake_case_						=      rescale_factor
										snake_case_						=      do_normalize
										snake_case_						=      image_mean if image_mean is not None else OPENAI_CLIP_MEAN
										snake_case_						=      image_std if image_std is not None else OPENAI_CLIP_STD
										snake_case_						=      do_convert_rgb




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__ = PILImageResampling.BICUBIC				,							a__ = None				,							**a__				,							)				->				np.ndarray:

										'''simple docstring'''




										snake_case_						=      get_size_dict(_UpperCamelCase				,							default_to_square=_UpperCamelCase							)
										if "height" not in size or "width" not in size:
																	raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'							)
										snake_case_						=      (size['height'], size['width'])
										return resize(_UpperCamelCase				,							size=_UpperCamelCase				,							resample=_UpperCamelCase				,							data_format=_UpperCamelCase				,							**_UpperCamelCase							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__ = None				,							**a__				,							)				->				Dict:

										'''simple docstring'''




										return rescale(_UpperCamelCase				,							scale=_UpperCamelCase				,							data_format=_UpperCamelCase				,							**_UpperCamelCase							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__				,							a__ = None				,							**a__				,							)				->				np.ndarray:

										'''simple docstring'''




										return normalize(_UpperCamelCase				,							mean=_UpperCamelCase				,							std=_UpperCamelCase				,							data_format=_UpperCamelCase				,							**_UpperCamelCase							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = None				,							a__ = ChannelDimension.FIRST				,							**a__				,							)				->				PIL.Image.Image:

										'''simple docstring'''




										snake_case_						=      do_resize if do_resize is not None else self.do_resize
										snake_case_						=      resample if resample is not None else self.resample
										snake_case_						=      do_rescale if do_rescale is not None else self.do_rescale
										snake_case_						=      rescale_factor if rescale_factor is not None else self.rescale_factor
										snake_case_						=      do_normalize if do_normalize is not None else self.do_normalize
										snake_case_						=      image_mean if image_mean is not None else self.image_mean
										snake_case_						=      image_std if image_std is not None else self.image_std
										snake_case_						=      do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

										snake_case_						=      size if size is not None else self.size
										snake_case_						=      get_size_dict(_UpperCamelCase				,							default_to_square=_UpperCamelCase							)

										snake_case_						=      make_list_of_images(_UpperCamelCase							)

										if not valid_images(_UpperCamelCase							):
																	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_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."							)

										# PIL RGBA images are converted to RGB
										if do_convert_rgb:
																	snake_case_						=      [convert_to_rgb(_UpperCamelCase							) for image in images]

										# All transformations expect numpy arrays.
										snake_case_						=      [to_numpy_array(_UpperCamelCase							) for image in images]

										if do_resize:
																	snake_case_						=      [self.resize(image=_UpperCamelCase				,							size=_UpperCamelCase				,							resample=_UpperCamelCase							) for image in images]

										if do_rescale:
																	snake_case_						=      [self.rescale(image=_UpperCamelCase				,							scale=_UpperCamelCase							) for image in images]

										if do_normalize:
																	snake_case_						=      [self.normalize(image=_UpperCamelCase				,							mean=_UpperCamelCase				,							std=_UpperCamelCase							) for image in images]

										snake_case_						=      [to_channel_dimension_format(_UpperCamelCase				,							_UpperCamelCase							) for image in images]

										snake_case_						=      BatchFeature(data={"pixel_values": images}				,							tensor_type=_UpperCamelCase							)

										return encoded_outputs












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								=						'\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   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		_snake_case    :    Union[PIL.Image.Image, np.ndarray]





class   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		def __init__(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		)	->							Any:
							super().__init__()

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



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )	->							List[Any]:
							if latents is None:
												UpperCAmelCase_    :      str            =						randn_tensor(_UpperCamelCase				,		generator=_UpperCamelCase				,		device=_UpperCamelCase				,		dtype=_UpperCamelCase   )
							else:
												if latents.shape != shape:
																	raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"   )
												UpperCAmelCase_    :      Tuple            =						latents.to(_UpperCamelCase   )

							UpperCAmelCase_    :      Tuple            =						latents * scheduler.init_noise_sigma
							return latents



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase=0   )	->							Union[str, Any]:
							if is_accelerate_available():
												from accelerate import cpu_offload
							else:
												raise ImportError('Please install accelerate via `pip install accelerate`'   )

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

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



		@property
		def 					__UpperCAmelCase			(							self   )	->							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(_UpperCamelCase				,		'_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				,		)	->							str:
							if isinstance(_UpperCamelCase				,		_UpperCamelCase   ) and isinstance(image[0]				,		torch.Tensor   ):
												UpperCAmelCase_    :      int            =						torch.cat(_UpperCamelCase				,		axis=0   ) if image[0].ndim == 4 else torch.stack(_UpperCamelCase				,		axis=0   )

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

							UpperCAmelCase_    :      Tuple            =						image.to(dtype=self.image_encoder.dtype				,		device=_UpperCamelCase   )

							UpperCAmelCase_    :      Optional[Any]            =						self.image_encoder(_UpperCamelCase   )['last_hidden_state']
							UpperCAmelCase_    :      Union[str, Any]            =						image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

							UpperCAmelCase_    :      List[str]            =						image_embeds.repeat_interleave(_UpperCamelCase				,		dim=0   )

							if do_classifier_free_guidance:
												UpperCAmelCase_    :      Dict            =						torch.zeros_like(_UpperCamelCase   )

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

							return image_embeds



		@torch.no_grad()
		@replace_example_docstring(_UpperCamelCase   )
		def __call__(							self				,		_UpperCamelCase				,		_UpperCamelCase = 1				,		_UpperCamelCase = 2_5				,		_UpperCamelCase = None				,		_UpperCamelCase = None				,		_UpperCamelCase = 4.0				,		_UpperCamelCase = 6_4				,		_UpperCamelCase = "pil"				,		_UpperCamelCase = True				,		)	->							Union[str, Any]:

							if isinstance(_UpperCamelCase				,		PIL.Image.Image   ):
												UpperCAmelCase_    :      Tuple            =						1
							elif isinstance(_UpperCamelCase				,		torch.Tensor   ):
												UpperCAmelCase_    :      str            =						image.shape[0]
							elif isinstance(_UpperCamelCase				,		_UpperCamelCase   ) and isinstance(image[0]				,		(torch.Tensor, PIL.Image.Image)   ):
												UpperCAmelCase_    :      Optional[int]            =						len(_UpperCamelCase   )
							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(_UpperCamelCase   )}"   )

							UpperCAmelCase_    :      Tuple            =						self._execution_device

							UpperCAmelCase_    :      str            =						batch_size * num_images_per_prompt

							UpperCAmelCase_    :      str            =						guidance_scale > 1.0
							UpperCAmelCase_    :      str            =						self._encode_image(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )

							# prior

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

							UpperCAmelCase_    :      int            =						self.prior.config.num_embeddings
							UpperCAmelCase_    :      Any            =						self.prior.config.embedding_dim

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

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

												UpperCAmelCase_    :      int            =						self.prior(
												    _UpperCamelCase				,		timestep=_UpperCamelCase				,		proj_embedding=_UpperCamelCase				,		).predicted_image_embedding

												# remove the variance
												UpperCAmelCase_       ,  UpperCAmelCase_    :      Optional[int]            =						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_    :      str            =						noise_pred.chunk(2   )
																	UpperCAmelCase_    :      List[Any]            =						noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

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

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

							UpperCAmelCase_    :      List[Any]            =						[]
							for i, latent in enumerate(_UpperCamelCase   ):
												print()
												UpperCAmelCase_    :      List[str]            =						self.renderer.decode(
												    latent[None, :]				,		_UpperCamelCase				,		size=_UpperCamelCase				,		ray_batch_size=4_0_9_6				,		n_coarse_samples=6_4				,		n_fine_samples=1_2_8				,		)

												images.append(_UpperCamelCase   )

							UpperCAmelCase_    :      Optional[int]            =						torch.stack(_UpperCamelCase   )

							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_    :      Dict            =						images.cpu().numpy()

							if output_type == "pil":
												UpperCAmelCase_    :      List[str]            =						[self.numpy_to_pil(_UpperCamelCase   ) 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=_UpperCamelCase   )






