



"""simple docstring"""





import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__lowerCAmelCase							:       str          =       logging.get_logger(__name__)


__lowerCAmelCase							:       Optional[int]          =       {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}

__lowerCAmelCase							:       Union[str, Any]          =       {
    '''vocab_file''': {
        '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json''',
        '''allenai/longformer-large-4096''': (
            '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json'''
        ),
        '''allenai/longformer-large-4096-finetuned-triviaqa''': (
            '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json'''
        ),
        '''allenai/longformer-base-4096-extra.pos.embd.only''': (
            '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json'''
        ),
        '''allenai/longformer-large-4096-extra.pos.embd.only''': (
            '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json'''
        ),
    },
    '''merges_file''': {
        '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt''',
        '''allenai/longformer-large-4096''': (
            '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt'''
        ),
        '''allenai/longformer-large-4096-finetuned-triviaqa''': (
            '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt'''
        ),
        '''allenai/longformer-base-4096-extra.pos.embd.only''': (
            '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt'''
        ),
        '''allenai/longformer-large-4096-extra.pos.embd.only''': (
            '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt'''
        ),
    },
}

__lowerCAmelCase							:       Dict          =       {
    '''allenai/longformer-base-4096''': 4096,
    '''allenai/longformer-large-4096''': 4096,
    '''allenai/longformer-large-4096-finetuned-triviaqa''': 4096,
    '''allenai/longformer-base-4096-extra.pos.embd.only''': 4096,
    '''allenai/longformer-large-4096-extra.pos.embd.only''': 4096,
}
@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def 						__lowerCAmelCase    (		):


						'''simple docstring'''






						snake_case_ :			List[Any]            =      (
						    list(range(ord("""!"""     )       ,			ord("""~"""     ) + 1     )     ) + list(range(ord("""¡"""     )       ,			ord("""¬"""     ) + 1     )     ) + list(range(ord("""®"""     )       ,			ord("""ÿ"""     ) + 1     )     )
						)
						snake_case_ :			List[Any]            =      bs[:]
						snake_case_ :			Union[str, Any]            =      0
						for b in range(2**8     ):
												if b not in bs:
																		bs.append(__UpperCamelCase     )
																		cs.append(2**8 + n     )
																		n += 1
						snake_case_ :			Union[str, Any]            =      [chr(__UpperCamelCase     ) for n in cs]
						return dict(zip(__UpperCamelCase       ,			__UpperCamelCase     )     )
def 						__lowerCAmelCase    (		__UpperCamelCase   :      str     ):


						'''simple docstring'''






						snake_case_ :			List[str]            =      set()
						snake_case_ :			Optional[Any]            =      word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)     )
												snake_case_ :			List[str]            =      char
						return pairs






class  _lowerCAmelCase     (					SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		_lowerCamelCase      	=							VOCAB_FILES_NAMES
		_lowerCamelCase      	=							PRETRAINED_VOCAB_FILES_MAP
		_lowerCamelCase      	=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		_lowerCamelCase      	=							['''input_ids''', '''attention_mask''']





		def __init__(       self				,     _lowercase				,     _lowercase				,     _lowercase="replace"				,     _lowercase="<s>"				,     _lowercase="</s>"				,     _lowercase="</s>"				,     _lowercase="<s>"				,     _lowercase="<unk>"				,     _lowercase="<pad>"				,     _lowercase="<mask>"				,     _lowercase=False				,     **_lowercase				,     )			->    Any:







								'''simple docstring'''

								snake_case_ :			Optional[int]            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else bos_token
								snake_case_ :			Union[str, Any]            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else eos_token
								snake_case_ :			List[Any]            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else sep_token
								snake_case_ :			Union[str, Any]            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else cls_token
								snake_case_ :			str            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else unk_token
								snake_case_ :			Dict            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else pad_token

								# Mask token behave like a normal word, i.e. include the space before it
								snake_case_ :			str            =      AddedToken(_lowercase				,     lstrip=_lowercase				,     rstrip=_lowercase ) if isinstance(_lowercase				,     _lowercase ) else mask_token

								super().__init__(
								    errors=_lowercase				,     bos_token=_lowercase				,     eos_token=_lowercase				,     unk_token=_lowercase				,     sep_token=_lowercase				,     cls_token=_lowercase				,     pad_token=_lowercase				,     mask_token=_lowercase				,     add_prefix_space=_lowercase				,     **_lowercase				,     )

								with open(_lowercase				,     encoding="""utf-8""" ) as vocab_handle:
														snake_case_ :			Dict            =      json.load(_lowercase )
								snake_case_ :			Optional[int]            =      {v: k for k, v in self.encoder.items()}
								snake_case_ :			Optional[Any]            =      errors  # how to handle errors in decoding
								snake_case_ :			str            =      bytes_to_unicode()
								snake_case_ :			Any            =      {v: k for k, v in self.byte_encoder.items()}
								with open(_lowercase				,     encoding="""utf-8""" ) as merges_handle:
														snake_case_ :			Dict            =      merges_handle.read().split("""\n""" )[1:-1]
								snake_case_ :			List[Any]            =      [tuple(merge.split() ) for merge in bpe_merges]
								snake_case_ :			str            =      dict(zip(_lowercase				,     range(len(_lowercase ) ) ) )
								snake_case_ :			List[str]            =      {}
								snake_case_ :			List[Any]            =      add_prefix_space

								# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
								snake_case_ :			Dict            =      re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" )





		@property
		def  UpperCAmelCase__				(       self )			->    Any:







								'''simple docstring'''

								return len(self.encoder )





		def  UpperCAmelCase__				(       self )			->    int:







								'''simple docstring'''

								return dict(self.encoder				,     **self.added_tokens_encoder )





		def  UpperCAmelCase__				(       self				,     _lowercase )			->    Tuple:







								'''simple docstring'''

								if token in self.cache:
														return self.cache[token]
								snake_case_ :			Union[str, Any]            =      tuple(_lowercase )
								snake_case_ :			Optional[int]            =      get_pairs(_lowercase )

								if not pairs:
														return token

								while True:
														snake_case_ :			Tuple            =      min(_lowercase				,     key=lambda _lowercase : self.bpe_ranks.get(_lowercase				,     float("""inf""" ) ) )
														if bigram not in self.bpe_ranks:
																				break
														snake_case_      ,		snake_case_ :			str            =      bigram
														snake_case_ :			List[Any]            =      []
														snake_case_ :			str            =      0
														while i < len(_lowercase ):
																				try:
																										snake_case_ :			Optional[Any]            =      word.index(_lowercase				,     _lowercase )
																				except ValueError:
																										new_word.extend(word[i:] )
																										break
																				else:
																										new_word.extend(word[i:j] )
																										snake_case_ :			Dict            =      j

																				if word[i] == first and i < len(_lowercase ) - 1 and word[i + 1] == second:
																										new_word.append(first + second )
																										i += 2
																				else:
																										new_word.append(word[i] )
																										i += 1
														snake_case_ :			Optional[int]            =      tuple(_lowercase )
														snake_case_ :			Any            =      new_word
														if len(_lowercase ) == 1:
																				break
														else:
																				snake_case_ :			Any            =      get_pairs(_lowercase )
								snake_case_ :			List[Any]            =      """ """.join(_lowercase )
								snake_case_ :			int            =      word
								return word





		def  UpperCAmelCase__				(       self				,     _lowercase )			->    str:







								'''simple docstring'''

								snake_case_ :			List[Any]            =      []
								for token in re.findall(self.pat				,     _lowercase ):
														snake_case_ :			Any            =      """""".join(
														    self.byte_encoder[b] for b in token.encode("""utf-8""" ) )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
														bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowercase ).split(""" """ ) )
								return bpe_tokens





		def  UpperCAmelCase__				(       self				,     _lowercase )			->    Union[str, Any]:







								'''simple docstring'''

								return self.encoder.get(_lowercase				,     self.encoder.get(self.unk_token ) )





		def  UpperCAmelCase__				(       self				,     _lowercase )			->    List[str]:







								'''simple docstring'''

								return self.decoder.get(_lowercase )





		def  UpperCAmelCase__				(       self				,     _lowercase )			->    Union[str, Any]:







								'''simple docstring'''

								snake_case_ :			Optional[int]            =      """""".join(_lowercase )
								snake_case_ :			Dict            =      bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8"""				,     errors=self.errors )
								return text





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase = None )			->    Tuple[str]:







								'''simple docstring'''

								if not os.path.isdir(_lowercase ):
														logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
														return
								snake_case_ :			str            =      os.path.join(
								    _lowercase				,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
								snake_case_ :			Union[str, Any]            =      os.path.join(
								    _lowercase				,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] )

								with open(_lowercase				,     """w"""				,     encoding="""utf-8""" ) as f:
														f.write(json.dumps(self.encoder				,     indent=2				,     sort_keys=_lowercase				,     ensure_ascii=_lowercase ) + """\n""" )

								snake_case_ :			str            =      0
								with open(_lowercase				,     """w"""				,     encoding="""utf-8""" ) as writer:
														writer.write("""#version: 0.2\n""" )
														for bpe_tokens, token_index in sorted(self.bpe_ranks.items()				,     key=lambda _lowercase : kv[1] ):
																				if index != token_index:
																										logger.warning(
																										    f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
																										    """ Please check that the tokenizer is not corrupted!""" )
																										snake_case_ :			List[Any]            =      token_index
																				writer.write(""" """.join(_lowercase ) + """\n""" )
																				index += 1

								return vocab_file, merge_file





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase = None )			->    List[int]:







								'''simple docstring'''

								if token_ids_a is None:
														return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
								snake_case_ :			int            =      [self.cls_token_id]
								snake_case_ :			str            =      [self.sep_token_id]
								return cls + token_ids_a + sep + sep + token_ids_a + sep





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase = None				,     _lowercase = False )			->    List[int]:







								'''simple docstring'''

								if already_has_special_tokens:
														return super().get_special_tokens_mask(
														    token_ids_a=_lowercase				,     token_ids_a=_lowercase				,     already_has_special_tokens=_lowercase )

								if token_ids_a is None:
														return [1] + ([0] * len(_lowercase )) + [1]
								return [1] + ([0] * len(_lowercase )) + [1, 1] + ([0] * len(_lowercase )) + [1]





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase = None )			->    List[int]:







								'''simple docstring'''

								snake_case_ :			Tuple            =      [self.sep_token_id]
								snake_case_ :			Dict            =      [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 + sep + token_ids_a + sep ) * [0]





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase=False				,     **_lowercase )			->    List[Any]:







								'''simple docstring'''

								snake_case_ :			List[str]            =      kwargs.pop("""add_prefix_space"""				,     self.add_prefix_space )
								if (is_split_into_words or add_prefix_space) and (len(_lowercase ) > 0 and not text[0].isspace()):
														snake_case_ :			List[str]            =      """ """ + text
								return (text, kwargs)





"""simple docstring"""


import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
__snake_case    					=					'src/transformers'
__snake_case    					=					'docs/source/en'
__snake_case    					=					'.'


def    _lowerCamelCase   (     lowerCamelCase__	:							Union[str, Any]       ,		lowerCamelCase__	:							Optional[Any]       ,		lowerCamelCase__	:							Any  ):
 with open(lowerCamelCase__       ,		"""r"""       ,		encoding="""utf-8"""       ,		newline="""\n"""  ) as f:
  lowercase__       :       List[str]				=						f.readlines()
 # Find the start prompt.
 lowercase__       :       str				=						0
 while not lines[start_index].startswith(lowerCamelCase__  ):
  start_index += 1
 start_index += 1

 lowercase__       :       Optional[Any]				=						start_index
 while not lines[end_index].startswith(lowerCamelCase__  ):
  end_index += 1
 end_index -= 1

 while len(lines[start_index]  ) <= 1:
  start_index += 1
 while len(lines[end_index]  ) <= 1:
  end_index -= 1
 end_index += 1
 return "".join(lines[start_index:end_index]  ), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
__snake_case    					=					'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
__snake_case    					=					re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
__snake_case    					=					re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
__snake_case    					=					re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')


# This is to make sure the transformers module imported is the one in the repo.
__snake_case    					=					direct_transformers_import(TRANSFORMERS_PATH)


def    _lowerCamelCase   (     lowerCamelCase__	:							List[Any]  ):
 lowercase__       :       Union[str, Any]				=						re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)"""       ,		lowerCamelCase__  )
 return [m.group(0  ) for m in matches]


def    _lowerCamelCase   (     lowerCamelCase__	:							Optional[int]       ,		lowerCamelCase__	:							int  ):
 lowercase__       :       Any				=						2 if text == """✅""" or text == """❌""" else len(lowerCamelCase__  )
 lowercase__       :       int				=						(width - text_length) // 2
 lowercase__       :       List[str]				=						width - text_length - left_indent
 return " " * left_indent + text + " " * right_indent


def    _lowerCamelCase   (     ):
 lowercase__       :       List[str]				=						transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
 lowercase__       :       Optional[int]				=						{
     name: config_maping_names[code]
     for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
     if code in config_maping_names
 }
 lowercase__       :       str				=						{name: config.replace("""Config"""       ,		""""""  ) for name, config in model_name_to_config.items()}

 # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
 lowercase__       :       Tuple				=						collections.defaultdict(lowerCamelCase__  )
 lowercase__       :       Optional[Any]				=						collections.defaultdict(lowerCamelCase__  )
 lowercase__       :       Optional[int]				=						collections.defaultdict(lowerCamelCase__  )
 lowercase__       :       Dict				=						collections.defaultdict(lowerCamelCase__  )
 lowercase__       :       Union[str, Any]				=						collections.defaultdict(lowerCamelCase__  )

 # Let's lookup through all transformers object (once).
 for attr_name in dir(lowerCamelCase__  ):
  lowercase__       :       Optional[Any]				=						None
  if attr_name.endswith("""Tokenizer"""  ):
   lowercase__       :       List[Any]				=						slow_tokenizers
   lowercase__       :       List[str]				=						attr_name[:-9]
  elif attr_name.endswith("""TokenizerFast"""  ):
   lowercase__       :       Tuple				=						fast_tokenizers
   lowercase__       :       str				=						attr_name[:-13]
  elif _re_tf_models.match(lowerCamelCase__  ) is not None:
   lowercase__       :       Tuple				=						tf_models
   lowercase__       :       List[Any]				=						_re_tf_models.match(lowerCamelCase__  ).groups()[0]
  elif _re_flax_models.match(lowerCamelCase__  ) is not None:
   lowercase__       :       List[Any]				=						flax_models
   lowercase__       :       List[Any]				=						_re_flax_models.match(lowerCamelCase__  ).groups()[0]
  elif _re_pt_models.match(lowerCamelCase__  ) is not None:
   lowercase__       :       Union[str, Any]				=						pt_models
   lowercase__       :       Optional[int]				=						_re_pt_models.match(lowerCamelCase__  ).groups()[0]

  if lookup_dict is not None:
   while len(lowerCamelCase__  ) > 0:
    if attr_name in model_name_to_prefix.values():
     lowercase__       :       Tuple				=						True
     break
    # Try again after removing the last word in the name
    lowercase__       :       Union[str, Any]				=						"""""".join(camel_case_split(lowerCamelCase__  )[:-1]  )

    # Let's build that table!
 lowercase__       :       Union[str, Any]				=						list(model_name_to_config.keys()  )
 model_names.sort(key=str.lower  )
 lowercase__       :       List[Any]				=						["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""]
 # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
 lowercase__       :       str				=						[len(lowerCamelCase__  ) + 2 for c in columns]
 lowercase__       :       Tuple				=						max([len(lowerCamelCase__  ) for name in model_names]  ) + 2

 # Build the table per se
 lowercase__       :       List[Any]				=						"""|""" + """|""".join([_center_text(lowerCamelCase__       ,		lowerCamelCase__  ) for c, w in zip(lowerCamelCase__       ,		lowerCamelCase__  )]  ) + """|\n"""
 # Use ":-----:" format to center-aligned table cell texts
 table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths]  ) + "|\n"

 lowercase__       :       List[Any]				=						{True: """✅""", False: """❌"""}
 for name in model_names:
  lowercase__       :       int				=						model_name_to_prefix[name]
  lowercase__       :       List[str]				=						[
      name,
      check[slow_tokenizers[prefix]],
      check[fast_tokenizers[prefix]],
      check[pt_models[prefix]],
      check[tf_models[prefix]],
      check[flax_models[prefix]],
  ]
  table += "|" + "|".join([_center_text(lowerCamelCase__       ,		lowerCamelCase__  ) for l, w in zip(lowerCamelCase__       ,		lowerCamelCase__  )]  ) + "|\n"
 return table


def    _lowerCamelCase   (     lowerCamelCase__	:							Union[str, Any]=False  ):
 lowercase__	,       lowercase__	,       lowercase__	,       lowercase__       :       str				=						_find_text_in_file(
     filename=os.path.join(lowerCamelCase__       ,		"""index.md"""  )       ,		start_prompt="""<!--This table is updated automatically from the auto modules"""       ,		end_prompt="""<!-- End table-->"""       ,		)
 lowercase__       :       Union[str, Any]				=						get_model_table_from_auto_modules()

 if current_table != new_table:
  if overwrite:
   with open(os.path.join(lowerCamelCase__       ,		"""index.md"""  )       ,		"""w"""       ,		encoding="""utf-8"""       ,		newline="""\n"""  ) as f:
    f.writelines(lines[:start_index] + [new_table] + lines[end_index:]  )
  else:
   raise ValueError(
       """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this."""  )


if __name__ == "__main__":
   __snake_case    					=					argparse.ArgumentParser()
   parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
   __snake_case    					=					parser.parse_args()

   check_model_table(args.fix_and_overwrite)