

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


snake_case_   :   Optional[int]        =       logging.get_logger(__name__)

snake_case_   :   int        =       {"""vocab_file""": """spiece.model"""}

snake_case_   :   Tuple        =       {
    """vocab_file""": {
        """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""",
    }
}







class       snake_case__  ( lowerCAmelCase_     ):







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





								'''simple docstring'''



								UpperCAmelCase			:   Optional[int]      =				AddedToken(lowercase			,  lstrip=lowercase			,  rstrip=lowercase  ) if isinstance(lowercase			,  lowercase  ) else mask_token

								UpperCAmelCase			:   Tuple      =				{} if sp_model_kwargs is None else sp_model_kwargs

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

								UpperCAmelCase			:   List[Any]      =				3

								UpperCAmelCase			:   Optional[Any]      =				do_lower_case
								UpperCAmelCase			:   List[str]      =				remove_space
								UpperCAmelCase			:   Optional[Any]      =				keep_accents
								UpperCAmelCase			:   List[Any]      =				vocab_file

								UpperCAmelCase			:   Optional[int]      =				spm.SentencePieceProcessor(**self.sp_model_kwargs  )
								self.sp_model.Load(lowercase  )

								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."  )
								UpperCAmelCase			:   Optional[Any]      =				jieba
								UpperCAmelCase			:   List[Any]      =				str.maketrans(" \n"			,  "\u2582\u2583"  )







			@property
			# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
			def 			__lowerCAmelCase				(			self			: Any  ):





								'''simple docstring'''



								return len(self.sp_model  )







			def 			__lowerCAmelCase				(			self			: List[str]  ):





								'''simple docstring'''



								UpperCAmelCase			:   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			: str  ):





								'''simple docstring'''



								UpperCAmelCase			:   int      =				self.__dict__.copy()
								UpperCAmelCase			:   Optional[int]      =				None
								return state







			def __setstate__(			self			: Tuple			,  lowercase			: List[Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[Any]      =				d

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

								UpperCAmelCase			:   str      =				spm.SentencePieceProcessor(**self.sp_model_kwargs  )
								self.sp_model.Load(self.vocab_file  )







			def 			__lowerCAmelCase				(			self			: int			,  lowercase			: Optional[int]  ):





								'''simple docstring'''



								if self.remove_space:
													UpperCAmelCase			:   Tuple      =				" ".join(inputs.strip().split()  )
								else:
													UpperCAmelCase			:   int      =				inputs
								UpperCAmelCase			:   Optional[int]      =				outputs.replace("``"			,  "\""  ).replace("''"			,  "\""  )

								if not self.keep_accents:
													UpperCAmelCase			:   List[str]      =				unicodedata.normalize("NFKD"			,  lowercase  )
													UpperCAmelCase			:   Optional[int]      =				"".join([c for c in outputs if not unicodedata.combining(lowercase  )]  )
								if self.do_lower_case:
													UpperCAmelCase			:   List[Any]      =				outputs.lower()

								return outputs







			def 			__lowerCAmelCase				(			self			: str			,  lowercase			: str  ):





								'''simple docstring'''



								UpperCAmelCase			:   str      =				self.preprocess_text(lowercase  )
								UpperCAmelCase			:   List[str]      =				self.sp_model.encode(lowercase			,  out_type=lowercase  )
								UpperCAmelCase			:   Union[str, Any]      =				[]
								for piece in pieces:
													if len(lowercase  ) > 1 and piece[-1] == str(","  ) and piece[-2].isdigit():
																		UpperCAmelCase			:   int      =				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:
																												UpperCAmelCase			:   Union[str, Any]      =				cur_pieces[1:]
																							else:
																												UpperCAmelCase			:   str      =				cur_pieces[0][1:]
																		cur_pieces.append(piece[-1]  )
																		new_pieces.extend(lowercase  )
													else:
																		new_pieces.append(lowercase  )

								return new_pieces







			def 			__lowerCAmelCase				(			self			: Optional[int]			,  lowercase			: List[Any]  ):





								'''simple docstring'''



								return self.sp_model.PieceToId(lowercase  )







			def 			__lowerCAmelCase				(			self			: Dict			,  lowercase			: str  ):





								'''simple docstring'''



								return self.sp_model.IdToPiece(lowercase  )







			def 			__lowerCAmelCase				(			self			: Union[str, Any]			,  lowercase			: Dict  ):





								'''simple docstring'''



								UpperCAmelCase			:   str      =				"".join(lowercase  ).replace(lowercase			,  " "  ).strip()
								return out_string







			def 			__lowerCAmelCase				(			self			: Optional[int]			,  lowercase			: List[int]			,  lowercase			: Optional[List[int]] = None  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[int]      =				[self.sep_token_id]
								UpperCAmelCase			:   List[Any]      =				[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 			__lowerCAmelCase				(			self			: int			,  lowercase			: List[int]			,  lowercase			: Optional[List[int]] = None			,  lowercase			: bool = False  ):





								'''simple docstring'''



								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 ([0] * len(lowercase  )) + [1] + ([0] * len(lowercase  )) + [1, 1]
								return ([0] * len(lowercase  )) + [1, 1]







			def 			__lowerCAmelCase				(			self			: Any			,  lowercase			: List[int]			,  lowercase			: Optional[List[int]] = None  ):





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				[self.sep_token_id]
								UpperCAmelCase			:   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 			__lowerCAmelCase				(			self			: Tuple			,  lowercase			: str			,  lowercase			: Optional[str] = None  ):





								'''simple docstring'''



								if not os.path.isdir(lowercase  ):
													logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""  )
													return
								UpperCAmelCase			:   List[str]      =				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:
																		UpperCAmelCase			:   List[Any]      =				self.sp_model.serialized_model_proto()
																		fi.write(lowercase  )

								return (out_vocab_file,)







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  *lowercase			: Tuple			,  **lowercase			: Optional[int]  ):





								'''simple docstring'''



								UpperCAmelCase			:   Tuple      =				super()._decode(*lowercase			,  **lowercase  )
								UpperCAmelCase			:   str      =				text.replace(" "			,  ""  ).replace("\u2582"			,  " "  ).replace("\u2583"			,  "\n"  )
								return text





"""simple docstring"""






def   lowercase_	(    _lowercase       :		list							,      _lowercase       :		int							,      _lowercase       :		int = 0							,      _lowercase       :		int = 0	):




					'''simple docstring'''






					UpperCAmelCase			:   Tuple      =				right or len(_lowercase	) - 1
					if left > right:
										return -1
					elif list_data[left] == key:
										return left
					elif list_data[right] == key:
										return right
					else:
										return search(_lowercase							,      _lowercase							,      left + 1							,      right - 1	)


if __name__ == "__main__":
	import doctest

	doctest.testmod()


