






"""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


SCREAMING_SNAKE_CASE    :    Optional[Any]        =							logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE    :    Any        =							'\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    snake_case_							(     _lowerCamelCase							):



	"""simple docstring"""

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





class    snake_case_							(     _lowerCamelCase							):



	"""simple docstring"""

	def __init__(   self	,       __a	,       __a	,       __a	,       __a	,       __a	,       ):


					"""simple docstring"""

					super().__init__()

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


	def    _UpperCAmelCase    (   self	,       __a	,       __a	,       __a	,       __a	,       __a	,       __a    ):


					"""simple docstring"""

					if latents is None:
									A__							=							randn_tensor(A__	,       generator=A__	,       device=A__	,       dtype=A__    )
					else:
									if latents.shape != shape:
													raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''    )
									A__							=							latents.to(A__    )

					A__							=							latents * scheduler.init_noise_sigma
					return latents


	def    _UpperCAmelCase    (   self	,       __a=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(A__	,       A__    )


	@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(A__	,       '_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	,       __a	,       __a	,       __a	,       __a	,       ):


					"""simple docstring"""

					if isinstance(A__	,       A__    ) and isinstance(image[0]	,       torch.Tensor    ):
									A__							=							torch.cat(A__	,       axis=0    ) if image[0].ndim == 4 else torch.stack(A__	,       axis=0    )

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

					A__							=							image.to(dtype=self.image_encoder.dtype	,       device=A__    )

					A__							=							self.image_encoder(A__    )["""last_hidden_state"""]
					A__							=							image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

					A__							=							image_embeds.repeat_interleave(A__	,       dim=0    )

					if do_classifier_free_guidance:
									A__							=							torch.zeros_like(A__    )

									# 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(A__    )
	def __call__(   self	,       __a	,       __a = 1	,       __a = 25	,       __a = None	,       __a = None	,       __a = 4.0	,       __a = 64	,       __a = "pil"	,       __a = True	,       ):


					"""simple docstring"""

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

					A__							=							self._execution_device

					A__							=							batch_size * num_images_per_prompt

					A__							=							guidance_scale > 1.0
					A__							=							self._encode_image(A__	,       A__	,       A__	,       A__    )

					# prior

					self.scheduler.set_timesteps(A__	,       device=A__    )
					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	,       A__	,       A__	,       A__	,       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]	,       A__	,       A__    )

					for i, t in enumerate(self.progress_bar(A__    )    ):
									# 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(A__	,       A__    )

									A__							=							self.prior(
									    A__	,       timestep=A__	,       proj_embedding=A__	,       ).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(
									    A__	,       timestep=A__	,       sample=A__	,       ).prev_sample

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

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

									images.append(A__    )

					A__							=							torch.stack(A__    )

					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(A__    ) 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=A__    )





from ..utils import DummyObject, requires_backends



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[str]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Any    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Union[str, Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Dict    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[str]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Any    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Optional[int]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  str    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Dict    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  int    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  int    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  str    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[str]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Optional[int]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Union[str, Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Tuple    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  List[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  str    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Dict    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  str    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Any    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Union[str, Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Optional[Any]    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



class        _a		(metaclass=__magic_name__							):


					'''simple docstring'''






					UpperCAmelCase__:  Tuple    				=			['''sentencepiece''']






					def __init__(					self       ,			*A__       ,			**A__     ):
						requires_backends(self       ,			["""sentencepiece"""]     )



