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


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

lowercase__						       =      "\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__       (      __SCREAMING_SNAKE_CASE					):







		"""simple docstring"""

		lowerCamelCase     							=						42







class 	snake_case__       (      __SCREAMING_SNAKE_CASE					):







		"""simple docstring"""

		def __init__(      self				:			Any  ,	UpperCamelCase__				:			PriorTransformer  ,	UpperCamelCase__				:			CLIPVisionModel  ,	UpperCamelCase__				:			CLIPImageProcessor  ,	UpperCamelCase__				:			HeunDiscreteScheduler  ,	UpperCamelCase__				:			ShapERenderer  ,	)						->			List[Any]:






				"""simple docstring"""







				super().__init__()

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



		def       lowerCAmelCase				(      self				:			List[Any]  ,	UpperCamelCase__				:			int  ,	UpperCamelCase__				:			int  ,	UpperCamelCase__				:			Tuple  ,	UpperCamelCase__				:			Any  ,	UpperCamelCase__				:			int  ,	UpperCamelCase__				:			Tuple      )						->			int:






				"""simple docstring"""







				if latents is None:
						snake_case  :       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}'      )
						snake_case  :       Optional[Any]     			=						latents.to(UpperCamelCase__      )

				snake_case  :       Optional[int]     			=						latents * scheduler.init_noise_sigma
				return latents



		def       lowerCAmelCase				(      self				:			Optional[int]  ,	UpperCamelCase__				:			Optional[int]=0      )						->			Optional[int]:






				"""simple docstring"""







				if is_accelerate_available():
						from accelerate import cpu_offload
				else:
						raise ImportError('''Please install accelerate via `pip install accelerate`'''      )

				snake_case  :       Optional[int]     			=						torch.device(f'cuda:{gpu_id}'      )

				snake_case  :       Optional[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       lowerCAmelCase				(      self				:			Optional[int]      )						->			List[Any]:






				"""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(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       lowerCAmelCase				(      self				:			Optional[int]  ,	UpperCamelCase__				:			List[Any]  ,	UpperCamelCase__				:			Optional[Any]  ,	UpperCamelCase__				:			Optional[Any]  ,	UpperCamelCase__				:			str  ,	)						->			str:






				"""simple docstring"""







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

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

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

				snake_case  :       Dict     			=						self.image_encoder(UpperCamelCase__      )['''last_hidden_state''']
				snake_case  :       Any     			=						image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

				snake_case  :       Any     			=						image_embeds.repeat_interleave(UpperCamelCase__  ,	dim=0      )

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

				return image_embeds



		@torch.no_grad()
		@replace_example_docstring(UpperCamelCase__      )
		def __call__(      self				:			Optional[Any]  ,	UpperCamelCase__				:			Union[PIL.Image.Image, List[PIL.Image.Image]]  ,	UpperCamelCase__				:			int = 1  ,	UpperCamelCase__				:			int = 25  ,	UpperCamelCase__				:			Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,	UpperCamelCase__				:			Optional[torch.FloatTensor] = None  ,	UpperCamelCase__				:			float = 4.0  ,	UpperCamelCase__				:			int = 64  ,	UpperCamelCase__				:			Optional[str] = "pil"  ,	UpperCamelCase__				:			bool = True  ,	)						->			Union[str, Any]:






				"""simple docstring"""







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

				snake_case  :       int     			=						self._execution_device

				snake_case  :       List[Any]     			=						batch_size * num_images_per_prompt

				snake_case  :       Dict     			=						guidance_scale > 1.0
				snake_case  :       Optional[int]     			=						self._encode_image(UpperCamelCase__  ,	UpperCamelCase__  ,	UpperCamelCase__  ,	UpperCamelCase__      )

				# prior

				self.scheduler.set_timesteps(UpperCamelCase__  ,	device=UpperCamelCase__      )
				snake_case  :       List[str]     			=						self.scheduler.timesteps

				snake_case  :       Tuple     			=						self.prior.config.num_embeddings
				snake_case  :       int     			=						self.prior.config.embedding_dim

				snake_case  :       Union[str, Any]     			=						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
				snake_case  :       Dict     			=						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
						snake_case  :       Dict     			=						torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
						snake_case  :       Union[str, Any]     			=						self.scheduler.scale_model_input(UpperCamelCase__  ,	UpperCamelCase__      )

						snake_case  :       Dict     			=						self.prior(
						    UpperCamelCase__  ,	timestep=UpperCamelCase__  ,	proj_embedding=UpperCamelCase__  ,	).predicted_image_embedding

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

						snake_case  :       Optional[Any]     			=						self.scheduler.step(
						    UpperCamelCase__  ,	timestep=UpperCamelCase__  ,	sample=UpperCamelCase__  ,	).prev_sample

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

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

						images.append(UpperCamelCase__      )

				snake_case  :       Optional[Any]     			=						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}'      )

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

				if output_type == "pil":
						snake_case  :       List[Any]     			=						[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__      )




'''simple docstring'''
from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow


if is_tf_available():
						import numpy as np
						import tensorflow as tf

						from transformers import TFCamembertModel






@require_tf
@require_sentencepiece
@require_tokenizers
class 	snake_case__       (      unittest.TestCase					):







		"""simple docstring"""

		@slow
		def       lowerCAmelCase				(      self				:			Optional[Any]      )						->			Optional[Any]:






				"""simple docstring"""







				snake_case  :       Any     			=						TFCamembertModel.from_pretrained('''jplu/tf-camembert-base'''      )

				snake_case  :       List[Any]     			=						tf.convert_to_tensor(
				    [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]]  ,	dtype=tf.intaa  ,	)  # J'aime le camembert !"

				snake_case  :       Any     			=						model(UpperCamelCase__      )['''last_hidden_state''']
				snake_case  :       int     			=						tf.TensorShape((1, 10, 768)      )
				self.assertEqual(output.shape  ,	UpperCamelCase__      )
				# compare the actual values for a slice.
				snake_case  :       Dict     			=						tf.convert_to_tensor(
				    [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]]  ,	dtype=tf.floataa  ,	)
				# camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
				# camembert.eval()
				# expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()

				self.assertTrue(np.allclose(output[:, :3, :3].numpy()  ,	expected_slice.numpy()  ,	atol=1e-4      )      )


