


import os
import re
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_UpperCAmelCase     :					Any       =logging.get_logger(__name__)
_UpperCAmelCase     :					Optional[int]       ={"""vocab_file""": """spiece.model"""}

_UpperCAmelCase     :					Optional[Any]       ={
    """vocab_file""": {
        """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/spiece.model""",
        """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/spiece.model""",
    },
}

_UpperCAmelCase     :					List[str]       ={
    """google/fnet-base""": 512,
    """google/fnet-large""": 512,
}

_UpperCAmelCase     :					Any       ="""▁"""







class 			snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__ :					List[str]   =							VOCAB_FILES_NAMES
						SCREAMING_SNAKE_CASE__ :					Dict   =							PRETRAINED_VOCAB_FILES_MAP
						SCREAMING_SNAKE_CASE__ :					Optional[int]   =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						SCREAMING_SNAKE_CASE__ :					Dict   =							["""input_ids""", """token_type_ids"""]




						def __init__(			self				,  __lowercase				,  __lowercase=False				,  __lowercase=True				,  __lowercase=True				,  __lowercase="<unk>"				,  __lowercase="[SEP]"				,  __lowercase="<pad>"				,  __lowercase="[CLS]"				,  __lowercase="[MASK]"				,  __lowercase = None				,  **__lowercase				,  )   ->      None:
										# Mask token behave like a normal word, i.e. include the space before it and
										# is included in the raw text, there should be a match in a non-normalized sentence.
										lowerCAmelCase_	: Union[str, Any]      			=			(
										    AddedToken(__lowercase				,  lstrip=__lowercase				,  rstrip=__lowercase				,  normalized=__lowercase							)
										    if isinstance(__lowercase				,  __lowercase							)
										    else mask_token
										)

										lowerCAmelCase_	: Dict      			=			{} if sp_model_kwargs is None else sp_model_kwargs

										super().__init__(
										    do_lower_case=__lowercase				,  remove_space=__lowercase				,  keep_accents=__lowercase				,  unk_token=__lowercase				,  sep_token=__lowercase				,  pad_token=__lowercase				,  cls_token=__lowercase				,  mask_token=__lowercase				,  sp_model_kwargs=self.sp_model_kwargs				,  **__lowercase				,  )

										lowerCAmelCase_	: Union[str, Any]      			=			do_lower_case
										lowerCAmelCase_	: Any      			=			remove_space
										lowerCAmelCase_	: Tuple      			=			keep_accents
										lowerCAmelCase_	: List[Any]      			=			vocab_file

										lowerCAmelCase_	: Union[str, Any]      			=			spm.SentencePieceProcessor(**self.sp_model_kwargs							)
										self.sp_model.Load(__lowercase							)




						@property
						def   lowercase_	(			self							)   ->      Optional[Any]:
										return len(self.sp_model							)




						def   lowercase_	(			self							)   ->      Any:
										lowerCAmelCase_	: Tuple      			=			{self.convert_ids_to_tokens(__lowercase							): i for i in range(self.vocab_size							)}
										vocab.update(self.added_tokens_encoder							)
										return vocab




						def __getstate__(			self							)   ->      Union[str, Any]:
										lowerCAmelCase_	: Optional[Any]      			=			self.__dict__.copy()
										lowerCAmelCase_	: Union[str, Any]      			=			None
										return state




						def __setstate__(			self				,  __lowercase							)   ->      Dict:
										lowerCAmelCase_	: Optional[Any]      			=			d

										# for backward compatibility
										if not hasattr(self				,  '''sp_model_kwargs'''							):
														lowerCAmelCase_	: Optional[int]      			=			{}

										lowerCAmelCase_	: Optional[Any]      			=			spm.SentencePieceProcessor(**self.sp_model_kwargs							)
										self.sp_model.Load(self.vocab_file							)




						def   lowercase_	(			self				,  __lowercase							)   ->      Tuple:
										if self.remove_space:
														lowerCAmelCase_	: Union[str, Any]      			=			''' '''.join(inputs.strip().split()							)
										else:
														lowerCAmelCase_	: Dict      			=			inputs
										lowerCAmelCase_	: str      			=			outputs.replace('''``'''				,  '''"'''							).replace('''\'\''''				,  '''"'''							)

										if not self.keep_accents:
														lowerCAmelCase_	: Optional[Any]      			=			unicodedata.normalize('''NFKD'''				,  __lowercase							)
														lowerCAmelCase_	: int      			=			''''''.join([c for c in outputs if not unicodedata.combining(__lowercase							)]							)
										if self.do_lower_case:
														lowerCAmelCase_	: str      			=			outputs.lower()

										return outputs




						def   lowercase_	(			self				,  __lowercase							)   ->      List[str]:
										lowerCAmelCase_	: List[str]      			=			self.preprocess_text(__lowercase							)
										lowerCAmelCase_	: Optional[Any]      			=			self.sp_model.encode(__lowercase				,  out_type=__lowercase							)
										lowerCAmelCase_	: Union[str, Any]      			=			[]
										for piece in pieces:
														if len(__lowercase							) > 1 and piece[-1] == str(''','''							) and piece[-2].isdigit():
																		lowerCAmelCase_	: List[str]      			=			self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowercase				,  ''''''							)							)
																		if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																						if len(cur_pieces[0]							) == 1:
																										lowerCAmelCase_	: List[str]      			=			cur_pieces[1:]
																						else:
																										lowerCAmelCase_	: Dict      			=			cur_pieces[0][1:]
																		cur_pieces.append(piece[-1]							)
																		new_pieces.extend(__lowercase							)
														else:
																		new_pieces.append(__lowercase							)

										return new_pieces




						def   lowercase_	(			self				,  __lowercase							)   ->      List[str]:
										return self.sp_model.PieceToId(__lowercase							)




						def   lowercase_	(			self				,  __lowercase							)   ->      Union[str, Any]:
										return self.sp_model.IdToPiece(__lowercase							)




						def   lowercase_	(			self				,  __lowercase							)   ->      Optional[int]:
										lowerCAmelCase_	: List[str]      			=			[]
										lowerCAmelCase_	: Any      			=			''''''
										lowerCAmelCase_	: List[Any]      			=			False
										for token in tokens:
														# make sure that special tokens are not decoded using sentencepiece model
														if token in self.all_special_tokens:
																		if not prev_is_special:
																						out_string += " "
																		out_string += self.sp_model.decode(__lowercase							) + token
																		lowerCAmelCase_	: int      			=			True
																		lowerCAmelCase_	: Optional[Any]      			=			[]
														else:
																		current_sub_tokens.append(__lowercase							)
																		lowerCAmelCase_	: List[str]      			=			False
										out_string += self.sp_model.decode(__lowercase							)
										return out_string.strip()




						def   lowercase_	(			self				,  __lowercase				,  __lowercase = False				,  __lowercase = None				,  __lowercase = True				,  **__lowercase				,  )   ->      str:
										lowerCAmelCase_	: Any      			=			kwargs.pop('''use_source_tokenizer'''				,  __lowercase							)

										lowerCAmelCase_	: Union[str, Any]      			=			self.convert_ids_to_tokens(__lowercase				,  skip_special_tokens=__lowercase							)

										# To avoid mixing byte-level and unicode for byte-level BPT
										# we need to build string separately for added tokens and byte-level tokens
										# cf. https://github.com/huggingface/transformers/issues/1133
										lowerCAmelCase_	: str      			=			[]
										lowerCAmelCase_	: Optional[int]      			=			[]
										for token in filtered_tokens:
														if skip_special_tokens and token in self.all_special_ids:
																		continue
														if token in self.added_tokens_encoder:
																		if current_sub_text:
																						sub_texts.append(self.convert_tokens_to_string(__lowercase							)							)
																						lowerCAmelCase_	: Optional[int]      			=			[]
																		sub_texts.append(__lowercase							)
														else:
																		current_sub_text.append(__lowercase							)
										if current_sub_text:
														sub_texts.append(self.convert_tokens_to_string(__lowercase							)							)

										# Mimic the behavior of the Rust tokenizer:
										# No space after <unk>
										if spaces_between_special_tokens:
														lowerCAmelCase_	: List[str]      			=			re.sub(R'''(<unk>) '''				,  R'''\1'''				,  ''' '''.join(__lowercase							)							)
										else:
														lowerCAmelCase_	: List[str]      			=			''''''.join(__lowercase							)

										lowerCAmelCase_	: Union[str, Any]      			=			(
										    clean_up_tokenization_spaces
										    if clean_up_tokenization_spaces is not None
										    else self.clean_up_tokenization_spaces
										)
										if clean_up_tokenization_spaces:
														lowerCAmelCase_	: int      			=			self.clean_up_tokenization(__lowercase							)
														return clean_text
										else:
														return text




						def   lowercase_	(			self				,  __lowercase				,  __lowercase = None							)   ->      List[int]:
										lowerCAmelCase_	: int      			=			[self.sep_token_id]
										lowerCAmelCase_	: Tuple      			=			[self.cls_token_id]
										if token_ids_a is None:
														return cls + token_ids_a + sep
										return cls + token_ids_a + sep + token_ids_a + sep




						def   lowercase_	(			self				,  __lowercase				,  __lowercase = None				,  __lowercase = False							)   ->      List[int]:

										if already_has_special_tokens:
														return super().get_special_tokens_mask(
														    token_ids_a=__lowercase				,  token_ids_a=__lowercase				,  already_has_special_tokens=__lowercase							)

										if token_ids_a is not None:
														return [1] + ([0] * len(__lowercase							)) + [1] + ([0] * len(__lowercase							)) + [1]
										return [1] + ([0] * len(__lowercase							)) + [1]




						def   lowercase_	(			self				,  __lowercase				,  __lowercase = None							)   ->      List[int]:
										lowerCAmelCase_	: Dict      			=			[self.sep_token_id]
										lowerCAmelCase_	: str      			=			[self.cls_token_id]

										if token_ids_a is None:
														return len(cls + token_ids_a + sep							) * [0]
										return len(cls + token_ids_a + sep							) * [0] + len(token_ids_a + sep							) * [1]




						def   lowercase_	(			self				,  __lowercase				,  __lowercase = None							)   ->      Tuple[str]:
										if not os.path.isdir(__lowercase							):
														logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""							)
														return
										lowerCAmelCase_	: Optional[int]      			=			os.path.join(
										    __lowercase				,  (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']							)

										if os.path.abspath(self.vocab_file							) != os.path.abspath(__lowercase							) and os.path.isfile(self.vocab_file							):
														copyfile(self.vocab_file				,  __lowercase							)
										elif not os.path.isfile(self.vocab_file							):
														with open(__lowercase				,  '''wb'''							) as fi:
																		lowerCAmelCase_	: List[Any]      			=			self.sp_model.serialized_model_proto()
																		fi.write(__lowercase							)

										return (out_vocab_file,)



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     :					Tuple       =logging.get_logger(__name__)  # pylint: disable=invalid-name

_UpperCAmelCase     :					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 			snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__ :					Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]







class 			snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						def __init__(			self				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  )   ->      Optional[Any]:
										super().__init__()

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




						def   lowercase_	(			self				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase							)   ->      Tuple:
										if latents is None:
														lowerCAmelCase_	: Dict      			=			randn_tensor(__lowercase				,  generator=__lowercase				,  device=__lowercase				,  dtype=__lowercase							)
										else:
														if latents.shape != shape:
																		raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""							)
														lowerCAmelCase_	: Dict      			=			latents.to(__lowercase							)

										lowerCAmelCase_	: Tuple      			=			latents * scheduler.init_noise_sigma
										return latents




						def   lowercase_	(			self				,  __lowercase=0							)   ->      List[Any]:
										if is_accelerate_available():
														from accelerate import cpu_offload
										else:
														raise ImportError('''Please install accelerate via `pip install accelerate`'''							)

										lowerCAmelCase_	: Tuple      			=			torch.device(f"""cuda:{gpu_id}"""							)

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




						def   lowercase_	(			self				,  __lowercase=0							)   ->      Optional[int]:
										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.'''							)

										lowerCAmelCase_	: Union[str, Any]      			=			torch.device(f"""cuda:{gpu_id}"""							)

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

										lowerCAmelCase_	: str      			=			None
										for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
														lowerCAmelCase_			,					lowerCAmelCase_	: Optional[int]      			=			cpu_offload_with_hook(__lowercase				,  __lowercase				,  prev_module_hook=__lowercase							)

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

										# We'll offload the last model manually.
										lowerCAmelCase_	: Union[str, Any]      			=			hook




						@property
						def   lowercase_	(			self							)   ->      Optional[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(__lowercase				,  '''_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   lowercase_	(			self				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  )   ->      Dict:
										len(__lowercase							) if isinstance(__lowercase				,  __lowercase							) else 1

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

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

										lowerCAmelCase_	: Any      			=			self.text_encoder(text_input_ids.to(__lowercase							)							)
										lowerCAmelCase_	: Dict      			=			text_encoder_output.text_embeds

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

										if do_classifier_free_guidance:
														lowerCAmelCase_	: Optional[Any]      			=			torch.zeros_like(__lowercase							)

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

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

										return prompt_embeds




						@torch.no_grad()
						@replace_example_docstring(__lowercase							)
						def __call__(			self				,  __lowercase				,  __lowercase = 1				,  __lowercase = 2_5				,  __lowercase = None				,  __lowercase = None				,  __lowercase = 4.0				,  __lowercase = 6_4				,  __lowercase = "pil"				,  __lowercase = True				,  )   ->      Tuple:

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

										lowerCAmelCase_	: Union[str, Any]      			=			self._execution_device

										lowerCAmelCase_	: Dict      			=			batch_size * num_images_per_prompt

										lowerCAmelCase_	: List[str]      			=			guidance_scale > 1.0
										lowerCAmelCase_	: List[Any]      			=			self._encode_prompt(__lowercase				,  __lowercase				,  __lowercase				,  __lowercase							)

										# prior

										self.scheduler.set_timesteps(__lowercase				,  device=__lowercase							)
										lowerCAmelCase_	: Any      			=			self.scheduler.timesteps

										lowerCAmelCase_	: Union[str, Any]      			=			self.prior.config.num_embeddings
										lowerCAmelCase_	: Dict      			=			self.prior.config.embedding_dim

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

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

														lowerCAmelCase_	: List[str]      			=			self.prior(
														    __lowercase				,  timestep=__lowercase				,  proj_embedding=__lowercase				,  ).predicted_image_embedding

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

														lowerCAmelCase_	: Optional[int]      			=			self.scheduler.step(
														    __lowercase				,  timestep=__lowercase				,  sample=__lowercase				,  ).prev_sample

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

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

										lowerCAmelCase_	: List[str]      			=			torch.stack(__lowercase							)

										if output_type not in ["np", "pil"]:
														raise ValueError(f"""Only the output types `pil` and `np` are supported not output_type={output_type}"""							)

										lowerCAmelCase_	: Optional[int]      			=			images.cpu().numpy()

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