

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_       :				Optional[int]		   =      logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCAmelCase_       :				Tuple		   =      '''
    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_			(  _lowercase  ):
	_lowercase		:      Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class     lowerCamelCase_			(  _lowercase  ):




	def __init__(    self	:    Dict				,			__A	:    PriorTransformer				,			__A	:    CLIPTextModelWithProjection				,			__A	:    CLIPTokenizer				,			__A	:    HeunDiscreteScheduler				,			__A	:    ShapERenderer				,			):
		super().__init__()

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




	def 					lowerCAmelCase_					(    self	:    List[str]				,			__A	:    List[str]				,			__A	:    str				,			__A	:    Any				,			__A	:    List[str]				,			__A	:    str				,			__A	:    Any       ):
		if latents is None:
			__A   : str								= randn_tensor(__A				,			generator=__A				,			device=__A				,			dtype=__A       )
		else:
			if latents.shape != shape:
				raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""       )
			__A   : Dict								= latents.to(__A       )

		__A   : Tuple								= latents * scheduler.init_noise_sigma
		return latents




	def 					lowerCAmelCase_					(    self	:    str				,			__A	:    Optional[Any]=0       ):
		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(__A				,			__A       )




	def 					lowerCAmelCase_					(    self	:    Tuple				,			__A	:    int=0       ):
		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=__A       )
			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   : Tuple								= cpu_offload_with_hook(__A				,			__A				,			prev_module_hook=__A       )

		if self.safety_checker is not None:
			__A   : Union[str, Any]								= cpu_offload_with_hook(self.safety_checker				,			__A				,			prev_module_hook=__A       )

		# We'll offload the last model manually.
		__A   : List[Any]								= hook




	@property
	def 					lowerCAmelCase_					(    self	:    Union[str, Any]       ):
		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(__A				,			"""_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]				,			__A	:    str				,			__A	:    Any				,			__A	:    Optional[Any]				,			__A	:    Optional[int]				,			):
		len(__A       ) if isinstance(__A				,			__A       ) else 1

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

		if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__A				,			__A       ):
			__A   : Tuple								= 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   : Dict								= self.text_encoder(text_input_ids.to(__A       )       )
		__A   : Any								= text_encoder_output.text_embeds

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

		if do_classifier_free_guidance:
			__A   : Dict								= torch.zeros_like(__A       )

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

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

		return prompt_embeds




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

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

		__A   : Dict								= self._execution_device

		__A   : Union[str, Any]								= batch_size * num_images_per_prompt

		__A   : Dict								= guidance_scale > 1.0
		__A   : Any								= self._encode_prompt(__A				,			__A				,			__A				,			__A       )

		# prior

		self.scheduler.set_timesteps(__A				,			device=__A       )
		__A   : Optional[Any]								= self.scheduler.timesteps

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

		__A   : Tuple								= self.prepare_latents(
		    (batch_size, num_embeddings * embedding_dim)				,			prompt_embeds.dtype				,			__A				,			__A				,			__A				,			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   : List[str]								= latents.reshape(latents.shape[0]				,			__A				,			__A       )

		for i, t in enumerate(self.progress_bar(__A       )       ):
			# expand the latents if we are doing classifier free guidance
			__A   : Optional[Any]								= torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents
			__A   : Optional[Any]								= self.scheduler.scale_model_input(__A				,			__A       )

			__A   : Any								= self.prior(
			    __A				,			timestep=__A				,			proj_embedding=__A				,			).predicted_image_embedding

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

			__A   : Any								= self.scheduler.step(
			    __A				,			timestep=__A				,			sample=__A				,			).prev_sample

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

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

		__A   : str								= torch.stack(__A       )

		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   : Dict								= images.cpu().numpy()

		if output_type == "pil":
			__A   : Any								= [self.numpy_to_pil(__A       ) 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=__A       )








import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer






class     lowerCamelCase_			(  tf.keras.layers.Layer  ):




	def __init__(    self	:    int				,			__A	:    List				,			__A	:    bool				,			__A	:    int = None				,			__A	:    int = None				,			__A	:    int = None				,			__A	:    str = "longest"				,			__A	:    bool = True				,			__A	:    int = 512				,			__A	:    int = None				,			__A	:    bool = True				,			__A	:    bool = True				,			__A	:    bool = True				,			**__A	:    Any				,			):
		super().__init__()
		if use_fast_bert_tokenizer:
			__A   : Optional[int]								= FastBertTokenizer(
			    __A				,			token_out_type=tf.intaa				,			lower_case_nfd_strip_accents=__A				,			**__A       )
		else:
			__A   : Optional[Any]								= tf.lookup.StaticVocabularyTable(
			    tf.lookup.KeyValueTensorInitializer(
			        keys=__A				,			key_dtype=tf.string				,			values=tf.range(tf.size(__A				,			out_type=tf.intaa       )				,			dtype=tf.intaa       )				,			value_dtype=tf.intaa				,			)				,			num_oov_buckets=1				,			)
			__A   : Any								= BertTokenizerLayer(
			    __A				,			token_out_type=tf.intaa				,			lower_case=__A				,			**__A       )

		__A   : Union[str, Any]								= vocab_list
		__A   : List[str]								= do_lower_case
		__A   : List[Any]								= cls_token_id or vocab_list.index("""[CLS]"""       )
		__A   : Tuple								= sep_token_id or vocab_list.index("""[SEP]"""       )
		__A   : str								= pad_token_id or vocab_list.index("""[PAD]"""       )
		__A   : Optional[int]								= ShrinkLongestTrimmer(max_length - 3				,			axis=1       )  # Allow room for special tokens
		__A   : Union[str, Any]								= max_length
		__A   : List[Any]								= padding
		__A   : Optional[int]								= truncation
		__A   : Tuple								= pad_to_multiple_of
		__A   : Optional[Any]								= return_token_type_ids
		__A   : int								= return_attention_mask




	@classmethod
	def 					lowerCAmelCase_					(    cls	:    List[Any]				,			__A	:    "PreTrainedTokenizerBase"				,			**__A	:    List[str]       ):  # noqa: F821
		__A   : Any								= kwargs.pop("""do_lower_case"""				,			__A       )
		__A   : Dict								= tokenizer.do_lower_case if do_lower_case is None else do_lower_case
		__A   : List[str]								= kwargs.pop("""cls_token_id"""				,			__A       )
		__A   : str								= tokenizer.cls_token_id if cls_token_id is None else cls_token_id
		__A   : str								= kwargs.pop("""sep_token_id"""				,			__A       )
		__A   : Dict								= tokenizer.sep_token_id if sep_token_id is None else sep_token_id
		__A   : Tuple								= kwargs.pop("""pad_token_id"""				,			__A       )
		__A   : List[Any]								= tokenizer.pad_token_id if pad_token_id is None else pad_token_id

		__A   : Union[str, Any]								= tokenizer.get_vocab()
		__A   : Any								= sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]				,			key=lambda __A       : x[1]       )
		__A   : int								= [entry[0] for entry in vocab]
		return cls(
		    vocab_list=__A				,			do_lower_case=__A				,			cls_token_id=__A				,			sep_token_id=__A				,			pad_token_id=__A				,			**__A				,			)




	@classmethod
	def 					lowerCAmelCase_					(    cls	:    List[str]				,			__A	:    Union[str, os.PathLike]				,			*__A	:    Tuple				,			**__A	:    Optional[int]       ):
		try:
			__A   : int								= BertTokenizer.from_pretrained(__A				,			*__A				,			**__A       )
		except:  # noqa: E722
			from .tokenization_bert_fast import BertTokenizerFast

			__A   : Optional[int]								= BertTokenizerFast.from_pretrained(__A				,			*__A				,			**__A       )
		return cls.from_tokenizer(__A				,			**__A       )




	def 					lowerCAmelCase_					(    self	:    Optional[int]				,			__A	:    Optional[Any]       ):
		if self.do_lower_case:
			__A   : Tuple								= case_fold_utfa(__A       )
		__A   : Optional[int]								= self.tf_tokenizer.tokenize(__A       )
		return tokens.merge_dims(1				,			-1       )




	def 					lowerCAmelCase_					(    self	:    Any				,			__A	:    Optional[Any]				,			__A	:    Dict=None				,			__A	:    List[Any]=None				,			__A	:    str=None				,			__A	:    Union[str, Any]=None				,			__A	:    Union[str, Any]=None				,			__A	:    int=None				,			__A	:    Any=None				,			):
		if padding is None:
			__A   : List[Any]								= self.padding
		if padding not in ("longest", "max_length"):
			raise ValueError("""Padding must be either 'longest' or 'max_length'!"""       )
		if max_length is not None and text_pair is not None:
			# Because we have to instantiate a Trimmer to do it properly
			raise ValueError("""max_length cannot be overridden at call time when truncating paired texts!"""       )
		if max_length is None:
			__A   : Any								= self.max_length
		if truncation is None:
			__A   : int								= self.truncation
		if pad_to_multiple_of is None:
			__A   : List[str]								= self.pad_to_multiple_of
		if return_token_type_ids is None:
			__A   : int								= self.return_token_type_ids
		if return_attention_mask is None:
			__A   : Any								= self.return_attention_mask
		if not isinstance(__A				,			tf.Tensor       ):
			__A   : str								= tf.convert_to_tensor(__A       )
		if text_pair is not None and not isinstance(__A				,			tf.Tensor       ):
			__A   : Optional[Any]								= tf.convert_to_tensor(__A       )
		if text_pair is not None:
			if text.shape.rank > 1:
				raise ValueError("""text argument should not be multidimensional when a text pair is supplied!"""       )
			if text_pair.shape.rank > 1:
				raise ValueError("""text_pair should not be multidimensional!"""       )
		if text.shape.rank == 2:
			__A						,							__A   : Optional[int]								= text[:, 0], text[:, 1]
		__A   : List[Any]								= self.unpaired_tokenize(__A       )
		if text_pair is None:  # Unpaired text
			if truncation:
				__A   : Union[str, Any]								= text[:, : max_length - 2]  # Allow room for special tokens
			__A						,							__A   : List[Any]								= combine_segments(
			    (text,)				,			start_of_sequence_id=self.cls_token_id				,			end_of_segment_id=self.sep_token_id       )
		else:  # Paired text
			__A   : Tuple								= self.unpaired_tokenize(__A       )
			if truncation:
				__A						,							__A   : Optional[int]								= self.paired_trimmer.trim([text, text_pair]       )
			__A						,							__A   : int								= combine_segments(
			    (text, text_pair)				,			start_of_sequence_id=self.cls_token_id				,			end_of_segment_id=self.sep_token_id       )
		if padding == "longest":
			__A   : str								= input_ids.bounding_shape(axis=1       )
			if pad_to_multiple_of is not None:
				# No ceiling division in tensorflow, so we negate floordiv instead
				__A   : Optional[Any]								= pad_to_multiple_of * (-tf.math.floordiv(-pad_length				,			__A       ))
		else:
			__A   : Dict								= max_length

		__A						,							__A   : str								= pad_model_inputs(__A				,			max_seq_length=__A				,			pad_value=self.pad_token_id       )
		__A   : List[str]								= {"""input_ids""": input_ids}
		if return_attention_mask:
			__A   : Any								= attention_mask
		if return_token_type_ids:
			__A						,							__A   : Tuple								= pad_model_inputs(
			    __A				,			max_seq_length=__A				,			pad_value=self.pad_token_id       )
			__A   : List[str]								= token_type_ids
		return output




	def 					lowerCAmelCase_					(    self	:    Optional[int]       ):
		return {
		    "vocab_list": self.vocab_list,
		    "do_lower_case": self.do_lower_case,
		    "cls_token_id": self.cls_token_id,
		    "sep_token_id": self.sep_token_id,
		    "pad_token_id": self.pad_token_id,
		}





