


import argparse
import os

import transformers

from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
from .utils import logging


logging.set_verbosity_info()

snake_case_						:			Union[str, Any]													=							logging.get_logger(__name__)


snake_case_						:			str													=							{name: getattr(transformers, name + '''Fast''') for name in SLOW_TO_FAST_CONVERTERS}







def 						lowerCamelCase(   a__	,a__	,a__	,a__):
				if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES:
								raise ValueError(f"Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys())}.")

				if tokenizer_name is None:
								_SCREAMING_SNAKE_CASE			  =TOKENIZER_CLASSES
				else:
								_SCREAMING_SNAKE_CASE			  ={tokenizer_name: getattr(a__	,tokenizer_name + '''Fast''')}

				logger.info(f"Loading tokenizer classes: {tokenizer_names}")

				for tokenizer_name in tokenizer_names:
								_SCREAMING_SNAKE_CASE			  =TOKENIZER_CLASSES[tokenizer_name]

								_SCREAMING_SNAKE_CASE			  =True
								if checkpoint_name is None:
												_SCREAMING_SNAKE_CASE			  =list(tokenizer_class.max_model_input_sizes.keys())
								else:
												_SCREAMING_SNAKE_CASE			  =[checkpoint_name]

								logger.info(f"For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}")

								for checkpoint in checkpoint_names:
												logger.info(f"Loading {tokenizer_class.__class__.__name__} {checkpoint}")

												# Load tokenizer
												_SCREAMING_SNAKE_CASE			  =tokenizer_class.from_pretrained(a__	,force_download=a__)

												# Save fast tokenizer
												logger.info(f"Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}")

												# For organization names we create sub-directories
												if "/" in checkpoint:
																_SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE			  =checkpoint.split('''/''')
																_SCREAMING_SNAKE_CASE			  =os.path.join(a__	,a__)
												elif add_prefix:
																_SCREAMING_SNAKE_CASE			  =checkpoint
																_SCREAMING_SNAKE_CASE			  =dump_path
												else:
																_SCREAMING_SNAKE_CASE			  =None
																_SCREAMING_SNAKE_CASE			  =dump_path

												logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}")

												if checkpoint in list(tokenizer.pretrained_vocab_files_map.values())[0]:
																_SCREAMING_SNAKE_CASE			  =list(tokenizer.pretrained_vocab_files_map.values())[0][checkpoint]
																_SCREAMING_SNAKE_CASE			  =file_path.split(a__)[-1][0]
																if next_char == "/":
																				_SCREAMING_SNAKE_CASE			  =os.path.join(a__	,a__)
																				_SCREAMING_SNAKE_CASE			  =None

																logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}")

												_SCREAMING_SNAKE_CASE			  =tokenizer.save_pretrained(
												    a__	,legacy_format=a__	,filename_prefix=a__)
												logger.info(f"=> File names {file_names}")

												for file_name in file_names:
																if not file_name.endswith('''tokenizer.json'''):
																				os.remove(a__)
																				logger.info(f"=> removing {file_name}")


if __name__ == "__main__":
							snake_case_						:			str													=							argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '''--dump_path''', default=None, type=str, required=True, help='''Path to output generated fast tokenizer files.'''
							)
							parser.add_argument(
							    '''--tokenizer_name''',
							    default=None,
							    type=str,
							    help=(
							        f"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """
							        '''download and convert all the checkpoints from AWS.'''
							    ),
							)
							parser.add_argument(
							    '''--checkpoint_name''',
							    default=None,
							    type=str,
							    help='''Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.''',
							)
							parser.add_argument(
							    '''--force_download''',
							    action='''store_true''',
							    help='''Re-download checkpoints.''',
							)
							snake_case_						:			int													=							parser.parse_args()

							convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)



import os
import unittest

from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow

from ...test_tokenization_common import TokenizerTesterMixin

class 						A__							(		UpperCamelCase__   ,     unittest.TestCase  ):
						UpperCAmelCase             =						ProphetNetTokenizer
						UpperCAmelCase             =						False




						def 							__UpperCamelCase				(       self					:      List[Any]  )							->     int:


										"""simple docstring"""





										super().setUp()

										_SCREAMING_SNAKE_CASE			  =[
										    '''[UNK]''',
										    '''[CLS]''',
										    '''[SEP]''',
										    '''[PAD]''',
										    '''[MASK]''',
										    '''want''',
										    '''##want''',
										    '''##ed''',
										    '''wa''',
										    '''un''',
										    '''runn''',
										    '''##ing''',
										    ''',''',
										    '''low''',
										    '''lowest''',
										]
										_SCREAMING_SNAKE_CASE			  =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 							__UpperCamelCase				(       self					:      str				,    _a					:      Union[str, Any]  )							->     List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  ='''UNwant\u00E9d,running'''
										_SCREAMING_SNAKE_CASE			  ='''unwanted, running'''
										return input_text, output_text




						def 							__UpperCamelCase				(       self					:      Optional[int]  )							->     str:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =self.tokenizer_class(self.vocab_file  )

										_SCREAMING_SNAKE_CASE			  =tokenizer.tokenize('''UNwant\u00E9d,running'''  )
										self.assertListEqual(_a				,    ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']  )
										self.assertListEqual(tokenizer.convert_tokens_to_ids(_a  )				,    [9, 6, 7, 12, 10, 11]  )




						def 							__UpperCamelCase				(       self					:      Tuple  )							->     Tuple:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer()

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




						def 							__UpperCamelCase				(       self					:      Dict  )							->     List[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(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 							__UpperCamelCase				(       self					:      Dict  )							->     Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(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 							__UpperCamelCase				(       self					:      List[str]  )							->     int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(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 							__UpperCamelCase				(       self					:      Optional[int]  )							->     Tuple:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(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 							__UpperCamelCase				(       self					:      Any  )							->     Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(do_lower_case=_a  )

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




						def 							__UpperCamelCase				(       self					:      Dict  )							->     int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(do_lower_case=_a				,    strip_accents=_a  )

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




						def 							__UpperCamelCase				(       self					:      Optional[Any]  )							->     int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(do_lower_case=_a				,    strip_accents=_a  )

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




						def 							__UpperCamelCase				(       self					:      List[str]  )							->     Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =BasicTokenizer(do_lower_case=_a				,    never_split=['''[UNK]''']  )

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




						def 							__UpperCamelCase				(       self					:      List[Any]  )							->     List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

										_SCREAMING_SNAKE_CASE			  ={}
										for i, token in enumerate(_a  ):
														_SCREAMING_SNAKE_CASE			  =i
										_SCREAMING_SNAKE_CASE			  =WordpieceTokenizer(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''']  )




						@require_torch
						def 							__UpperCamelCase				(       self					:      Any  )							->     Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

										_SCREAMING_SNAKE_CASE			  =['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
										_SCREAMING_SNAKE_CASE			  =[1037, 2146, 2_0423, 2005, 7680, 7849, 3989, 1012, 102]
										_SCREAMING_SNAKE_CASE			  =tokenizer(_a				,    padding=_a				,    return_tensors='''pt'''  )
										self.assertIsInstance(_a				,    _a  )
										_SCREAMING_SNAKE_CASE			  =list(batch.input_ids.numpy()[0]  )
										self.assertListEqual(_a				,    _a  )

										self.assertEqual((2, 9)				,    batch.input_ids.shape  )
										self.assertEqual((2, 9)				,    batch.attention_mask.shape  )




						def 							__UpperCamelCase				(       self					:      List[str]  )							->     Optional[int]:


										"""simple docstring"""





										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 							__UpperCamelCase				(       self					:      int  )							->     Dict:


										"""simple docstring"""





										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 							__UpperCamelCase				(       self					:      List[str]  )							->     List[str]:


										"""simple docstring"""





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




						@slow
						def 							__UpperCamelCase				(       self					:      Tuple  )							->     int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

										_SCREAMING_SNAKE_CASE			  =tokenizer.encode('''sequence builders'''				,    add_special_tokens=_a  )
										_SCREAMING_SNAKE_CASE			  =tokenizer.encode('''multi-sequence build'''				,    add_special_tokens=_a  )

										_SCREAMING_SNAKE_CASE			  =tokenizer.build_inputs_with_special_tokens(_a  )
										_SCREAMING_SNAKE_CASE			  =tokenizer.build_inputs_with_special_tokens(_a				,    _a  )

										assert encoded_sentence == text + [102]
										assert encoded_pair == text + [102] + text_a + [102]