import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

_SCREAMING_SNAKE_CASE:						Optional[Any]    	=       '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\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], "shark_3d.gif")\n        ```\n'

@dataclass
class 	_SCREAMING_SNAKE_CASE							(     _UpperCAmelCase							):






		"""simple docstring"""







		A_						 =      42

class 	_SCREAMING_SNAKE_CASE							(     _UpperCAmelCase							):






		"""simple docstring"""







		def __init__(			self    :				str  ,					__SCREAMING_SNAKE_CASE    :				Dict  ,					__SCREAMING_SNAKE_CASE    :				Optional[int]  ,					__SCREAMING_SNAKE_CASE    :				Dict  ,					__SCREAMING_SNAKE_CASE    :				List[Any]  ,					__SCREAMING_SNAKE_CASE    :				str  ,					):






					"""simple docstring"""
					super().__init__()

					self.register_modules(
					    prior=__SCREAMING_SNAKE_CASE  ,					text_encoder=__SCREAMING_SNAKE_CASE  ,					tokenizer=__SCREAMING_SNAKE_CASE  ,					scheduler=__SCREAMING_SNAKE_CASE  ,					renderer=__SCREAMING_SNAKE_CASE  ,					)



		def 				_a				(			self    :				Any  ,					__SCREAMING_SNAKE_CASE    :				Tuple  ,					__SCREAMING_SNAKE_CASE    :				Optional[Any]  ,					__SCREAMING_SNAKE_CASE    :				Tuple  ,					__SCREAMING_SNAKE_CASE    :				Any  ,					__SCREAMING_SNAKE_CASE    :				Optional[int]  ,					__SCREAMING_SNAKE_CASE    :				int   ):






					"""simple docstring"""






					if latents is None:
								_snake_case              =      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}'   )
								_snake_case              =      latents.to(__SCREAMING_SNAKE_CASE   )

					_snake_case              =      latents * scheduler.init_noise_sigma
					return latents



		def 				_a				(			self    :				str  ,					__SCREAMING_SNAKE_CASE    :				str=0   ):






					"""simple docstring"""






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

					_snake_case              =      torch.device(F'cuda:{gpu_id}'   )

					_snake_case              =      [self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
								if cpu_offloaded_model is not None:
											cpu_offload(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   )



		def 				_a				(			self    :				List[str]  ,					__SCREAMING_SNAKE_CASE    :				Tuple=0   ):






					"""simple docstring"""






					if is_accelerate_available() and is_accelerate_version(">="  ,					"0.17.0.dev0"   ):
								from accelerate import cpu_offload_with_hook
					else:
								raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."   )

					_snake_case              =      torch.device(F'cuda:{gpu_id}'   )

					if self.device.type != "cpu":
								self.to("cpu"  ,					silence_dtype_warnings=__SCREAMING_SNAKE_CASE   )
								torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

					_snake_case              =      None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
								_snake_case       , _snake_case              =      cpu_offload_with_hook(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE  ,					prev_module_hook=__SCREAMING_SNAKE_CASE   )

					if self.safety_checker is not None:
								_snake_case       , _snake_case              =      cpu_offload_with_hook(self.safety_checker  ,					__SCREAMING_SNAKE_CASE  ,					prev_module_hook=__SCREAMING_SNAKE_CASE   )

					# We'll offload the last model manually.
					_snake_case              =      hook



		@property
		def 				_a				(			self    :				Optional[Any]   ):






					"""simple docstring"""






					if self.device != torch.device("meta"   ) or not hasattr(self.text_encoder  ,					"_hf_hook"   ):
								return self.device
					for module in self.text_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 				_a				(			self    :				List[str]  ,					__SCREAMING_SNAKE_CASE    :				List[str]  ,					__SCREAMING_SNAKE_CASE    :				Union[str, Any]  ,					__SCREAMING_SNAKE_CASE    :				Tuple  ,					__SCREAMING_SNAKE_CASE    :				Tuple  ,					):






					"""simple docstring"""
					len(__SCREAMING_SNAKE_CASE   ) if isinstance(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   ) else 1

					# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
					_snake_case              =      0
					# get prompt text embeddings
					_snake_case              =      self.tokenizer(
					    __SCREAMING_SNAKE_CASE  ,					padding="max_length"  ,					max_length=self.tokenizer.model_max_length  ,					truncation=__SCREAMING_SNAKE_CASE  ,					return_tensors="pt"  ,					)
					_snake_case              =      text_inputs.input_ids
					_snake_case              =      self.tokenizer(__SCREAMING_SNAKE_CASE  ,					padding="longest"  ,					return_tensors="pt"   ).input_ids

					if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   ):
								_snake_case              =      self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]   )
								logger.warning(
								    "The following part of your input was truncated because CLIP can only handle sequences up to"
								    F' {self.tokenizer.model_max_length} tokens: {removed_text}'   )

					_snake_case              =      self.text_encoder(text_input_ids.to(__SCREAMING_SNAKE_CASE   )   )
					_snake_case              =      text_encoder_output.text_embeds

					_snake_case              =      prompt_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE  ,					dim=0   )
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					_snake_case              =      prompt_embeds / torch.linalg.norm(__SCREAMING_SNAKE_CASE  ,					dim=-1  ,					keepdim=__SCREAMING_SNAKE_CASE   )

					if do_classifier_free_guidance:
								_snake_case              =      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
								_snake_case              =      torch.cat([negative_prompt_embeds, prompt_embeds]   )

					# Rescale the features to have unit variance
					_snake_case              =      math.sqrt(prompt_embeds.shape[1]   ) * prompt_embeds

					return prompt_embeds







		@torch.no_grad()
		@replace_example_docstring(__SCREAMING_SNAKE_CASE   )
		def __call__(			self    :				List[Any]  ,					__SCREAMING_SNAKE_CASE    :				List[str]  ,					__SCREAMING_SNAKE_CASE    :				Any = 1  ,					__SCREAMING_SNAKE_CASE    :				List[str] = 25  ,					__SCREAMING_SNAKE_CASE    :				Tuple = None  ,					__SCREAMING_SNAKE_CASE    :				Union[str, Any] = None  ,					__SCREAMING_SNAKE_CASE    :				List[str] = 4.0  ,					__SCREAMING_SNAKE_CASE    :				Union[str, Any] = 64  ,					__SCREAMING_SNAKE_CASE    :				Tuple = "pil"  ,					__SCREAMING_SNAKE_CASE    :				Optional[Any] = True  ,					):






					"""simple docstring"""






					if isinstance(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   ):
								_snake_case              =      1
					elif isinstance(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   ):
								_snake_case              =      len(__SCREAMING_SNAKE_CASE   )
					else:
								raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(__SCREAMING_SNAKE_CASE   )}'   )

					_snake_case              =      self._execution_device

					_snake_case              =      batch_size * num_images_per_prompt

					_snake_case              =      guidance_scale > 1.0
					_snake_case              =      self._encode_prompt(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   )

					# prior

					self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE  ,					device=__SCREAMING_SNAKE_CASE   )
					_snake_case              =      self.scheduler.timesteps

					_snake_case              =      self.prior.config.num_embeddings
					_snake_case              =      self.prior.config.embedding_dim

					_snake_case              =      self.prepare_latents(
					    (batch_size, num_embeddings * embedding_dim)  ,					prompt_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
					_snake_case              =      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
								_snake_case              =      torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
								_snake_case              =      self.scheduler.scale_model_input(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   )

								_snake_case              =      self.prior(
								    __SCREAMING_SNAKE_CASE  ,					timestep=__SCREAMING_SNAKE_CASE  ,					proj_embedding=__SCREAMING_SNAKE_CASE  ,					).predicted_image_embedding

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

								_snake_case              =      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   )

					_snake_case              =      []
					for i, latent in enumerate(__SCREAMING_SNAKE_CASE   ):
								_snake_case              =      self.renderer.decode(
								    latent[None, :]  ,					__SCREAMING_SNAKE_CASE  ,					size=__SCREAMING_SNAKE_CASE  ,					ray_batch_size=4_096  ,					n_coarse_samples=64  ,					n_fine_samples=128  ,					)
								images.append(__SCREAMING_SNAKE_CASE   )

					_snake_case              =      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}'   )

					_snake_case              =      images.cpu().numpy()

					if output_type == "pil":
								_snake_case              =      [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   )


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import TvltImageProcessor






def    UpperCAmelCase__(						lowerCamelCase_							,	lowerCamelCase_=10							,	lowerCamelCase_=10							,	lowerCamelCase_=False							,	lowerCamelCase_=False  ):



			"""simple docstring"""





			_snake_case              =      []
			for i in range(image_processor_tester.num_frames  ):
						video.append(np.random.randint(255							,	size=(image_processor_tester.num_channels, width, height)							,	dtype=np.uinta  )  )

			if not numpify and not torchify:
						# PIL expects the channel dimension as last dimension
						_snake_case              =      [Image.fromarray(np.moveaxis(lowerCamelCase_							,	0							,	-1  )  ) for frame in video]

			if torchify:
						_snake_case              =      [torch.from_numpy(lowerCamelCase_  ) for frame in video]

			return video






def    UpperCAmelCase__(						lowerCamelCase_							,	lowerCamelCase_=False							,	lowerCamelCase_=False							,	lowerCamelCase_=False  ):



			"""simple docstring"""





			assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

			_snake_case              =      []
			for i in range(image_processor_tester.batch_size  ):
						if equal_resolution:
									_snake_case              =      _snake_case              =      image_processor_tester.max_resolution
						else:
									_snake_case       , _snake_case              =      np.random.choice(
									    np.arange(image_processor_tester.min_resolution							,	image_processor_tester.max_resolution  )							,	2  )
									_snake_case              =      prepare_video(
									    image_processor_tester=lowerCamelCase_							,	width=lowerCamelCase_							,	height=lowerCamelCase_							,	numpify=lowerCamelCase_							,	torchify=lowerCamelCase_							,	)
						video_inputs.append(lowerCamelCase_  )

			return video_inputs

class 	_SCREAMING_SNAKE_CASE							(     unittest.TestCase							):






		"""simple docstring"""







		def __init__(			self    :				str  ,					__SCREAMING_SNAKE_CASE    :				Optional[int]  ,					__SCREAMING_SNAKE_CASE    :				Optional[int]=7  ,					__SCREAMING_SNAKE_CASE    :				Union[str, Any]=3  ,					__SCREAMING_SNAKE_CASE    :				List[str]=4  ,					__SCREAMING_SNAKE_CASE    :				Tuple=18  ,					__SCREAMING_SNAKE_CASE    :				Union[str, Any]=30  ,					__SCREAMING_SNAKE_CASE    :				List[Any]=400  ,					__SCREAMING_SNAKE_CASE    :				Union[str, Any]=True  ,					__SCREAMING_SNAKE_CASE    :				Tuple=None  ,					__SCREAMING_SNAKE_CASE    :				int=True  ,					__SCREAMING_SNAKE_CASE    :				Any=[0.5, 0.5, 0.5]  ,					__SCREAMING_SNAKE_CASE    :				Optional[int]=[0.5, 0.5, 0.5]  ,					__SCREAMING_SNAKE_CASE    :				Optional[Any]=True  ,					__SCREAMING_SNAKE_CASE    :				List[Any]=None  ,					):






					"""simple docstring"""
					_snake_case              =      size if size is not None else {"shortest_edge": 18}
					_snake_case              =      crop_size if crop_size is not None else {"height": 18, "width": 18}

					_snake_case              =      parent
					_snake_case              =      batch_size
					_snake_case              =      num_channels
					_snake_case              =      num_frames
					_snake_case              =      image_size
					_snake_case              =      min_resolution
					_snake_case              =      max_resolution
					_snake_case              =      do_resize
					_snake_case              =      size
					_snake_case              =      do_normalize
					_snake_case              =      image_mean
					_snake_case              =      image_std
					_snake_case              =      do_center_crop
					_snake_case              =      crop_size







		def 				_a				(			self    :				List[Any]   ):






					"""simple docstring"""
					return {
					    "image_mean": self.image_mean,
					    "image_std": self.image_std,
					    "do_normalize": self.do_normalize,
					    "do_resize": self.do_resize,
					    "size": self.size,
					    "do_center_crop": self.do_center_crop,
					    "crop_size": self.crop_size,
					}

@require_torch
@require_vision
class 	_SCREAMING_SNAKE_CASE							(     _lowercase      ,     unittest.TestCase							):






		"""simple docstring"""







		A_						 =      TvltImageProcessor if is_vision_available() else None



		def 				_a				(			self    :				str   ):






					"""simple docstring"""
					_snake_case              =      TvltImageProcessorTester(self   )



		@property
		def 				_a				(			self    :				List[Any]   ):






					"""simple docstring"""
					return self.image_processor_tester.prepare_image_processor_dict()



		def 				_a				(			self    :				Dict   ):






					"""simple docstring"""
					_snake_case              =      self.image_processing_class(**self.image_processor_dict   )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,					"image_mean"   )   )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,					"image_std"   )   )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,					"do_normalize"   )   )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,					"do_resize"   )   )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,					"do_center_crop"   )   )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,					"size"   )   )



		def 				_a				(			self    :				Optional[Any]   ):






					"""simple docstring"""
					# Initialize image_processor
					_snake_case              =      self.image_processing_class(**self.image_processor_dict   )
					# create random PIL videos
					_snake_case              =      prepare_video_inputs(self.image_processor_tester  ,					equal_resolution=__SCREAMING_SNAKE_CASE   )
					for video in video_inputs:
								self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   )
								self.assertIsInstance(video[0]  ,					Image.Image   )

					# Test not batched input
					_snake_case              =      image_processor(video_inputs[0]  ,					return_tensors="pt"   ).pixel_values
					self.assertEqual(
					    encoded_videos.shape  ,					(
					        1,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )  ,					)

					# Test batched
					_snake_case              =      image_processor(__SCREAMING_SNAKE_CASE  ,					return_tensors="pt"   ).pixel_values
					self.assertEqual(
					    encoded_videos.shape  ,					(
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )  ,					)



		def 				_a				(			self    :				str   ):






					"""simple docstring"""
					# Initialize image_processor
					_snake_case              =      self.image_processing_class(**self.image_processor_dict   )
					# create random numpy tensors
					_snake_case              =      prepare_video_inputs(self.image_processor_tester  ,					equal_resolution=__SCREAMING_SNAKE_CASE  ,					numpify=__SCREAMING_SNAKE_CASE   )
					for video in video_inputs:
								self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   )
								self.assertIsInstance(video[0]  ,					np.ndarray   )

					# Test not batched input
					_snake_case              =      image_processor(video_inputs[0]  ,					return_tensors="pt"   ).pixel_values
					self.assertEqual(
					    encoded_videos.shape  ,					(
					        1,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )  ,					)

					# Test batched
					_snake_case              =      image_processor(__SCREAMING_SNAKE_CASE  ,					return_tensors="pt"   ).pixel_values
					self.assertEqual(
					    encoded_videos.shape  ,					(
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )  ,					)







		def 				_a				(			self    :				int   ):






					"""simple docstring"""
					# Initialize image_processor
					_snake_case              =      self.image_processing_class(**self.image_processor_dict   )
					# create random PyTorch tensors
					_snake_case              =      prepare_video_inputs(self.image_processor_tester  ,					equal_resolution=__SCREAMING_SNAKE_CASE  ,					torchify=__SCREAMING_SNAKE_CASE   )
					for video in video_inputs:
								self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE   )
								self.assertIsInstance(video[0]  ,					torch.Tensor   )

					# Test not batched input
					_snake_case              =      image_processor(video_inputs[0]  ,					return_tensors="pt"   ).pixel_values
					self.assertEqual(
					    encoded_videos.shape  ,					(
					        1,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )  ,					)

					# Test batched
					_snake_case              =      image_processor(__SCREAMING_SNAKE_CASE  ,					return_tensors="pt"   ).pixel_values
					self.assertEqual(
					    encoded_videos.shape  ,					(
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )  ,					)

