





"""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      __lowerCamelCase   (							a_     :		List[str]							)			->      List[Any]:





      @wraps(SCREAMING_SNAKE_CASE__							)
      def wrapper(self     :		Union[str, Any] ,   a_     :		Optional[Any]							):
            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_     :		Union[str, Any]							)			->      Dict:





      @wraps(SCREAMING_SNAKE_CASE__							)
      def wrapper(self     :		str ,   a_     :		Optional[Any]							):
            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_     :		List[str]							)			->      str:





      @wraps(SCREAMING_SNAKE_CASE__							)
      def wrapper(self     :		int ,   a_     :		Dict							):
            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   (							)			->      Optional[Any]:
      __SCREAMING_SNAKE_CASE   :Dict						=  [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 					_SCREAMING_SNAKE_CASE(   parameterized.TestCase  ):
       SCREAMING_SNAKE_CASE_   :      Optional[int]							=  {}
       SCREAMING_SNAKE_CASE_   :      Union[str, Any]							=  None




       @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''							)
       @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''							)
       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__							)			->      Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  """[...]"""
             __SCREAMING_SNAKE_CASE   :Any						=  importlib.import_module(
                 datasets.load.metric_module_factory(os.path.join('''metrics'''		,__snake_case							)							).module_path							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  datasets.load.import_main_class(metric_module.__name__		,dataset=__snake_case							)
             # check parameters
             __SCREAMING_SNAKE_CASE   :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(__snake_case		,metric_module.__name__							):
                   with self.use_local_metrics():
                         try:
                               __SCREAMING_SNAKE_CASE   :int						=  doctest.testmod(__snake_case		,verbose=__snake_case		,raise_on_error=__snake_case							)
                         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		,SCREAMING_SNAKE_CASE__							)			->      Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  """[...]"""
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  importlib.import_module(
                 datasets.load.metric_module_factory(os.path.join('''metrics'''		,__snake_case							)							).module_path							)
             # run doctest
             with self.use_local_metrics():
                   __SCREAMING_SNAKE_CASE   :List[str]						=  doctest.testmod(__snake_case		,verbose=__snake_case		,raise_on_error=__snake_case							)
             self.assertEqual(results.failed		,0							)
             self.assertGreater(results.attempted		,1							)




       @contextmanager
       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      Union[str, Any]:





             """simple docstring"""






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




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





             """simple docstring"""






             def load_local_metric(SCREAMING_SNAKE_CASE__		,*SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							):
                   return load_metric(os.path.join('''metrics'''		,__snake_case							)		,*__snake_case		,**__snake_case							)

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




       @classmethod
       def     _UpperCamelCase     (						cls		,SCREAMING_SNAKE_CASE__							)			->      Optional[Any]:





             """simple docstring"""






             def wrapper(SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :Any						=  contextmanager(__snake_case							)
                   __SCREAMING_SNAKE_CASE   :int						=  patcher
                   return patcher

             return wrapper




@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''							)
def      __lowerCamelCase   (							a_     :		Any							)			->      List[Any]:
      import tensorflow.compat.va as tf
      from bleurt.score import Predictor

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






      class 					_SCREAMING_SNAKE_CASE(   _snake_case  ):




             def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__							)			->      Any:





                   """simple docstring"""






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



@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''							)
def      __lowerCamelCase   (							a_     :		List[str]							)			->      Union[str, Any]:
      import torch

      def bert_cos_score_idf(a_     :		int ,   a_     :		Any ,   *a_     :		Optional[Any] ,   **a_     :		str							):
            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   :Any						=  bert_cos_score_idf
            yield



@LocalMetricTest.register_intensive_calls_patcher('''comet'''							)
def      __lowerCamelCase   (							a_     :		Tuple							)			->      List[Any]:





      def load_from_checkpoint(a_     :		int							):






            class 					_SCREAMING_SNAKE_CASE:




                   def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,*SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)			->      List[Any]:





                         """simple docstring"""






                         assert len(__snake_case							) == 2
                         __SCREAMING_SNAKE_CASE   :Dict						=  [0.1_9, 0.9_2]
                         return scores, sum(__snake_case							) / len(__snake_case							)




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







def      __lowerCamelCase   (							)			->      Optional[int]:
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  load_metric(os.path.join('''metrics''' ,   '''seqeval'''							)							)
      __SCREAMING_SNAKE_CASE   :List[str]						=  """ERROR"""
      __SCREAMING_SNAKE_CASE   :Tuple						=  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'''


UpperCAmelCase_		:   Dict							   =		[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

UpperCAmelCase_		:   Any							   =		[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

UpperCAmelCase_		:   Tuple							   =		[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

UpperCAmelCase_		:   Dict							   =		[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

UpperCAmelCase_		:   Tuple							   =		[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

UpperCAmelCase_		:   Union[str, Any]							   =		[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

UpperCAmelCase_		:   Tuple							   =		[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

UpperCAmelCase_		:   int							   =		[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]




