





import copy
import re







class     __snake_case       :





       '''simple docstring'''







       lowerCAmelCase__      		=     """hp"""
       lowerCAmelCase__      		=     {}
       lowerCAmelCase__      		=     None




       @classmethod
       def 							UpperCAmelCase__ (  cls :    Optional[Any]							,				A :    List[Any]							,				A :    Tuple		):
         __snake_case:						str   =						prefix
         __snake_case:						List[Any]   =						defaults
         cls.build_naming_info()




       @staticmethod
       def 							UpperCAmelCase__ (  A :    Union[str, Any]							,				A :    List[Any]		):
         if len(A		) == 0:
           return ""
         __snake_case:						Dict   =						None
         if any(char.isdigit() for char in word		):
           raise Exception(f'''Parameters should not contain numbers: \'{word}\' contains a number'''		)
         if word in info["short_word"]:
           return info["short_word"][word]
         for prefix_len in range(1							,				len(A		) + 1		):
           __snake_case:						Optional[Any]   =						word[:prefix_len]
           if prefix in info["reverse_short_word"]:
             continue
           else:
             __snake_case:						Union[str, Any]   =						prefix
             break

         if short_word is None:
           # Paranoid fallback
           def int_to_alphabetic(A :    int		):
             __snake_case:						str   =						""""""
             while integer != 0:
               __snake_case:						List[Any]   =						chr(ord("""A"""		) + integer % 10		) + s
               integer //= 10
             return s

           __snake_case:						Tuple   =						0
           while True:
             __snake_case:						str   =						word + """#""" + int_to_alphabetic(A		)
             if sword in info["reverse_short_word"]:
               continue
             else:
               __snake_case:						Tuple   =						sword
               break

         __snake_case:						Any   =						short_word
         __snake_case:						str   =						word
         return short_word




       @staticmethod
       def 							UpperCAmelCase__ (  A :    str							,				A :    Any		):
         __snake_case:						Optional[int]   =						param_name.split("""_"""		)

         __snake_case:						Tuple   =						[TrialShortNamer.shortname_for_word(A							,				A		) for word in words]

         # We try to create a separatorless short name, but if there is a collision we have to fallback
         # to a separated short name
         __snake_case:						Optional[int]   =						["""""", """_"""]

         for separator in separators:
           __snake_case:						Union[str, Any]   =						separator.join(A		)
           if shortname not in info["reverse_short_param"]:
             __snake_case:						Optional[Any]   =						shortname
             __snake_case:						Tuple   =						param_name
             return shortname

         return param_name




       @staticmethod
       def 							UpperCAmelCase__ (  A :    Any							,				A :    List[str]		):
         __snake_case:						Dict   =						TrialShortNamer.shortname_for_key(A							,				A		)
         __snake_case:						List[Any]   =						short_name
         __snake_case:						Union[str, Any]   =						param_name




       @classmethod
       def 							UpperCAmelCase__ (  cls :    Any		):
         if cls.NAMING_INFO is not None:
           return

         __snake_case:						Optional[Any]   =						{
             """short_word""": {},
             """reverse_short_word""": {},
             """short_param""": {},
             """reverse_short_param""": {},
         }

         __snake_case:						List[Any]   =						list(cls.DEFAULTS.keys()		)

         for k in field_keys:
           cls.add_new_param_name(A							,				A		)

         __snake_case:						Dict   =						info




       @classmethod
       def 							UpperCAmelCase__ (  cls :    List[Any]							,				A :    List[str]		):
         cls.build_naming_info()
         assert cls.PREFIX is not None
         __snake_case:						Dict   =						[copy.copy(cls.PREFIX		)]

         for k, v in params.items():
           if k not in cls.DEFAULTS:
             raise Exception(f'''You should provide a default value for the param name {k} with value {v}'''		)
           if v == cls.DEFAULTS[k]:
             # The default value is not added to the name
             continue

           __snake_case:						Tuple   =						cls.NAMING_INFO["""short_param"""][k]

           if isinstance(A							,				A		):
             __snake_case:						Tuple   =						1 if v else 0

           __snake_case:						Any   =						"""""" if isinstance(A							,				(int, float)		) else """-"""
           __snake_case:						Dict   =						f'''{key}{sep}{v}'''
           name.append(A		)

         return "_".join(A		)






       @classmethod
       def 							UpperCAmelCase__ (  cls :    int							,				A :    Optional[Any]		):
         __snake_case:						Any   =						repr[len(cls.PREFIX		) + 1 :]
         if repr == "":
           __snake_case:						Tuple   =						[]
         else:
           __snake_case:						str   =						repr.split("""_"""		)

         __snake_case:						Union[str, Any]   =						{}

         for value in values:
           if "-" in value:
             __snake_case  ,   __snake_case:						Union[str, Any]   =						value.split("""-"""		)
           else:
             __snake_case:						Union[str, Any]   =						re.sub("""[0-9.]"""							,				""""""							,				A		)
             __snake_case:						Tuple   =						float(re.sub("""[^0-9.]"""							,				""""""							,				A		)		)

           __snake_case:						Any   =						cls.NAMING_INFO["""reverse_short_param"""][p_k]

           __snake_case:						Optional[Any]   =						p_v

         for k in cls.DEFAULTS:
           if k not in parameters:
             __snake_case:						List[str]   =						cls.DEFAULTS[k]

         return parameters










import comet  # From: unbabel-comet
import torch

import datasets


UpperCAmelCase__   	=							datasets.logging.get_logger(__name__)

UpperCAmelCase__   	=							'''\
@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",
}
'''

UpperCAmelCase__   	=							'''\
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.
'''

UpperCAmelCase__   	=							'''
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       lowerCamelCase__   (       datasets.Metric):





     def      __A					(self       )     ->   Optional[int]:
      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      __A					(self		,     UpperCAmelCase       )     ->   Dict:
      if self.config_name == "default":
       _lowercase							      =comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
      else:
       _lowercase							      =comet.load_from_checkpoint(comet.download_model(self.config_name       )       )





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase=None		,     UpperCAmelCase=False       )     ->   int:
      if gpus is None:
       _lowercase							      =1 if torch.cuda.is_available() else 0
      _lowercase							      ={'''src''': sources, '''mt''': predictions, '''ref''': references}
      _lowercase							      =[dict(zip(UpperCAmelCase		,     UpperCAmelCase       )       ) for t in zip(*data.values()       )]
      _lowercase      ,    _lowercase							      =self.scorer.predict(UpperCAmelCase		,     gpus=UpperCAmelCase		,     progress_bar=UpperCAmelCase       )
      return {"mean_score": mean_score, "scores": scores}

