






'''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
__lowerCamelCase   :					Tuple   							=					'''src/transformers'''
__lowerCamelCase   :					Any   							=					'''docs/source/en'''
__lowerCamelCase   :					str   							=					'''.'''

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__						)->    List[Any]:



			"""simple docstring"""



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

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


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

def 	__UpperCAmelCase       ( __magic_name__						)->    Optional[Any]:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    Optional[int]:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( )->    Dict:



			"""simple docstring"""



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

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

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

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

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

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

def 	__UpperCAmelCase       ( __magic_name__=False						)->    Tuple:



			"""simple docstring"""



			snake_case_,	snake_case_,	snake_case_,	snake_case_				:					List[Any]   =       _find_text_in_file(
			    filename=os.path.join(__magic_name__     ,"index.md"						)     ,start_prompt="<!--This table is updated automatically from the auto modules"     ,end_prompt="<!-- End table-->"     ,)
			snake_case_				:					List[Any]   =       get_model_table_from_auto_modules()

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

		check_model_table(args.fix_and_overwrite)












'''simple docstring'''




import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


__lowerCamelCase   :					str   							=					'''\
@inproceedings{snover-etal-2006-study,
    title = "A Study of Translation Edit Rate with Targeted Human Annotation",
    author = "Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John",
    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",
    month = aug # " 8-12",
    year = "2006",
    address = "Cambridge, Massachusetts, USA",
    publisher = "Association for Machine Translation in the Americas",
    url = "https://aclanthology.org/2006.amta-papers.25",
    pages = "223--231",
}
@inproceedings{post-2018-call,
    title = "A Call for Clarity in Reporting {BLEU} Scores",
    author = "Post, Matt",
    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
    month = oct,
    year = "2018",
    address = "Belgium, Brussels",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W18-6319",
    pages = "186--191",
}
'''

__lowerCamelCase   :					Dict   							=					'''\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
'''

__lowerCamelCase   :					int   							=					'''
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)
    \'num_edits\' (int): The cumulative number of edits
    \'ref_length\' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?",
        ...                     "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}

    Example 2:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}

    Example 3:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}

    Example 4:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}

    Example 5:
        >>> predictions = ["does this sentence match??",
        ...                    "what about this sentence?",
        ...                    "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION							)
class    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:Optional[Any]				)				->  Optional[int]:


										'''simple docstring'''




										if version.parse(scb.__version__				) < version.parse("1.4.12"				):
													raise ImportWarning(
													    "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
													    "You can install it with `pip install \"sacrebleu>=1.4.12\"`."				)
										return datasets.MetricInfo(
										    description=_DESCRIPTION       ,							citation=_CITATION       ,							homepage="http://www.cs.umd.edu/~snover/tercom/"       ,							inputs_description=_KWARGS_DESCRIPTION       ,							features=datasets.Features(
										        {
										            "predictions": datasets.Value("string"       ,							id="sequence"				),
										            "references": datasets.Sequence(datasets.Value("string"       ,							id="sequence"				)       ,							id="references"				),
										        }				)       ,							codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]       ,							reference_urls=[
										        "https://github.com/jhclark/tercom",
										    ]       ,							)






							def 							_A	(		self			:Any       ,							lowerCAmelCase__			:Any       ,							lowerCAmelCase__			:str       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					List[str]   =       len(references[0]				)
										if any(len(lowerCAmelCase__				) != references_per_prediction for refs in references				):
													raise ValueError("Sacrebleu requires the same number of references for each prediction"				)
										snake_case_				:					List[str]   =       [[refs[i] for refs in references] for i in range(lowerCAmelCase__				)]

										snake_case_				:					List[str]   =       TER(
										    normalized=lowerCAmelCase__       ,							no_punct=lowerCAmelCase__       ,							asian_support=lowerCAmelCase__       ,							case_sensitive=lowerCAmelCase__       ,							)
										snake_case_				:					Any   =       sb_ter.corpus_score(lowerCAmelCase__       ,							lowerCAmelCase__				)

										return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}




