






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  _lowerCAmelCase      (		datasets.Metric   ):



				"""simple docstring"""



				def        __magic_name__				(   self     :     Union[str, Any]):






											'''simple docstring'''







											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        __magic_name__				(   self     :     Union[str, Any]      ,		UpperCamelCase__     :     Optional[Any]):






											'''simple docstring'''







											if self.config_name == "default":
																		snake_case__							=							comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""))
											else:
																		snake_case__							=							comet.load_from_checkpoint(comet.download_model(self.config_name))



				def        __magic_name__				(   self     :     Tuple      ,		UpperCamelCase__     :     List[Any]      ,		UpperCamelCase__     :     Optional[int]      ,		UpperCamelCase__     :     Dict      ,		UpperCamelCase__     :     List[Any]=None      ,		UpperCamelCase__     :     Tuple=False):






											'''simple docstring'''







											if gpus is None:
																		snake_case__							=							1 if torch.cuda.is_available() else 0
											snake_case__							=							{"""src""": sources, """mt""": predictions, """ref""": references}
											snake_case__							=							[dict(zip(__a      ,		__a)) for t in zip(*data.values())]
											snake_case__							=							self.scorer.predict(__a      ,		gpus=__a      ,		progress_bar=__a)
											return {"mean_score": mean_score, "scores": scores}






'''simple docstring'''







import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase      :   Optional[int]      =       logging.get_logger(__name__)

lowercase      :   Union[str, Any]      =       {
    """microsoft/unispeech-sat-base-100h-libri-ft""": (
        """https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json"""
    ),
    # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}







class 					_a (a__	):





     '''simple docstring'''



     lowerCAmelCase_  :     List[Any]          =					"""unispeech-sat"""







     def __init__(				self							,__a=32							,__a=768							,__a=12							,__a=12							,__a=3_072							,__a="gelu"							,__a=0.1							,__a=0.1							,__a=0.1							,__a=0.0							,__a=0.0							,__a=0.1							,__a=0.1							,__a=0.02							,__a=1E-5							,__a="group"							,__a="gelu"							,__a=(512, 512, 512, 512, 512, 512, 512)							,__a=(5, 2, 2, 2, 2, 2, 2)							,__a=(10, 3, 3, 3, 3, 2, 2)							,__a=False							,__a=128							,__a=16							,__a=False							,__a=True							,__a=0.05							,__a=10							,__a=2							,__a=0.0							,__a=10							,__a=0							,__a=320							,__a=2							,__a=0.1							,__a=100							,__a=256							,__a=256							,__a=0.1							,__a="mean"							,__a=False							,__a=False							,__a=256							,__a=(512, 512, 512, 512, 1_500)							,__a=(5, 3, 3, 1, 1)							,__a=(1, 2, 3, 1, 1)							,__a=512							,__a=0							,__a=1							,__a=2							,__a=504							,**__a							,)      ->				str:
          super().__init__(**__a							,pad_token_id=__a							,bos_token_id=__a							,eos_token_id=__a							)
          snake_case			:      List[Any]        =			hidden_size
          snake_case			:      Any        =			feat_extract_norm
          snake_case			:      Dict        =			feat_extract_activation
          snake_case			:      List[Any]        =			list(__a							)
          snake_case			:      int        =			list(__a							)
          snake_case			:      Dict        =			list(__a							)
          snake_case			:      int        =			conv_bias
          snake_case			:      Optional[Any]        =			num_conv_pos_embeddings
          snake_case			:      Any        =			num_conv_pos_embedding_groups
          snake_case			:      Dict        =			len(self.conv_dim							)
          snake_case			:      str        =			num_hidden_layers
          snake_case			:      Optional[Any]        =			intermediate_size
          snake_case			:      Optional[Any]        =			hidden_act
          snake_case			:      Union[str, Any]        =			num_attention_heads
          snake_case			:      str        =			hidden_dropout
          snake_case			:      Tuple        =			attention_dropout
          snake_case			:      Tuple        =			activation_dropout
          snake_case			:      List[Any]        =			feat_proj_dropout
          snake_case			:      List[str]        =			final_dropout
          snake_case			:      Union[str, Any]        =			layerdrop
          snake_case			:      Optional[int]        =			layer_norm_eps
          snake_case			:      int        =			initializer_range
          snake_case			:      List[Any]        =			vocab_size
          snake_case			:      Any        =			num_clusters
          snake_case			:      Dict        =			do_stable_layer_norm
          snake_case			:      int        =			use_weighted_layer_sum

          if (
              (len(self.conv_stride							) != self.num_feat_extract_layers)
              or (len(self.conv_kernel							) != self.num_feat_extract_layers)
              or (len(self.conv_dim							) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
                   """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
                   F''' {len(self.conv_dim							)}`, `len(config.conv_stride) = {len(self.conv_stride							)}`,'''
                   F''' `len(config.conv_kernel) = {len(self.conv_kernel							)}`.'''							)

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          snake_case			:      Dict        =			apply_spec_augment
          snake_case			:      Optional[int]        =			mask_time_prob
          snake_case			:      int        =			mask_time_length
          snake_case			:      int        =			mask_time_min_masks
          snake_case			:      int        =			mask_feature_prob
          snake_case			:      Optional[Any]        =			mask_feature_length
          snake_case			:      List[Any]        =			mask_feature_min_masks

          # parameters for pretraining with codevector quantized representations
          snake_case			:      Optional[Any]        =			num_codevectors_per_group
          snake_case			:      Optional[int]        =			num_codevector_groups
          snake_case			:      Any        =			contrastive_logits_temperature
          snake_case			:      List[str]        =			feat_quantizer_dropout
          snake_case			:      Dict        =			num_negatives
          snake_case			:      int        =			codevector_dim
          snake_case			:      Optional[int]        =			proj_codevector_dim
          snake_case			:      Union[str, Any]        =			diversity_loss_weight

          # ctc loss
          snake_case			:      Union[str, Any]        =			ctc_loss_reduction
          snake_case			:      Optional[int]        =			ctc_zero_infinity

          # SequenceClassification-specific parameter. Feel free to ignore for other classes.
          snake_case			:      Dict        =			classifier_proj_size

          # XVector-specific parameters. Feel free to ignore for other classes.
          snake_case			:      int        =			list(__a							)
          snake_case			:      Tuple        =			list(__a							)
          snake_case			:      List[Any]        =			list(__a							)
          snake_case			:      Dict        =			xvector_output_dim







     @property
     def 			snake_case_      (				self							)      ->				List[str]:
          return functools.reduce(operator.mul							,self.conv_stride							,1							)



