


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


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

UpperCamelCase :				List[str]						    =       '''
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = "a shark"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")
        ```
'''

@dataclass
class     __snake_case							(      _UpperCAmelCase):
					SCREAMING_SNAKE_CASE_		:					Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]







class     __snake_case							(      _UpperCAmelCase):
					def __init__(	self					:	int  ,			_lowerCAmelCase					:	PriorTransformer  ,			_lowerCAmelCase					:	CLIPTextModelWithProjection  ,			_lowerCAmelCase					:	CLIPTokenizer  ,			_lowerCAmelCase					:	HeunDiscreteScheduler  ,			_lowerCAmelCase					:	ShapERenderer  ,			)       ->				Dict:



											'''simple docstring'''





											super().__init__()

											self.register_modules(
											    prior=UpperCAmelCase_  ,			text_encoder=UpperCAmelCase_  ,			tokenizer=UpperCAmelCase_  ,			scheduler=UpperCAmelCase_  ,			renderer=UpperCAmelCase_  ,			)
					def   a (	self					:	Optional[Any]  ,			_lowerCAmelCase					:	Any  ,			_lowerCAmelCase					:	Any  ,			_lowerCAmelCase					:	Optional[Any]  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	List[Any]     )       ->				Dict:



											'''simple docstring'''





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

											__magic_name__ 		=			latents * scheduler.init_noise_sigma
											return latents
					def   a (	self					:	Optional[Any]  ,			_lowerCAmelCase					:	str=0     )       ->				List[str]:



											'''simple docstring'''





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

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

											__magic_name__ 		=			[self.text_encoder, self.prior]
											for cpu_offloaded_model in models:
																	if cpu_offloaded_model is not None:
																							cpu_offload(UpperCAmelCase_  ,			UpperCAmelCase_     )
					def   a (	self					:	Union[str, Any]  ,			_lowerCAmelCase					:	str=0     )       ->				List[str]:



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

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

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

											if self.safety_checker is not None:
																	__magic_name__ 		=			cpu_offload_with_hook(self.safety_checker  ,			UpperCAmelCase_  ,			prev_module_hook=UpperCAmelCase_     )

											# We'll offload the last model manually.
											__magic_name__ 		=			hook
					@property
					def   a (	self					:	Any     )       ->				Dict:



											'''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   a (	self					:	Tuple  ,			_lowerCAmelCase					:	Dict  ,			_lowerCAmelCase					:	Optional[int]  ,			_lowerCAmelCase					:	List[Any]  ,			_lowerCAmelCase					:	Any  ,			)       ->				str:



											'''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
											__magic_name__ 		=			0
											# get prompt text embeddings
											__magic_name__ 		=			self.tokenizer(
											    UpperCAmelCase_  ,			padding='max_length'  ,			max_length=self.tokenizer.model_max_length  ,			truncation=UpperCAmelCase_  ,			return_tensors='pt'  ,			)
											__magic_name__ 		=			text_inputs.input_ids
											__magic_name__ 		=			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_     ):
																	__magic_name__ 		=			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}'''     )

											__magic_name__ 		=			self.text_encoder(text_input_ids.to(UpperCAmelCase_     )     )
											__magic_name__ 		=			text_encoder_output.text_embeds

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

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

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

											return prompt_embeds







					@torch.no_grad()
					@replace_example_docstring(UpperCAmelCase_     )
					def __call__(	self					:	Optional[Any]  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	int = 1  ,			_lowerCAmelCase					:	int = 2_5  ,			_lowerCAmelCase					:	Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,			_lowerCAmelCase					:	Optional[torch.FloatTensor] = None  ,			_lowerCAmelCase					:	float = 4.0  ,			_lowerCAmelCase					:	int = 6_4  ,			_lowerCAmelCase					:	Optional[str] = "pil"  ,			_lowerCAmelCase					:	bool = True  ,			)       ->				Optional[int]:



											'''simple docstring'''





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

											__magic_name__ 		=			self._execution_device

											__magic_name__ 		=			batch_size * num_images_per_prompt

											__magic_name__ 		=			guidance_scale > 1.0
											__magic_name__ 		=			self._encode_prompt(UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_     )

											# prior

											self.scheduler.set_timesteps(UpperCAmelCase_  ,			device=UpperCAmelCase_     )
											__magic_name__ 		=			self.scheduler.timesteps

											__magic_name__ 		=			self.prior.config.num_embeddings
											__magic_name__ 		=			self.prior.config.embedding_dim

											__magic_name__ 		=			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
											__magic_name__ 		=			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
																	__magic_name__ 		=			torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
																	__magic_name__ 		=			self.scheduler.scale_model_input(UpperCAmelCase_  ,			UpperCAmelCase_     )

																	__magic_name__ 		=			self.prior(
																	    UpperCAmelCase_  ,			timestep=UpperCAmelCase_  ,			proj_embedding=UpperCAmelCase_  ,			).predicted_image_embedding

																	# remove the variance
																	__magic_name__ 		=			noise_pred.split(
																	    scaled_model_input.shape[2]  ,			dim=2     )  # batch_size, num_embeddings, embedding_dim

																	if do_classifier_free_guidance is not None:
																							__magic_name__ 		=			noise_pred.chunk(2     )
																							__magic_name__ 		=			noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

																	__magic_name__ 		=			self.scheduler.step(
																	    UpperCAmelCase_  ,			timestep=UpperCAmelCase_  ,			sample=UpperCAmelCase_  ,			).prev_sample

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

											__magic_name__ 		=			[]
											for i, latent in enumerate(UpperCAmelCase_     ):
																	__magic_name__ 		=			self.renderer.decode(
																	    latent[None, :]  ,			UpperCAmelCase_  ,			size=UpperCAmelCase_  ,			ray_batch_size=4_0_9_6  ,			n_coarse_samples=6_4  ,			n_fine_samples=1_2_8  ,			)
																	images.append(UpperCAmelCase_     )

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

											__magic_name__ 		=			images.cpu().numpy()

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



import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding

class     __snake_case							(      _UpperCAmelCase):
					SCREAMING_SNAKE_CASE_		:					Union[str, Any] 				= ["image_processor", "tokenizer"]
					SCREAMING_SNAKE_CASE_		:					Tuple 				= "AutoImageProcessor"
					SCREAMING_SNAKE_CASE_		:					Dict 				= "AutoTokenizer"
					def __init__(	self					:	List[str]  ,			_lowerCAmelCase					:	str=None  ,			_lowerCAmelCase					:	Dict=None  ,			**_lowerCAmelCase					:	List[str]     )       ->				Optional[int]:



											'''simple docstring'''





											__magic_name__ 		=			None
											if "feature_extractor" in kwargs:
																	warnings.warn(
																	    'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
																	    ' instead.'  ,			_lowerCAmelCase  ,			)
																	__magic_name__ 		=			kwargs.pop('feature_extractor'     )

											__magic_name__ 		=			image_processor if image_processor is not None else feature_extractor
											if image_processor is None:
																	raise ValueError('You have to specify an image_processor.'     )
											if tokenizer is None:
																	raise ValueError('You have to specify a tokenizer.'     )

											super().__init__(_lowerCAmelCase  ,			_lowerCAmelCase     )
											__magic_name__ 		=			self.image_processor
					def __call__(	self					:	str  ,			_lowerCAmelCase					:	Any=None  ,			_lowerCAmelCase					:	int=None  ,			_lowerCAmelCase					:	List[str]=None  ,			**_lowerCAmelCase					:	int     )       ->				int:



											'''simple docstring'''





											if text is None and images is None:
																	raise ValueError('You have to specify either text or images. Both cannot be none.'     )

											if text is not None:
																	__magic_name__ 		=			self.tokenizer(_lowerCAmelCase  ,			return_tensors=_lowerCAmelCase  ,			**_lowerCAmelCase     )

											if images is not None:
																	__magic_name__ 		=			self.image_processor(_lowerCAmelCase  ,			return_tensors=_lowerCAmelCase  ,			**_lowerCAmelCase     )

											if text is not None and images is not None:
																	__magic_name__ 		=			image_features.pixel_values
																	return encoding
											elif text is not None:
																	return encoding
											else:
																	return BatchEncoding(data=dict(**_lowerCAmelCase     )  ,			tensor_type=_lowerCAmelCase     )
					def   a (	self					:	Optional[int]  ,			*_lowerCAmelCase					:	Optional[int]  ,			**_lowerCAmelCase					:	Optional[Any]     )       ->				Optional[int]:



											'''simple docstring'''





											return self.tokenizer.batch_decode(*_lowerCAmelCase  ,			**_lowerCAmelCase     )
					def   a (	self					:	Union[str, Any]  ,			*_lowerCAmelCase					:	str  ,			**_lowerCAmelCase					:	Tuple     )       ->				int:



											'''simple docstring'''





											return self.tokenizer.decode(*_lowerCAmelCase  ,			**_lowerCAmelCase     )
					@property
					def   a (	self					:	List[Any]     )       ->				Tuple:



											'''simple docstring'''





											__magic_name__ 		=			self.tokenizer.model_input_names
											__magic_name__ 		=			self.image_processor.model_input_names
											return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names     )     )
					@property
					def   a (	self					:	Optional[Any]     )       ->				Dict:



											'''simple docstring'''





											warnings.warn(
											    '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'  ,			_lowerCAmelCase  ,			)
											return self.image_processor_class







					@property
					def   a (	self					:	Dict     )       ->				Tuple:



											'''simple docstring'''





											warnings.warn(
											    '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'  ,			_lowerCAmelCase  ,			)
											return self.image_processor

