






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 _UpperCAmelCase   (	a						:	Any ):
							@wraps(a )
							def wrapper(self						:	int  ,					a						:	Tuple ):
														if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
																					self.skipTest("""\"test requires Fairseq\"""" )
														else:
																					test_case(self  ,					a )

							return wrapper

def _UpperCAmelCase   (	a						:	Tuple ):
							@wraps(a )
							def wrapper(self						:	Optional[int]  ,					a						:	List[Any] ):
														if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
																					self.skipTest("""\"test requires transformers\"""" )
														else:
																					test_case(self  ,					a )

							return wrapper

def _UpperCAmelCase   (	a						:	Any ):
							@wraps(a )
							def wrapper(self						:	List[Any]  ,					a						:	Optional[Any] ):
														if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
																					self.skipTest("""\"test not supported on Windows\"""" )
														else:
																					test_case(self  ,					a )

							return wrapper

def _UpperCAmelCase   (	):
							snake_case__	  =       [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(
    lowercase_     ,      lowercase_     ,      lowercase_      )
@local
class    _lowerCAmelCase			(		parameterized.TestCase      ):



				"""simple docstring"""



				_lowercase				:   Optional[Any]      =  {}
				_lowercase				:   Optional[int]      =  None



				@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""")
				@pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""")
				def 					__magic_name__							(      self    :    Union[str, Any]			,		UpperCamelCase__    :    Dict):






											'''simple docstring'''







											snake_case__	  =       """[...]"""
											snake_case__	  =       importlib.import_module(
											    datasets.load.metric_module_factory(os.path.join("""metrics"""			,		UpperCamelCase__)).module_path)
											snake_case__	  =       datasets.load.import_main_class(metric_module.__name__			,		dataset=UpperCamelCase__)
											# check parameters
											snake_case__	  =       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:
																																snake_case__	  =       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 					__magic_name__							(      self    :    Any			,		UpperCamelCase__    :    Dict):






											'''simple docstring'''







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



				@contextmanager
				def 					__magic_name__							(      self    :    int			,		UpperCamelCase__    :    int			,		UpperCamelCase__    :    List[str]):






											'''simple docstring'''







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



				@contextmanager
				def 					__magic_name__							(      self    :    List[Any]):






											'''simple docstring'''







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

											with patch("""datasets.load_metric""") as mock_load_metric:
																		snake_case__	  =       load_local_metric
																		yield



				@classmethod
				def 					__magic_name__							(      cls    :    Optional[Any]			,		UpperCamelCase__    :    Optional[Any]):






											'''simple docstring'''







											def wrapper(UpperCamelCase__    :    Dict):
																		snake_case__	  =       contextmanager(UpperCamelCase__)
																		snake_case__	  =       patcher
																		return patcher

											return wrapper


@LocalMetricTest.register_intensive_calls_patcher("""bleurt""" )
def _UpperCAmelCase   (	a						:	Dict ):
							import tensorflow.compat.va as tf
							from bleurt.score import Predictor

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


							class    _lowerCAmelCase			(		lowercase_      ):



											"""simple docstring"""



											def 					__magic_name__							(      self    :    Any			,		UpperCamelCase__    :    Dict):






																		'''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:
														snake_case__	  =       MockedPredictor()
														yield

@LocalMetricTest.register_intensive_calls_patcher("""bertscore""" )
def _UpperCAmelCase   (	a						:	str ):
							import torch

							def bert_cos_score_idf(a						:	Optional[Any]  ,					a						:	int  ,					*a						:	Dict  ,					**a						:	Any ):
														return torch.tensor([[1.0, 1.0, 1.0]] * len(a ) )

							# 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:
														snake_case__	  =       bert_cos_score_idf
														yield

@LocalMetricTest.register_intensive_calls_patcher("""comet""" )
def _UpperCAmelCase   (	a						:	Optional[Any] ):
							def load_from_checkpoint(a						:	int ):


														class    _lowerCAmelCase			:



																		"""simple docstring"""



																		def 					__magic_name__							(      self    :    Union[str, Any]			,		UpperCamelCase__    :    Optional[int]			,		*UpperCamelCase__    :    Optional[Any]			,		**UpperCamelCase__    :    str):






																									'''simple docstring'''







																									assert len(UpperCamelCase__) == 2
																									snake_case__	  =       [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:
														snake_case__	  =       None
														with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint:
																					snake_case__	  =       load_from_checkpoint
																					yield



def _UpperCAmelCase   (	):
							snake_case__	  =       load_metric(os.path.join("""metrics"""  ,					"""seqeval""" ) )
							snake_case__	  =       """ERROR"""
							snake_case__	  =       F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
							with pytest.raises(a  ,					match=re.escape(a ) ):
														metric.compute(predictions=[]  ,					references=[]  ,					scheme=a )








from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
	import torch

if is_torch_tpu_available(check_device=False):
	import torch_xla.core.xla_model as xm


a__       =     logging.get_logger(__name__)


@dataclass
class    _lowerCAmelCase			(		lowercase_      ):



				"""simple docstring"""



				_lowercase				:   Dict      =  [
				    '''no_inference''',
				    '''no_cuda''',
				    '''no_tpu''',
				    '''no_speed''',
				    '''no_memory''',
				    '''no_env_print''',
				    '''no_multi_process''',
				]



				def __init__(      self    :    str			,		**UpperCamelCase__    :    Dict):






											'''simple docstring'''







											for deprecated_arg in self.deprecated_args:
																		if deprecated_arg in kwargs:
																									snake_case__	  =       deprecated_arg[3:]
																									setattr(self			,		UpperCamelCase__			,		not kwargs.pop(UpperCamelCase__))
																									logger.warning(
																									    F'''{deprecated_arg} is depreciated. Please use --no_{positive_arg} or'''
																									    F''' {positive_arg}={kwargs[positive_arg]}''')

											snake_case__	  =       kwargs.pop("""torchscript"""			,		self.torchscript)
											snake_case__	  =       kwargs.pop("""torch_xla_tpu_print_metrics"""			,		self.torch_xla_tpu_print_metrics)
											snake_case__	  =       kwargs.pop("""fp16_opt_level"""			,		self.fpaa_opt_level)
											super().__init__(**UpperCamelCase__)

				_lowercase				:   bool      =  field(default=lowercase_     ,      metadata={'''help''': '''Trace the models using torchscript'''}      )
				_lowercase				:   bool      =  field(default=lowercase_     ,      metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''}      )
				_lowercase				:   str      =  field(
				    default='''O1'''     ,      metadata={
				        '''help''': (
				            '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. '''
				            '''See details at https://nvidia.github.io/apex/amp.html'''
				        )
				    }     ,      )



				@cached_property
				def 					__magic_name__							(      self    :    Tuple):






											'''simple docstring'''







											requires_backends(self			,		["""torch"""])
											logger.info("""PyTorch: setting up devices""")
											if not self.cuda:
																		snake_case__	  =       torch.device("""cpu""")
																		snake_case__	  =       0
											elif is_torch_tpu_available():
																		snake_case__	  =       xm.xla_device()
																		snake_case__	  =       0
											else:
																		snake_case__	  =       torch.device("""cuda""" if torch.cuda.is_available() else """cpu""")
																		snake_case__	  =       torch.cuda.device_count()
											return device, n_gpu



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






											'''simple docstring'''







											return is_torch_tpu_available() and self.tpu



				@property
				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											requires_backends(self			,		["""torch"""])
											# TODO(PVP): currently only single GPU is supported
											return torch.cuda.current_device()



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






											'''simple docstring'''







											requires_backends(self			,		["""torch"""])
											return self._setup_devices[0]



				@property
				def 					__magic_name__							(      self    :    str):






											'''simple docstring'''







											requires_backends(self			,		["""torch"""])
											return self._setup_devices[1]



				@property
				def 					__magic_name__							(      self    :    str):






											'''simple docstring'''







											return self.n_gpu > 0
