



from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
				import tensorflow as tf

				from ..tf_utils import stable_softmax


if is_torch_available():
				import torch


A__								=						logging.get_logger(__name__)


@add_end_docstrings(
    __lowerCamelCase  ,							r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """  ,							)
class       a							(			__lowerCamelCase				):



		def 	__lowerCamelCase			(     self     :Optional[int]   ,__lowercase     :GenericTensor  ):
						if self.framework == "tf":
										snake_case__	:      List[str]     		=	tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
						elif self.framework == "pt":
										snake_case__	:      Union[str, Any]     		=	torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,as_tuple=__lowercase  )
						else:
										raise ValueError('''Unsupported framework'''  )
						return masked_index



		def 	__lowerCamelCase			(     self     :List[str]   ,__lowercase     :GenericTensor  ):
						snake_case__	:      List[Any]     		=	self.get_masked_index(__lowercase  )
						snake_case__	:      Any     		=	np.prod(masked_index.shape  )
						if numel < 1:
										raise PipelineException(
										    '''fill-mask'''   ,self.model.base_model_prefix   ,F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""   ,)



		def 	__lowerCamelCase			(     self     :Optional[int]   ,__lowercase     :GenericTensor  ):
						if isinstance(__lowercase   ,__lowercase  ):
										for model_input in model_inputs:
														self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]  )
						else:
										for input_ids in model_inputs["input_ids"]:
														self._ensure_exactly_one_mask_token(__lowercase  )



		def 	__lowerCamelCase			(     self     :Union[str, Any]   ,__lowercase     :List[Any]   ,__lowercase     :Optional[int]=None   ,**__lowercase     :Optional[Any]  ):
						if return_tensors is None:
										snake_case__	:      Any     		=	self.framework
						snake_case__	:      str     		=	self.tokenizer(__lowercase   ,return_tensors=__lowercase  )
						self.ensure_exactly_one_mask_token(__lowercase  )
						return model_inputs



		def 	__lowerCamelCase			(     self     :Dict   ,__lowercase     :List[str]  ):
						snake_case__	:      List[str]     		=	self.model(**__lowercase  )
						snake_case__	:      List[Any]     		=	model_inputs['''input_ids''']
						return model_outputs



		def 	__lowerCamelCase			(     self     :Optional[Any]   ,__lowercase     :Optional[Any]   ,__lowercase     :Any=5   ,__lowercase     :Optional[Any]=None  ):
						# Cap top_k if there are targets
						if target_ids is not None and target_ids.shape[0] < top_k:
										snake_case__	:      Optional[Any]     		=	target_ids.shape[0]
						snake_case__	:      Optional[Any]     		=	model_outputs['''input_ids'''][0]
						snake_case__	:      Dict     		=	model_outputs['''logits''']

						if self.framework == "tf":
										snake_case__	:      List[str]     		=	tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()[:, 0]

										snake_case__	:      Dict     		=	outputs.numpy()

										snake_case__	:      List[str]     		=	outputs[0, masked_index, :]
										snake_case__	:      Any     		=	stable_softmax(__lowercase   ,axis=-1  )
										if target_ids is not None:
														snake_case__	:      str     		=	tf.gather_nd(tf.squeeze(__lowercase   ,0  )   ,target_ids.reshape(-1   ,1  )  )
														snake_case__	:      Tuple     		=	tf.expand_dims(__lowercase   ,0  )

										snake_case__	:      Any     		=	tf.math.top_k(__lowercase   ,k=__lowercase  )
										snake_case__		, snake_case__	:      List[Any]     		=	topk.values.numpy(), topk.indices.numpy()
						else:
										snake_case__	:      Optional[Any]     		=	torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,as_tuple=__lowercase  ).squeeze(-1  )
										# Fill mask pipeline supports only one ${mask_token} per sample

										snake_case__	:      int     		=	outputs[0, masked_index, :]
										snake_case__	:      int     		=	logits.softmax(dim=-1  )
										if target_ids is not None:
														snake_case__	:      List[str]     		=	probs[..., target_ids]

										snake_case__		, snake_case__	:      Tuple     		=	probs.topk(__lowercase  )

						snake_case__	:      Union[str, Any]     		=	[]
						snake_case__	:      Union[str, Any]     		=	values.shape[0] == 1
						for i, (_values, _predictions) in enumerate(zip(values.tolist()   ,predictions.tolist()  )  ):
										snake_case__	:      Any     		=	[]
										for v, p in zip(_values   ,_predictions  ):
														# Copy is important since we're going to modify this array in place
														snake_case__	:      Optional[Any]     		=	input_ids.numpy().copy()
														if target_ids is not None:
																		snake_case__	:      Dict     		=	target_ids[p].tolist()

														snake_case__	:      Optional[Any]     		=	p
														# Filter padding out:
														snake_case__	:      Union[str, Any]     		=	tokens[np.where(tokens != self.tokenizer.pad_token_id  )]
														# Originally we skip special tokens to give readable output.
														# For multi masks though, the other [MASK] would be removed otherwise
														# making the output look odd, so we add them back
														snake_case__	:      Optional[Any]     		=	self.tokenizer.decode(__lowercase   ,skip_special_tokens=__lowercase  )
														snake_case__	:      str     		=	{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]  ), '''sequence''': sequence}
														row.append(__lowercase  )
										result.append(__lowercase  )
						if single_mask:
										return result[0]
						return result



		def 	__lowerCamelCase			(     self     :str   ,__lowercase     :str   ,__lowercase     :Dict=None  ):
						if isinstance(__lowercase   ,__lowercase  ):
										snake_case__	:      int     		=	[targets]
						try:
										snake_case__	:      Union[str, Any]     		=	self.tokenizer.get_vocab()
						except Exception:
										snake_case__	:      Tuple     		=	{}
						snake_case__	:      int     		=	[]
						for target in targets:
										snake_case__	:      int     		=	vocab.get(__lowercase   ,__lowercase  )
										if id_ is None:
														snake_case__	:      Optional[Any]     		=	self.tokenizer(
														    __lowercase   ,add_special_tokens=__lowercase   ,return_attention_mask=__lowercase   ,return_token_type_ids=__lowercase   ,max_length=1   ,truncation=__lowercase   ,)['''input_ids''']
														if len(__lowercase  ) == 0:
																		logger.warning(
																		    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																		    '''We cannot replace it with anything meaningful, ignoring it'''  )
																		continue
														snake_case__	:      str     		=	input_ids[0]
														# XXX: If users encounter this pass
														# it becomes pretty slow, so let's make sure
														# The warning enables them to fix the input to
														# get faster performance.
														logger.warning(
														    F"""The specified target token `{target}` does not exist in the model vocabulary. """
														    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_  )}`."""  )
										target_ids.append(id_  )
						snake_case__	:      Tuple     		=	list(set(__lowercase  )  )
						if len(__lowercase  ) == 0:
										raise ValueError('''At least one target must be provided when passed.'''  )
						snake_case__	:      str     		=	np.array(__lowercase  )
						return target_ids



		def 	__lowerCamelCase			(     self     :Optional[Any]   ,__lowercase     :Any=None   ,__lowercase     :Any=None  ):
						snake_case__	:      Any     		=	{}

						if targets is not None:
										snake_case__	:      Union[str, Any]     		=	self.get_target_ids(__lowercase   ,__lowercase  )
										snake_case__	:      Optional[int]     		=	target_ids

						if top_k is not None:
										snake_case__	:      List[str]     		=	top_k

						if self.tokenizer.mask_token_id is None:
										raise PipelineException(
										    '''fill-mask'''   ,self.model.base_model_prefix   ,'''The tokenizer does not define a `mask_token`.'''  )
						return {}, {}, postprocess_params






		def __call__(     self     :int   ,__lowercase     :Union[str, Any]   ,*__lowercase     :Optional[Any]   ,**__lowercase     :Optional[Any]  ):
						snake_case__	:      Optional[int]     		=	super().__call__(__lowercase   ,**__lowercase  )
						if isinstance(__lowercase   ,__lowercase  ) and len(__lowercase  ) == 1:
										return outputs[0]
						return outputs






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


A__								=						logging.get_logger(__name__)

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

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


class       a							(			__lowerCamelCase				):



		def __init__(     self     :Union[str, Any]   ,__lowercase     :Optional[Any]   ,__lowercase     :int=False   ,__lowercase     :int=True   ,__lowercase     :Optional[int]=False   ,__lowercase     :List[str]="<s>"   ,__lowercase     :str="</s>"   ,__lowercase     :Dict="<unk>"   ,__lowercase     :Optional[int]="<sep>"   ,__lowercase     :Tuple="<pad>"   ,__lowercase     :Union[str, Any]="<cls>"   ,__lowercase     :Dict="<mask>"   ,__lowercase     :List[Any]=["<eop>", "<eod>"]   ,__lowercase     :Optional[Dict[str, Any]] = None   ,**__lowercase     :int   ,):
						snake_case__	:      Any     		=	AddedToken(__lowercase   ,lstrip=__lowercase   ,rstrip=__lowercase  ) if isinstance(__lowercase   ,__lowercase  ) else mask_token

						snake_case__	:      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   ,)

						snake_case__	:      Optional[Any]     		=	3

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

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



		@property
		# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
		def 	__lowerCamelCase			(     self     :Union[str, Any]  ):
						return len(self.sp_model  )



		def 	__lowerCamelCase			(     self     :Any  ):
						snake_case__	:      Optional[Any]     		=	{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     :List[str]  ):
						snake_case__	:      Optional[Any]     		=	self.__dict__.copy()
						snake_case__	:      Optional[int]     		=	None
						return state



		def __setstate__(     self     :int   ,__lowercase     :str  ):
						snake_case__	:      Tuple     		=	d

						# for backward compatibility
						if not hasattr(self   ,'''sp_model_kwargs'''  ):
										snake_case__	:      List[Any]     		=	{}

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



		def 	__lowerCamelCase			(     self     :Dict   ,__lowercase     :Optional[int]  ):
						if self.remove_space:
										snake_case__	:      int     		=	''' '''.join(inputs.strip().split()  )
						else:
										snake_case__	:      Tuple     		=	inputs
						snake_case__	:      List[Any]     		=	outputs.replace('''``'''   ,'''"'''  ).replace('''\'\''''   ,'''"'''  )

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

						return outputs



		def 	__lowerCamelCase			(     self     :Optional[Any]   ,__lowercase     :str  ):
						snake_case__	:      Dict     		=	self.preprocess_text(__lowercase  )
						snake_case__	:      Any     		=	self.sp_model.encode(__lowercase   ,out_type=__lowercase  )
						snake_case__	:      List[str]     		=	[]
						for piece in pieces:
										if len(__lowercase  ) > 1 and piece[-1] == str(''','''  ) and piece[-2].isdigit():
														snake_case__	:      Union[str, Any]     		=	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:
																						snake_case__	:      Optional[Any]     		=	cur_pieces[1:]
																		else:
																						snake_case__	:      Optional[Any]     		=	cur_pieces[0][1:]
														cur_pieces.append(piece[-1]  )
														new_pieces.extend(__lowercase  )
										else:
														new_pieces.append(__lowercase  )

						return new_pieces



		def 	__lowerCamelCase			(     self     :Union[str, Any]   ,__lowercase     :Dict  ):
						return self.sp_model.PieceToId(__lowercase  )



		def 	__lowerCamelCase			(     self     :Tuple   ,__lowercase     :Optional[int]  ):
						return self.sp_model.IdToPiece(__lowercase  )



		def 	__lowerCamelCase			(     self     :Tuple   ,__lowercase     :List[Any]  ):
						snake_case__	:      Union[str, Any]     		=	''''''.join(__lowercase  ).replace(__lowercase   ,''' '''  ).strip()
						return out_string



		def 	__lowerCamelCase			(     self     :List[Any]   ,__lowercase     :List[int]   ,__lowercase     :Optional[List[int]] = None  ):
						snake_case__	:      Optional[Any]     		=	[self.sep_token_id]
						snake_case__	:      str     		=	[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     :str   ,__lowercase     :List[int]   ,__lowercase     :Optional[List[int]] = None   ,__lowercase     :bool = False  ):

						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     :List[str]   ,__lowercase     :List[int]   ,__lowercase     :Optional[List[int]] = None  ):
						snake_case__	:      List[Any]     		=	[self.sep_token_id]
						snake_case__	:      Optional[Any]     		=	[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     :Optional[int]   ,__lowercase     :str   ,__lowercase     :Optional[str] = None  ):
						if not os.path.isdir(__lowercase  ):
										logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""  )
										return
						snake_case__	:      Union[str, Any]     		=	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:
														snake_case__	:      str     		=	self.sp_model.serialized_model_proto()
														fi.write(__lowercase  )

						return (out_vocab_file,)






		def 	__lowerCamelCase			(     self     :Union[str, Any]   ,*__lowercase     :Optional[int]   ,**__lowercase     :Dict  ):
						snake_case__	:      Dict     		=	super()._decode(*__lowercase   ,**__lowercase  )
						snake_case__	:      List[Any]     		=	text.replace(''' '''   ,''''''  ).replace('''\u2582'''   ,''' '''  ).replace('''\u2583'''   ,'''\n'''  )
						return text

