





"""simple docstring"""






import json
import os
import unittest

from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin




@require_tokenizers
class 			__lowercase     (     _UpperCamelCase				, unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase					=					MgpstrTokenizer
					__lowerCAmelCase					=					False
					__lowerCAmelCase					=					{}
					__lowerCAmelCase					=					False







					def 	_lowerCamelCase						(  self       ):
									super().setUp()

									# fmt: off
									__a	:  Dict         =					['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z''']
									# fmt: on
									__a	:  Dict         =					dict(zip(_UpperCAmelCase		,     range(len(_UpperCAmelCase       )       )       )       )

									__a	:  Optional[Any]         =					os.path.join(self.tmpdirname		,     VOCAB_FILES_NAMES['''vocab_file''']       )
									with open(self.vocab_file		,     '''w'''		,     encoding='''utf-8'''       ) as fp:
													fp.write(json.dumps(_UpperCAmelCase       ) + '''\n'''       )







					def 	_lowerCamelCase						(  self		,     **_UpperCAmelCase       ):
									return MgpstrTokenizer.from_pretrained(self.tmpdirname		,     **_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									__a	:  List[Any]         =					'''tester'''
									__a	:  Union[str, Any]         =					'''tester'''
									return input_text, output_text







					@unittest.skip('''MGP-STR always lower cases letters.'''       )
					def 	_lowerCamelCase						(  self       ):
									pass







					def 	_lowerCamelCase						(  self       ):
									__a	:  List[str]         =					self.get_tokenizers(do_lower_case=_UpperCAmelCase       )
									for tokenizer in tokenizers:
													with self.subTest(f"""{tokenizer.__class__.__name__}"""       ):
																	__a	:  List[Any]         =					'''[SPECIAL_TOKEN]'''

																	tokenizer.add_special_tokens({'''cls_token''': special_token}       )
																	__a	:  List[str]         =					tokenizer.encode([special_token]		,     add_special_tokens=_UpperCAmelCase       )
																	self.assertEqual(len(_UpperCAmelCase       )		,     1       )

																	__a	:  List[Any]         =					tokenizer.decode(_UpperCAmelCase		,     skip_special_tokens=_UpperCAmelCase       )
																	self.assertTrue(special_token not in decoded       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  Optional[Any]         =					self.get_tokenizers()
									for tokenizer in tokenizers:
													with self.subTest(f"""{tokenizer.__class__.__name__}"""       ):
																	__a    ,  __a	:  Optional[Any]         =					self.get_input_output_texts(_UpperCAmelCase       )

																	__a	:  Tuple         =					tokenizer.tokenize(_UpperCAmelCase       )
																	__a	:  Any         =					tokenizer.convert_tokens_to_ids(_UpperCAmelCase       )
																	__a	:  List[Any]         =					tokenizer.encode(_UpperCAmelCase		,     add_special_tokens=_UpperCAmelCase       )
																	self.assertListEqual(_UpperCAmelCase		,     _UpperCAmelCase       )

																	__a	:  Optional[int]         =					tokenizer.convert_ids_to_tokens(_UpperCAmelCase       )
																	self.assertNotEqual(len(_UpperCAmelCase       )		,     0       )
																	__a	:  Union[str, Any]         =					tokenizer.decode(_UpperCAmelCase       )
																	self.assertIsInstance(_UpperCAmelCase		,     _UpperCAmelCase       )

																	self.assertEqual(text_a.replace(''' '''		,     ''''''       )		,     _UpperCAmelCase       )







					@unittest.skip('''MGP-STR tokenizer only handles one sequence.'''       )
					def 	_lowerCamelCase						(  self       ):
									pass







					@unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer'''       )
					def 	_lowerCamelCase						(  self       ):
									pass






"""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}