
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  :					Optional[Any]						    =							logging.get_logger(__name__)

lowercase  :					str						    =							"""▁"""

lowercase  :					Dict						    =							{"""vocab_file""": """vocab.txt""", """sentencepiece_model_ckpt""": """sentencepiece.bpe.model"""}

lowercase  :					Optional[Any]						    =							{
    """sentencepiece_model_file""": """sentencepiece.bpe.model""",
    """vocab_file""": """vocab.txt""",
}

lowercase  :					str						    =							{
    """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  :					int						    =							{
    """ernie-m-base""": 514,
    """ernie-m-large""": 514,
}

lowercase  :					List[Any]						    =							{
    """ernie-m-base""": {"""do_lower_case""": False},
    """ernie-m-large""": {"""do_lower_case""": False},
}

class __snake_case		(      lowerCAmelCase     ):
    _a		:						List[str]=				["input_ids"]

    _a		:						Optional[Any]=				VOCAB_FILES_NAMES
    _a		:						Tuple=				PRETRAINED_INIT_CONFIGURATION
    _a		:						Optional[int]=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    _a		:						int=				PRETRAINED_VOCAB_FILES_MAP
    _a		:						Dict=				RESOURCE_FILES_NAMES
    def __init__(  self		,snake_case		,snake_case=None		,snake_case=False		,snake_case="utf8"		,snake_case="[UNK]"		,snake_case="[SEP]"		,snake_case="[PAD]"		,snake_case="[CLS]"		,snake_case="[MASK]"		,snake_case = None		,**snake_case		,):



           '''simple docstring'''







           lowercase							:     Dict       	=      {} if sp_model_kwargs is None else sp_model_kwargs
           super().__init__(
               do_lower_case=snake_case		,unk_token=snake_case		,sep_token=snake_case		,pad_token=snake_case		,cls_token=snake_case		,mask_token=snake_case		,vocab_file=snake_case		,encoding=snake_case		,sp_model_kwargs=self.sp_model_kwargs		,**snake_case		,)
           lowercase							:     List[str]       	=      do_lower_case
           lowercase							:     List[Any]       	=      sentencepiece_model_ckpt
           lowercase							:     Optional[int]       	=      spm.SentencePieceProcessor(**self.sp_model_kwargs      )
           self.sp_model.Load(snake_case      )

           # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
           if vocab_file is not None:
                  lowercase							:     Dict       	=      self.load_vocab(filepath=snake_case      )
           else:
                  lowercase							:     Dict       	=      {self.sp_model.id_to_piece(snake_case      ): id for id in range(self.sp_model.get_piece_size()      )}
           lowercase							:     Optional[int]       	=      {v: k for k, v in self.vocab.items()}
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if text is None:
                  return None

           lowercase							:     Optional[Any]       	=      self.tokenize(snake_case      )
           lowercase	,			lowercase							:     Tuple       	=      """""", []

           for i, ch in enumerate(snake_case      ):
                  if ch in self.SP_CHAR_MAPPING:
                         lowercase							:     Tuple       	=      self.SP_CHAR_MAPPING.get(snake_case      )
                  else:
                         lowercase							:     str       	=      unicodedata.normalize("""NFKC"""		,snake_case      )
                  if self.is_whitespace(snake_case      ):
                         continue
                  normalized_text += ch
                  char_mapping.extend([i] * len(snake_case      )      )

           lowercase	,			lowercase	,			lowercase							:     Union[str, Any]       	=      normalized_text, [], 0

           if self.do_lower_case:
                  lowercase							:     str       	=      text.lower()

           for token in split_tokens:
                  if token[:1] == "▁":
                         lowercase							:     Optional[int]       	=      token[1:]
                  lowercase							:     Optional[int]       	=      text[offset:].index(snake_case      ) + offset
                  lowercase							:     Union[str, Any]       	=      start + len(snake_case      )

                  token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)      )
                  lowercase							:     List[Any]       	=      end
           return token_mapping
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           return len(self.vocab      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           return dict(self.vocab		,**self.added_tokens_encoder      )
    def __getstate__(  self      ):



           '''simple docstring'''







           lowercase							:     List[str]       	=      self.__dict__.copy()
           lowercase							:     Optional[int]       	=      None
           return state
    def __setstate__(  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      d

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

           lowercase							:     Optional[int]       	=      spm.SentencePieceProcessor(**self.sp_model_kwargs      )
           self.sp_model.Load(self.sentencepiece_model_ckpt      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           return "".join((self.SP_CHAR_MAPPING.get(snake_case		,snake_case      ) for c in text)      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=False		,snake_case=64		,snake_case=0.1      ):



           '''simple docstring'''







           if self.sp_model_kwargs.get("""enable_sampling"""      ) is True:
                  lowercase							:     Union[str, Any]       	=      True
           if self.sp_model_kwargs.get("""alpha"""      ) is not None:
                  lowercase							:     Optional[int]       	=      self.sp_model_kwargs.get("""alpha"""      )
           if self.sp_model_kwargs.get("""nbest_size"""      ) is not None:
                  lowercase							:     int       	=      self.sp_model_kwargs.get("""nbest_size"""      )

           if not enable_sampling:
                  lowercase							:     Tuple       	=      self.sp_model.EncodeAsPieces(snake_case      )
           else:
                  lowercase							:     Tuple       	=      self.sp_model.SampleEncodeAsPieces(snake_case		,snake_case		,snake_case      )
           lowercase							:     Any       	=      []
           for pi, piece in enumerate(snake_case      ):
                  if piece == SPIECE_UNDERLINE:
                         if not pieces[pi + 1].startswith(snake_case      ) and pi != 0:
                                new_pieces.append(snake_case      )
                                continue
                         else:
                                continue
                  lowercase							:     Optional[Any]       	=      0
                  for i, chunk in enumerate(snake_case      ):
                         if chunk == SPIECE_UNDERLINE:
                                continue
                         if self.is_ch_char(snake_case      ) or self.is_punct(snake_case      ):
                                if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                                       new_pieces.append(piece[lst_i:i]      )
                                new_pieces.append(snake_case      )
                                lowercase							:     List[Any]       	=      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]      )
                                lowercase							:     List[Any]       	=      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]      )
                                lowercase							:     List[Any]       	=      i
                  if len(snake_case      ) > lst_i:
                         new_pieces.append(piece[lst_i:]      )
           return new_pieces
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     int       	=      """""".join(snake_case      ).replace(snake_case		,""" """      ).strip()
           return out_string
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      self.convert_ids_to_tokens(snake_case      )
           lowercase							:     Any       	=      """""".join(snake_case      ).replace(snake_case		,""" """      ).strip()
           return out_string
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           return self.vocab.get(snake_case		,self.vocab.get(self.unk_token      )      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           return self.reverse_vocab.get(snake_case		,self.unk_token      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None      ):



           '''simple docstring'''







           if token_ids_a is None:
                  return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
           lowercase							:     int       	=      [self.cls_token_id]
           lowercase							:     Union[str, Any]       	=      [self.sep_token_id]
           return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None      ):



           '''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       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None		,snake_case=False      ):



           '''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(snake_case      )) + [1, 1] + ([0] * len(snake_case      )) + [1]
           return [1] + ([0] * len(snake_case      )) + [1]
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case = None      ):



           '''simple docstring'''







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

           # [CLS] A [SEP] [SEP] B [SEP]
           return [0] * (len(snake_case      ) + 1) + [1] * (len(snake_case      ) + 3)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if "\u4e00" <= char <= "\u9fff":
                  return True
           return False
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if ("a" <= char <= "z") or ("A" <= char <= "Z"):
                  return True
           return False
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







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



           '''simple docstring'''







           if char == " " or char == "\t" or char == "\n" or char == "\r":
                  return True
           if len(snake_case      ) == 1:
                  lowercase							:     Optional[Any]       	=      unicodedata.category(snake_case      )
                  if cat == "Zs":
                         return True
           return False
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      {}
           with io.open(snake_case		,"""r"""		,encoding="""utf-8"""      ) as f:
                  for index, line in enumerate(snake_case      ):
                         lowercase							:     Any       	=      line.rstrip("""\n"""      )
                         lowercase							:     Union[str, Any]       	=      int(snake_case      )

           return token_to_idx
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case = None      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      0
           if os.path.isdir(snake_case      ):
                  lowercase							:     int       	=      os.path.join(
                      snake_case		,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]      )
           else:
                  lowercase							:     List[str]       	=      (filename_prefix + """-""" if filename_prefix else """""") + save_directory
           with open(snake_case		,"""w"""		,encoding="""utf-8"""      ) as writer:
                  for token, token_index in sorted(self.vocab.items()		,key=lambda snake_case      : 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!"""      )
                                lowercase							:     Any       	=      token_index
                         writer.write(token + """\n"""      )
                         index += 1

           lowercase							:     List[Any]       	=      os.path.join(snake_case		,"""sentencepiece.bpe.model"""      )
           with open(snake_case		,"""wb"""      ) as fi:
                  lowercase							:     List[Any]       	=      self.sp_model.serialized_model_proto()
                  fi.write(snake_case      )

           return (vocab_file,)


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  :					List[str]						    =							logging.get_logger(__name__)

@add_end_docstrings(
    lowerCAmelCase					,	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 __snake_case		(      lowerCAmelCase     ):
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if self.framework == "tf":
                  lowercase							:     str       	=      tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
           elif self.framework == "pt":
                  lowercase							:     Optional[int]       	=      torch.nonzero(input_ids == self.tokenizer.mask_token_id		,as_tuple=snake_case      )
           else:
                  raise ValueError("""Unsupported framework"""      )
           return masked_index
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      self.get_masked_index(snake_case      )
           lowercase							:     Dict       	=      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       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if isinstance(snake_case		,snake_case      ):
                  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(snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None		,**snake_case      ):



           '''simple docstring'''







           if return_tensors is None:
                  lowercase							:     int       	=      self.framework
           lowercase							:     Optional[Any]       	=      self.tokenizer(snake_case		,return_tensors=snake_case      )
           self.ensure_exactly_one_mask_token(snake_case      )
           return model_inputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Optional[int]       	=      self.model(**snake_case      )
           lowercase							:     Tuple       	=      model_inputs["""input_ids"""]
           return model_outputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=5		,snake_case=None      ):



           '''simple docstring'''







           if target_ids is not None and target_ids.shape[0] < top_k:
                  lowercase							:     str       	=      target_ids.shape[0]
           lowercase							:     Optional[Any]       	=      model_outputs["""input_ids"""][0]
           lowercase							:     List[str]       	=      model_outputs["""logits"""]

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

                  lowercase							:     Tuple       	=      outputs.numpy()

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

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

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

                  lowercase	,			lowercase							:     Union[str, Any]       	=      probs.topk(snake_case      )

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

                         lowercase							:     Tuple       	=      p
                         # Filter padding out:
                         lowercase							:     List[str]       	=      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
                         lowercase							:     Tuple       	=      self.tokenizer.decode(snake_case		,skip_special_tokens=snake_case      )
                         lowercase							:     Optional[Any]       	=      {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]      ), """sequence""": sequence}
                         row.append(snake_case      )
                  result.append(snake_case      )
           if single_mask:
                  return result[0]
           return result
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None      ):



           '''simple docstring'''







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



           '''simple docstring'''







           lowercase							:     Dict       	=      {}

           if targets is not None:
                  lowercase							:     str       	=      self.get_target_ids(snake_case		,snake_case      )
                  lowercase							:     List[Any]       	=      target_ids

           if top_k is not None:
                  lowercase							:     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		,snake_case		,*snake_case		,**snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      super().__call__(snake_case		,**snake_case      )
           if isinstance(snake_case		,snake_case      ) and len(snake_case      ) == 1:
                  return outputs[0]
           return outputs
