




'''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 : Optional[int]  				=						'src/transformers'
_snake_case : str  				=						'docs/source/en'
_snake_case : Optional[Any]  				=						'.'
def 						snake_case_       (UpperCamelCase			:    Tuple					,		UpperCamelCase			:    str					,		UpperCamelCase			:    Tuple ):





							'''simple docstring'''


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

							_a      	=							start_index
							while not lines[end_index].startswith(UpperCamelCase ):
														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 : List[str]  				=						'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
_snake_case : Any  				=						re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
_snake_case : int  				=						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 : str  				=						re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')


# This is to make sure the transformers module imported is the one in the repo.
_snake_case : Optional[int]  				=						direct_transformers_import(TRANSFORMERS_PATH)
def 						snake_case_       (UpperCamelCase			:    List[str] ):





							'''simple docstring'''


							_a      	=							re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''					,		UpperCamelCase )
							return [m.group(0 ) for m in matches]
def 						snake_case_       (UpperCamelCase			:    int					,		UpperCamelCase			:    Optional[Any] ):





							'''simple docstring'''


							_a      	=							2 if text == '''✅''' or text == '''❌''' else len(UpperCamelCase )
							_a      	=							(width - text_length) // 2
							_a      	=							width - text_length - left_indent
							return " " * left_indent + text + " " * right_indent
def 						snake_case_       ():





							'''simple docstring'''


							_a      	=							transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
							_a      	=							{
							    name: config_maping_names[code]
							    for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
							    if code in config_maping_names
							}
							_a      	=							{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      	=							collections.defaultdict(UpperCamelCase )
							_a      	=							collections.defaultdict(UpperCamelCase )
							_a      	=							collections.defaultdict(UpperCamelCase )
							_a      	=							collections.defaultdict(UpperCamelCase )
							_a      	=							collections.defaultdict(UpperCamelCase )

							# Let's lookup through all transformers object (once).
							for attr_name in dir(UpperCamelCase ):
														_a      	=							None
														if attr_name.endswith('''Tokenizer''' ):
																					_a      	=							slow_tokenizers
																					_a      	=							attr_name[:-9]
														elif attr_name.endswith('''TokenizerFast''' ):
																					_a      	=							fast_tokenizers
																					_a      	=							attr_name[:-13]
														elif _re_tf_models.match(UpperCamelCase ) is not None:
																					_a      	=							tf_models
																					_a      	=							_re_tf_models.match(UpperCamelCase ).groups()[0]
														elif _re_flax_models.match(UpperCamelCase ) is not None:
																					_a      	=							flax_models
																					_a      	=							_re_flax_models.match(UpperCamelCase ).groups()[0]
														elif _re_pt_models.match(UpperCamelCase ) is not None:
																					_a      	=							pt_models
																					_a      	=							_re_pt_models.match(UpperCamelCase ).groups()[0]

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

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

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

							_a      	=							{True: '''✅''', False: '''❌'''}
							for name in model_names:
														_a      	=							model_name_to_prefix[name]
														_a      	=							[
														    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(UpperCamelCase					,		UpperCamelCase ) for l, w in zip(UpperCamelCase					,		UpperCamelCase )] ) + "|\n"
							return table
def 						snake_case_       (UpperCamelCase			:    str=False ):





							'''simple docstring'''


							_a	,				_a	,				_a	,				_a      	=							_find_text_in_file(
							    filename=os.path.join(UpperCamelCase					,		'''index.md''' )					,		start_prompt='''<!--This table is updated automatically from the auto modules'''					,		end_prompt='''<!-- End table-->'''					,		)
							_a      	=							get_model_table_from_auto_modules()

							if current_table != new_table:
														if overwrite:
																					with open(os.path.join(UpperCamelCase					,		'''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 : Dict  				=						argparse.ArgumentParser()
				parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
				_snake_case : Optional[Any]  				=						parser.parse_args()

				check_model_table(args.fix_and_overwrite)








"""simple docstring"""






from sklearn.metrics import matthews_corrcoef

import datasets


__UpperCAmelCase						=			'''
Compute the Matthews correlation coefficient (MCC)

The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary and multiclass classifications. It takes
into account true and false positives and negatives and is generally
regarded as a balanced measure which can be used even if the classes are of
very different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction.  The statistic
is also known as the phi coefficient. [source: Wikipedia]
'''

__UpperCAmelCase						=			'''
Args:
    predictions (list of int): Predicted labels, as returned by a model.
    references (list of int): Ground truth labels.
    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.
Returns:
    matthews_correlation (dict containing float): Matthews correlation.
Examples:
    Example 1, a basic example with only predictions and references as inputs:
        >>> matthews_metric = datasets.load_metric("matthews_correlation")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3])
        >>> print(round(results[\'matthews_correlation\'], 2))
        0.54

    Example 2, the same example as above, but also including sample weights:
        >>> matthews_metric = datasets.load_metric("matthews_correlation")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3],
        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])
        >>> print(round(results[\'matthews_correlation\'], 2))
        0.1

    Example 3, the same example as above, but with sample weights that cause a negative correlation:
        >>> matthews_metric = datasets.load_metric("matthews_correlation")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3],
        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])
        >>> print(round(results[\'matthews_correlation\'], 2))
        -0.25
'''

__UpperCAmelCase						=			'''\
@article{scikit-learn,
  title={Scikit-learn: Machine Learning in {P}ython},
  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  journal={Journal of Machine Learning Research},
  volume={12},
  pages={2825--2830},
  year={2011}
}
'''



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,  _KWARGS_DESCRIPTION  )
class 					__UpperCAmelCase							(						datasets.Metric  ):
				def       UpperCAmelCase      (		self    :			Optional[int]    )	->	str:



							'''simple docstring'''



							return datasets.MetricInfo(
							    description=_DESCRIPTION	, citation=_CITATION	, inputs_description=_KWARGS_DESCRIPTION	, features=datasets.Features(
							        {
							            "predictions": datasets.Value("int32"    ),
							            "references": datasets.Value("int32"    ),
							        }    )	, reference_urls=[
							        "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html"
							    ]	, )






				def       UpperCAmelCase      (		self    :			Tuple	, a_    :			Optional[Any]	, a_    :			Optional[Any]	, a_    :			Any=None    )	->	Union[str, Any]:



							'''simple docstring'''



							return {
							    "matthews_correlation": float(matthews_corrcoef(a_	, a_	, sample_weight=a_    )    ),
							}