

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


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

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

__lowerCamelCase						    =      {"bertscore", "frugalscore", "perplexity"}
__lowerCamelCase						    =      importlib.util.find_spec('''transformers''') is not None
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Optional[int]:



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

       return wrapper
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Optional[Any]:



       @wraps(UpperCAmelCase__			)
       def wrapper(self,    UpperCAmelCase__			):
              if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
                     self.skipTest("""\"test requires transformers\""""			)
              else:
                     test_case(self,    UpperCAmelCase__			)

       return wrapper
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     str:



       @wraps(UpperCAmelCase__			)
       def wrapper(self,    UpperCAmelCase__			):
              if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
                     self.skipTest("""\"test not supported on Windows\""""			)
              else:
                     test_case(self,    UpperCAmelCase__			)

       return wrapper
def  UpperCAmelCase__      ( )     ->     Dict:
       A_		   = [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(
    __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase     )
@local
class    A__ ( parameterized.TestCase     ):
    lowercase		   =						{}
    lowercase		   =						None



    @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""    )
    @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""    )
    def    snake_case_     (   self						,			UpperCamelCase__    )  -> int:





           '''simple docstring'''
           A_		   = '''[...]'''
           A_		   = importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("""metrics"""						,			lowerCamelCase__    )    ).module_path    )
           A_		   = datasets.load.import_main_class(metric_module.__name__						,			dataset=lowerCamelCase__    )
           # check parameters
           A_		   = 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(lowerCamelCase__						,			metric_module.__name__    ):
                  with self.use_local_metrics():
                         try:
                                A_		   = doctest.testmod(lowerCamelCase__						,			verbose=lowerCamelCase__						,			raise_on_error=lowerCamelCase__    )
                         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    snake_case_     (   self						,			UpperCamelCase__    )  -> List[str]:





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



    @contextmanager
    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Tuple:





           '''simple docstring'''






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



    @contextmanager
    def    snake_case_     (   self    )  -> str:





           '''simple docstring'''






           def load_local_metric(UpperCamelCase__						,			*UpperCamelCase__						,			**UpperCamelCase__    ):
                  return load_metric(os.path.join("""metrics"""						,			lowerCamelCase__    )						,			*lowerCamelCase__						,			**lowerCamelCase__    )

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







    @classmethod
    def    snake_case_     (   cls						,			UpperCamelCase__    )  -> Any:





           '''simple docstring'''






           def wrapper(UpperCamelCase__    ):
                  A_		   = contextmanager(lowerCamelCase__    )
                  A_		   = patcher
                  return patcher

           return wrapper

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

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


       class    A__ ( __lowerCAmelCase     ):



           def    snake_case_     (   self						,			UpperCamelCase__    )  -> Union[str, Any]:





                  '''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:
              A_		   = MockedPredictor()
              yield
@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     int:
       import torch

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

       # 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_		   = bert_cos_score_idf
              yield
@LocalMetricTest.register_intensive_calls_patcher("""comet"""			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Union[str, Any]:



       def load_from_checkpoint(UpperCAmelCase__			):


              class    A__ :



                  def    snake_case_     (   self						,			UpperCamelCase__						,			*UpperCamelCase__						,			**UpperCamelCase__    )  -> List[str]:





                         '''simple docstring'''
                         assert len(lowerCamelCase__    ) == 2
                         A_		   = [0.19, 0.92]
                         return scores, sum(lowerCamelCase__    ) / len(lowerCamelCase__    )

              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_		   = None
              with patch("""comet.load_from_checkpoint"""			) as mock_load_from_checkpoint:
                     A_		   = load_from_checkpoint
                     yield







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



'''simple docstring'''







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__ ( _snake_case     ):



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_		   = SMALL_MODEL_IDENTIFIER
           A_		   = """pt"""
           A_		   = """tf"""



    def    snake_case_     (   self						,			UpperCamelCase__    )  -> Tuple:





           '''simple docstring'''
           A_		   = AutoModel.from_pretrained(self.test_model    )
           model_pt.save_pretrained(UpperCamelCase__    )



    def    snake_case_     (   self						,			UpperCamelCase__    )  -> List[str]:





           '''simple docstring'''
           A_		   = TFAutoModel.from_pretrained(self.test_model						,			from_pt=UpperCamelCase__    )
           model_tf.save_pretrained(UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_		   = """mock_framework"""

           # Framework provided - return whatever the user provides
           A_		   = FeaturesManager.determine_framework(self.test_model						,			UpperCamelCase__    )
           self.assertEqual(UpperCamelCase__						,			UpperCamelCase__    )

           # Local checkpoint and framework provided - return provided framework
           # PyTorch checkpoint
           with TemporaryDirectory() as local_pt_ckpt:
                  self._setup_pt_ckpt(UpperCamelCase__    )
                  A_		   = FeaturesManager.determine_framework(UpperCamelCase__						,			UpperCamelCase__    )
                  self.assertEqual(UpperCamelCase__						,			UpperCamelCase__    )

           # TensorFlow checkpoint
           with TemporaryDirectory() as local_tf_ckpt:
                  self._setup_tf_ckpt(UpperCamelCase__    )
                  A_		   = FeaturesManager.determine_framework(UpperCamelCase__						,			UpperCamelCase__    )
                  self.assertEqual(UpperCamelCase__						,			UpperCamelCase__    )



    def    snake_case_     (   self    )  -> int:





           '''simple docstring'''
           # PyTorch checkpoint
           with TemporaryDirectory() as local_pt_ckpt:
                  self._setup_pt_ckpt(UpperCamelCase__    )
                  A_		   = FeaturesManager.determine_framework(UpperCamelCase__    )
                  self.assertEqual(UpperCamelCase__						,			self.framework_pt    )

           # TensorFlow checkpoint
           with TemporaryDirectory() as local_tf_ckpt:
                  self._setup_tf_ckpt(UpperCamelCase__    )
                  A_		   = FeaturesManager.determine_framework(UpperCamelCase__    )
                  self.assertEqual(UpperCamelCase__						,			self.framework_tf    )

           # Invalid local checkpoint
           with TemporaryDirectory() as local_invalid_ckpt:
                  with self.assertRaises(UpperCamelCase__    ):
                         A_		   = FeaturesManager.determine_framework(UpperCamelCase__    )







    def    snake_case_     (   self    )  -> List[Any]:





           '''simple docstring'''
           A_		   = MagicMock(return_value=UpperCamelCase__    )
           with patch("""transformers.onnx.features.is_tf_available"""						,			UpperCamelCase__    ):
                  A_		   = FeaturesManager.determine_framework(self.test_model    )
                  self.assertEqual(UpperCamelCase__						,			self.framework_pt    )

           # PyTorch not in environment -> use TensorFlow
           A_		   = MagicMock(return_value=UpperCamelCase__    )
           with patch("""transformers.onnx.features.is_torch_available"""						,			UpperCamelCase__    ):
                  A_		   = FeaturesManager.determine_framework(self.test_model    )
                  self.assertEqual(UpperCamelCase__						,			self.framework_tf    )

           # Both in environment -> use PyTorch
           A_		   = MagicMock(return_value=UpperCamelCase__    )
           A_		   = MagicMock(return_value=UpperCamelCase__    )
           with patch("""transformers.onnx.features.is_tf_available"""						,			UpperCamelCase__    ), patch(
               """transformers.onnx.features.is_torch_available"""						,			UpperCamelCase__    ):
                  A_		   = FeaturesManager.determine_framework(self.test_model    )
                  self.assertEqual(UpperCamelCase__						,			self.framework_pt    )

           # Both not in environment -> raise error
           A_		   = MagicMock(return_value=UpperCamelCase__    )
           A_		   = MagicMock(return_value=UpperCamelCase__    )
           with patch("""transformers.onnx.features.is_tf_available"""						,			UpperCamelCase__    ), patch(
               """transformers.onnx.features.is_torch_available"""						,			UpperCamelCase__    ):
                  with self.assertRaises(UpperCamelCase__    ):
                         A_		   = FeaturesManager.determine_framework(self.test_model    )
