



"""simple docstring"""







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

a_							=    '\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      ):







			"""simple docstring"""



			a_       :			List[Any]												=			42







class 					A_(_lowerCAmelCase      ):







			"""simple docstring"""



			def __init__(	self				,   A				,   A				,   A				,   A				,   A				,   ):
						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    _lowerCAmelCase		(	self				,   A				,   A				,   A				,   A				,   A				,   A							):
						if latents is None:
									_lowerCamelCase					:					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}"							)
									_lowerCamelCase					:					int	       =    latents.to(SCREAMING_SNAKE_CASE_							)

						_lowerCamelCase					:					List[Any]	       =    latents * scheduler.init_noise_sigma
						return latents
			def    _lowerCAmelCase		(	self				,   A=0							):
						if is_accelerate_available():
									from accelerate import cpu_offload
						else:
									raise ImportError('Please install accelerate via `pip install accelerate`'							)

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

						_lowerCamelCase					:					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    _lowerCAmelCase		(	self							):
						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    _lowerCAmelCase		(	self				,   A				,   A				,   A				,   A				,   ):
						if isinstance(SCREAMING_SNAKE_CASE_				,   SCREAMING_SNAKE_CASE_							) and isinstance(image[0]				,   torch.Tensor							):
									_lowerCamelCase					:					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							):
									_lowerCamelCase					:					Optional[int]	       =    self.image_processor(SCREAMING_SNAKE_CASE_				,   return_tensors='pt'							).pixel_values[0].unsqueeze(0							)

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

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

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

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

						return image_embeds

			@torch.no_grad()
			@replace_example_docstring(SCREAMING_SNAKE_CASE_							)
			def __call__(	self				,   A				,   A = 1				,   A = 25				,   A = None				,   A = None				,   A = 4.0				,   A = 64				,   A = "pil"				,   A = True				,   ):

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

						_lowerCamelCase					:					Optional[Any]	       =    self._execution_device

						_lowerCamelCase					:					List[Any]	       =    batch_size * num_images_per_prompt

						_lowerCamelCase					:					Optional[Any]	       =    guidance_scale > 1.0
						_lowerCamelCase					:					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_							)
						_lowerCamelCase					:					int	       =    self.scheduler.timesteps

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

						_lowerCamelCase					:					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
						_lowerCamelCase					:					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
									_lowerCamelCase					:					Optional[int]	       =    torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
									_lowerCamelCase					:					List[Any]	       =    self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_				,   SCREAMING_SNAKE_CASE_							)

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

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

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

						_lowerCamelCase					:					str	       =    []
						for i, latent in enumerate(SCREAMING_SNAKE_CASE_							):
									print()
									_lowerCamelCase					:					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_							)

						_lowerCamelCase					:					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}"							)

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

						if output_type == "pil":
									_lowerCamelCase					:					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,
    convert_to_rgb,
    get_resize_output_image_size,
    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


a      :  List[str]			     =			logging.get_logger(__name__)


if is_vision_available():
	import PIL







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

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

						UpperCAmelCase_:		Optional[int]							      =     do_resize
						UpperCAmelCase_:		Optional[int]							      =     size
						UpperCAmelCase_:		Optional[int]							      =     resample
						UpperCAmelCase_:		Tuple							      =     do_center_crop
						UpperCAmelCase_:		Optional[int]							      =     crop_size
						UpperCAmelCase_:		str							      =     do_rescale
						UpperCAmelCase_:		Optional[int]							      =     rescale_factor
						UpperCAmelCase_:		List[str]							      =     do_normalize
						UpperCAmelCase_:		Any							      =     image_mean if image_mean is not None else OPENAI_CLIP_MEAN
						UpperCAmelCase_:		Dict							      =     image_std if image_std is not None else OPENAI_CLIP_STD
						UpperCAmelCase_:		Any							      =     do_convert_rgb

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC,   SCREAMING_SNAKE_CASE_ = None,   **SCREAMING_SNAKE_CASE_,   )       ->   np.ndarray:
						UpperCAmelCase_:		Optional[Any]							      =     get_size_dict(SCREAMING_SNAKE_CASE_,   default_to_square=SCREAMING_SNAKE_CASE_					)
						if "shortest_edge" not in size:
									raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'					)
						UpperCAmelCase_:		Optional[Any]							      =     get_resize_output_image_size(SCREAMING_SNAKE_CASE_,   size=size["""shortest_edge"""],   default_to_square=SCREAMING_SNAKE_CASE_					)
						return resize(SCREAMING_SNAKE_CASE_,   size=SCREAMING_SNAKE_CASE_,   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_:		Any							      =     get_size_dict(SCREAMING_SNAKE_CASE_					)
						if "height" not in size or "width" not in size:
									raise ValueError(f'The `size` parameter must contain the keys (height, 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_,   )       ->   Union[str, Any]:
						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_ = None,   SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST,   **SCREAMING_SNAKE_CASE_,   )       ->   PIL.Image.Image:
						UpperCAmelCase_:		Tuple							      =     do_resize if do_resize is not None else self.do_resize
						UpperCAmelCase_:		Tuple							      =     size if size is not None else self.size
						UpperCAmelCase_:		str							      =     get_size_dict(SCREAMING_SNAKE_CASE_,   param_name="""size""",   default_to_square=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[str]							      =     resample if resample is not None else self.resample
						UpperCAmelCase_:		Optional[int]							      =     do_center_crop if do_center_crop is not None else self.do_center_crop
						UpperCAmelCase_:		Tuple							      =     crop_size if crop_size is not None else self.crop_size
						UpperCAmelCase_:		int							      =     get_size_dict(SCREAMING_SNAKE_CASE_,   param_name="""crop_size""",   default_to_square=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Union[str, Any]							      =     do_rescale if do_rescale is not None else self.do_rescale
						UpperCAmelCase_:		int							      =     rescale_factor if rescale_factor is not None else self.rescale_factor
						UpperCAmelCase_:		Tuple							      =     do_normalize if do_normalize is not None else self.do_normalize
						UpperCAmelCase_:		Dict							      =     image_mean if image_mean is not None else self.image_mean
						UpperCAmelCase_:		int							      =     image_std if image_std is not None else self.image_std
						UpperCAmelCase_:		Union[str, Any]							      =     do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

						UpperCAmelCase_:		List[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:
									raise ValueError("""Size 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."""					)

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

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

						if do_resize:
									UpperCAmelCase_:		str							      =     [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[Any]							      =     [self.rescale(image=SCREAMING_SNAKE_CASE_,   scale=SCREAMING_SNAKE_CASE_					) for image in images]

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

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

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






