"""simple docstring"""




# Note: if you intend to run this script make sure you look under scripts/fsmt/
# to locate the appropriate script to do the work correctly. There is a set of scripts to:
# - download and prepare data and run the conversion script
# - perform eval to get the best hparam into the config
# - generate model_cards - useful if you have multiple models from the same paper

import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname

import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary

from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging


logging.set_verbosity_warning()

_a      :		Union[str, Any]           =   2

# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
_a      :		Union[str, Any]           =   {
    # fairseq:
    'wmt19-ru-en': {'length_penalty': 1.1},
    'wmt19-en-ru': {'length_penalty': 1.15},
    'wmt19-en-de': {'length_penalty': 1.0},
    'wmt19-de-en': {'length_penalty': 1.1},
    # allenai:
    'wmt16-en-de-dist-12-1': {'length_penalty': 0.6},
    'wmt16-en-de-dist-6-1': {'length_penalty': 0.6},
    'wmt16-en-de-12-1': {'length_penalty': 0.8},
    'wmt19-de-en-6-6-base': {'length_penalty': 0.6},
    'wmt19-de-en-6-6-big': {'length_penalty': 0.6},
}

# this remaps the different models to their organization names
_a      :		Tuple           =   {}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
     _a      :		Union[str, Any]           =   'facebook'
for m in [
    "wmt16-en-de-dist-12-1",
    "wmt16-en-de-dist-6-1",
    "wmt16-en-de-12-1",
    "wmt19-de-en-6-6-base",
    "wmt19-de-en-6-6-big",
]:
     _a      :		Union[str, Any]           =   'allenai'





def 							SCREAMING_SNAKE_CASE     (			_lowerCamelCase						:       Optional[int]	)       ->      Dict:
  _lowerCAmelCase						:       List[Any]  			=     dict((re.sub(r"""@@$"""			,""""""			,__lowerCAmelCase	), v) if k.endswith("""@@"""	) else (re.sub(r"""$"""			,"""</w>"""			,__lowerCAmelCase	), v) for k, v in d.items()	)
  _lowerCAmelCase						:       List[str]  			=     '''<s> <pad> </s> <unk>'''.split()
  # restore the special tokens
  for k in keep_keys:
    del da[f"{k}</w>"]
    _lowerCAmelCase						:       List[str]  			=     d[k]  # restore
  return da





def 							SCREAMING_SNAKE_CASE     (			_lowerCamelCase						:       Tuple			,_lowerCamelCase						:       Any	)       ->      Optional[int]:
  assert os.path.exists(__lowerCAmelCase	)
  os.makedirs(__lowerCAmelCase			,exist_ok=__lowerCAmelCase	)
  print(f"Writing results to {pytorch_dump_folder_path}"	)

  # handle various types of models

  _lowerCAmelCase						:       int  			=     basename(__lowerCAmelCase	)
  _lowerCAmelCase						:       List[str]  			=     dirname(__lowerCAmelCase	)

  _lowerCAmelCase						:       Optional[int]  			=     fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
  _lowerCAmelCase						:       Tuple  			=     cls.hub_models()
  _lowerCAmelCase						:       Dict  			=     {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''}
  _lowerCAmelCase						:       List[Any]  			=     '''.'''
  # note: since the model dump is old, fairseq has upgraded its model some
  # time later, and it does a whole lot of rewrites and splits on the saved
  # weights, therefore we can't use torch.load() directly on the model file.
  # see: upgrade_state_dict(state_dict) in fairseq_model.py
  print(f"using checkpoint {checkpoint_file}"	)
  _lowerCAmelCase						:       Dict  			=     hub_utils.from_pretrained(
      __lowerCAmelCase			,__lowerCAmelCase			,__lowerCAmelCase			,archive_map=__lowerCAmelCase			,**__lowerCAmelCase	)

  _lowerCAmelCase						:       Tuple  			=     vars(chkpt["""args"""]["""model"""]	)

  _lowerCAmelCase						:       Union[str, Any]  			=     args['''source_lang''']
  _lowerCAmelCase						:       Optional[int]  			=     args['''target_lang''']

  _lowerCAmelCase						:       Optional[Any]  			=     dirname(__lowerCAmelCase	)
  _lowerCAmelCase						:       int  			=     basename(__lowerCAmelCase	)

  # dicts
  _lowerCAmelCase						:       List[str]  			=     os.path.join(__lowerCAmelCase			,f"dict.{src_lang}.txt"	)
  _lowerCAmelCase						:       Tuple  			=     os.path.join(__lowerCAmelCase			,f"dict.{tgt_lang}.txt"	)

  _lowerCAmelCase						:       Union[str, Any]  			=     Dictionary.load(__lowerCAmelCase	)
  _lowerCAmelCase						:       List[str]  			=     rewrite_dict_keys(src_dict.indices	)
  _lowerCAmelCase						:       List[Any]  			=     len(__lowerCAmelCase	)
  _lowerCAmelCase						:       List[str]  			=     os.path.join(__lowerCAmelCase			,"""vocab-src.json"""	)
  print(f"Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records"	)
  with open(__lowerCAmelCase			,"""w"""			,encoding="""utf-8"""	) as f:
    f.write(json.dumps(__lowerCAmelCase			,ensure_ascii=__lowerCAmelCase			,indent=__lowerCAmelCase	)	)

  # detect whether this is a do_lower_case situation, which can be derived by checking whether we
  # have at least one uppercase letter in the source vocab
  _lowerCAmelCase						:       List[Any]  			=     True
  for k in src_vocab.keys():
    if not k.islower():
      _lowerCAmelCase						:       Any  			=     False
      break

  _lowerCAmelCase						:       Optional[Any]  			=     Dictionary.load(__lowerCAmelCase	)
  _lowerCAmelCase						:       int  			=     rewrite_dict_keys(tgt_dict.indices	)
  _lowerCAmelCase						:       Any  			=     len(__lowerCAmelCase	)
  _lowerCAmelCase						:       Dict  			=     os.path.join(__lowerCAmelCase			,"""vocab-tgt.json"""	)
  print(f"Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records"	)
  with open(__lowerCAmelCase			,"""w"""			,encoding="""utf-8"""	) as f:
    f.write(json.dumps(__lowerCAmelCase			,ensure_ascii=__lowerCAmelCase			,indent=__lowerCAmelCase	)	)

  # merges_file (bpecodes)
  _lowerCAmelCase						:       Tuple  			=     os.path.join(__lowerCAmelCase			,VOCAB_FILES_NAMES["""merges_file"""]	)
  for fn in ["bpecodes", "code"]:  # older fairseq called the merges file "code"
    _lowerCAmelCase						:       Dict  			=     os.path.join(__lowerCAmelCase			,__lowerCAmelCase	)
    if os.path.exists(__lowerCAmelCase	):
      break
  with open(__lowerCAmelCase			,encoding="""utf-8"""	) as fin:
    _lowerCAmelCase						:       Union[str, Any]  			=     fin.read()
  _lowerCAmelCase						:       str  			=     re.sub(r""" \d+$"""			,""""""			,__lowerCAmelCase			,0			,re.M	)  # remove frequency number
  print(f"Generating {merges_file}"	)
  with open(__lowerCAmelCase			,"""w"""			,encoding="""utf-8"""	) as fout:
    fout.write(__lowerCAmelCase	)

  # model config
  _lowerCAmelCase						:       List[Any]  			=     os.path.join(__lowerCAmelCase			,"""config.json"""	)

  # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
  # may have to modify the tokenizer if a different type is used by a future model
  assert args["bpe"] == "fastbpe", f"need to extend tokenizer to support bpe={args['bpe']}"
  assert args["tokenizer"] == "moses", f"need to extend tokenizer to support bpe={args['tokenizer']}"

  _lowerCAmelCase						:       Tuple  			=     {
      '''architectures''': ['''FSMTForConditionalGeneration'''],
      '''model_type''': '''fsmt''',
      '''activation_dropout''': args['''activation_dropout'''],
      '''activation_function''': '''relu''',
      '''attention_dropout''': args['''attention_dropout'''],
      '''d_model''': args['''decoder_embed_dim'''],
      '''dropout''': args['''dropout'''],
      '''init_std''': 0.02,
      '''max_position_embeddings''': args['''max_source_positions'''],
      '''num_hidden_layers''': args['''encoder_layers'''],
      '''src_vocab_size''': src_vocab_size,
      '''tgt_vocab_size''': tgt_vocab_size,
      '''langs''': [src_lang, tgt_lang],
      '''encoder_attention_heads''': args['''encoder_attention_heads'''],
      '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''],
      '''encoder_layerdrop''': args['''encoder_layerdrop'''],
      '''encoder_layers''': args['''encoder_layers'''],
      '''decoder_attention_heads''': args['''decoder_attention_heads'''],
      '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''],
      '''decoder_layerdrop''': args['''decoder_layerdrop'''],
      '''decoder_layers''': args['''decoder_layers'''],
      '''bos_token_id''': 0,
      '''pad_token_id''': 1,
      '''eos_token_id''': 2,
      '''is_encoder_decoder''': True,
      '''scale_embedding''': not args['''no_scale_embedding'''],
      '''tie_word_embeddings''': args['''share_all_embeddings'''],
  }

  # good hparam defaults to start with
  _lowerCAmelCase						:       Any  			=     5
  _lowerCAmelCase						:       Optional[Any]  			=     False
  if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
    _lowerCAmelCase						:       Optional[Any]  			=     best_score_hparams[model_dir]['''length_penalty''']
  else:
    _lowerCAmelCase						:       Optional[Any]  			=     1.0

  print(f"Generating {fsmt_model_config_file}"	)
  with open(__lowerCAmelCase			,"""w"""			,encoding="""utf-8"""	) as f:
    f.write(json.dumps(__lowerCAmelCase			,ensure_ascii=__lowerCAmelCase			,indent=__lowerCAmelCase	)	)

  # tokenizer config
  _lowerCAmelCase						:       Tuple  			=     os.path.join(__lowerCAmelCase			,__lowerCAmelCase	)

  _lowerCAmelCase						:       Optional[Any]  			=     {
      '''langs''': [src_lang, tgt_lang],
      '''model_max_length''': 1024,
      '''do_lower_case''': do_lower_case,
  }

  print(f"Generating {fsmt_tokenizer_config_file}"	)
  with open(__lowerCAmelCase			,"""w"""			,encoding="""utf-8"""	) as f:
    f.write(json.dumps(__lowerCAmelCase			,ensure_ascii=__lowerCAmelCase			,indent=__lowerCAmelCase	)	)

  # model
  _lowerCAmelCase						:       Dict  			=     chkpt['''models'''][0]
  _lowerCAmelCase						:       int  			=     model.state_dict()

  # rename keys to start with 'model.'
  _lowerCAmelCase						:       str  			=     OrderedDict(("""model.""" + k, v) for k, v in model_state_dict.items()	)

  # remove unneeded keys
  _lowerCAmelCase						:       List[str]  			=     [
      '''model.model''',
      '''model.encoder.version''',
      '''model.decoder.version''',
      '''model.encoder_embed_tokens.weight''',
      '''model.decoder_embed_tokens.weight''',
      '''model.encoder.embed_positions._float_tensor''',
      '''model.decoder.embed_positions._float_tensor''',
  ]
  for k in ignore_keys:
    model_state_dict.pop(__lowerCAmelCase			,__lowerCAmelCase	)

  _lowerCAmelCase						:       str  			=     FSMTConfig.from_pretrained(__lowerCAmelCase	)
  _lowerCAmelCase						:       List[Any]  			=     FSMTForConditionalGeneration(__lowerCAmelCase	)

  # check that it loads ok
  model_new.load_state_dict(__lowerCAmelCase			,strict=__lowerCAmelCase	)

  # save
  _lowerCAmelCase						:       Optional[Any]  			=     os.path.join(__lowerCAmelCase			,__lowerCAmelCase	)
  print(f"Generating {pytorch_weights_dump_path}"	)
  torch.save(__lowerCAmelCase			,__lowerCAmelCase	)

  print("""Conversion is done!"""	)
  print("""\nLast step is to upload the files to s3"""	)
  print(f"cd {data_root}"	)
  print(f"transformers-cli upload {model_dir}"	)


if __name__ == "__main__":
     _a      :		Optional[int]           =   argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         '--fsmt_checkpoint_path',
         default=None,
         type=str,
         required=True,
         help=(
             'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,'
             ' bpecodes, etc.'
         ),
     )
     parser.add_argument(
         '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
     )
     _a      :		Union[str, Any]           =   parser.parse_args()
     convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)









import os
import unittest

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    BertTokenizer,
    WordpieceTokenizer,
    _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							(			__lowerCamelCase  ,							unittest.TestCase				):
		__lowerCAmelCase	:    int											=					BertTokenizer
		__lowerCAmelCase	:    int											=					BertTokenizerFast
		__lowerCAmelCase	:    int											=					True
		__lowerCAmelCase	:    List[Any]											=					True
		__lowerCAmelCase	:    Any											=					filter_non_english



		def 	__lowerCamelCase			(     self     :str  ):
						super().setUp()

						snake_case__	:      str     		=	[
						    '''[UNK]''',
						    '''[CLS]''',
						    '''[SEP]''',
						    '''[PAD]''',
						    '''[MASK]''',
						    '''want''',
						    '''##want''',
						    '''##ed''',
						    '''wa''',
						    '''un''',
						    '''runn''',
						    '''##ing''',
						    ''',''',
						    '''low''',
						    '''lowest''',
						]
						snake_case__	:      str     		=	os.path.join(self.tmpdirname   ,VOCAB_FILES_NAMES['''vocab_file''']  )
						with open(self.vocab_file   ,'''w'''   ,encoding='''utf-8'''  ) as vocab_writer:
										vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]  )  )



		def 	__lowerCamelCase			(     self     :List[str]   ,__lowercase     :str  ):
						snake_case__	:      List[Any]     		=	'''UNwant\u00E9d,running'''
						snake_case__	:      str     		=	'''unwanted, running'''
						return input_text, output_text



		def 	__lowerCamelCase			(     self     :Optional[int]  ):
						snake_case__	:      str     		=	self.tokenizer_class(self.vocab_file  )

						snake_case__	:      str     		=	tokenizer.tokenize('''UNwant\u00E9d,running'''  )
						self.assertListEqual(__lowercase   ,['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']  )
						self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase  )   ,[9, 6, 7, 1_2, 1_0, 1_1]  )



		def 	__lowerCamelCase			(     self     :List[str]  ):
						if not self.test_rust_tokenizer:
										return

						snake_case__	:      str     		=	self.get_tokenizer()
						snake_case__	:      Dict     		=	self.get_rust_tokenizer()

						snake_case__	:      List[Any]     		=	'''UNwant\u00E9d,running'''

						snake_case__	:      Dict     		=	tokenizer.tokenize(__lowercase  )
						snake_case__	:      int     		=	rust_tokenizer.tokenize(__lowercase  )
						self.assertListEqual(__lowercase   ,__lowercase  )

						snake_case__	:      List[str]     		=	tokenizer.encode(__lowercase   ,add_special_tokens=__lowercase  )
						snake_case__	:      List[str]     		=	rust_tokenizer.encode(__lowercase   ,add_special_tokens=__lowercase  )
						self.assertListEqual(__lowercase   ,__lowercase  )

						snake_case__	:      Optional[Any]     		=	self.get_rust_tokenizer()
						snake_case__	:      List[Any]     		=	tokenizer.encode(__lowercase  )
						snake_case__	:      Dict     		=	rust_tokenizer.encode(__lowercase  )
						self.assertListEqual(__lowercase   ,__lowercase  )

						# With lower casing
						snake_case__	:      List[Any]     		=	self.get_tokenizer(do_lower_case=__lowercase  )
						snake_case__	:      Optional[int]     		=	self.get_rust_tokenizer(do_lower_case=__lowercase  )

						snake_case__	:      int     		=	'''UNwant\u00E9d,running'''

						snake_case__	:      List[str]     		=	tokenizer.tokenize(__lowercase  )
						snake_case__	:      Union[str, Any]     		=	rust_tokenizer.tokenize(__lowercase  )
						self.assertListEqual(__lowercase   ,__lowercase  )

						snake_case__	:      int     		=	tokenizer.encode(__lowercase   ,add_special_tokens=__lowercase  )
						snake_case__	:      List[str]     		=	rust_tokenizer.encode(__lowercase   ,add_special_tokens=__lowercase  )
						self.assertListEqual(__lowercase   ,__lowercase  )

						snake_case__	:      Tuple     		=	self.get_rust_tokenizer()
						snake_case__	:      int     		=	tokenizer.encode(__lowercase  )
						snake_case__	:      Dict     		=	rust_tokenizer.encode(__lowercase  )
						self.assertListEqual(__lowercase   ,__lowercase  )



		def 	__lowerCamelCase			(     self     :Tuple  ):
						snake_case__	:      Optional[Any]     		=	BasicTokenizer()

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



		def 	__lowerCamelCase			(     self     :Any  ):
						snake_case__	:      Dict     		=	BasicTokenizer(do_lower_case=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      Optional[int]     		=	BasicTokenizer(do_lower_case=__lowercase   ,strip_accents=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :str  ):
						snake_case__	:      Union[str, Any]     		=	BasicTokenizer(do_lower_case=__lowercase   ,strip_accents=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :Optional[Any]  ):
						snake_case__	:      Union[str, Any]     		=	BasicTokenizer(do_lower_case=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :Optional[Any]  ):
						snake_case__	:      str     		=	BasicTokenizer(do_lower_case=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :Tuple  ):
						snake_case__	:      Any     		=	BasicTokenizer(do_lower_case=__lowercase   ,strip_accents=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :int  ):
						snake_case__	:      str     		=	BasicTokenizer(do_lower_case=__lowercase   ,strip_accents=__lowercase  )

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



		def 	__lowerCamelCase			(     self     :Tuple  ):
						snake_case__	:      List[Any]     		=	BasicTokenizer(do_lower_case=__lowercase   ,never_split=['''[UNK]''']  )

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



		def 	__lowerCamelCase			(     self     :Dict  ):
						snake_case__	:      List[str]     		=	BasicTokenizer()
						snake_case__	:      Any     		=	'''a\n\'ll !!to?\'d of, can\'t.'''
						snake_case__	:      Optional[int]     		=	['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.''']
						self.assertListEqual(tokenizer.tokenize(__lowercase  )   ,__lowercase  )



		def 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      Any     		=	['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

						snake_case__	:      Optional[Any]     		=	{}
						for i, token in enumerate(__lowercase  ):
										snake_case__	:      Dict     		=	i
						snake_case__	:      int     		=	WordpieceTokenizer(vocab=__lowercase   ,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 	__lowerCamelCase			(     self     :List[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 	__lowerCamelCase			(     self     :Union[str, Any]  ):
						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 	__lowerCamelCase			(     self     :str  ):
						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 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      str     		=	self.get_tokenizer()
						snake_case__	:      List[str]     		=	self.get_rust_tokenizer()

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

						self.assertListEqual(
						    [rust_tokenizer.tokenize(__lowercase  ) for t in ['''Test''', '''\xad''', '''test''']]   ,[['''[UNK]'''], [], ['''[UNK]''']]  )



		@slow
		def 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      List[str]     		=	self.tokenizer_class.from_pretrained('''bert-base-uncased'''  )

						snake_case__	:      Union[str, Any]     		=	tokenizer.encode('''sequence builders'''   ,add_special_tokens=__lowercase  )
						snake_case__	:      str     		=	tokenizer.encode('''multi-sequence build'''   ,add_special_tokens=__lowercase  )

						snake_case__	:      Tuple     		=	tokenizer.build_inputs_with_special_tokens(__lowercase  )
						snake_case__	:      int     		=	tokenizer.build_inputs_with_special_tokens(__lowercase   ,__lowercase  )

						assert encoded_sentence == [1_0_1] + text + [1_0_2]
						assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2]



		def 	__lowerCamelCase			(     self     :List[Any]  ):
						for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
										with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
														snake_case__	:      str     		=	self.rust_tokenizer_class.from_pretrained(__lowercase   ,**__lowercase  )

														snake_case__	:      List[str]     		=	F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
														snake_case__	:      List[Any]     		=	tokenizer_r.encode_plus(
														    __lowercase   ,return_attention_mask=__lowercase   ,return_token_type_ids=__lowercase   ,return_offsets_mapping=__lowercase   ,add_special_tokens=__lowercase   ,)

														snake_case__	:      List[str]     		=	tokenizer_r.do_lower_case if hasattr(__lowercase   ,'''do_lower_case'''  ) else False
														snake_case__	:      Optional[int]     		=	(
														    [
														        ((0, 0), tokenizer_r.cls_token),
														        ((0, 1), '''A'''),
														        ((1, 2), ''','''),
														        ((3, 5), '''na'''),
														        ((5, 6), '''##ï'''),
														        ((6, 8), '''##ve'''),
														        ((9, 1_5), tokenizer_r.mask_token),
														        ((1_6, 2_1), '''Allen'''),
														        ((2_1, 2_3), '''##NL'''),
														        ((2_3, 2_4), '''##P'''),
														        ((2_5, 3_3), '''sentence'''),
														        ((3_3, 3_4), '''.'''),
														        ((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, 1_5), tokenizer_r.mask_token),
														        ((1_6, 2_1), '''allen'''),
														        ((2_1, 2_3), '''##nl'''),
														        ((2_3, 2_4), '''##p'''),
														        ((2_5, 3_3), '''sentence'''),
														        ((3_3, 3_4), '''.'''),
														        ((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 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__	:      str     		=	['''的''', '''人''', '''有''']
						snake_case__	:      Optional[int]     		=	''''''.join(__lowercase  )
						for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
										with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
														snake_case__	:      Optional[Any]     		=	True
														snake_case__	:      int     		=	self.tokenizer_class.from_pretrained(__lowercase   ,**__lowercase  )
														snake_case__	:      Tuple     		=	self.rust_tokenizer_class.from_pretrained(__lowercase   ,**__lowercase  )

														snake_case__	:      Union[str, Any]     		=	tokenizer_p.encode(__lowercase   ,add_special_tokens=__lowercase  )
														snake_case__	:      List[str]     		=	tokenizer_r.encode(__lowercase   ,add_special_tokens=__lowercase  )

														snake_case__	:      List[str]     		=	tokenizer_r.convert_ids_to_tokens(__lowercase  )
														snake_case__	:      Optional[Any]     		=	tokenizer_p.convert_ids_to_tokens(__lowercase  )

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

														snake_case__	:      str     		=	False
														snake_case__	:      Dict     		=	self.rust_tokenizer_class.from_pretrained(__lowercase   ,**__lowercase  )
														snake_case__	:      int     		=	self.tokenizer_class.from_pretrained(__lowercase   ,**__lowercase  )

														snake_case__	:      int     		=	tokenizer_r.encode(__lowercase   ,add_special_tokens=__lowercase  )
														snake_case__	:      Tuple     		=	tokenizer_p.encode(__lowercase   ,add_special_tokens=__lowercase  )

														snake_case__	:      List[Any]     		=	tokenizer_r.convert_ids_to_tokens(__lowercase  )
														snake_case__	:      Union[str, Any]     		=	tokenizer_p.convert_ids_to_tokens(__lowercase  )

														# it is expected that only the first Chinese character is not preceded by "##".
														snake_case__	:      Optional[int]     		=	[
														    F"""##{token}""" if idx != 0 else token for idx, token in enumerate(__lowercase  )
														]
														self.assertListEqual(__lowercase   ,__lowercase  )
														self.assertListEqual(__lowercase   ,__lowercase  )

