


"""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
UpperCAmelCase   		=      '''src/transformers'''
UpperCAmelCase   		=      '''docs/source/en'''
UpperCAmelCase   		=      '''.'''






def    lowerCamelCase       (a_    :List[str]					,					a_    :str					,					a_    :List[str])  ->				List[Any]:
       with open(__snake_case					,					'''r'''					,					encoding='''utf-8'''					,					newline='''\n''') as f:
              lowercase		:int											=					f.readlines()
       # Find the start prompt.
       lowercase		:str											=					0
       while not lines[start_index].startswith(__snake_case):
              start_index += 1
       start_index += 1

       lowercase		:Tuple											=					start_index
       while not lines[end_index].startswith(__snake_case):
              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 |
UpperCAmelCase   		=      '''Model|Encoder|Decoder|ForConditionalGeneration'''
# Regexes that match TF/Flax/PT model names.
UpperCAmelCase   		=      re.compile(R'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''')
UpperCAmelCase   		=      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.
UpperCAmelCase   		=      re.compile(R'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''')


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






def    lowerCamelCase       (a_    :List[str])  ->				Tuple:
       lowercase		:Dict											=					re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''					,					__snake_case)
       return [m.group(0) for m in matches]






def    lowerCamelCase       (a_    :List[Any]					,					a_    :Optional[Any])  ->				List[Any]:
       lowercase		:Optional[Any]											=					2 if text == '''✅''' or text == '''❌''' else len(__snake_case)
       lowercase		:int											=					(width - text_length) // 2
       lowercase		:List[Any]											=					width - text_length - left_indent
       return " " * left_indent + text + " " * right_indent






def    lowerCamelCase       ()  ->				Tuple:
       lowercase		:List[str]											=					transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
       lowercase		:str											=					{
           name: config_maping_names[code]
           for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
           if code in config_maping_names
       }
       lowercase		:Optional[Any]											=					{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		:Optional[Any]											=					collections.defaultdict(__snake_case)
       lowercase		:Tuple											=					collections.defaultdict(__snake_case)
       lowercase		:List[str]											=					collections.defaultdict(__snake_case)
       lowercase		:List[Any]											=					collections.defaultdict(__snake_case)
       lowercase		:Optional[Any]											=					collections.defaultdict(__snake_case)

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

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

    # Let's build that table!
       lowercase		:Any											=					list(model_name_to_config.keys())
       model_names.sort(key=str.lower)
       lowercase		:List[str]											=					['''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		:int											=					[len(__snake_case) + 2 for c in columns]
       lowercase		:List[Any]											=					max([len(__snake_case) for name in model_names]) + 2

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

       lowercase		:Union[str, Any]											=					{True: '''✅''', False: '''❌'''}
       for name in model_names:
              lowercase		:List[Any]											=					model_name_to_prefix[name]
              lowercase		:Tuple											=					[
                  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(__snake_case					,					__snake_case) for l, w in zip(__snake_case					,					__snake_case)]) + "|\n"
       return table






def    lowerCamelCase       (a_    :List[Any]=False)  ->				Dict:
       lowercase				,	lowercase				,	lowercase				,	lowercase		:Any											=					_find_text_in_file(
           filename=os.path.join(__snake_case					,					'''index.md''')					,					start_prompt='''<!--This table is updated automatically from the auto modules'''					,					end_prompt='''<!-- End table-->'''					,					)
       lowercase		:Tuple											=					get_model_table_from_auto_modules()

       if current_table != new_table:
              if overwrite:
                     with open(os.path.join(__snake_case					,					'''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__":
 UpperCAmelCase   		=      argparse.ArgumentParser()
 parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
 UpperCAmelCase   		=      parser.parse_args()

 check_model_table(args.fix_and_overwrite)









from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase      :       Optional[int]    =						logging.get_logger(__name__)

lowerCamelCase      :       Optional[Any]    =						{
    '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''',
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}



class 				_UpperCamelCase      (a_      ):
      snake_case_	=				"""pegasus"""
      snake_case_	=				["""past_key_values"""]
      snake_case_	=				{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}


      def __init__(						self       ,    __UpperCamelCase=5_0_2_6_5       ,    __UpperCamelCase=1_0_2_4       ,    __UpperCamelCase=1_2       ,    __UpperCamelCase=4_0_9_6       ,    __UpperCamelCase=1_6       ,    __UpperCamelCase=1_2       ,    __UpperCamelCase=4_0_9_6       ,    __UpperCamelCase=1_6       ,    __UpperCamelCase=0.0       ,    __UpperCamelCase=0.0       ,    __UpperCamelCase=True       ,    __UpperCamelCase=True       ,    __UpperCamelCase="gelu"       ,    __UpperCamelCase=1_0_2_4       ,    __UpperCamelCase=0.1       ,    __UpperCamelCase=0.0       ,    __UpperCamelCase=0.0       ,    __UpperCamelCase=0.0_2       ,    __UpperCamelCase=0       ,    __UpperCamelCase=False       ,    __UpperCamelCase=0       ,    __UpperCamelCase=1       ,    __UpperCamelCase=1       ,    **__UpperCamelCase       ,    )->						Tuple:
           __lowerCAmelCase             =       vocab_size
           __lowerCAmelCase             =       max_position_embeddings
           __lowerCAmelCase             =       d_model
           __lowerCAmelCase             =       encoder_ffn_dim
           __lowerCAmelCase             =       encoder_layers
           __lowerCAmelCase             =       encoder_attention_heads
           __lowerCAmelCase             =       decoder_ffn_dim
           __lowerCAmelCase             =       decoder_layers
           __lowerCAmelCase             =       decoder_attention_heads
           __lowerCAmelCase             =       dropout
           __lowerCAmelCase             =       attention_dropout
           __lowerCAmelCase             =       activation_dropout
           __lowerCAmelCase             =       activation_function
           __lowerCAmelCase             =       init_std
           __lowerCAmelCase             =       encoder_layerdrop
           __lowerCAmelCase             =       decoder_layerdrop
           __lowerCAmelCase             =       use_cache
           __lowerCAmelCase             =       encoder_layers
           __lowerCAmelCase             =       scale_embedding  # scale factor will be sqrt(d_model) if True
           super().__init__(
               pad_token_id=__UpperCamelCase       ,    eos_token_id=__UpperCamelCase       ,    is_encoder_decoder=__UpperCamelCase       ,    decoder_start_token_id=__UpperCamelCase       ,    forced_eos_token_id=__UpperCamelCase       ,    **__UpperCamelCase       ,    )


      @property
      def 			__UpperCAmelCase		(						self						)->						int:
           return self.encoder_attention_heads


      @property
      def 			__UpperCAmelCase		(						self						)->						int:
           return self.d_model






