





"""simple docstring"""






import os
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 SPIECE_UNDERLINE, logging


__UpperCAmelCase						=			logging.get_logger(__name__)

__UpperCAmelCase						=			{'''vocab_file''': '''spiece.model'''}

__UpperCAmelCase						=			{
    '''vocab_file''': {
        '''TsinghuaAI/CPM-Generate''': '''https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model''',
    }
}



class 					__UpperCAmelCase							(						_UpperCamelCase  ):
				def __init__(		self    :			str	, a_    :			Dict	, a_    :			List[str]=False	, a_    :			Any=True	, a_    :			int=False	, a_    :			Union[str, Any]="<s>"	, a_    :			Optional[int]="</s>"	, a_    :			int="<unk>"	, a_    :			List[Any]="<sep>"	, a_    :			Dict="<pad>"	, a_    :			Any="<cls>"	, a_    :			Optional[Any]="<mask>"	, a_    :			int=["<eop>", "<eod>"]	, a_    :			Optional[Dict[str, Any]] = None	, **a_    :			int	, )	->	None:



							'''simple docstring'''



							a__  :	List[str]		 =			AddedToken(a_	, lstrip=a_	, rstrip=a_    ) if isinstance(a_	, a_    ) else mask_token

							a__  :	List[str]		 =			{} if sp_model_kwargs is None else sp_model_kwargs

							super().__init__(
							    do_lower_case=a_	, remove_space=a_	, keep_accents=a_	, bos_token=a_	, eos_token=a_	, unk_token=a_	, sep_token=a_	, pad_token=a_	, cls_token=a_	, mask_token=a_	, additional_special_tokens=a_	, sp_model_kwargs=self.sp_model_kwargs	, **a_	, )

							a__  :	Union[str, Any]		 =			3

							a__  :	Dict		 =			do_lower_case
							a__  :	Union[str, Any]		 =			remove_space
							a__  :	int		 =			keep_accents
							a__  :	str		 =			vocab_file

							a__  :	str		 =			spm.SentencePieceProcessor(**self.sp_model_kwargs    )
							self.sp_model.Load(a_    )

							try:
										import jieba
							except ModuleNotFoundError as error:
										raise error.__class__(
										    "You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
										    "See https://pypi.org/project/jieba/ for installation."    )
							a__  :	Optional[int]		 =			jieba
							a__  :	Optional[int]		 =			str.maketrans(" \n"	, "\u2582\u2583"    )
				@property
				# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
				def       UpperCAmelCase      (		self    :			Union[str, Any]    )	->	str:



							'''simple docstring'''



							return len(self.sp_model    )
				def       UpperCAmelCase      (		self    :			Dict    )	->	Union[str, Any]:



							'''simple docstring'''



							a__  :	Optional[int]		 =			{self.convert_ids_to_tokens(a_    ): i for i in range(self.vocab_size    )}
							vocab.update(self.added_tokens_encoder    )
							return vocab
				def __getstate__(		self    :			Tuple    )	->	List[str]:



							'''simple docstring'''



							a__  :	Tuple		 =			self.__dict__.copy()
							a__  :	Union[str, Any]		 =			None
							return state
				def __setstate__(		self    :			Tuple	, a_    :			int    )	->	List[str]:



							'''simple docstring'''



							a__  :	Any		 =			d

							# for backward compatibility
							if not hasattr(self	, "sp_model_kwargs"    ):
										a__  :	str		 =			{}

							a__  :	List[str]		 =			spm.SentencePieceProcessor(**self.sp_model_kwargs    )
							self.sp_model.Load(self.vocab_file    )
				def       UpperCAmelCase      (		self    :			List[Any]	, a_    :			Optional[Any]    )	->	List[str]:



							'''simple docstring'''



							if self.remove_space:
										a__  :	Union[str, Any]		 =			" ".join(inputs.strip().split()    )
							else:
										a__  :	Optional[Any]		 =			inputs
							a__  :	List[str]		 =			outputs.replace("``"	, "\""    ).replace("''"	, "\""    )

							if not self.keep_accents:
										a__  :	Union[str, Any]		 =			unicodedata.normalize("NFKD"	, a_    )
										a__  :	Union[str, Any]		 =			"".join([c for c in outputs if not unicodedata.combining(a_    )]    )
							if self.do_lower_case:
										a__  :	List[Any]		 =			outputs.lower()

							return outputs
				def       UpperCAmelCase      (		self    :			Any	, a_    :			str    )	->	List[str]:



							'''simple docstring'''



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

							return new_pieces
				def       UpperCAmelCase      (		self    :			int	, a_    :			Dict    )	->	int:



							'''simple docstring'''



							return self.sp_model.PieceToId(a_    )
				def       UpperCAmelCase      (		self    :			Dict	, a_    :			Tuple    )	->	List[Any]:



							'''simple docstring'''



							return self.sp_model.IdToPiece(a_    )
				def       UpperCAmelCase      (		self    :			Union[str, Any]	, a_    :			List[Any]    )	->	str:



							'''simple docstring'''



							a__  :	Optional[Any]		 =			"".join(a_    ).replace(a_	, " "    ).strip()
							return out_string
				def       UpperCAmelCase      (		self    :			str	, a_    :			List[int]	, a_    :			Optional[List[int]] = None    )	->	List[int]:



							'''simple docstring'''



							a__  :	List[Any]		 =			[self.sep_token_id]
							a__  :	int		 =			[self.cls_token_id]
							if token_ids_a is None:
										return token_ids_a + sep + cls
							return token_ids_a + sep + token_ids_a + sep + cls
				def       UpperCAmelCase      (		self    :			int	, a_    :			List[int]	, a_    :			Optional[List[int]] = None	, a_    :			bool = False    )	->	List[int]:



							'''simple docstring'''



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

							if token_ids_a is not None:
										return ([0] * len(a_    )) + [1] + ([0] * len(a_    )) + [1, 1]
							return ([0] * len(a_    )) + [1, 1]
				def       UpperCAmelCase      (		self    :			List[Any]	, a_    :			List[int]	, a_    :			Optional[List[int]] = None    )	->	List[int]:



							'''simple docstring'''



							a__  :	List[str]		 =			[self.sep_token_id]
							a__  :	Tuple		 =			[2]

							if token_ids_a is None:
										return len(token_ids_a + sep    ) * [0] + cls_segment_id
							return len(token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1] + cls_segment_id
				def       UpperCAmelCase      (		self    :			Dict	, a_    :			str	, a_    :			Optional[str] = None    )	->	Tuple[str]:



							'''simple docstring'''



							if not os.path.isdir(a_    ):
										logger.error(F"Vocabulary path ({save_directory}) should be a directory"    )
										return
							a__  :	Optional[int]		 =			os.path.join(
							    a_	, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]    )

							if os.path.abspath(self.vocab_file    ) != os.path.abspath(a_    ) and os.path.isfile(self.vocab_file    ):
										copyfile(self.vocab_file	, a_    )
							elif not os.path.isfile(self.vocab_file    ):
										with open(a_	, "wb"    ) as fi:
													a__  :	int		 =			self.sp_model.serialized_model_proto()
													fi.write(a_    )

							return (out_vocab_file,)






				def       UpperCAmelCase      (		self    :			str	, *a_    :			Union[str, Any]	, **a_    :			Any    )	->	int:



							'''simple docstring'''



							a__  :	Optional[int]		 =			super()._decode(*a_	, **a_    )
							a__  :	Tuple		 =			text.replace(" "	, ""    ).replace("\u2582"	, " "    ).replace("\u2583"	, "\n"    )
							return text






"""simple docstring"""






from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__UpperCAmelCase						=			logging.get_logger(__name__)






def      lowercase__ (					lowerCAmelCase__   :			Union[tf.Tensor, np.ndarray]			)    ->			List[int]:



			'''simple docstring'''
			if isinstance(lowerCAmelCase__							,			np.ndarray			):
						return list(tensor.shape			)

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)

			if tensor.shape == tf.TensorShape(lowerCAmelCase__			):
						return dynamic

			a__  :	Union[str, Any]		 =			tensor.shape.as_list()

			return [dynamic[i] if s is None else s for i, s in enumerate(lowerCAmelCase__			)]






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			Optional[int] = None							,			lowerCAmelCase__   :			Optional[str] = None			)    ->			tf.Tensor:



			'''simple docstring'''
			return tf.nn.softmax(logits=logits + 1E-9							,			axis=lowerCAmelCase__							,			name=lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			List[str]							,			lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Union[str, Any]=1E-5							,			lowerCAmelCase__   :			str=-1			)    ->			int:



			'''simple docstring'''
			# This is a very simplified functional layernorm, designed to duplicate
			# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
			# models in Transformers.

			if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowerCAmelCase__							,			lowerCAmelCase__			):
						raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis."			)

			# Get mean and variance on the axis to be normalized
			a__ ,	a__  :	Dict		 =			tf.nn.moments(lowerCAmelCase__							,			axes=[axis]							,			keepdims=lowerCAmelCase__			)

			if axis != -1:
						# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
						# on every dimension except axis
						a__  :	Dict		 =			[1] * inputs.shape.rank
						a__  :	Dict		 =			shape_list(lowerCAmelCase__			)[axis]
						a__  :	Any		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)
						a__  :	List[Any]		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)

			# Compute layer normalization using the batch_normalization
			# function.
			a__  :	List[str]		 =			tf.nn.batch_normalization(
			    lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__							,			offset=lowerCAmelCase__							,			scale=lowerCAmelCase__							,			variance_epsilon=lowerCAmelCase__							,			)
			return outputs






def      lowercase__ (					lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			Any=0							,			lowerCAmelCase__   :			List[str]=-1			)    ->			List[str]:



			'''simple docstring'''
			# Replicates the behavior of torch.flatten in TF

			# If end_dim or start_dim is negative, count them from the end
			if end_dim < 0:
						end_dim += input.shape.rank
			if start_dim < 0:
						start_dim += input.shape.rank

			if start_dim == end_dim:
						return input

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)
			a__  :	str		 =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]			)
			a__  :	Union[str, Any]		 =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]							,			axis=0			)
			return tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor			)    ->			tf.Tensor:



			'''simple docstring'''
			if not isinstance(lowerCAmelCase__							,			tf.Tensor			):
						a__  :	Optional[Any]		 =			tf.convert_to_tensor(lowerCAmelCase__			)  # Catches stray NumPy inputs
			if encoder_attention_mask.shape.rank == 3:
						a__  :	Tuple		 =			encoder_attention_mask[:, None, :, :]
			if encoder_attention_mask.shape.rank == 2:
						a__  :	int		 =			encoder_attention_mask[:, None, None, :]
			# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
			# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
			# /transformer/transformer_layers.py#L270
			# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
			# encoder_extended_attention_mask.transpose(-1, -2))
			a__  :	int		 =			(
			    tf.cast(1							,			encoder_attention_mask.dtype			) - encoder_extended_attention_mask
			) * encoder_extended_attention_mask.dtype.min

			return encoder_extended_attention_mask






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			str = "input_ids"			)    ->			None:



			'''simple docstring'''
			tf.debugging.assert_less(
			    lowerCAmelCase__							,			tf.cast(lowerCAmelCase__							,			dtype=tensor.dtype			)							,			message=(
			        F"The maximum value of {tensor_name} ({tf.math.reduce_max(lowerCAmelCase__			)}) must be smaller than the embedding "
			        F"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
			    )							,			)






def      lowercase__ (					lowerCAmelCase__   :			Dict							,			lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			Dict			)    ->			Tuple:



			'''simple docstring'''
			a__  :	Optional[Any]		 =			6_4_5_1_2
			# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
			# because in that case even chunking the array would not make the saving
			# possible.
			a__  :	Optional[Any]		 =			[x for x in data if len(lowerCAmelCase__			) > HDF5_OBJECT_HEADER_LIMIT]

			# Expecting this to never be true.
			if bad_attributes:
						raise RuntimeError(
						    "The following attributes cannot be saved to HDF5 file because "
						    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
						    F"bytes: {bad_attributes}"			)

			a__  :	List[str]		 =			np.asarray(lowerCAmelCase__			)

			a__  :	List[str]		 =			1
			a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			# This will never loop forever thanks to the test above.
			while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data			):
						num_chunks += 1
						a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			if num_chunks > 1:
						for chunk_id, chunk_data in enumerate(lowerCAmelCase__			):
									a__  :	List[Any]		 =			chunk_data
			else:
						a__  :	List[str]		 =			data






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			Tuple			)    ->			Tuple:



			'''simple docstring'''
			if name in group.attrs:
						a__  :	str		 =			[n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs[name]]
			else:
						a__  :	str		 =			[]
						a__  :	Any		 =			0
						while "%s%d" % (name, chunk_id) in group.attrs:
									data.extend(
									    [n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs["%s%d" % (name, chunk_id)]]			)
									chunk_id += 1
			return data






def      lowercase__ (					lowerCAmelCase__   :			Tuple			)    ->			List[Any]:



			'''simple docstring'''

			def _expand_single_ad_tensor(lowerCAmelCase__   :			List[str]			):
						if isinstance(lowerCAmelCase__							,			tf.Tensor			) and t.shape.rank == 1:
									return tf.expand_dims(lowerCAmelCase__							,			axis=-1			)
						return t

			return tf.nest.map_structure(_expand_single_ad_tensor							,			lowerCAmelCase__			)