
'''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
lowercase     :							Any       						=     'src/transformers'
lowercase     :							List[Any]       						=     'docs/source/en'
lowercase     :							List[Any]       						=     '.'







def 						lowerCAmelCase_							(  snake_case__						,							snake_case__						,							snake_case__		):




    '''simple docstring'''



    with open(snake_case__						,							'''r'''						,							encoding='''utf-8'''						,							newline='''\n'''		) as f:
        A			:  Optional[int]   =		f.readlines()
    # Find the start prompt.
    A			:  Optional[Any]   =		0
    while not lines[start_index].startswith(snake_case__		):
        start_index += 1
    start_index += 1

    A			:  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 |
lowercase     :							Tuple       						=     'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
lowercase     :							Any       						=     re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
lowercase     :							Tuple       						=     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.
lowercase     :							Tuple       						=     re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')


# This is to make sure the transformers module imported is the one in the repo.
lowercase     :							List[Any]       						=     direct_transformers_import(TRANSFORMERS_PATH)







def 						lowerCAmelCase_							(  snake_case__		):




    '''simple docstring'''



    A			:  Tuple   =		re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''						,							snake_case__		)
    return [m.group(0		) for m in matches]







def 						lowerCAmelCase_							(  snake_case__						,							snake_case__		):




    '''simple docstring'''



    A			:  List[str]   =		2 if text == '''✅''' or text == '''❌''' else len(snake_case__		)
    A			:  Union[str, Any]   =		(width - text_length) // 2
    A			:  Optional[int]   =		width - text_length - left_indent
    return " " * left_indent + text + " " * right_indent







def 						lowerCAmelCase_							(  ):




    '''simple docstring'''



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

    # Let's lookup through all transformers object (once).
    for attr_name in dir(snake_case__		):
        A			:  int   =		None
        if attr_name.endswith('''Tokenizer'''		):
            A			:  Any   =		slow_tokenizers
            A			:  str   =		attr_name[:-9]
        elif attr_name.endswith('''TokenizerFast'''		):
            A			:  Optional[Any]   =		fast_tokenizers
            A			:  Any   =		attr_name[:-13]
        elif _re_tf_models.match(snake_case__		) is not None:
            A			:  List[str]   =		tf_models
            A			:  Any   =		_re_tf_models.match(snake_case__		).groups()[0]
        elif _re_flax_models.match(snake_case__		) is not None:
            A			:  Tuple   =		flax_models
            A			:  Dict   =		_re_flax_models.match(snake_case__		).groups()[0]
        elif _re_pt_models.match(snake_case__		) is not None:
            A			:  Tuple   =		pt_models
            A			:  Optional[int]   =		_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():
                    A			:  List[str]   =		True
                    break
                # Try again after removing the last word in the name
                A			:  str   =		''''''.join(camel_case_split(snake_case__		)[:-1]		)

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

    # Build the table per se
    A			:  Dict   =		'''|''' + '''|'''.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"

    A			:  Union[str, Any]   =		{True: '''✅''', False: '''❌'''}
    for name in model_names:
        A			:  Any   =		model_name_to_prefix[name]
        A			:  Any   =		[
            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_							(  snake_case__=False		):




    '''simple docstring'''



    A,    A,    A,    A			:  Optional[int]   =		_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-->'''						,							)
    A			:  Optional[Any]   =		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__":
      lowercase     :							Any       						=     argparse.ArgumentParser()
      parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
      lowercase     :							Optional[Any]       						=     parser.parse_args()

      check_model_table(args.fix_and_overwrite)






'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import numpy as np
      import tensorflow as tf

      from transformers import (
          TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          FlaubertConfig,
          TFFlaubertForMultipleChoice,
          TFFlaubertForQuestionAnsweringSimple,
          TFFlaubertForSequenceClassification,
          TFFlaubertForTokenClassification,
          TFFlaubertModel,
          TFFlaubertWithLMHeadModel,
      )





class 					A							:





     def __init__(				self		,     SCREAMING_SNAKE_CASE		,     )					->							Optional[Any]:






         """simple docstring"""






         A			:  List[str]   =		parent
         A			:  int   =		13
         A			:  Dict   =		7
         A			:  str   =		True
         A			:  Dict   =		True
         A			:  Tuple   =		True
         A			:  Union[str, Any]   =		True
         A			:  Dict   =		True
         A			:  str   =		False
         A			:  Union[str, Any]   =		False
         A			:  Union[str, Any]   =		False
         A			:  List[str]   =		2
         A			:  Optional[int]   =		99
         A			:  List[str]   =		0
         A			:  int   =		32
         A			:  Any   =		2
         A			:  Optional[Any]   =		4
         A			:  List[Any]   =		0.1
         A			:  List[str]   =		0.1
         A			:  Tuple   =		512
         A			:  Optional[Any]   =		16
         A			:  List[str]   =		2
         A			:  Tuple   =		0.02
         A			:  List[str]   =		3
         A			:  List[Any]   =		4
         A			:  Any   =		'''last'''
         A			:  int   =		True
         A			:  Union[str, Any]   =		None
         A			:  Dict   =		0





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         A			:  int   =		ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size      )
         A			:  Any   =		random_attention_mask([self.batch_size, self.seq_length]		,     dtype=tf.floataa      )

         A			:  int   =		None
         if self.use_input_lengths:
             A			:  int   =		(
                 ids_tensor([self.batch_size]		,     vocab_size=2      ) + self.seq_length - 2
             )  # small variation of seq_length

         A			:  Tuple   =		None
         if self.use_token_type_ids:
             A			:  Union[str, Any]   =		ids_tensor([self.batch_size, self.seq_length]		,     self.n_langs      )

         A			:  List[Any]   =		None
         A			:  List[Any]   =		None
         A			:  Tuple   =		None
         if self.use_labels:
             A			:  Dict   =		ids_tensor([self.batch_size]		,     self.type_sequence_label_size      )
             A			:  Dict   =		ids_tensor([self.batch_size, self.seq_length]		,     self.num_labels      )
             A			:  List[Any]   =		ids_tensor([self.batch_size]		,     2		,     dtype=tf.floataa      )
             A			:  Optional[Any]   =		ids_tensor([self.batch_size]		,     self.num_choices      )

         A			:  Dict   =		FlaubertConfig(
             vocab_size=self.vocab_size		,     n_special=self.n_special		,     emb_dim=self.hidden_size		,     n_layers=self.num_hidden_layers		,     n_heads=self.num_attention_heads		,     dropout=self.hidden_dropout_prob		,     attention_dropout=self.attention_probs_dropout_prob		,     gelu_activation=self.gelu_activation		,     sinusoidal_embeddings=self.sinusoidal_embeddings		,     asm=self.asm		,     causal=self.causal		,     n_langs=self.n_langs		,     max_position_embeddings=self.max_position_embeddings		,     initializer_range=self.initializer_range		,     summary_type=self.summary_type		,     use_proj=self.use_proj		,     bos_token_id=self.bos_token_id		,     )

         return (
             config,
             input_ids,
             token_type_ids,
             input_lengths,
             sequence_labels,
             token_labels,
             is_impossible_labels,
             choice_labels,
             input_mask,
         )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							List[str]:






         """simple docstring"""






         A			:  int   =		TFFlaubertModel(config=SCREAMING_SNAKE_CASE      )
         A			:  Optional[int]   =		{'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
         A			:  int   =		model(SCREAMING_SNAKE_CASE      )

         A			:  List[str]   =		[input_ids, input_mask]
         A			:  str   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							List[str]:






         """simple docstring"""






         A			:  List[str]   =		TFFlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE      )

         A			:  Union[str, Any]   =		{'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
         A			:  Tuple   =		model(SCREAMING_SNAKE_CASE      )

         self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.vocab_size)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							Optional[Any]:






         """simple docstring"""






         A			:  Union[str, Any]   =		TFFlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE      )

         A			:  List[str]   =		{'''input_ids''': input_ids, '''lengths''': input_lengths}

         A			:  Tuple   =		model(SCREAMING_SNAKE_CASE      )

         self.parent.assertEqual(result.start_logits.shape		,     (self.batch_size, self.seq_length)      )
         self.parent.assertEqual(result.end_logits.shape		,     (self.batch_size, self.seq_length)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							Any:






         """simple docstring"""






         A			:  Union[str, Any]   =		TFFlaubertForSequenceClassification(SCREAMING_SNAKE_CASE      )

         A			:  Dict   =		{'''input_ids''': input_ids, '''lengths''': input_lengths}

         A			:  Optional[Any]   =		model(SCREAMING_SNAKE_CASE      )

         self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.type_sequence_label_size)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							str:






         """simple docstring"""






         A			:  Optional[Any]   =		self.num_labels
         A			:  str   =		TFFlaubertForTokenClassification(config=SCREAMING_SNAKE_CASE      )
         A			:  List[str]   =		{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
         A			:  int   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.num_labels)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							Any:






         """simple docstring"""






         A			:  str   =		self.num_choices
         A			:  int   =		TFFlaubertForMultipleChoice(config=SCREAMING_SNAKE_CASE      )
         A			:  str   =		tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE		,     1      )		,     (1, self.num_choices, 1)      )
         A			:  Optional[Any]   =		tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE		,     1      )		,     (1, self.num_choices, 1)      )
         A			:  str   =		tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE		,     1      )		,     (1, self.num_choices, 1)      )
         A			:  List[str]   =		{
             '''input_ids''': multiple_choice_inputs_ids,
             '''attention_mask''': multiple_choice_input_mask,
             '''token_type_ids''': multiple_choice_token_type_ids,
         }
         A			:  List[Any]   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_choices)      )





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  Tuple   =		self.prepare_config_and_inputs()
         (
             (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    
         )			:  Any   =		config_and_inputs
         A			:  List[str]   =		{
             '''input_ids''': input_ids,
             '''token_type_ids''': token_type_ids,
             '''langs''': token_type_ids,
             '''lengths''': input_lengths,
         }
         return config, inputs_dict





@require_tf
class 					A							(				__snake_case       ,     __snake_case       ,     unittest.TestCase		):
     __magic_name__          =						(
         (
             TFFlaubertModel,
             TFFlaubertWithLMHeadModel,
             TFFlaubertForSequenceClassification,
             TFFlaubertForQuestionAnsweringSimple,
             TFFlaubertForTokenClassification,
             TFFlaubertForMultipleChoice,
         )
         if is_tf_available()
         else ()
     )
     __magic_name__          =						(
         (TFFlaubertWithLMHeadModel,) if is_tf_available() else ()
     )  # TODO (PVP): Check other models whether language generation is also applicable
     __magic_name__          =						(
         {
             '''feature-extraction''': TFFlaubertModel,
             '''fill-mask''': TFFlaubertWithLMHeadModel,
             '''question-answering''': TFFlaubertForQuestionAnsweringSimple,
             '''text-classification''': TFFlaubertForSequenceClassification,
             '''token-classification''': TFFlaubertForTokenClassification,
             '''zero-shot''': TFFlaubertForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     __magic_name__          =						False
     __magic_name__          =						False





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							List[Any]:






         """simple docstring"""






         if (
             pipeline_test_casse_name == "QAPipelineTests"
             and tokenizer_name is not None
             and not tokenizer_name.endswith('''Fast'''      )
         ):
             # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
             # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
             # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
             return True

         return False





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  int   =		TFFlaubertModelTester(self      )
         A			:  Dict   =		ConfigTester(self		,     config_class=SCREAMING_SNAKE_CASE		,     emb_dim=37      )





     def 							__lowerCAmelCase				(				self      )					->							Optional[Any]:






         """simple docstring"""






         self.config_tester.run_common_tests()





     def 							__lowerCAmelCase				(				self      )					->							Optional[int]:






         """simple docstring"""






         A			:  List[Any]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






         A			:  int   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         A			:  Union[str, Any]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE      )





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






         """simple docstring"""






         A			:  Optional[int]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  Tuple   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_for_token_classification(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






         A			:  str   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_for_multiple_choice(*SCREAMING_SNAKE_CASE      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Union[str, Any]:






         """simple docstring"""






         for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             A			:  Union[str, Any]   =		TFFlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE      )
             self.assertIsNotNone(SCREAMING_SNAKE_CASE      )





@require_tf
@require_sentencepiece
@require_tokenizers
class 					A							(				unittest.TestCase		):





     @slow
     def 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         A			:  Tuple   =		TFFlaubertModel.from_pretrained('''jplu/tf-flaubert-small-cased'''      )

         A			:  List[str]   =		tf.convert_to_tensor(
             [[0, 158, 735, 2592, 1424, 6727, 82, 1]]		,     dtype=tf.intaa		,     )  # "J'aime flaubert !"

         A			:  int   =		model(SCREAMING_SNAKE_CASE      )[0]
         A			:  str   =		tf.TensorShape((1, 8, 512)      )
         self.assertEqual(output.shape		,     SCREAMING_SNAKE_CASE      )
         # compare the actual values for a slice.
         A			:  Union[str, Any]   =		tf.convert_to_tensor(
             [
                 [
                     [-1.8_768_773, -1.566_555, 0.27_072_418],
                     [-1.6_920_038, -0.5_873_505, 1.9_329_599],
                     [-2.9_563_985, -1.6_993_835, 1.7_972_052],
                 ]
             ]		,     dtype=tf.floataa		,     )

         self.assertTrue(np.allclose(output[:, :3, :3].numpy()		,     expected_slice.numpy()		,     atol=1e-4      )      )




