'''simple docstring'''





import json
import os
import unittest

from transformers.models.roc_bert.tokenization_roc_bert import (
    VOCAB_FILES_NAMES,
    RoCBertBasicTokenizer,
    RoCBertTokenizer,
    RoCBertWordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english




@require_tokenizers
class        __A      ( UpperCamelCase__		,	unittest.TestCase	):
    a__       :						str          =  RoCBertTokenizer
    a__       :						Union[str, Any]          =  None
    a__       :						List[Any]          =  False
    a__       :						str          =  True
    a__       :						Optional[int]          =  filter_non_english



    def 					_lowercase						(self    :    Union[str, Any] ):
         super().setUp()

         UpperCAmelCase_           =   ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"]
         UpperCAmelCase_           =   {}
         UpperCAmelCase_           =   {}
         for i, value in enumerate(__a ):
              UpperCAmelCase_           =   i
              UpperCAmelCase_           =   i
         UpperCAmelCase_           =   os.path.join(self.tmpdirname   ,			VOCAB_FILES_NAMES["vocab_file"] )
         UpperCAmelCase_           =   os.path.join(self.tmpdirname   ,			VOCAB_FILES_NAMES["word_shape_file"] )
         UpperCAmelCase_           =   os.path.join(self.tmpdirname   ,			VOCAB_FILES_NAMES["word_pronunciation_file"] )
         with open(self.vocab_file   ,			"w"   ,			encoding="utf-8" ) as vocab_writer:
              vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
         with open(self.word_shape_file   ,			"w"   ,			encoding="utf-8" ) as word_shape_writer:
              json.dump(__a   ,			__a   ,			ensure_ascii=__a )
         with open(self.word_pronunciation_file   ,			"w"   ,			encoding="utf-8" ) as word_pronunciation_writer:
              json.dump(__a   ,			__a   ,			ensure_ascii=__a )



    def 					_lowercase						(self    :    Optional[Any] ):
         UpperCAmelCase_           =   self.tokenizer_class(self.vocab_file   ,			self.word_shape_file   ,			self.word_pronunciation_file )

         UpperCAmelCase_           =   tokenizer.tokenize("你好[SEP]你是谁" )
         self.assertListEqual(__a   ,			["你", "好", "[SEP]", "你", "是", "谁"] )
         self.assertListEqual(tokenizer.convert_tokens_to_ids(__a )   ,			[5, 6, 2, 5, 7, 8] )
         self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a )   ,			[5, 6, 2, 5, 7, 8] )
         self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a )   ,			[5, 6, 2, 5, 7, 8] )



    def 					_lowercase						(self    :    Any ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer()

         self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" )   ,			["ah", "\u535A", "\u63A8", "zz"] )



    def 					_lowercase						(self    :    Dict ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  " )   ,			["hello", "!", "how", "are", "you", "?"] )
         self.assertListEqual(tokenizer.tokenize("H\u00E9llo" )   ,			["hello"] )



    def 					_lowercase						(self    :    Optional[int] ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a   ,			strip_accents=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  " )   ,			["hällo", "!", "how", "are", "you", "?"] )
         self.assertListEqual(tokenizer.tokenize("H\u00E9llo" )   ,			["h\u00E9llo"] )



    def 					_lowercase						(self    :    Dict ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a   ,			strip_accents=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  " )   ,			["hallo", "!", "how", "are", "you", "?"] )
         self.assertListEqual(tokenizer.tokenize("H\u00E9llo" )   ,			["hello"] )



    def 					_lowercase						(self    :    Optional[Any] ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  " )   ,			["hallo", "!", "how", "are", "you", "?"] )
         self.assertListEqual(tokenizer.tokenize("H\u00E9llo" )   ,			["hello"] )



    def 					_lowercase						(self    :    Any ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  " )   ,			["HeLLo", "!", "how", "Are", "yoU", "?"] )



    def 					_lowercase						(self    :    Union[str, Any] ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a   ,			strip_accents=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  " )   ,			["HäLLo", "!", "how", "Are", "yoU", "?"] )



    def 					_lowercase						(self    :    Union[str, Any] ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a   ,			strip_accents=__a )

         self.assertListEqual(
             tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  " )   ,			["HaLLo", "!", "how", "Are", "yoU", "?"] )



    def 					_lowercase						(self    :    Any ):
         UpperCAmelCase_           =   RoCBertBasicTokenizer(do_lower_case=__a   ,			never_split=["[UNK]"] )

         self.assertListEqual(
             tokenizer.tokenize(" \tHeLLo!how  \n Are yoU? [UNK]" )   ,			["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] )



    def 					_lowercase						(self    :    Tuple ):
         UpperCAmelCase_           =   ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]

         UpperCAmelCase_           =   {}
         for i, token in enumerate(__a ):
              UpperCAmelCase_           =   i
         UpperCAmelCase_           =   RoCBertWordpieceTokenizer(vocab=__a   ,			unk_token="[UNK]" )

         self.assertListEqual(tokenizer.tokenize("" )   ,			[] )

         self.assertListEqual(tokenizer.tokenize("unwanted running" )   ,			["un", "##want", "##ed", "runn", "##ing"] )

         self.assertListEqual(tokenizer.tokenize("unwantedX running" )   ,			["[UNK]", "runn", "##ing"] )



    def 					_lowercase						(self    :    Any ):
         self.assertTrue(_is_whitespace(" " ) )
         self.assertTrue(_is_whitespace("\t" ) )
         self.assertTrue(_is_whitespace("\r" ) )
         self.assertTrue(_is_whitespace("\n" ) )
         self.assertTrue(_is_whitespace("\u00A0" ) )

         self.assertFalse(_is_whitespace("A" ) )
         self.assertFalse(_is_whitespace("-" ) )



    def 					_lowercase						(self    :    Optional[int] ):
         self.assertTrue(_is_control("\u0005" ) )

         self.assertFalse(_is_control("A" ) )
         self.assertFalse(_is_control(" " ) )
         self.assertFalse(_is_control("\t" ) )
         self.assertFalse(_is_control("\r" ) )



    def 					_lowercase						(self    :    Union[str, Any] ):
         self.assertTrue(_is_punctuation("-" ) )
         self.assertTrue(_is_punctuation("$" ) )
         self.assertTrue(_is_punctuation("`" ) )
         self.assertTrue(_is_punctuation("." ) )

         self.assertFalse(_is_punctuation("A" ) )
         self.assertFalse(_is_punctuation(" " ) )



    def 					_lowercase						(self    :    List[Any] ):
         UpperCAmelCase_           =   self.get_tokenizer()

         # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
         self.assertListEqual([tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]]   ,			[["[UNK]"], [], ["[UNK]"]] )

         if self.test_rust_tokenizer:
              UpperCAmelCase_           =   self.get_rust_tokenizer()
              self.assertListEqual(
                  [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]]   ,			[["[UNK]"], [], ["[UNK]"]] )



    def 					_lowercase						(self    :    List[str] ):
         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
              with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
                   UpperCAmelCase_           =   self.rust_tokenizer_class.from_pretrained(__a   ,			**__a )

                   UpperCAmelCase_           =   f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
                   UpperCAmelCase_           =   tokenizer_r.encode_plus(
                       __a   ,			return_attention_mask=__a   ,			return_token_type_ids=__a   ,			return_offsets_mapping=__a   ,			add_special_tokens=__a   ,			)

                   UpperCAmelCase_           =   tokenizer_r.do_lower_case if hasattr(__a   ,			"do_lower_case" ) else False
                   UpperCAmelCase_           =   (
                       [
                           ((0, 0), tokenizer_r.cls_token),
                           ((0, 1), "A"),
                           ((1, 2), ","),
                           ((3, 5), "na"),
                           ((5, 6), "##ï"),
                           ((6, 8), "##ve"),
                           ((9, 15), tokenizer_r.mask_token),
                           ((16, 21), "Allen"),
                           ((21, 23), "##NL"),
                           ((23, 24), "##P"),
                           ((25, 33), "sentence"),
                           ((33, 34), "."),
                           ((0, 0), tokenizer_r.sep_token),
                       ]
                       if not do_lower_case
                       else [
                           ((0, 0), tokenizer_r.cls_token),
                           ((0, 1), "a"),
                           ((1, 2), ","),
                           ((3, 8), "naive"),
                           ((9, 15), tokenizer_r.mask_token),
                           ((16, 21), "allen"),
                           ((21, 23), "##nl"),
                           ((23, 24), "##p"),
                           ((25, 33), "sentence"),
                           ((33, 34), "."),
                           ((0, 0), tokenizer_r.sep_token),
                       ]
                   )

                   self.assertEqual(
                       [e[1] for e in expected_results]   ,			tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) )
                   self.assertEqual([e[0] for e in expected_results]   ,			tokens["offset_mapping"] )



    def 					_lowercase						(self    :    Dict ):
         UpperCAmelCase_           =   ["的", "人", "有"]
         UpperCAmelCase_           =   "".join(__a )
         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
              with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
                   UpperCAmelCase_           =   True
                   UpperCAmelCase_           =   self.tokenizer_class.from_pretrained(__a   ,			**__a )
                   UpperCAmelCase_           =   self.rust_tokenizer_class.from_pretrained(__a   ,			**__a )

                   UpperCAmelCase_           =   tokenizer_p.encode(__a   ,			add_special_tokens=__a )
                   UpperCAmelCase_           =   tokenizer_r.encode(__a   ,			add_special_tokens=__a )

                   UpperCAmelCase_           =   tokenizer_r.convert_ids_to_tokens(__a )
                   UpperCAmelCase_           =   tokenizer_p.convert_ids_to_tokens(__a )

                   # it is expected that each Chinese character is not preceded by "##"
                   self.assertListEqual(__a   ,			__a )
                   self.assertListEqual(__a   ,			__a )

                   UpperCAmelCase_           =   False
                   UpperCAmelCase_           =   self.rust_tokenizer_class.from_pretrained(__a   ,			**__a )
                   UpperCAmelCase_           =   self.tokenizer_class.from_pretrained(__a   ,			**__a )

                   UpperCAmelCase_           =   tokenizer_r.encode(__a   ,			add_special_tokens=__a )
                   UpperCAmelCase_           =   tokenizer_p.encode(__a   ,			add_special_tokens=__a )

                   UpperCAmelCase_           =   tokenizer_r.convert_ids_to_tokens(__a )
                   UpperCAmelCase_           =   tokenizer_p.convert_ids_to_tokens(__a )

                   # it is expected that only the first Chinese character is not preceded by "##".
                   UpperCAmelCase_           =   [
                       f"""##{token}""" if idx != 0 else token for idx, token in enumerate(__a )
                   ]
                   self.assertListEqual(__a   ,			__a )
                   self.assertListEqual(__a   ,			__a )



    @slow
    def 					_lowercase						(self    :    Tuple ):
         UpperCAmelCase_           =   self.tokenizer_class(self.vocab_file   ,			self.word_shape_file   ,			self.word_pronunciation_file )

         UpperCAmelCase_           =   tokenizer.encode("你好"   ,			add_special_tokens=__a )
         UpperCAmelCase_           =   tokenizer.encode("你是谁"   ,			add_special_tokens=__a )

         UpperCAmelCase_           =   tokenizer.build_inputs_with_special_tokens(__a )
         UpperCAmelCase_           =   tokenizer.build_inputs_with_special_tokens(__a   ,			__a )

         assert encoded_sentence == [1] + text + [2]
         assert encoded_pair == [1] + text + [2] + text_a + [2]






    def 					_lowercase						(self    :    List[str] ):
         UpperCAmelCase_           =   self.get_tokenizers(do_lower_case=__a )
         for tokenizer in tokenizers:
              with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
                   UpperCAmelCase_           =   "你好，你是谁"
                   UpperCAmelCase_           =   tokenizer.tokenize(__a )
                   UpperCAmelCase_           =   tokenizer.convert_tokens_to_ids(__a )
                   UpperCAmelCase_           =   tokenizer.convert_tokens_to_shape_ids(__a )
                   UpperCAmelCase_           =   tokenizer.convert_tokens_to_pronunciation_ids(__a )
                   UpperCAmelCase_           =   tokenizer.prepare_for_model(
                       __a   ,			__a   ,			__a   ,			add_special_tokens=__a )

                   UpperCAmelCase_           =   tokenizer.encode_plus(__a   ,			add_special_tokens=__a )

                   self.assertEqual(__a   ,			__a )





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


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




@add_end_docstrings(
    UpperCamelCase__		,	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      ( UpperCamelCase__	):



    def 					_lowercase						(self    :    str   ,			__a    :    GenericTensor ):
         if self.framework == "tf":
              UpperCAmelCase_           =   tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
         elif self.framework == "pt":
              UpperCAmelCase_           =   torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,			as_tuple=__a )
         else:
              raise ValueError("Unsupported framework" )
         return masked_index



    def 					_lowercase						(self    :    Tuple   ,			__a    :    GenericTensor ):
         UpperCAmelCase_           =   self.get_masked_index(__a )
         UpperCAmelCase_           =   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 					_lowercase						(self    :    List[Any]   ,			__a    :    GenericTensor ):
         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 					_lowercase						(self    :    Tuple   ,			__a    :    Dict   ,			__a    :    List[str]=None   ,			**__a    :    Any ):
         if return_tensors is None:
              UpperCAmelCase_           =   self.framework
         UpperCAmelCase_           =   self.tokenizer(__a   ,			return_tensors=__a )
         self.ensure_exactly_one_mask_token(__a )
         return model_inputs



    def 					_lowercase						(self    :    str   ,			__a    :    Optional[int] ):
         UpperCAmelCase_           =   self.model(**__a )
         UpperCAmelCase_           =   model_inputs["input_ids"]
         return model_outputs



    def 					_lowercase						(self    :    List[str]   ,			__a    :    Tuple   ,			__a    :    int=5   ,			__a    :    Dict=None ):
         # Cap top_k if there are targets
         if target_ids is not None and target_ids.shape[0] < top_k:
              UpperCAmelCase_           =   target_ids.shape[0]
         UpperCAmelCase_           =   model_outputs["input_ids"][0]
         UpperCAmelCase_           =   model_outputs["logits"]

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

              UpperCAmelCase_           =   outputs.numpy()

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

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

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

              UpperCAmelCase_    , UpperCAmelCase_           =   probs.topk(__a )

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

                   UpperCAmelCase_           =   p
                   # Filter padding out:
                   UpperCAmelCase_           =   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
                   UpperCAmelCase_           =   self.tokenizer.decode(__a   ,			skip_special_tokens=__a )
                   UpperCAmelCase_           =   {"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 					_lowercase						(self    :    Dict   ,			__a    :    List[Any]   ,			__a    :    List[str]=None ):
         if isinstance(__a   ,			__a ):
              UpperCAmelCase_           =   [targets]
         try:
              UpperCAmelCase_           =   self.tokenizer.get_vocab()
         except Exception:
              UpperCAmelCase_           =   {}
         UpperCAmelCase_           =   []
         for target in targets:
              UpperCAmelCase_           =   vocab.get(__a   ,			__a )
              if id_ is None:
                   UpperCAmelCase_           =   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
                   UpperCAmelCase_           =   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_ )
         UpperCAmelCase_           =   list(set(__a ) )
         if len(__a ) == 0:
              raise ValueError("At least one target must be provided when passed." )
         UpperCAmelCase_           =   np.array(__a )
         return target_ids



    def 					_lowercase						(self    :    Tuple   ,			__a    :    Dict=None   ,			__a    :    List[str]=None ):
         UpperCAmelCase_           =   {}

         if targets is not None:
              UpperCAmelCase_           =   self.get_target_ids(__a   ,			__a )
              UpperCAmelCase_           =   target_ids

         if top_k is not None:
              UpperCAmelCase_           =   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    :    Union[str, Any]   ,			__a    :    str   ,			*__a    :    Any   ,			**__a    :    Tuple ):
         UpperCAmelCase_           =   super().__call__(__a   ,			**__a )
         if isinstance(__a   ,			__a ) and len(__a ) == 1:
              return outputs[0]
         return outputs




