



'''simple docstring'''





import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase_	 =						logging.get_logger(__name__)

lowercase_	 =						'▁'

lowercase_	 =						{'vocab_file': 'vocab.txt', 'sentencepiece_model_ckpt': 'sentencepiece.bpe.model'}

lowercase_	 =						{
    'sentencepiece_model_file': 'sentencepiece.bpe.model',
    'vocab_file': 'vocab.txt',
}

lowercase_	 =						{
    'vocab_file': {
        'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
        'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
    },
    'sentencepiece_model_file': {
        'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
        'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
    },
}

lowercase_	 =						{
    'ernie-m-base': 514,
    'ernie-m-large': 514,
}

lowercase_	 =						{
    'ernie-m-base': {'do_lower_case': False},
    'ernie-m-large': {'do_lower_case': False},
}






class __A    (						a__		):



 '''simple docstring'''







 __lowerCamelCase					: List[str]    = ["input_ids"]

 __lowerCamelCase					: Any    = VOCAB_FILES_NAMES
 __lowerCamelCase					: Optional[int]    = PRETRAINED_INIT_CONFIGURATION
 __lowerCamelCase					: Dict    = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __lowerCamelCase					: Dict    = PRETRAINED_VOCAB_FILES_MAP
 __lowerCamelCase					: Union[str, Any]    = RESOURCE_FILES_NAMES



 def __init__(self				,     A				,     A=None				,     A=False				,     A="utf8"				,     A="[UNK]"				,     A="[SEP]"				,     A="[PAD]"				,     A="[CLS]"				,     A="[MASK]"				,     A = None				,     **A				,     )					->  None:


      """simple docstring"""



      _a											=						{} if sp_model_kwargs is None else sp_model_kwargs
      super().__init__(
          do_lower_case=lowercase__				,     unk_token=lowercase__				,     sep_token=lowercase__				,     pad_token=lowercase__				,     cls_token=lowercase__				,     mask_token=lowercase__				,     vocab_file=lowercase__				,     encoding=lowercase__				,     sp_model_kwargs=self.sp_model_kwargs				,     **lowercase__				,     )
      _a											=						do_lower_case
      _a											=						sentencepiece_model_ckpt
      _a											=						spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.Load(lowercase__ )

      # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
      if vocab_file is not None:
           _a											=						self.load_vocab(filepath=lowercase__ )
      else:
           _a											=						{self.sp_model.id_to_piece(lowercase__ ): id for id in range(self.sp_model.get_piece_size() )}
      _a											=						{v: k for k, v in self.vocab.items()}



 def       a__						(self				,     A )					->  Optional[Any]:


      """simple docstring"""



      if text is None:
           return None

      _a											=						self.tokenize(lowercase__ )
      _a											=						'''''', []

      for i, ch in enumerate(lowercase__ ):
           if ch in self.SP_CHAR_MAPPING:
                _a											=						self.SP_CHAR_MAPPING.get(lowercase__ )
           else:
                _a											=						unicodedata.normalize('''NFKC'''				,     lowercase__ )
           if self.is_whitespace(lowercase__ ):
                continue
           normalized_text += ch
           char_mapping.extend([i] * len(lowercase__ ) )

      _a											=						normalized_text, [], 0

      if self.do_lower_case:
           _a											=						text.lower()

      for token in split_tokens:
           if token[:1] == "▁":
                _a											=						token[1:]
           _a											=						text[offset:].index(lowercase__ ) + offset
           _a											=						start + len(lowercase__ )

           token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) )
           _a											=						end
      return token_mapping



 @property
 def       a__						(self )					->  Union[str, Any]:


      """simple docstring"""



      return len(self.vocab )



 def       a__						(self )					->  str:


      """simple docstring"""



      return dict(self.vocab				,     **self.added_tokens_encoder )



 def __getstate__(self )					->  Optional[Any]:


      """simple docstring"""



      _a											=						self.__dict__.copy()
      _a											=						None
      return state



 def __setstate__(self				,     A )					->  Tuple:


      """simple docstring"""



      _a											=						d

      # for backward compatibility
      if not hasattr(self				,     '''sp_model_kwargs''' ):
           _a											=						{}

      _a											=						spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.Load(self.sentencepiece_model_ckpt )



 def       a__						(self				,     A )					->  Union[str, Any]:


      """simple docstring"""



      return "".join((self.SP_CHAR_MAPPING.get(lowercase__				,     lowercase__ ) for c in text) )



 def       a__						(self				,     A				,     A=False				,     A=64				,     A=0.1 )					->  Any:


      """simple docstring"""



      if self.sp_model_kwargs.get('''enable_sampling''' ) is True:
           _a											=						True
      if self.sp_model_kwargs.get('''alpha''' ) is not None:
           _a											=						self.sp_model_kwargs.get('''alpha''' )
      if self.sp_model_kwargs.get('''nbest_size''' ) is not None:
           _a											=						self.sp_model_kwargs.get('''nbest_size''' )

      if not enable_sampling:
           _a											=						self.sp_model.EncodeAsPieces(lowercase__ )
      else:
           _a											=						self.sp_model.SampleEncodeAsPieces(lowercase__				,     lowercase__				,     lowercase__ )
      _a											=						[]
      for pi, piece in enumerate(lowercase__ ):
           if piece == SPIECE_UNDERLINE:
                if not pieces[pi + 1].startswith(lowercase__ ) and pi != 0:
                     new_pieces.append(lowercase__ )
                     continue
                else:
                     continue
           _a											=						0
           for i, chunk in enumerate(lowercase__ ):
                if chunk == SPIECE_UNDERLINE:
                     continue
                if self.is_ch_char(lowercase__ ) or self.is_punct(lowercase__ ):
                     if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                          new_pieces.append(piece[lst_i:i] )
                     new_pieces.append(lowercase__ )
                     _a											=						i + 1
                elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
                     if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                          new_pieces.append(piece[lst_i:i] )
                     _a											=						i
                elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
                     if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                          new_pieces.append(piece[lst_i:i] )
                     _a											=						i
           if len(lowercase__ ) > lst_i:
                new_pieces.append(piece[lst_i:] )
      return new_pieces



 def       a__						(self				,     A )					->  int:


      """simple docstring"""



      _a											=						''''''.join(lowercase__ ).replace(lowercase__				,     ''' ''' ).strip()
      return out_string



 def       a__						(self				,     A )					->  str:


      """simple docstring"""



      _a											=						self.convert_ids_to_tokens(lowercase__ )
      _a											=						''''''.join(lowercase__ ).replace(lowercase__				,     ''' ''' ).strip()
      return out_string



 def       a__						(self				,     A )					->  Union[str, Any]:


      """simple docstring"""



      return self.vocab.get(lowercase__				,     self.vocab.get(self.unk_token ) )



 def       a__						(self				,     A )					->  Optional[Any]:


      """simple docstring"""



      return self.reverse_vocab.get(lowercase__				,     self.unk_token )



 def       a__						(self				,     A				,     A=None )					->  str:


      """simple docstring"""



      if token_ids_a is None:
           return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      _a											=						[self.cls_token_id]
      _a											=						[self.sep_token_id]
      return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep



 def       a__						(self				,     A				,     A=None )					->  Union[str, Any]:


      """simple docstring"""



      if offset_mapping_a is None:
           return [(0, 0)] + offset_mapping_a + [(0, 0)]

      return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]



 def       a__						(self				,     A				,     A=None				,     A=False )					->  Optional[int]:


      """simple docstring"""



      if already_has_special_tokens:
           if token_ids_a is not None:
                raise ValueError(
                    '''You should not supply a second sequence if the provided sequence of '''
                    '''ids is already formatted with special tokens for the model.''' )
           return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

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



 def       a__						(self				,     A				,     A = None )					->  List[int]:


      """simple docstring"""



      if token_ids_a is None:
           # [CLS] X [SEP]
           return (len(lowercase__ ) + 2) * [0]

      # [CLS] A [SEP] [SEP] B [SEP]
      return [0] * (len(lowercase__ ) + 1) + [1] * (len(lowercase__ ) + 3)



 def       a__						(self				,     A )					->  Dict:


      """simple docstring"""



      if "\u4e00" <= char <= "\u9fff":
           return True
      return False



 def       a__						(self				,     A )					->  Any:


      """simple docstring"""



      if ("a" <= char <= "z") or ("A" <= char <= "Z"):
           return True
      return False



 def       a__						(self				,     A )					->  str:


      """simple docstring"""



      if char in ",;:.?!~，；：。？！《》【】":
           return True
      return False



 def       a__						(self				,     A )					->  Tuple:


      """simple docstring"""



      if char == " " or char == "\t" or char == "\n" or char == "\r":
           return True
      if len(lowercase__ ) == 1:
           _a											=						unicodedata.category(lowercase__ )
           if cat == "Zs":
                return True
      return False



 def       a__						(self				,     A )					->  Any:


      """simple docstring"""



      _a											=						{}
      with io.open(lowercase__				,     '''r'''				,     encoding='''utf-8''' ) as f:
           for index, line in enumerate(lowercase__ ):
                _a											=						line.rstrip('''\n''' )
                _a											=						int(lowercase__ )

      return token_to_idx



 def       a__						(self				,     A				,     A = None )					->  Tuple[str]:


      """simple docstring"""



      _a											=						0
      if os.path.isdir(lowercase__ ):
           _a											=						os.path.join(
               lowercase__				,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
      else:
           _a											=						(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
      with open(lowercase__				,     '''w'''				,     encoding='''utf-8''' ) as writer:
           for token, token_index in sorted(self.vocab.items()				,     key=lambda A : kv[1] ):
                if index != token_index:
                     logger.warning(
                         f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
                         ''' Please check that the vocabulary is not corrupted!''' )
                     _a											=						token_index
                writer.write(token + '''\n''' )
                index += 1

      _a											=						os.path.join(lowercase__				,     '''sentencepiece.bpe.model''' )
      with open(lowercase__				,     '''wb''' ) as fi:
           _a											=						self.sp_model.serialized_model_proto()
           fi.write(lowercase__ )

      return (vocab_file,)










'''simple docstring'''





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


lowercase_	 =						logging.get_logger(__name__)






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



 '''simple docstring'''







 def       a__						(self				,     A )					->  np.ndarray:


      """simple docstring"""



      if self.framework == "tf":
           _a											=						tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
      elif self.framework == "pt":
           _a											=						torch.nonzero(input_ids == self.tokenizer.mask_token_id				,     as_tuple=A )
      else:
           raise ValueError('''Unsupported framework''' )
      return masked_index



 def       a__						(self				,     A )					->  np.ndarray:


      """simple docstring"""



      _a											=						self.get_masked_index(A )
      _a											=						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       a__						(self				,     A )					->  Optional[int]:


      """simple docstring"""



      if isinstance(A				,     A ):
           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(A )



 def       a__						(self				,     A				,     A=None				,     **A )					->  Dict[str, GenericTensor]:


      """simple docstring"""



      if return_tensors is None:
           _a											=						self.framework
      _a											=						self.tokenizer(A				,     return_tensors=A )
      self.ensure_exactly_one_mask_token(A )
      return model_inputs



 def       a__						(self				,     A )					->  Optional[Any]:


      """simple docstring"""



      _a											=						self.model(**A )
      _a											=						model_inputs['''input_ids''']
      return model_outputs



 def       a__						(self				,     A				,     A=5				,     A=None )					->  Tuple:


      """simple docstring"""



      if target_ids is not None and target_ids.shape[0] < top_k:
           _a											=						target_ids.shape[0]
      _a											=						model_outputs['''input_ids'''][0]
      _a											=						model_outputs['''logits''']

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

           _a											=						outputs.numpy()

           _a											=						outputs[0, masked_index, :]
           _a											=						stable_softmax(A				,     axis=-1 )
           if target_ids is not None:
                _a											=						tf.gather_nd(tf.squeeze(A				,     0 )				,     target_ids.reshape(-1				,     1 ) )
                _a											=						tf.expand_dims(A				,     0 )

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

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

           _a						,					_a											=						probs.topk(A )

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

                _a											=						p
                # Filter padding out:
                _a											=						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
                _a											=						self.tokenizer.decode(A				,     skip_special_tokens=A )
                _a											=						{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p] ), '''sequence''': sequence}
                row.append(A )
           result.append(A )
      if single_mask:
           return result[0]
      return result



 def       a__						(self				,     A				,     A=None )					->  Optional[Any]:


      """simple docstring"""



      if isinstance(A				,     A ):
           _a											=						[targets]
      try:
           _a											=						self.tokenizer.get_vocab()
      except Exception:
           _a											=						{}
      _a											=						[]
      for target in targets:
           _a											=						vocab.get(A				,     A )
           if id_ is None:
                _a											=						self.tokenizer(
                    A				,     add_special_tokens=A				,     return_attention_mask=A				,     return_token_type_ids=A				,     max_length=1				,     truncation=A				,     )['''input_ids''']
                if len(A ) == 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
                _a											=						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_ )
      _a											=						list(set(A ) )
      if len(A ) == 0:
           raise ValueError('''At least one target must be provided when passed.''' )
      _a											=						np.array(A )
      return target_ids



 def       a__						(self				,     A=None				,     A=None )					->  List[str]:


      """simple docstring"""



      _a											=						{}

      if targets is not None:
           _a											=						self.get_target_ids(A				,     A )
           _a											=						target_ids

      if top_k is not None:
           _a											=						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				,     A				,     *A				,     **A )					->  str:


      """simple docstring"""



      _a											=						super().__call__(A				,     **A )
      if isinstance(A				,     A ) and len(A ) == 1:
           return outputs[0]
      return outputs



