





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  :    Any						    =  {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS}

def   a_    ( lowerCAmelCase_      :			Union[str, Any],	lowerCAmelCase_      :			Any,	lowerCAmelCase_      :			Optional[int],	lowerCAmelCase_      :			Optional[int]	):
   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:
      __lowerCAmelCase								=	TOKENIZER_CLASSES
   else:
      __lowerCAmelCase								=	{tokenizer_name: getattr(UpperCamelCase__,	tokenizer_name + 'Fast'	)}

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

   for tokenizer_name in tokenizer_names:
      __lowerCAmelCase								=	TOKENIZER_CLASSES[tokenizer_name]

      __lowerCAmelCase								=	True
      if checkpoint_name is None:
         __lowerCAmelCase								=	list(tokenizer_class.max_model_input_sizes.keys()	)
      else:
         __lowerCAmelCase								=	[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
         __lowerCAmelCase								=	tokenizer_class.from_pretrained(UpperCamelCase__,	force_download=UpperCamelCase__	)

         # 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:
            __lowerCAmelCase	,	__lowerCAmelCase								=	checkpoint.split('/'	)
            __lowerCAmelCase								=	os.path.join(UpperCamelCase__,	UpperCamelCase__	)
         elif add_prefix:
            __lowerCAmelCase								=	checkpoint
            __lowerCAmelCase								=	dump_path
         else:
            __lowerCAmelCase								=	None
            __lowerCAmelCase								=	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]:
            __lowerCAmelCase								=	list(tokenizer.pretrained_vocab_files_map.values()	)[0][checkpoint]
            __lowerCAmelCase								=	file_path.split(UpperCamelCase__	)[-1][0]
            if next_char == "/":
               __lowerCAmelCase								=	os.path.join(UpperCamelCase__,	UpperCamelCase__	)
               __lowerCAmelCase								=	None

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

         __lowerCAmelCase								=	tokenizer.save_pretrained(
             UpperCamelCase__,	legacy_format=UpperCamelCase__,	filename_prefix=UpperCamelCase__	)
         logger.info(F"""=> File names {file_names}"""	)

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


if __name__ == "__main__":
     _snake_case  :    Optional[Any]						    =  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  :    Union[str, Any]						    =  parser.parse_args()

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








import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer


a__:      Dict									=		logging.get_logger(__name__)

a__:      str									=		{'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

a__:      Any									=		{
    'vocab_file': {
        'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt',
        'distilbert-base-uncased-distilled-squad': (
            'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt'
        ),
        'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt',
        'distilbert-base-cased-distilled-squad': (
            'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt'
        ),
        'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt',
        'distilbert-base-multilingual-cased': (
            'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt'
        ),
    },
    'tokenizer_file': {
        'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json',
        'distilbert-base-uncased-distilled-squad': (
            'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json'
        ),
        'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json',
        'distilbert-base-cased-distilled-squad': (
            'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json'
        ),
        'distilbert-base-german-cased': (
            'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json'
        ),
        'distilbert-base-multilingual-cased': (
            'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json'
        ),
    },
}

a__:      Any									=		{
    'distilbert-base-uncased': 512,
    'distilbert-base-uncased-distilled-squad': 512,
    'distilbert-base-cased': 512,
    'distilbert-base-cased-distilled-squad': 512,
    'distilbert-base-german-cased': 512,
    'distilbert-base-multilingual-cased': 512,
}


a__:      Optional[Any]									=		{
    'distilbert-base-uncased': {'do_lower_case': True},
    'distilbert-base-uncased-distilled-squad': {'do_lower_case': True},
    'distilbert-base-cased': {'do_lower_case': False},
    'distilbert-base-cased-distilled-squad': {'do_lower_case': False},
    'distilbert-base-german-cased': {'do_lower_case': False},
    'distilbert-base-multilingual-cased': {'do_lower_case': False},
}




class     SCREAMING_SNAKE_CASE__ (						UpperCamelCase__      ):
 __SCREAMING_SNAKE_CASE							       =	VOCAB_FILES_NAMES
 __SCREAMING_SNAKE_CASE							       =	PRETRAINED_VOCAB_FILES_MAP
 __SCREAMING_SNAKE_CASE							       =	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __SCREAMING_SNAKE_CASE							       =	PRETRAINED_INIT_CONFIGURATION
 __SCREAMING_SNAKE_CASE							       =	['''input_ids''', '''attention_mask''']
 __SCREAMING_SNAKE_CASE							       =	DistilBertTokenizer



 def __init__(							self,__lowerCamelCase=None,__lowerCamelCase=None,__lowerCamelCase=True,__lowerCamelCase="[UNK]",__lowerCamelCase="[SEP]",__lowerCamelCase="[PAD]",__lowerCamelCase="[CLS]",__lowerCamelCase="[MASK]",__lowerCamelCase=True,__lowerCamelCase=None,**__lowerCamelCase,):
        super().__init__(
            __lowerCamelCase,tokenizer_file=__lowerCamelCase,do_lower_case=__lowerCamelCase,unk_token=__lowerCamelCase,sep_token=__lowerCamelCase,pad_token=__lowerCamelCase,cls_token=__lowerCamelCase,mask_token=__lowerCamelCase,tokenize_chinese_chars=__lowerCamelCase,strip_accents=__lowerCamelCase,**__lowerCamelCase,)

        A__											=						json.loads(self.backend_tokenizer.normalizer.__getstate__() )
        if (
            normalizer_state.get('''lowercase''',__lowerCamelCase ) != do_lower_case
            or normalizer_state.get('''strip_accents''',__lowerCamelCase ) != strip_accents
            or normalizer_state.get('''handle_chinese_chars''',__lowerCamelCase ) != tokenize_chinese_chars
        ):
               A__											=						getattr(__lowerCamelCase,normalizer_state.pop('''type''' ) )
               A__											=						do_lower_case
               A__											=						strip_accents
               A__											=						tokenize_chinese_chars
               A__											=						normalizer_class(**__lowerCamelCase )

        A__											=						do_lower_case



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase=None ):
        A__											=						[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 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase = None ):
        A__											=						[self.sep_token_id]
        A__											=						[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 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase = None ):
        A__											=						self._tokenizer.model.save(__lowerCamelCase,name=__lowerCamelCase )
        return tuple(__lowerCamelCase )





