
'''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 :  Dict    							=       "src/transformers"
_lowercase :  List[Any]    							=       "docs/source/en"
_lowercase :  Optional[Any]    							=       "."
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: Optional[int]      ,      __SCREAMING_SNAKE_CASE					: Tuple      ,      __SCREAMING_SNAKE_CASE					: Optional[Any]							):



						"""simple docstring"""





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

						lowercase_	:     List[str]													=       start_index
						while not lines[end_index].startswith(__SCREAMING_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 :  List[Any]    							=       "Model|Encoder|Decoder|ForConditionalGeneration"
# Regexes that match TF/Flax/PT model names.
_lowercase :  Dict    							=       re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
_lowercase :  Optional[Any]    							=       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 :  str    							=       re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")


# This is to make sure the transformers module imported is the one in the repo.
_lowercase :  Any    							=       direct_transformers_import(TRANSFORMERS_PATH)
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: Optional[int]							):



						"""simple docstring"""





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



						"""simple docstring"""





						lowercase_	:     Union[str, Any]													=       2 if text == '''✅''' or text == '''❌''' else len(__SCREAMING_SNAKE_CASE							)
						lowercase_	:     str													=       (width - text_length) // 2
						lowercase_	:     str													=       width - text_length - left_indent
						return " " * left_indent + text + " " * right_indent
def 					snake_case_		(				):



						"""simple docstring"""





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

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

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

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

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

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



						"""simple docstring"""





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

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

							check_model_table(args.fix_and_overwrite)







import numpy as np
from scipy.spatial.distance import cdist
from sklearn.metrics import fa_score

import datasets


__lowerCAmelCase	: Optional[int]  				='\\n    @inproceedings{kakwani2020indicnlpsuite,\n    title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n    author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n    year={2020},\n    booktitle={Findings of EMNLP},\n}\n'

__lowerCAmelCase	: Optional[Any]  				='\\n    IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n    variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n'

__lowerCAmelCase	: Dict  				='\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n    predictions: list of predictions to score (as int64),\n        except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32).\n    references: list of ground truth labels corresponding to the predictions (as int64),\n        except for \'cvit-mkb-clsr\' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n    "accuracy": Accuracy\n    "f1": F1 score\n    "precision": Precision@10\nExamples:\n\n    >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\')  # \'wnli\' or any of ["copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'accuracy\': 1.0}\n\n    >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'accuracy\': 1.0, \'f1\': 1.0}\n\n    >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\')\n    >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n    >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'precision@10\': 1.0}\n\n'


def        _UpperCamelCase							(      lowercase__    ,       lowercase__      ):
						return float((preds == labels).mean()      )


def        _UpperCamelCase							(      lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		simple_accuracy(lowercase__    ,       lowercase__      )
						__SCREAMING_SNAKE_CASE						:     List[str]					=		float(fa_score(y_true=lowercase__    ,       y_pred=lowercase__      )      )
						return {
						    "accuracy": acc,
						    "f1": fa,
						}


def        _UpperCamelCase							(      lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Optional[int]					=		np.array(lowercase__      )
						__SCREAMING_SNAKE_CASE						:     str					=		np.array(lowercase__      )
						__SCREAMING_SNAKE_CASE						:     str					=		en_sentvecs.shape[0]

						# mean centering
						__SCREAMING_SNAKE_CASE						:     Tuple					=		en_sentvecs - np.mean(lowercase__    ,       axis=0      )
						__SCREAMING_SNAKE_CASE						:     Optional[int]					=		in_sentvecs - np.mean(lowercase__    ,       axis=0      )

						__SCREAMING_SNAKE_CASE						:     str					=		cdist(lowercase__    ,       lowercase__    ,       '''cosine'''      )
						__SCREAMING_SNAKE_CASE						:     int					=		np.array(range(lowercase__      )      )
						__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		sim.argsort(axis=1      )[:, :10]
						__SCREAMING_SNAKE_CASE						:     str					=		np.any(preds == actual[:, None]    ,       axis=1      )
						return float(matches.mean()      )
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,			_KWARGS_DESCRIPTION       )
class        _lowercase      (			datasets.Metric       ):






				'''simple docstring'''



				def 		__magic_name__(       self			:Tuple	)		->			Tuple:
										if self.config_name not in [
										    "wnli",
										    "copa",
										    "sna",
										    "csqa",
										    "wstp",
										    "inltkh",
										    "bbca",
										    "cvit-mkb-clsr",
										    "iitp-mr",
										    "iitp-pr",
										    "actsa-sc",
										    "md",
										    "wiki-ner",
										]:
																raise KeyError(
																    '''You should supply a configuration name selected in '''
																    '''["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", '''
																    '''"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", '''
																    '''"wiki-ner"]'''	)
										return datasets.MetricInfo(
										    description=_DESCRIPTION			,			citation=_CITATION			,			inputs_description=_KWARGS_DESCRIPTION			,			features=datasets.Features(
										        {
										            '''predictions''': datasets.Value('''int64'''	)
										            if self.config_name != '''cvit-mkb-clsr'''
										            else datasets.Sequence(datasets.Value('''float32'''	)	),
										            '''references''': datasets.Value('''int64'''	)
										            if self.config_name != '''cvit-mkb-clsr'''
										            else datasets.Sequence(datasets.Value('''float32'''	)	),
										        }	)			,			codebase_urls=[]			,			reference_urls=[]			,			format='''numpy''' if self.config_name != '''cvit-mkb-clsr''' else None			,			)



				def 		__magic_name__(       self			:List[str]			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:Tuple	)		->			str:
										if self.config_name == "cvit-mkb-clsr":
																return {"precision@10": precision_at_aa(lowerCAmelCase__			,			lowerCAmelCase__	)}
										elif self.config_name in ["wiki-ner"]:
																return acc_and_fa(lowerCAmelCase__			,			lowerCAmelCase__	)
										elif self.config_name in [
										    "wnli",
										    "copa",
										    "sna",
										    "csqa",
										    "wstp",
										    "inltkh",
										    "bbca",
										    "iitp-mr",
										    "iitp-pr",
										    "actsa-sc",
										    "md",
										]:
																return {"accuracy": simple_accuracy(lowerCAmelCase__			,			lowerCAmelCase__	)}
										else:
																raise KeyError(
																    '''You should supply a configuration name selected in '''
																    '''["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", '''
																    '''"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", '''
																    '''"wiki-ner"]'''	)
