



'''simple docstring'''





import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


_lowerCAmelCase      						=	version.parse(importlib_metadata.version('''nltk'''))
if NLTK_VERSION >= version.Version('''3.6.4'''):
 from nltk import word_tokenize


_lowerCAmelCase      						=	'''\
@inproceedings{banarjee2005,
  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},
  author    = {Banerjee, Satanjeev  and Lavie, Alon},
  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},
  month     = jun,
  year      = {2005},
  address   = {Ann Arbor, Michigan},
  publisher = {Association for Computational Linguistics},
  url       = {https://www.aclweb.org/anthology/W05-0909},
  pages     = {65--72},
}
'''

_lowerCAmelCase      						=	'''\
METEOR, an automatic metric for machine translation evaluation
that is based on a generalized concept of unigram matching between the
machine-produced translation and human-produced reference translations.
Unigrams can be matched based on their surface forms, stemmed forms,
and meanings; furthermore, METEOR can be easily extended to include more
advanced matching strategies. Once all generalized unigram matches
between the two strings have been found, METEOR computes a score for
this matching using a combination of unigram-precision, unigram-recall, and
a measure of fragmentation that is designed to directly capture how
well-ordered the matched words in the machine translation are in relation
to the reference.

METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic
data and 0.331 on the Chinese data. This is shown to be an improvement on
using simply unigram-precision, unigram-recall and their harmonic F1
combination.
'''

_lowerCAmelCase      						=	'''
Computes METEOR score of translated segments against one or more references.
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9
    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3
    gamma: Relative weight assigned to fragmentation penalty. default: 0.5
Returns:
    \'meteor\': meteor score.
Examples:

    >>> meteor = datasets.load_metric(\'meteor\')
    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]
    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]
    >>> results = meteor.compute(predictions=predictions, references=references)
    >>> print(round(results["meteor"], 4))
    0.6944
'''






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




  def 							UpperCAmelCase_	(    self      )    ->		Dict:
      return datasets.MetricInfo(
          description=_DESCRIPTION  ,citation=_CITATION  ,inputs_description=_KWARGS_DESCRIPTION  ,features=datasets.Features(
              {
                  """predictions""": datasets.Value("""string"""  ,id="""sequence"""      ),
                  """references""": datasets.Value("""string"""  ,id="""sequence"""      ),
              }      )  ,codebase_urls=["""https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"""]  ,reference_urls=[
              """https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score""",
              """https://en.wikipedia.org/wiki/METEOR""",
          ]  ,)




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		List[Any]:
      import nltk

      nltk.download("""wordnet"""      )
      if NLTK_VERSION >= version.Version("""3.6.5"""      ):
          nltk.download("""punkt"""      )
      if NLTK_VERSION >= version.Version("""3.6.6"""      ):
          nltk.download("""omw-1.4"""      )






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase=0.9  ,__UpperCAmelCase=3  ,__UpperCAmelCase=0.5      )    ->		List[Any]:
      if NLTK_VERSION >= version.Version("""3.6.5"""      ):
          lowerCAmelCase__ :  Optional[int]							      =					[
              meteor_score.single_meteor_score(
                  word_tokenize(__UpperCAmelCase      )  ,word_tokenize(__UpperCAmelCase      )  ,alpha=__UpperCAmelCase  ,beta=__UpperCAmelCase  ,gamma=__UpperCAmelCase      )
              for ref, pred in zip(__UpperCAmelCase  ,__UpperCAmelCase      )
          ]
      else:
          lowerCAmelCase__ :  Dict							      =					[
              meteor_score.single_meteor_score(__UpperCAmelCase  ,__UpperCAmelCase  ,alpha=__UpperCAmelCase  ,beta=__UpperCAmelCase  ,gamma=__UpperCAmelCase      )
              for ref, pred in zip(__UpperCAmelCase  ,__UpperCAmelCase      )
          ]

      return {"meteor": np.mean(__UpperCAmelCase      )}







'''simple docstring'''





import os

from bleurt import score  # From: git+https://github.com/google-research/bleurt.git

import datasets


_lowerCAmelCase      						=	datasets.logging.get_logger(__name__)


_lowerCAmelCase      						=	'''\
@inproceedings{bleurt,
  title={BLEURT: Learning Robust Metrics for Text Generation},
  author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},
  booktitle={ACL},
  year={2020},
  url={https://arxiv.org/abs/2004.04696}
}
'''

_lowerCAmelCase      						=	'''\
BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)
and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune
it for your specific application (the latter is expected to perform better).

See the project\'s README at https://github.com/google-research/bleurt#readme for more information.
'''

_lowerCAmelCase      						=	'''
BLEURT score.

Args:
    `predictions` (list of str): prediction/candidate sentences
    `references` (list of str): reference sentences
    `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.

Returns:
    \'scores\': List of scores.
Examples:

    >>> predictions = ["hello there", "general kenobi"]
    >>> references = ["hello there", "general kenobi"]
    >>> bleurt = datasets.load_metric("bleurt")
    >>> results = bleurt.compute(predictions=predictions, references=references)
    >>> print([round(v, 2) for v in results["scores"]])
    [1.03, 1.04]
'''

_lowerCAmelCase      						=	{
    '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''',
    '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''',
    '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''',
    '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''',
    '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''',
    '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''',
    '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''',
    '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''',
    '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''',
    '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''',
}






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




  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      return datasets.MetricInfo(
          description=_DESCRIPTION  ,citation=_CITATION  ,homepage="""https://github.com/google-research/bleurt"""  ,inputs_description=_KWARGS_DESCRIPTION  ,features=datasets.Features(
              {
                  """predictions""": datasets.Value("""string"""  ,id="""sequence"""      ),
                  """references""": datasets.Value("""string"""  ,id="""sequence"""      ),
              }      )  ,codebase_urls=["""https://github.com/google-research/bleurt"""]  ,reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""]  ,)




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Tuple:
      # check that config name specifies a valid BLEURT model
      if self.config_name == "default":
          logger.warning(
              """Using default BLEURT-Base checkpoint for sequence maximum length 128. """
              """You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512')."""      )
          lowerCAmelCase__ :  str							      =					"""bleurt-base-128"""

      if self.config_name.lower() in CHECKPOINT_URLS:
          lowerCAmelCase__ :  Union[str, Any]							      =					self.config_name.lower()

      elif self.config_name.upper() in CHECKPOINT_URLS:
          lowerCAmelCase__ :  List[Any]							      =					self.config_name.upper()

      else:
          raise KeyError(
              F"""{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}"""      )

      # download the model checkpoint specified by self.config_name and set up the scorer
      lowerCAmelCase__ :  int							      =					dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name]      )
      lowerCAmelCase__ :  Dict							      =					score.BleurtScorer(os.path.join(__UpperCAmelCase  ,__UpperCAmelCase      )      )






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Union[str, Any]:
      lowerCAmelCase__ :  Union[str, Any]							      =					self.scorer.score(references=__UpperCAmelCase  ,candidates=__UpperCAmelCase      )
      return {"scores": scores}


