

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				:      Tuple   		=			pytest.mark.integration


__snake_case				:      Optional[Any]   		=			{"""comet"""}
__snake_case				:      List[str]   		=			importlib.util.find_spec("""fairseq""") is not None

__snake_case				:      Any   		=			{"""code_eval"""}
__snake_case				:      List[str]   		=			os.name == """nt"""

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


def 					_UpperCAmelCase				(						a__):

			'''simple docstring'''



			@wraps(a__)
			def wrapper(self  ,	a__):
						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__):

			'''simple docstring'''



			@wraps(a__)
			def wrapper(self  ,	a__):
						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__):

			'''simple docstring'''



			@wraps(a__)
			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  ,	a__)

			return wrapper


def 					_UpperCAmelCase				(						):

			'''simple docstring'''



			a_						:						List[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(
    a_,  a_,  a_							)
@local
class        A__(parameterized.TestCase							):
						"""simple docstring"""






						_A    :				Tuple       					=			{}
						_A    :				Tuple       					=			None





						@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""    )
						@pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""    )
						def 			UpperCamelCase__					(    self  ,      _lowercase    )     -> Tuple:
									a_						:						List[str] 							= """[...]"""
									a_						:						str 							= importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join("""metrics"""  ,      _lowercase    )    ).module_path    )
									a_						:						List[Any] 							= datasets.load.import_main_class(metric_module.__name__  ,      dataset=_lowercase    )
									# check parameters
									a_						:						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(_lowercase  ,      metric_module.__name__    ):
												with self.use_local_metrics():
															try:
																		a_						:						List[str] 							= doctest.testmod(_lowercase  ,      verbose=_lowercase  ,      raise_on_error=_lowercase    )
															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 			UpperCamelCase__					(    self  ,      _lowercase    )     -> Dict:
									a_						:						List[str] 							= """[...]"""
									a_						:						Dict 							= importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join("""metrics"""  ,      _lowercase    )    ).module_path    )
									# run doctest
									with self.use_local_metrics():
												a_						:						str 							= doctest.testmod(_lowercase  ,      verbose=_lowercase  ,      raise_on_error=_lowercase    )
									self.assertEqual(results.failed  ,      0    )
									self.assertGreater(results.attempted  ,      1    )





						@contextmanager
						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase    )     -> Tuple:
									if metric_name in self.INTENSIVE_CALLS_PATCHER:
												with self.INTENSIVE_CALLS_PATCHER[metric_name](_lowercase    ):
															yield
									else:
												yield





						@contextmanager
						def 			UpperCamelCase__					(    self    )     -> Any:
									def load_local_metric(_lowercase  ,      *_lowercase  ,      **_lowercase    ):
												return load_metric(os.path.join("""metrics"""  ,      _lowercase    )  ,      *_lowercase  ,      **_lowercase    )

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





						@classmethod
						def 			UpperCamelCase__					(    cls  ,      _lowercase    )     -> int:
									def wrapper(_lowercase    ):
												a_						:						List[Any] 							= contextmanager(_lowercase    )
												a_						:						Union[str, Any] 							= patcher
												return patcher

									return wrapper







@LocalMetricTest.register_intensive_calls_patcher("""bleurt""")
def 					_UpperCAmelCase				(						a__):

			'''simple docstring'''



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

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



			class        A__(a_							):
									"""simple docstring"""






									def 			UpperCamelCase__					(    self  ,      _lowercase    )     -> Union[str, Any]:
												assert len(input_dict["""input_ids"""]    ) == 2
												return np.array([1.0_3, 1.0_4]    )

    # 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:
						a_						:						Tuple 							= MockedPredictor()
						yield


@LocalMetricTest.register_intensive_calls_patcher("""bertscore""")
def 					_UpperCAmelCase				(						a__):

			'''simple docstring'''



			import torch

			def bert_cos_score_idf(a__  ,	a__  ,	*a__  ,	**a__):
						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:
						a_						:						int 							= bert_cos_score_idf
						yield


@LocalMetricTest.register_intensive_calls_patcher("""comet""")
def 					_UpperCAmelCase				(						a__):

			'''simple docstring'''



			def load_from_checkpoint(a__):



						class        A__:
												"""simple docstring"""






												def 			UpperCamelCase__					(    self  ,      _lowercase  ,      *_lowercase  ,      **_lowercase    )     -> int:
															assert len(_lowercase    ) == 2
															a_						:						int 							= [0.1_9, 0.9_2]
															return scores, sum(_lowercase    ) / len(_lowercase    )







						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:
						a_						:						List[Any] 							= None
						with patch("""comet.load_from_checkpoint""") as mock_load_from_checkpoint:
									a_						:						List[Any] 							= load_from_checkpoint
									yield



def 					_UpperCAmelCase				(						):

			'''simple docstring'''



			a_						:						List[str] 							= load_metric(os.path.join("""metrics"""  ,	"""seqeval"""))
			a_						:						Dict 							= """ERROR"""
			a_						:						Union[str, Any] 							= 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 tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch



@require_torch
@require_tf
class        A__(a_							):
						"""simple docstring"""






						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_						:						List[Any] 							= SMALL_MODEL_IDENTIFIER
									a_						:						Optional[int] 							= """pt"""
									a_						:						Union[str, Any] 							= """tf"""





						def 			UpperCamelCase__					(    self  ,      _lowercase    )     -> str:
									a_						:						Union[str, Any] 							= AutoModel.from_pretrained(self.test_model    )
									model_pt.save_pretrained(_lowercase    )





						def 			UpperCamelCase__					(    self  ,      _lowercase    )     -> List[str]:
									a_						:						int 							= TFAutoModel.from_pretrained(self.test_model  ,      from_pt=_lowercase    )
									model_tf.save_pretrained(_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									a_						:						str 							= """mock_framework"""

									# Framework provided - return whatever the user provides
									a_						:						Optional[int] 							= FeaturesManager.determine_framework(self.test_model  ,      _lowercase    )
									self.assertEqual(_lowercase  ,      _lowercase    )

									# Local checkpoint and framework provided - return provided framework
									# PyTorch checkpoint
									with TemporaryDirectory() as local_pt_ckpt:
												self._setup_pt_ckpt(_lowercase    )
												a_						:						Optional[int] 							= FeaturesManager.determine_framework(_lowercase  ,      _lowercase    )
												self.assertEqual(_lowercase  ,      _lowercase    )

									# TensorFlow checkpoint
									with TemporaryDirectory() as local_tf_ckpt:
												self._setup_tf_ckpt(_lowercase    )
												a_						:						List[str] 							= FeaturesManager.determine_framework(_lowercase  ,      _lowercase    )
												self.assertEqual(_lowercase  ,      _lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									# PyTorch checkpoint
									with TemporaryDirectory() as local_pt_ckpt:
												self._setup_pt_ckpt(_lowercase    )
												a_						:						Union[str, Any] 							= FeaturesManager.determine_framework(_lowercase    )
												self.assertEqual(_lowercase  ,      self.framework_pt    )

									# TensorFlow checkpoint
									with TemporaryDirectory() as local_tf_ckpt:
												self._setup_tf_ckpt(_lowercase    )
												a_						:						Union[str, Any] 							= FeaturesManager.determine_framework(_lowercase    )
												self.assertEqual(_lowercase  ,      self.framework_tf    )

									# Invalid local checkpoint
									with TemporaryDirectory() as local_invalid_ckpt:
												with self.assertRaises(_lowercase    ):
															a_						:						Union[str, Any] 							= FeaturesManager.determine_framework(_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> List[Any]:
									a_						:						int 							= MagicMock(return_value=_lowercase    )
									with patch("""transformers.onnx.features.is_tf_available"""  ,      _lowercase    ):
												a_						:						Union[str, Any] 							= FeaturesManager.determine_framework(self.test_model    )
												self.assertEqual(_lowercase  ,      self.framework_pt    )

									# PyTorch not in environment -> use TensorFlow
									a_						:						Dict 							= MagicMock(return_value=_lowercase    )
									with patch("""transformers.onnx.features.is_torch_available"""  ,      _lowercase    ):
												a_						:						Union[str, Any] 							= FeaturesManager.determine_framework(self.test_model    )
												self.assertEqual(_lowercase  ,      self.framework_tf    )

									# Both in environment -> use PyTorch
									a_						:						Optional[Any] 							= MagicMock(return_value=_lowercase    )
									a_						:						List[Any] 							= MagicMock(return_value=_lowercase    )
									with patch("""transformers.onnx.features.is_tf_available"""  ,      _lowercase    ), patch(
									    """transformers.onnx.features.is_torch_available"""  ,      _lowercase    ):
												a_						:						Any 							= FeaturesManager.determine_framework(self.test_model    )
												self.assertEqual(_lowercase  ,      self.framework_pt    )

									# Both not in environment -> raise error
									a_						:						List[str] 							= MagicMock(return_value=_lowercase    )
									a_						:						Optional[Any] 							= MagicMock(return_value=_lowercase    )
									with patch("""transformers.onnx.features.is_tf_available"""  ,      _lowercase    ), patch(
									    """transformers.onnx.features.is_torch_available"""  ,      _lowercase    ):
												with self.assertRaises(_lowercase    ):
															a_						:						Dict 							= FeaturesManager.determine_framework(self.test_model    )


