


'''simple docstring'''






import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


lowercase				='\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",\n    author = "Lin, Chin-Yew  and\n      Och, Franz Josef",\n    booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",\n    month = "aug 23{--}aug 27",\n    year = "2004",\n    address = "Geneva, Switzerland",\n    publisher = "COLING",\n    url = "https://www.aclweb.org/anthology/C04-1072",\n    pages = "501--507",\n}\n'

lowercase				='\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation,\nthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n'

lowercase				='\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    \'bleu\': bleu score,\n    \'precisions\': geometric mean of n-gram precisions,\n    \'brevity_penalty\': brevity penalty,\n    \'length_ratio\': ratio of lengths,\n    \'translation_length\': translation_length,\n    \'reference_length\': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     ["hello", "there", "general", "kenobi"],                             # tokenized prediction of the first sample\n    ...     ["foo", "bar", "foobar"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]],  # tokenized references for the first sample (2 references)\n    ...     [["foo", "bar", "foobar"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric("bleu")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results["bleu"])\n    1.0\n'






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






       def      lowerCAmelCase						(     self)		->    List[str]:




          '''simple docstring'''
          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'),
                  })    ,				codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py']    ,				reference_urls=[
                  'https://en.wikipedia.org/wiki/BLEU',
                  'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213',
              ]    ,				)






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case    ,				snake_case=4    ,				snake_case=False)		->    Optional[int]:




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[int]				       =compute_bleu(
              reference_corpus=snake_case    ,				translation_corpus=snake_case    ,				max_order=snake_case    ,				smooth=snake_case)
          ((_UpperCAmelCase)       ,			(_UpperCAmelCase)       ,			(_UpperCAmelCase)       ,			(_UpperCAmelCase)       ,			(_UpperCAmelCase)       ,			(_UpperCAmelCase))  :  Any				       =score
          return {
              "bleu": bleu,
              "precisions": precisions,
              "brevity_penalty": bp,
              "length_ratio": ratio,
              "translation_length": translation_length,
              "reference_length": reference_length,
          }





'''simple docstring'''






from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


lowercase				='\\n@inproceedings{wang2019glue,\n  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n  note={In the Proceedings of ICLR.},\n  year={2019}\n}\n'

lowercase				='\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n'

lowercase				='\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n    "accuracy": Accuracy\n    "f1": F1 score\n    "pearson": Pearson Correlation\n    "spearmanr": Spearman Correlation\n    "matthews_correlation": Matthew Correlation\nExamples:\n\n    >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\')  # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'accuracy\': 1.0}\n\n    >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\')  # \'mrpc\' or \'qqp\'\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'accuracy\': 1.0, \'f1\': 1.0}\n\n    >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\')\n    >>> references = [0., 1., 2., 3., 4., 5.]\n    >>> predictions = [0., 1., 2., 3., 4., 5.]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)})\n    {\'pearson\': 1.0, \'spearmanr\': 1.0}\n\n    >>> glue_metric = datasets.load_metric(\'glue\', \'cola\')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'matthews_correlation\': 1.0}\n'





def lowerCamelCase__     (		__lowerCamelCase			:				Optional[Any]			,       __lowerCamelCase			:				str				):







   '''simple docstring'''




   return float((preds == labels).mean()				)





def lowerCamelCase__     (		__lowerCamelCase			:				Tuple			,       __lowerCamelCase			:				Union[str, Any]				):







   '''simple docstring'''




   _UpperCAmelCase  :  Union[str, Any]				       =simple_accuracy(__lowerCamelCase			,       __lowerCamelCase				)
   _UpperCAmelCase  :  List[Any]				       =float(fa_score(y_true=__lowerCamelCase			,       y_pred=__lowerCamelCase				)				)
   return {
       "accuracy": acc,
       "f1": fa,
   }





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				int				):







   '''simple docstring'''




   _UpperCAmelCase  :  Dict				       =float(pearsonr(__lowerCamelCase			,       __lowerCamelCase				)[0]				)
   _UpperCAmelCase  :  int				       =float(spearmanr(__lowerCamelCase			,       __lowerCamelCase				)[0]				)
   return {
       "pearson": pearson_corr,
       "spearmanr": spearman_corr,
   }






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






       def      lowerCAmelCase						(     self)		->    str:




          '''simple docstring'''
          if self.config_name not in [
              "sst2",
              "mnli",
              "mnli_mismatched",
              "mnli_matched",
              "cola",
              "stsb",
              "mrpc",
              "qqp",
              "qnli",
              "rte",
              "wnli",
              "hans",
          ]:
             raise KeyError(
                 'You should supply a configuration name selected in '
                 '["sst2", "mnli", "mnli_mismatched", "mnli_matched", '
                 '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]')
          return datasets.MetricInfo(
              description=_DESCRIPTION    ,				citation=_CITATION    ,				inputs_description=_KWARGS_DESCRIPTION    ,				features=datasets.Features(
                  {
                      'predictions': datasets.Value('int64' if self.config_name != 'stsb' else 'float32'),
                      'references': datasets.Value('int64' if self.config_name != 'stsb' else 'float32'),
                  })    ,				codebase_urls=[]    ,				reference_urls=[]    ,				format='numpy'    ,				)






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case)		->    int:




          '''simple docstring'''
          if self.config_name == "cola":
             return {"matthews_correlation": matthews_corrcoef(snake_case    ,				snake_case)}
          elif self.config_name == "stsb":
             return pearson_and_spearman(snake_case    ,				snake_case)
          elif self.config_name in ["mrpc", "qqp"]:
             return acc_and_fa(snake_case    ,				snake_case)
          elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
             return {"accuracy": simple_accuracy(snake_case    ,				snake_case)}
          else:
             raise KeyError(
                 'You should supply a configuration name selected in '
                 '["sst2", "mnli", "mnli_mismatched", "mnli_matched", '
                 '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]')

