



'''simple docstring'''






from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


UpperCamelCase__:     List[Any]										=    "\\n@misc{wu2016googles,\n      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n"

UpperCamelCase__:     str										=    "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n"

UpperCamelCase__:     int										=    "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    'google_bleu': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.4\n"

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







 """simple docstring"""






 def   A			(		self    :  Optional[int]	)    ->	MetricInfo:
        return datasets.MetricInfo(
            description=_DESCRIPTION	,    citation=_CITATION	,    inputs_description=_KWARGS_DESCRIPTION	,    features=datasets.Features(
                {
                    '''predictions''': datasets.Sequence(datasets.Value('''string'''	,    id='''token'''	)	,    id='''sequence'''	),
                    '''references''': datasets.Sequence(
                        datasets.Sequence(datasets.Value('''string'''	,    id='''token'''	)	,    id='''sequence'''	)	,    id='''references'''	),
                }	)	,    )







 def   A			(		self    :  str	,    __snake_case    :  List[List[List[str]]]	,    __snake_case    :  List[List[str]]	,    __snake_case    :  int = 1	,    __snake_case    :  int = 4	,    )    ->	Dict[str, float]:
        return {
            "google_bleu": gleu_score.corpus_gleu(
                list_of_references=__snake_case	,    hypotheses=__snake_case	,    min_len=__snake_case	,    max_len=__snake_case	)
        }










'''simple docstring'''






from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


UpperCamelCase__:     int										=    "\\n@article{wang2019superglue,\n  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n  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},\n  journal={arXiv preprint arXiv:1905.00537},\n  year={2019}\n}\n"

UpperCamelCase__:     Dict										=    "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n"

UpperCamelCase__:     str										=    "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n    predictions: list of predictions to score. Depending on the SuperGlUE subset:\n        - for 'record': list of question-answer dictionaries with the following keys:\n            - 'idx': index of the question as specified by the dataset\n            - 'prediction_text': the predicted answer text\n        - for 'multirc': list of question-answer dictionaries with the following keys:\n            - 'idx': index of the question-answer pair as specified by the dataset\n            - 'prediction': the predicted answer label\n        - otherwise: list of predicted labels\n    references: list of reference labels. Depending on the SuperGLUE subset:\n        - for 'record': list of question-answers dictionaries with the following keys:\n            - 'idx': index of the question as specified by the dataset\n            - 'answers': list of possible answers\n        - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n    - for 'record':\n        - 'exact_match': Exact match between answer and gold answer\n        - 'f1': F1 score\n    - for 'multirc':\n        - 'exact_match': Exact match between answer and gold answer\n        - 'f1_m': Per-question macro-F1 score\n        - 'f1_a': Average F1 score over all answers\n    - for 'axb':\n        'matthews_correlation': Matthew Correlation\n    - for 'cb':\n        - 'accuracy': Accuracy\n        - 'f1': F1 score\n    - for all others:\n        - 'accuracy': Accuracy\nExamples:\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'copa')  # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n    >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n    >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 1.0, 'f1': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n    >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def 				snake_case_  (      _lowerCAmelCase						:		str     ,   _lowerCAmelCase						:		Tuple						)   ->     Dict:
							return float((preds == labels).mean()						)


def 				snake_case_  (      _lowerCAmelCase						:		List[Any]     ,   _lowerCAmelCase						:		Union[str, Any]     ,   _lowerCAmelCase						:		Dict="binary"						)   ->     Any:
							UpperCAmelCase				: str											=	simple_accuracy(_lowerCAmelCase     ,   _lowerCAmelCase						)
							UpperCAmelCase				: str											=	float(fa_score(y_true=_lowerCAmelCase     ,   y_pred=_lowerCAmelCase     ,   average=_lowerCAmelCase						)						)
							return {
							    "accuracy": acc,
							    "f1": fa,
							}


def 				snake_case_  (      _lowerCAmelCase						:		int     ,   _lowerCAmelCase						:		str						)   ->     List[str]:
							UpperCAmelCase				: Optional[int]											=	{}
							for id_pred, label in zip(_lowerCAmelCase     ,   _lowerCAmelCase						):
														UpperCAmelCase				: Union[str, Any]											=	f"""{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}"""
														UpperCAmelCase				: List[str]											=	id_pred['''prediction''']
														if question_id in question_map:
																					question_map[question_id].append((pred, label)						)
														else:
																					UpperCAmelCase				: Union[str, Any]											=	[(pred, label)]
							UpperCAmelCase							,	UpperCAmelCase				: Dict											=	[], []
							for question, preds_labels in question_map.items():
														UpperCAmelCase							,	UpperCAmelCase				: List[Any]											=	zip(*_lowerCAmelCase						)
														UpperCAmelCase				: int											=	fa_score(y_true=_lowerCAmelCase     ,   y_pred=_lowerCAmelCase     ,   average='''macro'''						)
														fas.append(_lowerCAmelCase						)
														UpperCAmelCase				: Dict											=	int(sum(pred == label for pred, label in preds_labels						) == len(_lowerCAmelCase						)						)
														ems.append(_lowerCAmelCase						)
							UpperCAmelCase				: int											=	float(sum(_lowerCAmelCase						) / len(_lowerCAmelCase						)						)
							UpperCAmelCase				: Optional[int]											=	sum(_lowerCAmelCase						) / len(_lowerCAmelCase						)
							UpperCAmelCase				: str											=	float(fa_score(y_true=_lowerCAmelCase     ,   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        SCREAMING_SNAKE_CASE(							datasets.Metric    ):







	"""simple docstring"""






	def   A			(		self    :  Optional[Any]	)    ->	Dict:
								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   A			(		self    :  Union[str, Any]	)    ->	Dict:
								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   A			(		self    :  Dict	,    __snake_case    :  str	,    __snake_case    :  str	)    ->	Optional[int]:
								if self.config_name == "axb":
															return {"matthews_correlation": matthews_corrcoef(__snake_case	,    __snake_case	)}
								elif self.config_name == "cb":
															return acc_and_fa(__snake_case	,    __snake_case	,    fa_avg='''macro'''	)
								elif self.config_name == "record":
															UpperCAmelCase				: Tuple											=	[
															    {
															        '''qas''': [
															            {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]}
															            for ref in references
															        ]
															    }
															]
															UpperCAmelCase				: int											=	{pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions}
															return evaluate_record(__snake_case	,    __snake_case	)[0]
								elif self.config_name == "multirc":
															return evaluate_multirc(__snake_case	,    __snake_case	)
								elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
															return {"accuracy": simple_accuracy(__snake_case	,    __snake_case	)}
								else:
															raise KeyError(
															    '''You should supply a configuration name selected in '''
															    '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]'''	)





