
'''simple docstring'''







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		:  Dict        =      '\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   ):
	lowercase__	    =							42







class  SCREAMING_SNAKE_CASE__       (  __UpperCamelCase   ):
	def __init__(				self  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    ):



					'''simple docstring'''






					super().__init__()

					self.register_modules(
					    prior=__UpperCamelCase  ,    text_encoder=__UpperCamelCase  ,    tokenizer=__UpperCamelCase  ,    scheduler=__UpperCamelCase  ,    renderer=__UpperCamelCase  ,    )
	def __lowerCamelCase    (				self  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			):



					'''simple docstring'''






					if latents is None:
									__a       :     Any								=	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}"""			)
									__a       :     Optional[Any]								=	latents.to(__UpperCamelCase			)

					__a       :     int								=	latents * scheduler.init_noise_sigma
					return latents
	def __lowerCamelCase    (				self  ,    __UpperCamelCase=0			):



					'''simple docstring'''






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

					__a       :     List[Any]								=	torch.device(f"""cuda:{gpu_id}"""			)

					__a       :     Optional[int]								=	[self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
													cpu_offload(__UpperCamelCase  ,    __UpperCamelCase			)
	def __lowerCamelCase    (				self  ,    __UpperCamelCase=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."""			)

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

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

					__a       :     Optional[int]								=	None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
									__a							,	__a       :     Any								=	cpu_offload_with_hook(__UpperCamelCase  ,    __UpperCamelCase  ,    prev_module_hook=__UpperCamelCase			)

					if self.safety_checker is not None:
									__a							,	__a       :     Optional[Any]								=	cpu_offload_with_hook(self.safety_checker  ,    __UpperCamelCase  ,    prev_module_hook=__UpperCamelCase			)

					# We'll offload the last model manually.
					__a       :     Optional[Any]								=	hook
	@property
	def __lowerCamelCase    (				self			):



					'''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(__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  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    ):



					'''simple docstring'''






					len(__UpperCamelCase			) if isinstance(__UpperCamelCase  ,    __UpperCamelCase			) else 1

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

					if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__UpperCamelCase  ,    __UpperCamelCase			):
									__a       :     Any								=	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}"""			)

					__a       :     List[str]								=	self.text_encoder(text_input_ids.to(__UpperCamelCase			)			)
					__a       :     Optional[int]								=	text_encoder_output.text_embeds

					__a       :     Dict								=	prompt_embeds.repeat_interleave(__UpperCamelCase  ,    dim=0			)
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					__a       :     Optional[int]								=	prompt_embeds / torch.linalg.norm(__UpperCamelCase  ,    dim=-1  ,    keepdim=__UpperCamelCase			)

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

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

					return prompt_embeds

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



					'''simple docstring'''






					if isinstance(__UpperCamelCase  ,    __UpperCamelCase			):
									__a       :     Optional[Any]								=	1
					elif isinstance(__UpperCamelCase  ,    __UpperCamelCase			):
									__a       :     str								=	len(__UpperCamelCase			)
					else:
									raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(__UpperCamelCase			)}"""			)

					__a       :     Tuple								=	self._execution_device

					__a       :     List[str]								=	batch_size * num_images_per_prompt

					__a       :     List[str]								=	guidance_scale > 1.0
					__a       :     Tuple								=	self._encode_prompt(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			)

					# prior

					self.scheduler.set_timesteps(__UpperCamelCase  ,    device=__UpperCamelCase			)
					__a       :     int								=	self.scheduler.timesteps

					__a       :     Dict								=	self.prior.config.num_embeddings
					__a       :     Optional[int]								=	self.prior.config.embedding_dim

					__a       :     str								=	self.prepare_latents(
					    (batch_size, num_embeddings * embedding_dim)  ,    prompt_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
					__a       :     str								=	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
									__a       :     Union[str, Any]								=	torch.cat([latents] * 2			) if do_classifier_free_guidance else latents
									__a       :     Optional[Any]								=	self.scheduler.scale_model_input(__UpperCamelCase  ,    __UpperCamelCase			)

									__a       :     List[Any]								=	self.prior(
									    __UpperCamelCase  ,    timestep=__UpperCamelCase  ,    proj_embedding=__UpperCamelCase  ,    ).predicted_image_embedding

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

									__a       :     int								=	self.scheduler.step(
									    __UpperCamelCase  ,    timestep=__UpperCamelCase  ,    sample=__UpperCamelCase  ,    ).prev_sample

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

					__a       :     Optional[int]								=	[]
					for i, latent in enumerate(__UpperCamelCase			):
									__a       :     str								=	self.renderer.decode(
									    latent[None, :]  ,    __UpperCamelCase  ,    size=__UpperCamelCase  ,    ray_batch_size=4096  ,    n_coarse_samples=64  ,    n_fine_samples=128  ,    )
									images.append(__UpperCamelCase			)

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

					__a       :     str								=	images.cpu().numpy()

					if output_type == "pil":
									__a       :     Optional[int]								=	[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'''







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 				_snake_case (		lowercase			,    lowercase=1_0			,    lowercase=1_0			,    lowercase=False			,    lowercase=False						)       ->       Any:
				__a       :     Union[str, Any]								=	[]
				for i in range(image_processor_tester.num_frames						):
								video.append(np.random.randint(2_5_5			,    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
								__a       :     Optional[Any]								=	[Image.fromarray(np.moveaxis(lowercase			,    0			,    -1						)						) for frame in video]

				if torchify:
								__a       :     List[str]								=	[torch.from_numpy(lowercase						) for frame in video]

				return video

def 				_snake_case (		lowercase			,    lowercase=False			,    lowercase=False			,    lowercase=False						)       ->       Optional[Any]:
				assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

				return video_inputs
class  SCREAMING_SNAKE_CASE__       (  unittest.TestCase   ):
	def __init__(				self  ,    __UpperCamelCase  ,    __UpperCamelCase=7  ,    __UpperCamelCase=3  ,    __UpperCamelCase=4  ,    __UpperCamelCase=18  ,    __UpperCamelCase=30  ,    __UpperCamelCase=400  ,    __UpperCamelCase=True  ,    __UpperCamelCase=None  ,    __UpperCamelCase=True  ,    __UpperCamelCase=[0.5, 0.5, 0.5]  ,    __UpperCamelCase=[0.5, 0.5, 0.5]  ,    __UpperCamelCase=True  ,    __UpperCamelCase=None  ,    ):



					'''simple docstring'''






					__a       :     int								=	size if size is not None else {"""shortest_edge""": 18}
					__a       :     Optional[int]								=	crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

					__a       :     Optional[Any]								=	parent
					__a       :     Dict								=	batch_size
					__a       :     Optional[Any]								=	num_channels
					__a       :     Dict								=	num_frames
					__a       :     Dict								=	image_size
					__a       :     int								=	min_resolution
					__a       :     Tuple								=	max_resolution
					__a       :     Optional[Any]								=	do_resize
					__a       :     str								=	size
					__a       :     int								=	do_normalize
					__a       :     Any								=	image_mean
					__a       :     Optional[Any]								=	image_std
					__a       :     List[Any]								=	do_center_crop
					__a       :     List[Any]								=	crop_size

	def __lowerCamelCase    (				self			):



					'''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__       (  __UpperCamelCase			,					unittest.TestCase   ):
	lowercase__	    =							TvltImageProcessor if is_vision_available() else None
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Optional[int]								=	TvltImageProcessorTester(self			)
	@property
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					return self.image_processor_tester.prepare_image_processor_dict()
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Optional[Any]								=	self.image_processing_class(**self.image_processor_dict			)
					self.assertTrue(hasattr(__UpperCamelCase  ,    """image_mean"""			)			)
					self.assertTrue(hasattr(__UpperCamelCase  ,    """image_std"""			)			)
					self.assertTrue(hasattr(__UpperCamelCase  ,    """do_normalize"""			)			)
					self.assertTrue(hasattr(__UpperCamelCase  ,    """do_resize"""			)			)
					self.assertTrue(hasattr(__UpperCamelCase  ,    """do_center_crop"""			)			)
					self.assertTrue(hasattr(__UpperCamelCase  ,    """size"""			)			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Union[str, Any]								=	self.image_processing_class(**self.image_processor_dict			)
					# create random PIL videos
					__a       :     List[str]								=	prepare_video_inputs(self.image_processor_tester  ,    equal_resolution=__UpperCamelCase			)
					for video in video_inputs:
									self.assertIsInstance(__UpperCamelCase  ,    __UpperCamelCase			)
									self.assertIsInstance(video[0]  ,    Image.Image			)

					# Test not batched input
					__a       :     int								=	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
					__a       :     int								=	image_processor(__UpperCamelCase  ,    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 __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     List[str]								=	self.image_processing_class(**self.image_processor_dict			)
					# create random numpy tensors
					__a       :     Union[str, Any]								=	prepare_video_inputs(self.image_processor_tester  ,    equal_resolution=__UpperCamelCase  ,    numpify=__UpperCamelCase			)
					for video in video_inputs:
									self.assertIsInstance(__UpperCamelCase  ,    __UpperCamelCase			)
									self.assertIsInstance(video[0]  ,    np.ndarray			)

					# Test not batched input
					__a       :     Optional[int]								=	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
					__a       :     Dict								=	image_processor(__UpperCamelCase  ,    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 __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Optional[Any]								=	self.image_processing_class(**self.image_processor_dict			)
					# create random PyTorch tensors
					__a       :     Optional[int]								=	prepare_video_inputs(self.image_processor_tester  ,    equal_resolution=__UpperCamelCase  ,    torchify=__UpperCamelCase			)
					for video in video_inputs:
									self.assertIsInstance(__UpperCamelCase  ,    __UpperCamelCase			)
									self.assertIsInstance(video[0]  ,    torch.Tensor			)

					# Test not batched input
					__a       :     Optional[int]								=	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
					__a       :     int								=	image_processor(__UpperCamelCase  ,    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"""],
					    )  ,    )