

"""simple docstring"""






import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


_lowerCAmelCase						=		logging.get_logger(__name__)

_lowerCAmelCase						=		{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

_lowerCAmelCase						=		{
    """vocab_file""": {
        """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt""",
        """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt""",
        """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/vocab.txt""",
        """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/vocab.txt""",
        """bert-base-multilingual-uncased""": (
            """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"""
        ),
        """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt""",
        """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt""",
        """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt""",
        """bert-large-uncased-whole-word-masking""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"""
        ),
        """bert-large-cased-whole-word-masking""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"""
        ),
        """bert-large-uncased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"""
        ),
        """bert-large-cased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"""
        ),
        """bert-base-cased-finetuned-mrpc""": (
            """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"""
        ),
        """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt""",
        """bert-base-german-dbmdz-uncased""": (
            """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"""
        ),
        """TurkuNLP/bert-base-finnish-cased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"""
        ),
        """TurkuNLP/bert-base-finnish-uncased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"""
        ),
        """wietsedv/bert-base-dutch-cased""": (
            """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json""",
        """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json""",
        """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json""",
        """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json""",
        """bert-base-multilingual-uncased""": (
            """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"""
        ),
        """bert-base-multilingual-cased""": (
            """https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"""
        ),
        """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json""",
        """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json""",
        """bert-large-uncased-whole-word-masking""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"""
        ),
        """bert-large-cased-whole-word-masking""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"""
        ),
        """bert-large-uncased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"""
        ),
        """bert-large-cased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"""
        ),
        """bert-base-cased-finetuned-mrpc""": (
            """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"""
        ),
        """bert-base-german-dbmdz-cased""": (
            """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"""
        ),
        """bert-base-german-dbmdz-uncased""": (
            """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"""
        ),
        """TurkuNLP/bert-base-finnish-cased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"""
        ),
        """TurkuNLP/bert-base-finnish-uncased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"""
        ),
        """wietsedv/bert-base-dutch-cased""": (
            """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"""
        ),
    },
}

_lowerCAmelCase						=		{
    """bert-base-uncased""": 5_1_2,
    """bert-large-uncased""": 5_1_2,
    """bert-base-cased""": 5_1_2,
    """bert-large-cased""": 5_1_2,
    """bert-base-multilingual-uncased""": 5_1_2,
    """bert-base-multilingual-cased""": 5_1_2,
    """bert-base-chinese""": 5_1_2,
    """bert-base-german-cased""": 5_1_2,
    """bert-large-uncased-whole-word-masking""": 5_1_2,
    """bert-large-cased-whole-word-masking""": 5_1_2,
    """bert-large-uncased-whole-word-masking-finetuned-squad""": 5_1_2,
    """bert-large-cased-whole-word-masking-finetuned-squad""": 5_1_2,
    """bert-base-cased-finetuned-mrpc""": 5_1_2,
    """bert-base-german-dbmdz-cased""": 5_1_2,
    """bert-base-german-dbmdz-uncased""": 5_1_2,
    """TurkuNLP/bert-base-finnish-cased-v1""": 5_1_2,
    """TurkuNLP/bert-base-finnish-uncased-v1""": 5_1_2,
    """wietsedv/bert-base-dutch-cased""": 5_1_2,
}

_lowerCAmelCase						=		{
    """bert-base-uncased""": {"""do_lower_case""": True},
    """bert-large-uncased""": {"""do_lower_case""": True},
    """bert-base-cased""": {"""do_lower_case""": False},
    """bert-large-cased""": {"""do_lower_case""": False},
    """bert-base-multilingual-uncased""": {"""do_lower_case""": True},
    """bert-base-multilingual-cased""": {"""do_lower_case""": False},
    """bert-base-chinese""": {"""do_lower_case""": False},
    """bert-base-german-cased""": {"""do_lower_case""": False},
    """bert-large-uncased-whole-word-masking""": {"""do_lower_case""": True},
    """bert-large-cased-whole-word-masking""": {"""do_lower_case""": False},
    """bert-large-uncased-whole-word-masking-finetuned-squad""": {"""do_lower_case""": True},
    """bert-large-cased-whole-word-masking-finetuned-squad""": {"""do_lower_case""": False},
    """bert-base-cased-finetuned-mrpc""": {"""do_lower_case""": False},
    """bert-base-german-dbmdz-cased""": {"""do_lower_case""": False},
    """bert-base-german-dbmdz-uncased""": {"""do_lower_case""": True},
    """TurkuNLP/bert-base-finnish-cased-v1""": {"""do_lower_case""": False},
    """TurkuNLP/bert-base-finnish-uncased-v1""": {"""do_lower_case""": True},
    """wietsedv/bert-base-dutch-cased""": {"""do_lower_case""": False},
}







class 	__UpperCamelCase    (    a__						):
  _UpperCAmelCase          =		VOCAB_FILES_NAMES
  _UpperCAmelCase          =		PRETRAINED_VOCAB_FILES_MAP
  _UpperCAmelCase          =		PRETRAINED_INIT_CONFIGURATION
  _UpperCAmelCase          =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _UpperCAmelCase          =		BertTokenizer

  def __init__(		self    ,_A=None    ,_A=None    ,_A=True    ,_A="[UNK]"    ,_A="[SEP]"    ,_A="[PAD]"    ,_A="[CLS]"    ,_A="[MASK]"    ,_A=True    ,_A=None    ,**_A    ,):
      '''simple docstring'''

      super().__init__(
          _A    ,tokenizer_file=_A    ,do_lower_case=_A    ,unk_token=_A    ,sep_token=_A    ,pad_token=_A    ,cls_token=_A    ,mask_token=_A    ,tokenize_chinese_chars=_A    ,strip_accents=_A    ,**_A    ,)

      _lowerCAmelCase       :   Tuple  =    json.loads(self.backend_tokenizer.normalizer.__getstate__()      )
      if (
          normalizer_state.get('lowercase'    ,_A      ) != do_lower_case
          or normalizer_state.get('strip_accents'    ,_A      ) != strip_accents
          or normalizer_state.get('handle_chinese_chars'    ,_A      ) != tokenize_chinese_chars
      ):
          _lowerCAmelCase       :   Dict  =    getattr(_A    ,normalizer_state.pop('type'      )      )
          _lowerCAmelCase       :   Dict  =    do_lower_case
          _lowerCAmelCase       :   Optional[int]  =    strip_accents
          _lowerCAmelCase       :   Union[str, Any]  =    tokenize_chinese_chars
          _lowerCAmelCase       :   Dict  =    normalizer_class(**_A      )

      _lowerCAmelCase       :   Union[str, Any]  =    do_lower_case

  def __lowerCamelCase		(		self    ,_A    ,_A=None      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    [self.cls_token_id] + token_ids_a + [self.sep_token_id]

      if token_ids_a:
          output += token_ids_a + [self.sep_token_id]

      return output

  def __lowerCamelCase		(		self    ,_A    ,_A = None      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    [self.sep_token_id]
      _lowerCAmelCase       :   str  =    [self.cls_token_id]
      if token_ids_a is None:
          return len(cls + token_ids_a + sep      ) * [0]
      return len(cls + token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]







  def __lowerCamelCase		(		self    ,_A    ,_A = None      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    self._tokenizer.model.save(_A    ,name=_A      )
      return tuple(_A      )








"""simple docstring"""






import argparse
import json
from typing import List

from ltp import LTP

from transformers import BertTokenizer

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    if (
        (cp >= 0X4E00 and cp <= 0X9FFF)
        or (cp >= 0X3400 and cp <= 0X4DBF)  #
        or (cp >= 0X20000 and cp <= 0X2A6DF)  #
        or (cp >= 0X2A700 and cp <= 0X2B73F)  #
        or (cp >= 0X2B740 and cp <= 0X2B81F)  #
        or (cp >= 0X2B820 and cp <= 0X2CEAF)  #
        or (cp >= 0XF900 and cp <= 0XFAFF)
        or (cp >= 0X2F800 and cp <= 0X2FA1F)  #
    ):  #
        return True

    return False

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    for char in word:
        _lowerCAmelCase       :   Dict  =    ord(_lowerCamelCase   )
        if not _is_chinese_char(_lowerCamelCase   ):
            return 0
    return 1

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    _lowerCAmelCase       :   Tuple  =    set()

    for token in tokens:
        _lowerCAmelCase       :   Optional[int]  =    len(_lowerCamelCase   ) > 1 and is_chinese(_lowerCamelCase   )
        if chinese_word:
            word_set.add(_lowerCamelCase   )
    _lowerCAmelCase       :   Union[str, Any]  =    list(_lowerCamelCase   )
    return word_list

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase   ):

    '''simple docstring'''



    if not chinese_word_set:
        return bert_tokens
    _lowerCAmelCase       :   Optional[Any]  =    max([len(_lowerCamelCase   ) for w in chinese_word_set]   )

    _lowerCAmelCase       :   str  =    bert_tokens
    _lowerCAmelCase,					_lowerCAmelCase       :   Optional[Any]  =    0, len(_lowerCamelCase   )
    while start < end:
        _lowerCAmelCase       :   Dict  =    True
        if is_chinese(bert_word[start]   ):
            _lowerCAmelCase       :   str  =    min(end - start ,   _lowerCamelCase   )
            for i in range(_lowerCamelCase ,   1 ,   -1   ):
                _lowerCAmelCase       :   List[Any]  =    ''.join(bert_word[start : start + i]   )
                if whole_word in chinese_word_set:
                    for j in range(start + 1 ,   start + i   ):
                        _lowerCAmelCase       :   Tuple  =    '##' + bert_word[j]
                    _lowerCAmelCase       :   Optional[int]  =    start + i
                    _lowerCAmelCase       :   Any  =    False
                    break
        if single_word:
            start += 1
    return bert_word

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase   ):

    '''simple docstring'''



    _lowerCAmelCase       :   Dict  =    []

    for i in range(0 ,   len(_lowerCamelCase   ) ,   100   ):
        _lowerCAmelCase       :   Tuple  =    ltp_tokenizer.seg(lines[i : i + 100]   )[0]
        _lowerCAmelCase       :   List[Any]  =    [get_chinese_word(_lowerCamelCase   ) for r in res]
        ltp_res.extend(_lowerCamelCase   )
    assert len(_lowerCamelCase   ) == len(_lowerCamelCase   )

    _lowerCAmelCase       :   int  =    []
    for i in range(0 ,   len(_lowerCamelCase   ) ,   100   ):
        _lowerCAmelCase       :   Dict  =    bert_tokenizer(lines[i : i + 100] ,   add_special_tokens=_lowerCamelCase ,   truncation=_lowerCamelCase ,   max_length=512   )
        bert_res.extend(res['input_ids']   )
    assert len(_lowerCamelCase   ) == len(_lowerCamelCase   )

    _lowerCAmelCase       :   Union[str, Any]  =    []
    for input_ids, chinese_word in zip(_lowerCamelCase ,   _lowerCamelCase   ):
        _lowerCAmelCase       :   Optional[int]  =    []
        for id in input_ids:
            _lowerCAmelCase       :   List[Any]  =    bert_tokenizer._convert_id_to_token(_lowerCamelCase   )
            input_tokens.append(_lowerCamelCase   )
        _lowerCAmelCase       :   Any  =    add_sub_symbol(_lowerCamelCase ,   _lowerCamelCase   )
        _lowerCAmelCase       :   List[str]  =    []
        # We only save pos of chinese subwords start with ##, which mean is part of a whole word.
        for i, token in enumerate(_lowerCamelCase   ):
            if token[:2] == "##":
                _lowerCAmelCase       :   List[Any]  =    token[2:]
                # save chinese tokens' pos
                if len(_lowerCamelCase   ) == 1 and _is_chinese_char(ord(_lowerCamelCase   )   ):
                    ref_id.append(_lowerCamelCase   )
        ref_ids.append(_lowerCamelCase   )

    assert len(_lowerCamelCase   ) == len(_lowerCamelCase   )

    return ref_ids

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    with open(args.file_name ,   'r' ,   encoding='utf-8'   ) as f:
        _lowerCAmelCase       :   int  =    f.readlines()
    _lowerCAmelCase       :   int  =    [line.strip() for line in data if len(_lowerCamelCase   ) > 0 and not line.isspace()]  # avoid delimiter like '\u2029'
    _lowerCAmelCase       :   Dict  =    LTP(args.ltp   )  # faster in GPU device
    _lowerCAmelCase       :   Optional[int]  =    BertTokenizer.from_pretrained(args.bert   )

    _lowerCAmelCase       :   Optional[Any]  =    prepare_ref(_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase   )

    with open(args.save_path ,   'w' ,   encoding='utf-8'   ) as f:
        _lowerCAmelCase       :   Any  =    [json.dumps(_lowerCamelCase   ) + '\n' for ref in ref_ids]
        f.writelines(_lowerCamelCase   )


if __name__ == "__main__":
 _lowerCAmelCase						=		argparse.ArgumentParser(description="""prepare_chinese_ref""")
 parser.add_argument(
     """--file_name""",
     type=str,
     default="""./resources/chinese-demo.txt""",
     help="""file need process, same as training data in lm""",
 )
 parser.add_argument(
     """--ltp""", type=str, default="""./resources/ltp""", help="""resources for LTP tokenizer, usually a path"""
 )
 parser.add_argument("""--bert""", type=str, default="""./resources/robert""", help="""resources for Bert tokenizer""")
 parser.add_argument("""--save_path""", type=str, default="""./resources/ref.txt""", help="""path to save res""")

 _lowerCAmelCase						=		parser.parse_args()
 main(args)





