

"""simple docstring"""


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__A						       =      pytest.mark.integration


__A						       =      {"comet"}
__A						       =      importlib.util.find_spec("fairseq") is not None

__A						       =      {"code_eval"}
__A						       =      os.name == "nt"

__A						       =      {"bertscore", "frugalscore", "perplexity"}
__A						       =      importlib.util.find_spec("transformers") is not None






def    a__   (   __SCREAMING_SNAKE_CASE			)     ->     Any:
		@wraps(__SCREAMING_SNAKE_CASE			)
		def wrapper(self ,			__SCREAMING_SNAKE_CASE			):
				if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
						self.skipTest("\"test requires Fairseq\""			)
				else:
						test_case(self ,			__SCREAMING_SNAKE_CASE			)

		return wrapper






def    a__   (   __SCREAMING_SNAKE_CASE			)     ->     Union[str, Any]:
		@wraps(__SCREAMING_SNAKE_CASE			)
		def wrapper(self ,			__SCREAMING_SNAKE_CASE			):
				if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
						self.skipTest("\"test requires transformers\""			)
				else:
						test_case(self ,			__SCREAMING_SNAKE_CASE			)

		return wrapper






def    a__   (   __SCREAMING_SNAKE_CASE			)     ->     Optional[int]:
		@wraps(__SCREAMING_SNAKE_CASE			)
		def wrapper(self ,			__SCREAMING_SNAKE_CASE			):
				if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
						self.skipTest("\"test not supported on Windows\""			)
				else:
						test_case(self ,			__SCREAMING_SNAKE_CASE			)

		return wrapper






def    a__   (   )     ->     Any:
		__lowerCAmelCase:	Optional[Any]   				=      [metric_dir.split(os.sep			)[-2] for metric_dir in glob.glob("./metrics/*/"			)]
		return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names()  )
@for_all_test_methods(
    __snake_case,							__snake_case,							__snake_case  )
@local
class    snake_case     (    parameterized.TestCase  ):
				SCREAMING_SNAKE_CASE_       :				str       				=  {}
				SCREAMING_SNAKE_CASE_       :				Optional[int]       				=  None

				@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning")
				@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning")
				def 							lowercase_					(     self							:    int					,  UpperCamelCase__							:    Union[str, Any])->       List[str]:



						'''simple docstring'''


						__lowerCAmelCase:	Dict   				=      "[...]"
						__lowerCAmelCase:	Optional[Any]   				=      importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join("metrics"					,  UpperCamelCase__)).module_path)
						__lowerCAmelCase:	List[Any]   				=      datasets.load.import_main_class(metric_module.__name__					,  dataset=UpperCamelCase__)
						# check parameters
						__lowerCAmelCase:	Tuple   				=      inspect.signature(metric._compute).parameters
						self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()))  # no **kwargs
						# run doctest
						with self.patch_intensive_calls(UpperCamelCase__					,  metric_module.__name__):
								with self.use_local_metrics():
										try:
												__lowerCAmelCase:	Optional[Any]   				=      doctest.testmod(UpperCamelCase__					,  verbose=UpperCamelCase__					,  raise_on_error=UpperCamelCase__)
										except doctest.UnexpectedException as e:
												raise e.exc_info[1]  # raise the exception that doctest caught
						self.assertEqual(results.failed					,  0)
						self.assertGreater(results.attempted					,  1)

				@slow
				def 							lowercase_					(     self							:    Tuple					,  UpperCamelCase__							:    Optional[int])->       Tuple:



						'''simple docstring'''


						__lowerCAmelCase:	Optional[int]   				=      "[...]"
						__lowerCAmelCase:	Optional[Any]   				=      importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join("metrics"					,  UpperCamelCase__)).module_path)
						# run doctest
						with self.use_local_metrics():
								__lowerCAmelCase:	Optional[Any]   				=      doctest.testmod(UpperCamelCase__					,  verbose=UpperCamelCase__					,  raise_on_error=UpperCamelCase__)
						self.assertEqual(results.failed					,  0)
						self.assertGreater(results.attempted					,  1)

				@contextmanager
				def 							lowercase_					(     self							:    int					,  UpperCamelCase__							:    Tuple					,  UpperCamelCase__							:    List[str])->       Optional[int]:



						'''simple docstring'''


						if metric_name in self.INTENSIVE_CALLS_PATCHER:
								with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCamelCase__):
										yield
						else:
								yield

				@contextmanager
				def 							lowercase_					(     self							:    int)->       Tuple:



						'''simple docstring'''


						def load_local_metric(UpperCamelCase__							:    Any					,  *UpperCamelCase__							:    Tuple					,  **UpperCamelCase__							:    Optional[Any]):
								return load_metric(os.path.join("metrics"					,  UpperCamelCase__)					,  *UpperCamelCase__					,  **UpperCamelCase__)

						with patch("datasets.load_metric") as mock_load_metric:
								__lowerCAmelCase:	Union[str, Any]   				=      load_local_metric
								yield




				@classmethod
				def 							lowercase_					(     cls							:    List[Any]					,  UpperCamelCase__							:    Any)->       Tuple:



						'''simple docstring'''


						def wrapper(UpperCamelCase__							:    Any):
								__lowerCAmelCase:	Optional[int]   				=      contextmanager(UpperCamelCase__)
								__lowerCAmelCase:	List[str]   				=      patcher
								return patcher

						return wrapper






@LocalMetricTest.register_intensive_calls_patcher("bleurt"			)
def    a__   (   __SCREAMING_SNAKE_CASE			)     ->     int:
		import tensorflow.compat.va as tf
		from bleurt.score import Predictor

		tf.flags.DEFINE_string("sv" ,			"" ,			""			)  # handle pytest cli flags





		class    snake_case     (    __snake_case  ):

						def 							lowercase_					(     self							:    List[Any]					,  UpperCamelCase__							:    str)->       Tuple:



								'''simple docstring'''


								assert len(input_dict["input_ids"]) == 2
								return np.array([1.03, 1.04])

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
		with patch("bleurt.score._create_predictor"			) as mock_create_predictor:
				__lowerCAmelCase:	Optional[int]   				=      MockedPredictor()
				yield






@LocalMetricTest.register_intensive_calls_patcher("bertscore"			)
def    a__   (   __SCREAMING_SNAKE_CASE			)     ->     str:
		import torch

		def bert_cos_score_idf(__SCREAMING_SNAKE_CASE ,			__SCREAMING_SNAKE_CASE ,			*__SCREAMING_SNAKE_CASE ,			**__SCREAMING_SNAKE_CASE			):
				return torch.tensor([[1.0, 1.0, 1.0]] * len(__SCREAMING_SNAKE_CASE			)			)

		# mock get_model which is supposed to do download a bert model
		# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
		with patch("bert_score.scorer.get_model"			), patch(
		    "bert_score.scorer.bert_cos_score_idf"			) as mock_bert_cos_score_idf:
				__lowerCAmelCase:	Dict   				=      bert_cos_score_idf
				yield






@LocalMetricTest.register_intensive_calls_patcher("comet"			)
def    a__   (   __SCREAMING_SNAKE_CASE			)     ->     List[str]:
		def load_from_checkpoint(__SCREAMING_SNAKE_CASE			):





				class    snake_case     :

								def 							lowercase_					(     self							:    str					,  UpperCamelCase__							:    Dict					,  *UpperCamelCase__							:    Dict					,  **UpperCamelCase__							:    Union[str, Any])->       int:



										'''simple docstring'''


										assert len(UpperCamelCase__) == 2
										__lowerCAmelCase:	Tuple   				=      [0.19, 0.92]
										return scores, sum(UpperCamelCase__) / len(UpperCamelCase__)


				return Model()

		# mock load_from_checkpoint which is supposed to do download a bert model
		# mock load_from_checkpoint which is supposed to do download a bert model
		with patch("comet.download_model"			) as mock_download_model:
				__lowerCAmelCase:	Tuple   				=      None
				with patch("comet.load_from_checkpoint"			) as mock_load_from_checkpoint:
						__lowerCAmelCase:	Any   				=      load_from_checkpoint
						yield






def    a__   (   )     ->     Tuple:
		__lowerCAmelCase:	Optional[Any]   				=      load_metric(os.path.join("metrics" ,			"seqeval"			)			)
		__lowerCAmelCase:	Any   				=      "ERROR"
		__lowerCAmelCase:	List[str]   				=      F"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"
		with pytest.raises(__SCREAMING_SNAKE_CASE ,			match=re.escape(__SCREAMING_SNAKE_CASE			)			):
				metric.compute(predictions=[] ,			references=[] ,			scheme=__SCREAMING_SNAKE_CASE			)





"""simple docstring"""


import comet  # From: unbabel-comet
import torch

import datasets


__A						       =      datasets.logging.get_logger(__name__)

__A						       =      "\\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						       =      "\\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						       =      "\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    snake_case     (    datasets.Metric  ):

				def 							lowercase_					(     self							:    List[Any])->       Dict:



						'''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							:    Tuple					,  UpperCamelCase__							:    Any)->       Dict:



						'''simple docstring'''


						if self.config_name == "default":
								__lowerCAmelCase:	Union[str, Any]   				=      comet.load_from_checkpoint(comet.download_model("wmt20-comet-da"))
						else:
								__lowerCAmelCase:	Tuple   				=      comet.load_from_checkpoint(comet.download_model(self.config_name))




				def 							lowercase_					(     self							:    Optional[int]					,  UpperCamelCase__							:    Optional[Any]					,  UpperCamelCase__							:    Optional[Any]					,  UpperCamelCase__							:    int					,  UpperCamelCase__							:    Optional[int]=None					,  UpperCamelCase__							:    List[str]=False)->       str:



						'''simple docstring'''


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


