





"""simple docstring"""






import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
  import torch_xla.core.xla_model as xm
  import torch_xla.debug.metrics as met




class 			__lowercase     (     _UpperCamelCase							):







     '''simple docstring'''




     def __init__(  self		,     *_UpperCAmelCase		,     _UpperCAmelCase=None		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
         super().__init__(*__UpperCAmelCase		,     **__UpperCAmelCase       )
         __a	:  Dict         =					eval_examples
         __a	:  Any         =					post_process_function







     def 	_lowerCamelCase						(  self		,     _UpperCAmelCase = None		,     _UpperCAmelCase=None		,     _UpperCAmelCase = None		,     _UpperCAmelCase = "eval"		,     **_UpperCAmelCase		,     ):
         __a	:  Dict         =					gen_kwargs.copy()
         __a	:  List[str]         =					(
             gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''       ) is not None else self.args.generation_max_length
         )
         __a	:  Dict         =					(
             gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''       ) is not None else self.args.generation_num_beams
         )
         __a	:  str         =					gen_kwargs

         __a	:  Any         =					self.eval_dataset if eval_dataset is None else eval_dataset
         __a	:  List[str]         =					self.get_eval_dataloader(__UpperCAmelCase       )
         __a	:  Optional[int]         =					self.eval_examples if eval_examples is None else eval_examples

         # Temporarily disable metric computation, we will do it in the loop here.
         __a	:  Optional[Any]         =					self.compute_metrics
         __a	:  Optional[Any]         =					None
         __a	:  List[str]         =					time.time()
         __a	:  Optional[int]         =					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         try:
             __a	:  Tuple         =					eval_loop(
                 __UpperCAmelCase		,     description='''Evaluation'''		,     prediction_loss_only=True if compute_metrics is None else None		,     ignore_keys=__UpperCAmelCase		,     metric_key_prefix=__UpperCAmelCase		,     )
         finally:
             __a	:  List[str]         =					compute_metrics
         __a	:  str         =					self.args.eval_batch_size * self.args.world_size
         if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
             start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""]
         output.metrics.update(
             speed_metrics(
                 __UpperCAmelCase		,     __UpperCAmelCase		,     num_samples=output.num_samples		,     num_steps=math.ceil(output.num_samples / total_batch_size       )		,     )       )

         if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
             # Only the main node write the results by default
             __a	:  Optional[int]         =					self.post_process_function(__UpperCAmelCase		,     __UpperCAmelCase		,     __UpperCAmelCase       )
             __a	:  Tuple         =					self.compute_metrics(__UpperCAmelCase       )

             # Prefix all keys with metric_key_prefix + '_'
             for key in list(metrics.keys()       ):
                 if not key.startswith(f"""{metric_key_prefix}_"""       ):
                     __a	:  str         =					metrics.pop(__UpperCAmelCase       )

             metrics.update(output.metrics       )
         else:
             __a	:  Any         =					output.metrics

         if self.args.should_log:
             # Only the main node log the results by default
             self.log(__UpperCAmelCase       )

         if self.args.tpu_metrics_debug or self.args.debug:
             # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
             xm.master_print(met.metrics_report()       )

         __a	:  Dict         =					self.callback_handler.on_evaluate(self.args		,     self.state		,     self.control		,     __UpperCAmelCase       )
         return metrics







     def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     _UpperCAmelCase = "test"		,     **_UpperCAmelCase       ):
         __a	:  Dict         =					gen_kwargs.copy()

         __a	:  Dict         =					self.get_test_dataloader(__UpperCAmelCase       )

         # Temporarily disable metric computation, we will do it in the loop here.
         __a	:  int         =					self.compute_metrics
         __a	:  str         =					None
         __a	:  Optional[int]         =					time.time()
         __a	:  int         =					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         try:
             __a	:  Any         =					eval_loop(
                 __UpperCAmelCase		,     description='''Prediction'''		,     prediction_loss_only=True if compute_metrics is None else None		,     ignore_keys=__UpperCAmelCase		,     metric_key_prefix=__UpperCAmelCase		,     )
         finally:
             __a	:  Union[str, Any]         =					compute_metrics

         __a	:  int         =					self.args.eval_batch_size * self.args.world_size
         if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
             start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""]
         output.metrics.update(
             speed_metrics(
                 __UpperCAmelCase		,     __UpperCAmelCase		,     num_samples=output.num_samples		,     num_steps=math.ceil(output.num_samples / total_batch_size       )		,     )       )
         if self.post_process_function is None or self.compute_metrics is None:
             return output

         __a	:  List[str]         =					self.post_process_function(__UpperCAmelCase		,     __UpperCAmelCase		,     __UpperCAmelCase		,     '''predict'''       )
         __a	:  int         =					self.compute_metrics(__UpperCAmelCase       )

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()       ):
             if not key.startswith(f"""{metric_key_prefix}_"""       ):
                 __a	:  List[str]         =					metrics.pop(__UpperCAmelCase       )
         metrics.update(output.metrics       )
         return PredictionOutput(predictions=predictions.predictions		,     label_ids=predictions.label_ids		,     metrics=__UpperCAmelCase       )






"""simple docstring"""






import comet  # From: unbabel-comet
import torch

import datasets


A	     =					datasets.logging.get_logger(__name__)

A	     =					'''\
@inproceedings{rei-EtAl:2020:WMT,
   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},
   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},
   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},
   month          = {November},
   year           = {2020},
   address        = {Online},
   publisher      = {Association for Computational Linguistics},
   pages     = {909--918},
}
@inproceedings{rei-etal-2020-comet,
   title = "{COMET}: A Neural Framework for {MT} Evaluation",
   author = "Rei, Ricardo  and
      Stewart, Craig  and
      Farinha, Ana C  and
      Lavie, Alon",
   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",
   month = nov,
   year = "2020",
   address = "Online",
   publisher = "Association for Computational Linguistics",
   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",
   pages = "2685--2702",
}
'''

A	     =					'''\
Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).
With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.

See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.
'''

A	     =					'''
COMET score.

Args:

`sources` (list of str): Source sentences
`predictions` (list of str): candidate translations
`references` (list of str): reference translations
`cuda` (bool): If set to True, runs COMET using GPU
`show_progress` (bool): Shows progress
`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.

Returns:
    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.
    `scores`: List of scores.

Examples:

    >>> comet_metric = datasets.load_metric(\'comet\')
    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use
    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]
    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]
    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]
    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)
    >>> print([round(v, 2) for v in results["scores"]])
    [0.19, 0.92]
'''




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







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION		,     citation=_CITATION		,     homepage='''https://unbabel.github.io/COMET/html/index.html'''		,     inputs_description=_KWARGS_DESCRIPTION		,     features=datasets.Features(
									        {
									            '''sources''': datasets.Value('''string'''		,     id='''sequence'''       ),
									            '''predictions''': datasets.Value('''string'''		,     id='''sequence'''       ),
									            '''references''': datasets.Value('''string'''		,     id='''sequence'''       ),
									        }       )		,     codebase_urls=['''https://github.com/Unbabel/COMET''']		,     reference_urls=[
									        '''https://github.com/Unbabel/COMET''',
									        '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
									        '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
									    ]		,     )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									if self.config_name == "default":
													__a	:  List[str]         =					comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
									else:
													__a	:  List[str]         =					comet.load_from_checkpoint(comet.download_model(self.config_name       )       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     _UpperCAmelCase=False       ):
									if gpus is None:
													__a	:  str         =					1 if torch.cuda.is_available() else 0
									__a	:  Optional[Any]         =					{'''src''': sources, '''mt''': predictions, '''ref''': references}
									__a	:  Dict         =					[dict(zip(_UpperCAmelCase		,     _UpperCAmelCase       )       ) for t in zip(*data.values()       )]
									__a    ,  __a	:  int         =					self.scorer.predict(_UpperCAmelCase		,     gpus=_UpperCAmelCase		,     progress_bar=_UpperCAmelCase       )
									return {"mean_score": mean_score, "scores": scores}