
'''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
__snake_case							   =  pytest.mark.integration


__snake_case							   =  {'comet'}
__snake_case							   =  importlib.util.find_spec('''fairseq''') is not None

__snake_case							   =  {'code_eval'}
__snake_case							   =  os.name == 'nt'

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


def     a   (    __a     )						->			str:



					'''simple docstring'''






					@wraps(_SCREAMING_SNAKE_CASE     )
					def wrapper(self				,      __a     ):
										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   (    __a     )						->			Optional[int]:



					'''simple docstring'''






					@wraps(_SCREAMING_SNAKE_CASE     )
					def wrapper(self				,      __a     ):
										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   (    __a     )						->			str:



					'''simple docstring'''






					@wraps(_SCREAMING_SNAKE_CASE     )
					def wrapper(self				,      __a     ):
										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   (    )						->			List[str]:



					'''simple docstring'''






					UpperCamelCase__     :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      lowercase			(							parameterized.TestCase      ):

		"""simple docstring"""

		_a									=       {}
		_a									=       None




		@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''							)
		@pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''							)
		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :Optional[Any]							      =				'''[...]'''
							UpperCamelCase__     :List[Any]							      =				importlib.import_module(
							    datasets.load.metric_module_factory(os.path.join('''metrics'''					,     UpperCAmelCase_							)							).module_path							)
							UpperCamelCase__     :List[Any]							      =				datasets.load.import_main_class(metric_module.__name__					,     dataset=UpperCAmelCase_							)
							# check parameters
							UpperCamelCase__     :Optional[Any]							      =				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:
																						UpperCamelCase__     :List[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 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


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




		@contextmanager
		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


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




		@contextmanager
		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							def load_local_metric(UpperCamelCase_					,     *UpperCamelCase_					,     **UpperCamelCase_							):
												return load_metric(os.path.join('''metrics'''					,     UpperCAmelCase_							)					,     *UpperCAmelCase_					,     **UpperCAmelCase_							)

							with patch('''datasets.load_metric'''							) as mock_load_metric:
												UpperCamelCase__     :Optional[Any]							      =				load_local_metric
												yield




		@classmethod
		def 					lowerCAmelCase__       (	cls					,     UpperCamelCase_							):

							'''simple docstring'''


							def wrapper(UpperCamelCase_							):
												UpperCamelCase__     :Tuple							      =				contextmanager(UpperCAmelCase_							)
												UpperCamelCase__     :int							      =				patcher
												return patcher

							return wrapper



@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''     )
def     a   (    __a     )						->			str:



					'''simple docstring'''






					import tensorflow.compat.va as tf
					from bleurt.score import Predictor

					tf.flags.DEFINE_string('''sv'''				,      ''''''				,      ''''''     )  # handle pytest cli flags
					class      lowercase			(							snake_case__      ):

							"""simple docstring"""

							def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

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


@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''     )
def     a   (    __a     )						->			Optional[Any]:



					'''simple docstring'''






					import torch

					def bert_cos_score_idf(__a				,      __a				,      *__a				,      **__a     ):
										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:
										UpperCamelCase__     :List[Any]							      =				bert_cos_score_idf
										yield


@LocalMetricTest.register_intensive_calls_patcher('''comet'''     )
def     a   (    __a     )						->			Any:



					'''simple docstring'''






					def load_from_checkpoint(__a     ):
										class      lowercase			:

												"""simple docstring"""

												def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     *UpperCamelCase_					,     **UpperCamelCase_							):

																	'''simple docstring'''


																	assert len(UpperCAmelCase_							) == 2
																	UpperCamelCase__     :Any							      =				[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:
										UpperCamelCase__     :List[Any]							      =				None
										with patch('''comet.load_from_checkpoint'''     ) as mock_load_from_checkpoint:
															UpperCamelCase__     :List[str]							      =				load_from_checkpoint
															yield







def     a   (    )						->			List[str]:



					'''simple docstring'''






					UpperCamelCase__     :Union[str, Any]							      =				load_metric(os.path.join('''metrics'''				,      '''seqeval'''     )     )
					UpperCamelCase__     :int							      =				'''ERROR'''
					UpperCamelCase__     :Union[str, Any]							      =				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'''
from .integrations import (
    is_optuna_available,
    is_ray_available,
    is_sigopt_available,
    is_wandb_available,
    run_hp_search_optuna,
    run_hp_search_ray,
    run_hp_search_sigopt,
    run_hp_search_wandb,
)
from .trainer_utils import (
    HPSearchBackend,
    default_hp_space_optuna,
    default_hp_space_ray,
    default_hp_space_sigopt,
    default_hp_space_wandb,
)
from .utils import logging


__snake_case							   =  logging.get_logger(__name__)
class      lowercase			:

		"""simple docstring"""

		_a									=       42
		_a									=       None




		@staticmethod
		def 					lowerCAmelCase__       (	):

							'''simple docstring'''


							raise NotImplementedError




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							raise NotImplementedError




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							raise NotImplementedError




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							if not self.is_available():
												raise RuntimeError(
												    F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.'''							)




		@classmethod
		def 					lowerCAmelCase__       (	cls							):

							'''simple docstring'''


							return F'''`pip install {cls.pip_package or cls.name}`'''



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       'optuna'




		@staticmethod
		def 					lowerCAmelCase__       (	):

							'''simple docstring'''


							return is_optuna_available()




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return run_hp_search_optuna(UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							return default_hp_space_optuna(UpperCamelCase_							)



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       'ray'
		_a									=       '\'ray[tune]\''




		@staticmethod
		def 					lowerCAmelCase__       (	):

							'''simple docstring'''


							return is_ray_available()




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return run_hp_search_ray(UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							return default_hp_space_ray(UpperCamelCase_							)



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       'sigopt'




		@staticmethod
		def 					lowerCAmelCase__       (	):

							'''simple docstring'''


							return is_sigopt_available()




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return run_hp_search_sigopt(UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							return default_hp_space_sigopt(UpperCamelCase_							)



class      lowercase			(							A__      ):

		"""simple docstring"""

		_a									=       'wandb'




		@staticmethod
		def 					lowerCAmelCase__       (	):

							'''simple docstring'''


							return is_wandb_available()




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							):

							'''simple docstring'''


							return run_hp_search_wandb(UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_					,     **UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							return default_hp_space_wandb(UpperCamelCase_							)



__snake_case							   =  {
    HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}


def     a   (    )						->			str:



					'''simple docstring'''






					UpperCamelCase__     :List[Any]							      =				[backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
					if len(__a     ) > 0:
										UpperCamelCase__     :Tuple							      =				available_backends[0].name
										if len(__a     ) > 1:
															logger.info(
															    f'''{len(__a     )} hyperparameter search backends available. Using {name} as the default.'''     )
										return name
					raise RuntimeError(
					    '''No hyperparameter search backend available.\n'''
					    + '''\n'''.join(
					        f''' - To install {backend.name} run {backend.pip_install()}'''
					        for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()     )     )