



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


_A					:     Union[str, Any]      =logging.get_logger(__name__)  # pylint: disable=invalid-name

_A					:     Optional[Any]      ='''
    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 		lowerCamelCase__   (    A  ):




					'''simple docstring'''



					A_         =    42






class 		lowerCamelCase__   (    A  ):




					'''simple docstring'''



					def __init__(	self					:						str  ,	UpperCamelCase_					:						PriorTransformer  ,	UpperCamelCase_					:						CLIPTextModelWithProjection  ,	UpperCamelCase_					:						CLIPTokenizer  ,	UpperCamelCase_					:						HeunDiscreteScheduler  ,	UpperCamelCase_					:						ShapERenderer  ,	)	->							Optional[int]:



						'''simple docstring'''





						super().__init__()

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




					def     __UpperCAmelCase  (	self					:						Dict  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						int  ,	UpperCamelCase_					:						List[Any]  ,	UpperCamelCase_					:						int       )	->							Any:



						'''simple docstring'''





						if latents is None:
							_lowercase       :							List[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}'''       )
							_lowercase       :							Union[str, Any]  	=		latents.to(UpperCamelCase_       )

						_lowercase       :							int  	=		latents * scheduler.init_noise_sigma
						return latents




					def     __UpperCAmelCase  (	self					:						Union[str, Any]  ,	UpperCamelCase_					:						Tuple=0       )	->							Optional[Any]:



						'''simple docstring'''





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

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

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




					def     __UpperCAmelCase  (	self					:						Union[str, Any]  ,	UpperCamelCase_					:						str=0       )	->							Optional[Any]:



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

						_lowercase       :							Tuple  	=		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)

						_lowercase       :							Tuple  	=		None
						for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
							_lowercase	,     _lowercase       :							Optional[int]  	=		cpu_offload_with_hook(UpperCamelCase_  ,	UpperCamelCase_  ,	prev_module_hook=UpperCamelCase_       )

						if self.safety_checker is not None:
							_lowercase	,     _lowercase       :							List[str]  	=		cpu_offload_with_hook(self.safety_checker  ,	UpperCamelCase_  ,	prev_module_hook=UpperCamelCase_       )

						# We'll offload the last model manually.
						_lowercase       :							Any  	=		hook




					@property
					def     __UpperCAmelCase  (	self					:						Optional[Any]       )	->							str:



						'''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     __UpperCAmelCase  (	self					:						Dict  ,	UpperCamelCase_					:						Any  ,	UpperCamelCase_					:						List[str]  ,	UpperCamelCase_					:						Union[str, Any]  ,	UpperCamelCase_					:						Union[str, Any]  ,	)	->							Tuple:



						'''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
						_lowercase       :							Union[str, Any]  	=		0
						# get prompt text embeddings
						_lowercase       :							Union[str, Any]  	=		self.tokenizer(
						    UpperCamelCase_  ,	padding='max_length'  ,	max_length=self.tokenizer.model_max_length  ,	truncation=UpperCamelCase_  ,	return_tensors='pt'  ,	)
						_lowercase       :							int  	=		text_inputs.input_ids
						_lowercase       :							int  	=		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_       ):
							_lowercase       :							str  	=		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}'''       )

						_lowercase       :							Optional[int]  	=		self.text_encoder(text_input_ids.to(UpperCamelCase_       )       )
						_lowercase       :							str  	=		text_encoder_output.text_embeds

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

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

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

						return prompt_embeds




					@torch.no_grad()
					@replace_example_docstring(UpperCamelCase_       )
					def __call__(	self					:						str  ,	UpperCamelCase_					:						str  ,	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  ,	)	->							Any:



						'''simple docstring'''





						if isinstance(UpperCamelCase_  ,	UpperCamelCase_       ):
							_lowercase       :							List[str]  	=		1
						elif isinstance(UpperCamelCase_  ,	UpperCamelCase_       ):
							_lowercase       :							Any  	=		len(UpperCamelCase_       )
						else:
							raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase_       )}'''       )

						_lowercase       :							str  	=		self._execution_device

						_lowercase       :							Optional[Any]  	=		batch_size * num_images_per_prompt

						_lowercase       :							Any  	=		guidance_scale > 1.0
						_lowercase       :							Union[str, Any]  	=		self._encode_prompt(UpperCamelCase_  ,	UpperCamelCase_  ,	UpperCamelCase_  ,	UpperCamelCase_       )

						# prior

						self.scheduler.set_timesteps(UpperCamelCase_  ,	device=UpperCamelCase_       )
						_lowercase       :							Dict  	=		self.scheduler.timesteps

						_lowercase       :							Optional[Any]  	=		self.prior.config.num_embeddings
						_lowercase       :							Union[str, Any]  	=		self.prior.config.embedding_dim

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

							_lowercase       :							Union[str, Any]  	=		self.prior(
							    UpperCamelCase_  ,	timestep=UpperCamelCase_  ,	proj_embedding=UpperCamelCase_  ,	).predicted_image_embedding

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

							_lowercase       :							int  	=		self.scheduler.step(
							    UpperCamelCase_  ,	timestep=UpperCamelCase_  ,	sample=UpperCamelCase_  ,	).prev_sample

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

						_lowercase       :							Optional[Any]  	=		[]
						for i, latent in enumerate(UpperCamelCase_       ):
							_lowercase       :							Optional[Any]  	=		self.renderer.decode(
							    latent[None, :]  ,	UpperCamelCase_  ,	size=UpperCamelCase_  ,	ray_batch_size=4096  ,	n_coarse_samples=64  ,	n_fine_samples=128  ,	)
							images.append(UpperCamelCase_       )

						_lowercase       :							List[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}'''       )

						_lowercase       :							Dict  	=		images.cpu().numpy()

						if output_type == "pil":
							_lowercase       :							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



class 		lowerCamelCase__   :




					'''simple docstring'''



					def __init__(	self					:						str  ,	UpperCamelCase_					:						int       )	->							None:



						'''simple docstring'''





						_lowercase       :							Any  	=		value
						_lowercase       :							Node | None  	=		None
						_lowercase       :							Node | None  	=		None






class 		lowerCamelCase__   :




					'''simple docstring'''



					A_         =    42




					def __init__(	self					:						List[Any]       )	->							None:



						'''simple docstring'''





						_lowercase       :							Optional[int]  	=		0




					def     __UpperCAmelCase  (	self					:						str  ,	UpperCamelCase_					:						Node | None  ,	UpperCamelCase_					:						int       )	->							None:



						'''simple docstring'''





						if node is None:
							return

						if path_sum == self.target:
							self.paths += 1

						if node.left:
							self.depth_first_search(node.left  ,	path_sum + node.left.value       )
						if node.right:
							self.depth_first_search(node.right  ,	path_sum + node.right.value       )




					def     __UpperCAmelCase  (	self					:						Optional[int]  ,	UpperCamelCase_					:						Node | None  ,	UpperCamelCase_					:						int | None = None       )	->							int:



						'''simple docstring'''





						if node is None:
							return 0
						if target is not None:
							_lowercase       :							Union[str, Any]  	=		target

						self.depth_first_search(UpperCamelCase_  ,	node.value       )
						self.path_sum(node.left       )
						self.path_sum(node.right       )

						return self.paths


if __name__ == "__main__":
		import doctest

		doctest.testmod()
