






"""simple docstring"""







import comet  # From: unbabel-comet
import torch

import datasets


__a       :	Any             = datasets.logging.get_logger(__name__)

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

__a       :	List[str]             = '\\nCrosslingual 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).\nWith 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.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

__a       :	Optional[int]             = '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'







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





							"""simple docstring"""





							def  lowercase		(   self:     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  lowercase		(   self:     List[str]				,		__A:     Any    ):

												'''simple docstring'''

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





							def  lowercase		(   self:     str				,		__A:     List[Any]				,		__A:     Any				,		__A:     List[Any]				,		__A:     int=None				,		__A:     Optional[Any]=False    ):

												'''simple docstring'''

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










"""simple docstring"""







import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
	pass

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


__a       :	List[Any]             = logging.get_logger(__name__)

__a       :	Tuple             = {
    'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json',
}







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='align_text_model'




							def __init__(   self:     Tuple				,		__A:     Optional[int]=30522				,		__A:     Tuple=768				,		__A:     Any=12				,		__A:     Any=12				,		__A:     Dict=3072				,		__A:     Tuple="gelu"				,		__A:     Union[str, Any]=0.1				,		__A:     List[str]=0.1				,		__A:     Optional[int]=512				,		__A:     Tuple=2				,		__A:     str=0.0_2				,		__A:     int=1e-12				,		__A:     Optional[int]=0				,		__A:     Optional[int]="absolute"				,		__A:     List[Any]=True				,		**__A:     Tuple				,		):

												'''simple docstring'''

												super().__init__(**__A    )

												a__          =  vocab_size
												a__          =  hidden_size
												a__          =  num_hidden_layers
												a__          =  num_attention_heads
												a__          =  hidden_act
												a__          =  intermediate_size
												a__          =  hidden_dropout_prob
												a__          =  attention_probs_dropout_prob
												a__          =  max_position_embeddings
												a__          =  type_vocab_size
												a__          =  initializer_range
												a__          =  layer_norm_eps
												a__          =  position_embedding_type
												a__          =  use_cache
												a__          =  pad_token_id





							@classmethod
							def  lowercase		(   cls:     Any				,		__A:     Union[str, os.PathLike]				,		**__A:     Tuple    ):

												'''simple docstring'''

												cls._set_token_in_kwargs(__A    )

												a__       ,a__          =  cls.get_config_dict(__A				,		**__A    )

												# get the text config dict if we are loading from AlignConfig
												if config_dict.get('''model_type'''    ) == "align":
																	a__          =  config_dict['''text_config''']

												if "model_type" in config_dict and hasattr(cls				,		'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
																	    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

												return cls.from_dict(__A				,		**__A    )







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='align_vision_model'




							def __init__(   self:     Dict				,		__A:     int = 3				,		__A:     int = 600				,		__A:     float = 2.0				,		__A:     float = 3.1				,		__A:     int = 8				,		__A:     List[int] = [3, 3, 5, 3, 5, 5, 3]				,		__A:     List[int] = [32, 16, 24, 40, 80, 112, 192]				,		__A:     List[int] = [16, 24, 40, 80, 112, 192, 320]				,		__A:     List[int] = []				,		__A:     List[int] = [1, 2, 2, 2, 1, 2, 1]				,		__A:     List[int] = [1, 2, 2, 3, 3, 4, 1]				,		__A:     List[int] = [1, 6, 6, 6, 6, 6, 6]				,		__A:     float = 0.2_5				,		__A:     str = "swish"				,		__A:     int = 2560				,		__A:     str = "mean"				,		__A:     float = 0.0_2				,		__A:     float = 0.0_0_1				,		__A:     float = 0.9_9				,		__A:     float = 0.2				,		**__A:     List[Any]				,		):

												'''simple docstring'''

												super().__init__(**__A    )

												a__          =  num_channels
												a__          =  image_size
												a__          =  width_coefficient
												a__          =  depth_coefficient
												a__          =  depth_divisor
												a__          =  kernel_sizes
												a__          =  in_channels
												a__          =  out_channels
												a__          =  depthwise_padding
												a__          =  strides
												a__          =  num_block_repeats
												a__          =  expand_ratios
												a__          =  squeeze_expansion_ratio
												a__          =  hidden_act
												a__          =  hidden_dim
												a__          =  pooling_type
												a__          =  initializer_range
												a__          =  batch_norm_eps
												a__          =  batch_norm_momentum
												a__          =  drop_connect_rate
												a__          =  sum(__A    ) * 4





							@classmethod
							def  lowercase		(   cls:     Dict				,		__A:     Union[str, os.PathLike]				,		**__A:     List[Any]    ):

												'''simple docstring'''

												cls._set_token_in_kwargs(__A    )

												a__       ,a__          =  cls.get_config_dict(__A				,		**__A    )

												# get the vision config dict if we are loading from AlignConfig
												if config_dict.get('''model_type'''    ) == "align":
																	a__          =  config_dict['''vision_config''']

												if "model_type" in config_dict and hasattr(cls				,		'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
																	    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

												return cls.from_dict(__A				,		**__A    )







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='align'
							_SCREAMING_SNAKE_CASE    =True




							def __init__(   self:     Optional[int]				,		__A:     Optional[int]=None				,		__A:     Dict=None				,		__A:     List[str]=640				,		__A:     Optional[int]=1.0				,		__A:     str=0.0_2				,		**__A:     List[str]				,		):

												'''simple docstring'''

												super().__init__(**__A    )

												if text_config is None:
																	a__          =  {}
																	logger.info('''text_config is None. Initializing the AlignTextConfig with default values.'''    )

												if vision_config is None:
																	a__          =  {}
																	logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.'''    )

												a__          =  AlignTextConfig(**__A    )
												a__          =  AlignVisionConfig(**__A    )

												a__          =  projection_dim
												a__          =  temperature_init_value
												a__          =  initializer_range




							@classmethod
							def  lowercase		(   cls:     Dict				,		__A:     AlignTextConfig				,		__A:     AlignVisionConfig				,		**__A:     str    ):

												'''simple docstring'''

												return cls(text_config=text_config.to_dict()				,		vision_config=vision_config.to_dict()				,		**__A    )





							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												a__          =  copy.deepcopy(self.__dict__    )
												a__          =  self.text_config.to_dict()
												a__          =  self.vision_config.to_dict()
												a__          =  self.__class__.model_type
												return output


