'''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  :Union[str, Any]  				=    pytest.mark.integration


_lowerCAmelCase  :Optional[int]  				=    {'comet'}
_lowerCAmelCase  :Union[str, Any]  				=    importlib.util.find_spec("""fairseq""") is not None

_lowerCAmelCase  :Dict  				=    {'code_eval'}
_lowerCAmelCase  :str  				=    os.name == 'nt'

_lowerCAmelCase  :Union[str, Any]  				=    {'bertscore', 'frugalscore', 'perplexity'}
_lowerCAmelCase  :Any  				=    importlib.util.find_spec("""transformers""") is not None


def     __lowerCAmelCase						(       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     __lowerCAmelCase						(       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     __lowerCAmelCase						(       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     __lowerCAmelCase						(       )      ->	List[str]:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			Union[str, 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 				UpperCAmelCase (       parameterized.TestCase ):




    '''simple docstring'''







    snake_case__							:   Tuple							=						{}
    snake_case__							:   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__ )							-> Optional[Any]:
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       '[...]'
         SCREAMING_SNAKE_CASE					:			Any    	=       importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('metrics'    ,							UpperCAmelCase_ ) ).module_path )
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       datasets.load.import_main_class(metric_module.__name__    ,							dataset=UpperCAmelCase_ )
         # check parameters
         SCREAMING_SNAKE_CASE					:			Dict    	=       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:
                        SCREAMING_SNAKE_CASE					:			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       _UpperCamelCase    (       self    ,							lowercase__ )							-> Any:
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       '[...]'
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('metrics'    ,							UpperCAmelCase_ ) ).module_path )
         # run doctest
         with self.use_local_metrics():
              SCREAMING_SNAKE_CASE					:			List[str]    	=       doctest.testmod(UpperCAmelCase_    ,							verbose=UpperCAmelCase_    ,							raise_on_error=UpperCAmelCase_ )
         self.assertEqual(results.failed    ,							0 )
         self.assertGreater(results.attempted    ,							1 )






    @contextmanager
    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__ )							-> int:



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






    @contextmanager
    def       _UpperCamelCase    (       self )							-> Optional[Any]:



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

         with patch('datasets.load_metric' ) as mock_load_metric:
              SCREAMING_SNAKE_CASE					:			List[str]    	=       load_local_metric
              yield






    @classmethod
    def       _UpperCamelCase    (       cls    ,							lowercase__ )							-> List[Any]:



         def wrapper(lowercase__ ):
              SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       contextmanager(UpperCAmelCase_ )
              SCREAMING_SNAKE_CASE					:			Optional[int]    	=       patcher
              return patcher

         return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt'		)
def     __lowerCAmelCase						(       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 				UpperCAmelCase (       snake_case__ ):




         '''simple docstring'''







         def       _UpperCamelCase    (       self    ,							lowercase__ )							-> List[str]:
              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:
          SCREAMING_SNAKE_CASE					:			Dict    	=       MockedPredictor()
          yield


@LocalMetricTest.register_intensive_calls_patcher('bertscore'		)
def     __lowerCAmelCase						(       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:
          SCREAMING_SNAKE_CASE					:			str    	=       bert_cos_score_idf
          yield


@LocalMetricTest.register_intensive_calls_patcher('comet'		)
def     __lowerCAmelCase						(       a_		)      ->	Any:





     '''simple docstring'''





     def load_from_checkpoint(a_		):






          class 				UpperCAmelCase :




              '''simple docstring'''







              def       _UpperCamelCase    (       self    ,							lowercase__    ,							*lowercase__    ,							**lowercase__ )							-> Any:
                   assert len(UpperCAmelCase_ ) == 2
                   SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       [0.1_9, 0.9_2]
                   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:
          SCREAMING_SNAKE_CASE					:			List[str]    	=       None
          with patch('comet.load_from_checkpoint'		) as mock_load_from_checkpoint:
               SCREAMING_SNAKE_CASE					:			Optional[int]    	=       load_from_checkpoint
               yield


def     __lowerCAmelCase						(       )      ->	List[str]:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			int    	=       load_metric(os.path.join('metrics'       ,      'seqeval'		)		)
     SCREAMING_SNAKE_CASE					:			Dict    	=       'ERROR'
     SCREAMING_SNAKE_CASE					:			Dict    	=       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 unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
 import torch

 from transformers.activations import gelu_new, gelu_python, get_activation






@require_torch
class 				UpperCAmelCase (       unittest.TestCase ):




    '''simple docstring'''







    def       _UpperCamelCase    (       self )							-> int:
         SCREAMING_SNAKE_CASE					:			str    	=       torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] )
         SCREAMING_SNAKE_CASE					:			str    	=       get_activation('gelu' )
         self.assertTrue(torch.allclose(gelu_python(lowercase__ )    ,							torch_builtin(lowercase__ ) ) )
         self.assertFalse(torch.allclose(gelu_python(lowercase__ )    ,							gelu_new(lowercase__ ) ) )






    def       _UpperCamelCase    (       self )							-> Optional[Any]:
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] )
         SCREAMING_SNAKE_CASE					:			str    	=       get_activation('gelu' )
         SCREAMING_SNAKE_CASE					:			Dict    	=       get_activation('gelu_10' )

         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       torch_builtin(lowercase__ )
         SCREAMING_SNAKE_CASE					:			str    	=       geluaa(lowercase__ )

         SCREAMING_SNAKE_CASE					:			List[Any]    	=       torch.where(y_gelu_aa < 1_0.0    ,							1    ,							0 )

         self.assertTrue(torch.max(lowercase__ ).item() == 1_0.0 )
         self.assertTrue(torch.allclose(y_gelu * clipped_mask    ,							y_gelu_aa * clipped_mask ) )






    def       _UpperCamelCase    (       self )							-> Optional[Any]:
         get_activation('gelu' )
         get_activation('gelu_10' )
         get_activation('gelu_fast' )
         get_activation('gelu_new' )
         get_activation('gelu_python' )
         get_activation('gelu_pytorch_tanh' )
         get_activation('linear' )
         get_activation('mish' )
         get_activation('quick_gelu' )
         get_activation('relu' )
         get_activation('sigmoid' )
         get_activation('silu' )
         get_activation('swish' )
         get_activation('tanh' )
         with self.assertRaises(lowercase__ ):
              get_activation('bogus' )
         with self.assertRaises(lowercase__ ):
              get_activation(lowercase__ )






    def       _UpperCamelCase    (       self )							-> int:
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       get_activation('gelu' )
         SCREAMING_SNAKE_CASE					:			str    	=       1
         SCREAMING_SNAKE_CASE					:			List[str]    	=       get_activation('gelu' )
         self.assertEqual(acta.a    ,							1 )
         with self.assertRaises(lowercase__ ):
              SCREAMING_SNAKE_CASE					:			Dict    	=       acta.a



