



"""simple docstring"""





import re
import string
from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


__lowerCAmelCase       :					List[str]      					=					'''
@inproceedings{xu-etal-2016-optimizing,
    title = {Optimizing Statistical Machine Translation for Text Simplification},
    authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},
    journal = {Transactions of the Association for Computational Linguistics},
    volume = {4},
    year={2016},
    url = {https://www.aclweb.org/anthology/Q16-1029},
    pages = {401--415
},
@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       :					Optional[int]      					=					'''\
WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU
It can be used to evaluate the quality of machine-generated texts.
'''


__lowerCAmelCase       :					Dict      					=					'''
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.
Args:
    sources: list of source sentences where each sentence should be a string.
    predictions: list of predicted sentences where each sentence should be a string.
    references: list of lists of reference sentences where each sentence should be a string.
Returns:
    sari: sari score
    sacrebleu: sacrebleu score
    exact: exact score

Examples:
    >>> sources=["About 95 species are currently accepted ."]
    >>> predictions=["About 95 you now get in ."]
    >>> references=[["About 95 species are currently known ."]]
    >>> wiki_split = datasets.load_metric("wiki_split")
    >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)
    >>> print(results)
    {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}
'''
def 	__lowerCAmelCase						(		__UpperCamelCase      :			int    ):


						'''simple docstring'''






						def remove_articles(__UpperCamelCase      :			str    ):
												snake_case_   : Tuple						=			re.compile(r"""\b(a|an|the)\b"""					, re.UNICODE    )
												return re.sub(__UpperCamelCase					, """ """					, __UpperCamelCase    )

						def white_space_fix(__UpperCamelCase      :			Optional[Any]    ):
												return " ".join(text.split()    )

						def remove_punc(__UpperCamelCase      :			Any    ):
												snake_case_   : Optional[int]						=			set(string.punctuation    )
												return "".join(ch for ch in text if ch not in exclude    )

						def lower(__UpperCamelCase      :			Dict    ):
												return text.lower()

						return white_space_fix(remove_articles(remove_punc(lower(__UpperCamelCase    )    )    )    )
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			Optional[int]    ):


						'''simple docstring'''






						return int(normalize_answer(__UpperCamelCase    ) == normalize_answer(__UpperCamelCase    )    )
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			List[Any]    ):


						'''simple docstring'''






						snake_case_   : Optional[Any]						=			[any(compute_exact(__UpperCamelCase					, __UpperCamelCase    ) for ref in refs    ) for pred, refs in zip(__UpperCamelCase					, __UpperCamelCase    )]
						return (sum(__UpperCamelCase    ) / len(__UpperCamelCase    )) * 1_0_0
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Any					, __UpperCamelCase      :			Union[str, Any]					, __UpperCamelCase      :			int					, __UpperCamelCase      :			Union[str, Any]    ):


						'''simple docstring'''






						snake_case_   : Dict						=			[rgram for rgrams in rgramslist for rgram in rgrams]
						snake_case_   : List[str]						=			Counter(__UpperCamelCase    )

						snake_case_   : str						=			Counter(__UpperCamelCase    )
						snake_case_   : str						=			Counter()
						for sgram, scount in sgramcounter.items():
												snake_case_   : Optional[int]						=			scount * numref

						snake_case_   : int						=			Counter(__UpperCamelCase    )
						snake_case_   : Tuple						=			Counter()
						for cgram, ccount in cgramcounter.items():
												snake_case_   : str						=			ccount * numref

						# KEEP
						snake_case_   : Optional[Any]						=			sgramcounter_rep & cgramcounter_rep
						snake_case_   : Dict						=			keepgramcounter_rep & rgramcounter
						snake_case_   : Optional[Any]						=			sgramcounter_rep & rgramcounter

						snake_case_   : Optional[int]						=			0
						snake_case_   : Tuple						=			0
						for keepgram in keepgramcountergood_rep:
												keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
												# Fix an alleged bug [2] in the keep score computation.
												# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
												keeptmpscorea += keepgramcountergood_rep[keepgram]
						# Define 0/0=1 instead of 0 to give higher scores for predictions that match
						#      a target exactly.
						snake_case_   : Optional[int]						=			1
						snake_case_   : Tuple						=			1
						if len(__UpperCamelCase    ) > 0:
												snake_case_   : int						=			keeptmpscorea / len(__UpperCamelCase    )
						if len(__UpperCamelCase    ) > 0:
												# Fix an alleged bug [2] in the keep score computation.
												# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
												snake_case_   : List[str]						=			keeptmpscorea / sum(keepgramcounterall_rep.values()    )
						snake_case_   : Tuple						=			0
						if keepscore_precision > 0 or keepscore_recall > 0:
												snake_case_   : Union[str, Any]						=			2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)

						# DELETION
						snake_case_   : Union[str, Any]						=			sgramcounter_rep - cgramcounter_rep
						snake_case_   : Optional[Any]						=			delgramcounter_rep - rgramcounter
						snake_case_   : Tuple						=			sgramcounter_rep - rgramcounter
						snake_case_   : Optional[Any]						=			0
						snake_case_   : Dict						=			0
						for delgram in delgramcountergood_rep:
												deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
												deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
						# Define 0/0=1 instead of 0 to give higher scores for predictions that match
						# a target exactly.
						snake_case_   : str						=			1
						if len(__UpperCamelCase    ) > 0:
												snake_case_   : Tuple						=			deltmpscorea / len(__UpperCamelCase    )

						# ADDITION
						snake_case_   : Any						=			set(__UpperCamelCase    ) - set(__UpperCamelCase    )
						snake_case_   : Tuple						=			set(__UpperCamelCase    ) & set(__UpperCamelCase    )
						snake_case_   : Union[str, Any]						=			set(__UpperCamelCase    ) - set(__UpperCamelCase    )

						snake_case_   : int						=			0
						for addgram in addgramcountergood:
												addtmpscore += 1

						# Define 0/0=1 instead of 0 to give higher scores for predictions that match
						# a target exactly.
						snake_case_   : Tuple						=			1
						snake_case_   : Optional[Any]						=			1
						if len(__UpperCamelCase    ) > 0:
												snake_case_   : Dict						=			addtmpscore / len(__UpperCamelCase    )
						if len(__UpperCamelCase    ) > 0:
												snake_case_   : Tuple						=			addtmpscore / len(__UpperCamelCase    )
						snake_case_   : int						=			0
						if addscore_precision > 0 or addscore_recall > 0:
												snake_case_   : Optional[int]						=			2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

						return (keepscore, delscore_precision, addscore)
def 	__lowerCAmelCase						(		__UpperCamelCase      :			List[str]					, __UpperCamelCase      :			Tuple					, __UpperCamelCase      :			List[str]    ):


						'''simple docstring'''






						snake_case_   : List[str]						=			len(__UpperCamelCase    )

						snake_case_   : Union[str, Any]						=			ssent.split(""" """    )
						snake_case_   : Optional[Any]						=			csent.split(""" """    )
						snake_case_   : int						=			[]
						snake_case_   : int						=			[]
						snake_case_   : Optional[int]						=			[]
						snake_case_   : List[str]						=			[]
						snake_case_   : str						=			[]
						snake_case_   : Union[str, Any]						=			[]

						snake_case_   : Dict						=			[]
						snake_case_   : List[str]						=			[]
						snake_case_   : int						=			[]
						snake_case_   : Dict						=			[]
						for rsent in rsents:
												snake_case_   : Any						=			rsent.split(""" """    )
												snake_case_   : List[str]						=			[]
												snake_case_   : Tuple						=			[]
												snake_case_   : Optional[Any]						=			[]
												ragramslist.append(__UpperCamelCase    )
												for i in range(0					, len(__UpperCamelCase    ) - 1    ):
																		if i < len(__UpperCamelCase    ) - 1:
																								snake_case_   : Optional[int]						=			ragrams[i] + """ """ + ragrams[i + 1]
																								ragrams.append(__UpperCamelCase    )
																		if i < len(__UpperCamelCase    ) - 2:
																								snake_case_   : Union[str, Any]						=			ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2]
																								ragrams.append(__UpperCamelCase    )
																		if i < len(__UpperCamelCase    ) - 3:
																								snake_case_   : Union[str, Any]						=			ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3]
																								ragrams.append(__UpperCamelCase    )
												ragramslist.append(__UpperCamelCase    )
												ragramslist.append(__UpperCamelCase    )
												ragramslist.append(__UpperCamelCase    )

						for i in range(0					, len(__UpperCamelCase    ) - 1    ):
												if i < len(__UpperCamelCase    ) - 1:
																		snake_case_   : Optional[Any]						=			sagrams[i] + """ """ + sagrams[i + 1]
																		sagrams.append(__UpperCamelCase    )
												if i < len(__UpperCamelCase    ) - 2:
																		snake_case_   : List[str]						=			sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2]
																		sagrams.append(__UpperCamelCase    )
												if i < len(__UpperCamelCase    ) - 3:
																		snake_case_   : Optional[Any]						=			sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3]
																		sagrams.append(__UpperCamelCase    )

						for i in range(0					, len(__UpperCamelCase    ) - 1    ):
												if i < len(__UpperCamelCase    ) - 1:
																		snake_case_   : Union[str, Any]						=			cagrams[i] + """ """ + cagrams[i + 1]
																		cagrams.append(__UpperCamelCase    )
												if i < len(__UpperCamelCase    ) - 2:
																		snake_case_   : Any						=			cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2]
																		cagrams.append(__UpperCamelCase    )
												if i < len(__UpperCamelCase    ) - 3:
																		snake_case_   : Optional[int]						=			cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3]
																		cagrams.append(__UpperCamelCase    )

						((snake_case_)			,		(snake_case_)			,		(snake_case_))   : Tuple						=			SARIngram(__UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase    )
						((snake_case_)			,		(snake_case_)			,		(snake_case_))   : Any						=			SARIngram(__UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase    )
						((snake_case_)			,		(snake_case_)			,		(snake_case_))   : Any						=			SARIngram(__UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase    )
						((snake_case_)			,		(snake_case_)			,		(snake_case_))   : str						=			SARIngram(__UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase    )
						snake_case_   : Dict						=			sum([keepascore, keepascore, keepascore, keepascore]    ) / 4
						snake_case_   : Tuple						=			sum([delascore, delascore, delascore, delascore]    ) / 4
						snake_case_   : Any						=			sum([addascore, addascore, addascore, addascore]    ) / 4
						snake_case_   : Tuple						=			(avgkeepscore + avgdelscore + avgaddscore) / 3
						return finalscore
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			bool = True					, __UpperCamelCase      :			str = "13a"					, __UpperCamelCase      :			bool = True    ):


						'''simple docstring'''






						if lowercase:
												snake_case_   : Optional[int]						=			sentence.lower()

						if tokenizer in ["13a", "intl"]:
												if version.parse(sacrebleu.__version__    ).major >= 2:
																		snake_case_   : str						=			sacrebleu.metrics.bleu._get_tokenizer(__UpperCamelCase    )()(__UpperCamelCase    )
												else:
																		snake_case_   : Optional[int]						=			sacrebleu.TOKENIZERS[tokenizer]()(__UpperCamelCase    )
						elif tokenizer == "moses":
												snake_case_   : int						=			sacremoses.MosesTokenizer().tokenize(__UpperCamelCase					, return_str=__UpperCamelCase					, escape=__UpperCamelCase    )
						elif tokenizer == "penn":
												snake_case_   : Tuple						=			sacremoses.MosesTokenizer().penn_tokenize(__UpperCamelCase					, return_str=__UpperCamelCase    )
						else:
												snake_case_   : str						=			sentence

						if not return_str:
												snake_case_   : List[Any]						=			normalized_sent.split()

						return normalized_sent
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Union[str, Any]					, __UpperCamelCase      :			Dict					, __UpperCamelCase      :			Tuple    ):


						'''simple docstring'''






						if not (len(__UpperCamelCase    ) == len(__UpperCamelCase    ) == len(__UpperCamelCase    )):
												raise ValueError("""Sources length must match predictions and references lengths."""    )
						snake_case_   : Dict						=			0
						for src, pred, refs in zip(__UpperCamelCase					, __UpperCamelCase					, __UpperCamelCase    ):
												sari_score += SARIsent(normalize(__UpperCamelCase    )					, normalize(__UpperCamelCase    )					, [normalize(__UpperCamelCase    ) for sent in refs]    )
						snake_case_   : Dict						=			sari_score / len(__UpperCamelCase    )
						return 1_0_0 * sari_score
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Optional[int]					, __UpperCamelCase      :			List[Any]					, __UpperCamelCase      :			List[Any]="exp"					, __UpperCamelCase      :			Dict=None					, __UpperCamelCase      :			Optional[int]=False					, __UpperCamelCase      :			str=False					, __UpperCamelCase      :			int=False					, ):


						'''simple docstring'''






						snake_case_   : str						=			len(references[0]    )
						if any(len(__UpperCamelCase    ) != 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(__UpperCamelCase    )]
						snake_case_   : List[Any]						=			sacrebleu.corpus_bleu(
						    __UpperCamelCase					, __UpperCamelCase					, smooth_method=__UpperCamelCase					, smooth_value=__UpperCamelCase					, force=__UpperCamelCase					, lowercase=__UpperCamelCase					, use_effective_order=__UpperCamelCase					, )
						return output.score






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,				_KWARGS_DESCRIPTION		)
class    _lowerCAmelCase    (				datasets.Metric		):





		"""simple docstring"""






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







								'''simple docstring'''

								return datasets.MetricInfo(
								    description=_DESCRIPTION							,    citation=_CITATION							,    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/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py""",
								        """https://github.com/cocoxu/simplification/blob/master/SARI.py""",
								        """https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py""",
								        """https://github.com/mjpost/sacreBLEU""",
								    ]							,    reference_urls=[
								        """https://www.aclweb.org/anthology/Q16-1029.pdf""",
								        """https://github.com/mjpost/sacreBLEU""",
								        """https://en.wikipedia.org/wiki/BLEU""",
								        """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""",
								    ]							,    )





		def    UpperCAmelCase__							(					self							,    _lowercase							,    _lowercase							,    _lowercase   ) ->						List[str]:







								'''simple docstring'''

								snake_case_   : int						=			{}
								result.update({"""sari""": compute_sari(sources=_lowercase							,    predictions=_lowercase							,    references=_lowercase   )}   )
								result.update({"""sacrebleu""": compute_sacrebleu(predictions=_lowercase							,    references=_lowercase   )}   )
								result.update({"""exact""": compute_em(predictions=_lowercase							,    references=_lowercase   )}   )
								return result






"""simple docstring"""





from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


__lowerCAmelCase       :					List[str]      					=					'''\
@article{wang2019superglue,
  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
  author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},
  journal={arXiv preprint arXiv:1905.00537},
  year={2019}
}
'''

__lowerCAmelCase       :					Optional[Any]      					=					'''\
SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after
GLUE with a new set of more difficult language understanding tasks, improved
resources, and a new public leaderboard.
'''

__lowerCAmelCase       :					str      					=					'''
Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset.
Args:
    predictions: list of predictions to score. Depending on the SuperGlUE subset:
        - for \'record\': list of question-answer dictionaries with the following keys:
            - \'idx\': index of the question as specified by the dataset
            - \'prediction_text\': the predicted answer text
        - for \'multirc\': list of question-answer dictionaries with the following keys:
            - \'idx\': index of the question-answer pair as specified by the dataset
            - \'prediction\': the predicted answer label
        - otherwise: list of predicted labels
    references: list of reference labels. Depending on the SuperGLUE subset:
        - for \'record\': list of question-answers dictionaries with the following keys:
            - \'idx\': index of the question as specified by the dataset
            - \'answers\': list of possible answers
        - otherwise: list of reference labels
Returns: depending on the SuperGLUE subset:
    - for \'record\':
        - \'exact_match\': Exact match between answer and gold answer
        - \'f1\': F1 score
    - for \'multirc\':
        - \'exact_match\': Exact match between answer and gold answer
        - \'f1_m\': Per-question macro-F1 score
        - \'f1_a\': Average F1 score over all answers
    - for \'axb\':
        \'matthews_correlation\': Matthew Correlation
    - for \'cb\':
        - \'accuracy\': Accuracy
        - \'f1\': F1 score
    - for all others:
        - \'accuracy\': Accuracy
Examples:

    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\')  # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0}

    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0, \'f1\': 1.0}

    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')
    >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]
    >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact_match\': 1.0, \'f1\': 1.0}

    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')
    >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}

    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'matthews_correlation\': 1.0}
'''
def 	__lowerCAmelCase						(		__UpperCamelCase      :			List[str]					, __UpperCamelCase      :			Any    ):


						'''simple docstring'''






						return float((preds == labels).mean()    )
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Any					, __UpperCamelCase      :			Optional[int]					, __UpperCamelCase      :			str="binary"    ):


						'''simple docstring'''






						snake_case_   : Optional[Any]						=			simple_accuracy(__UpperCamelCase					, __UpperCamelCase    )
						snake_case_   : Dict						=			float(fa_score(y_true=__UpperCamelCase					, y_pred=__UpperCamelCase					, average=__UpperCamelCase    )    )
						return {
						    "accuracy": acc,
						    "f1": fa,
						}
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			int    ):


						'''simple docstring'''






						snake_case_   : List[Any]						=			{}
						for id_pred, label in zip(__UpperCamelCase					, __UpperCamelCase    ):
												snake_case_   : Optional[int]						=			F'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}'
												snake_case_   : Union[str, Any]						=			id_pred["""prediction"""]
												if question_id in question_map:
																		question_map[question_id].append((pred, label)    )
												else:
																		snake_case_   : str						=			[(pred, label)]
						snake_case_			,		snake_case_   : List[str]						=			[], []
						for question, preds_labels in question_map.items():
												snake_case_			,		snake_case_   : Optional[Any]						=			zip(*__UpperCamelCase    )
												snake_case_   : int						=			fa_score(y_true=__UpperCamelCase					, y_pred=__UpperCamelCase					, average="""macro"""    )
												fas.append(__UpperCamelCase    )
												snake_case_   : Dict						=			int(sum(pred == label for pred, label in preds_labels    ) == len(__UpperCamelCase    )    )
												ems.append(__UpperCamelCase    )
						snake_case_   : Optional[int]						=			float(sum(__UpperCamelCase    ) / len(__UpperCamelCase    )    )
						snake_case_   : Any						=			sum(__UpperCamelCase    ) / len(__UpperCamelCase    )
						snake_case_   : int						=			float(fa_score(y_true=__UpperCamelCase					, y_pred=[id_pred["""prediction"""] for id_pred in ids_preds]    )    )
						return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a}






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,				_KWARGS_DESCRIPTION		)
class    _lowerCAmelCase    (				datasets.Metric		):





		"""simple docstring"""






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







								'''simple docstring'''

								if self.config_name not in [
								    "boolq",
								    "cb",
								    "copa",
								    "multirc",
								    "record",
								    "rte",
								    "wic",
								    "wsc",
								    "wsc.fixed",
								    "axb",
								    "axg",
								]:
														raise KeyError(
														    """You should supply a configuration name selected in """
														    """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]"""   )
								return datasets.MetricInfo(
								    description=_DESCRIPTION							,    citation=_CITATION							,    inputs_description=_KWARGS_DESCRIPTION							,    features=datasets.Features(self._get_feature_types()   )							,    codebase_urls=[]							,    reference_urls=[]							,    format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None							,    )





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







								'''simple docstring'''

								if self.config_name == "record":
														return {
														    "predictions": {
														        "idx": {
														            "passage": datasets.Value("""int64"""   ),
														            "query": datasets.Value("""int64"""   ),
														        },
														        "prediction_text": datasets.Value("""string"""   ),
														    },
														    "references": {
														        "idx": {
														            "passage": datasets.Value("""int64"""   ),
														            "query": datasets.Value("""int64"""   ),
														        },
														        "answers": datasets.Sequence(datasets.Value("""string"""   )   ),
														    },
														}
								elif self.config_name == "multirc":
														return {
														    "predictions": {
														        "idx": {
														            "answer": datasets.Value("""int64"""   ),
														            "paragraph": datasets.Value("""int64"""   ),
														            "question": datasets.Value("""int64"""   ),
														        },
														        "prediction": datasets.Value("""int64"""   ),
														    },
														    "references": datasets.Value("""int64"""   ),
														}
								else:
														return {
														    "predictions": datasets.Value("""int64"""   ),
														    "references": datasets.Value("""int64"""   ),
														}





		def    UpperCAmelCase__							(					self							,    _lowercase							,    _lowercase   ) ->						List[str]:







								'''simple docstring'''

								if self.config_name == "axb":
														return {"matthews_correlation": matthews_corrcoef(_lowercase							,    _lowercase   )}
								elif self.config_name == "cb":
														return acc_and_fa(_lowercase							,    _lowercase							,    fa_avg="""macro"""   )
								elif self.config_name == "record":
														snake_case_   : Optional[Any]						=			[
														    {
														        """qas""": [
														            {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]}
														            for ref in references
														        ]
														    }
														]
														snake_case_   : Dict						=			{pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions}
														return evaluate_record(_lowercase							,    _lowercase   )[0]
								elif self.config_name == "multirc":
														return evaluate_multirc(_lowercase							,    _lowercase   )
								elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
														return {"accuracy": simple_accuracy(_lowercase							,    _lowercase   )}
								else:
														raise KeyError(
														    """You should supply a configuration name selected in """
														    """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]"""   )

