

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


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

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

lowercase_             =     {'bertscore', 'frugalscore', 'perplexity'}
lowercase_             =     importlib.util.find_spec('transformers') is not None
def   a   (    A__			:     Dict  )					->   Any:





      """simple docstring"""



      @wraps(A__  )
      def wrapper(self			:     Tuple   ,     A__			:     List[Any]  ):
            if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
                  self.skipTest('"test requires Fairseq"'  )
            else:
                  test_case(self   ,     A__  )

      return wrapper
def   a   (    A__			:     List[str]  )					->   str:





      """simple docstring"""



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

      return wrapper
def   a   (    A__			:     Any  )					->   int:





      """simple docstring"""



      @wraps(A__  )
      def wrapper(self			:     str   ,     A__			:     Optional[Any]  ):
            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   a   (    )					->   Any:





      """simple docstring"""



      _lowercase			 =[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(
    SCREAMING_SNAKE_CASE    ,    SCREAMING_SNAKE_CASE    ,    SCREAMING_SNAKE_CASE							)
@local
class 				__lowerCAmelCase  (      parameterized.TestCase							):
  _a		    =						{}
  _a		    =						None




  @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'      )
  @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'      )
  def 						A__  (       self							,     lowerCAmelCase      )						->				int:
        '''simple docstring'''






        _lowercase			 ='[...]'
        _lowercase			 =importlib.import_module(
            datasets.load.metric_module_factory(os.path.join('metrics'							,     lowerCAmelCase      )      ).module_path      )
        _lowercase			 =datasets.load.import_main_class(metric_module.__name__							,     dataset=lowerCAmelCase      )
        # check parameters
        _lowercase			 =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:
                          _lowercase			 =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 						A__  (       self							,     lowerCAmelCase      )						->				Optional[int]:
        '''simple docstring'''






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




  @contextmanager
  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase      )						->				Union[str, Any]:
        '''simple docstring'''






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




  @contextmanager
  def 						A__  (       self      )						->				List[str]:
        '''simple docstring'''






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

        with patch('datasets.load_metric'      ) as mock_load_metric:
              _lowercase			 =load_local_metric
              yield




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase      )						->				Any:
        '''simple docstring'''






        def wrapper(lowerCAmelCase      ):
              _lowercase			 =contextmanager(lowerCAmelCase      )
              _lowercase			 =patcher
              return patcher

        return wrapper
@LocalMetricTest.register_intensive_calls_patcher('bleurt'  )
def   a   (    A__			:     Optional[Any]  )					->   Tuple:





      """simple docstring"""



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

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





      class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):




        def 						A__  (       self							,     lowerCAmelCase      )						->				List[str]:
              '''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:
            _lowercase			 =MockedPredictor()
            yield
@LocalMetricTest.register_intensive_calls_patcher('bertscore'  )
def   a   (    A__			:     Optional[int]  )					->   int:





      """simple docstring"""



      import torch

      def bert_cos_score_idf(A__			:     Optional[int]   ,     A__			:     List[Any]   ,     *A__			:     List[Any]   ,     **A__			:     List[Any]  ):
            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:
            _lowercase			 =bert_cos_score_idf
            yield
@LocalMetricTest.register_intensive_calls_patcher('comet'  )
def   a   (    A__			:     Optional[int]  )					->   str:





      """simple docstring"""



      def load_from_checkpoint(A__			:     Optional[Any]  ):





            class 				__lowerCAmelCase  :




              def 						A__  (       self							,     lowerCAmelCase							,     *lowerCAmelCase							,     **lowerCAmelCase      )						->				Dict:
                    '''simple docstring'''






                    assert len(lowerCAmelCase      ) == 2
                    _lowercase			 =[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:
            _lowercase			 =None
            with patch('comet.load_from_checkpoint'  ) as mock_load_from_checkpoint:
                  _lowercase			 =load_from_checkpoint
                  yield







def   a   (    )					->   List[Any]:





      """simple docstring"""



      _lowercase			 =load_metric(os.path.join('metrics'   ,     'seqeval'  )  )
      _lowercase			 ='ERROR'
      _lowercase			 =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__  )





def   a   (    A__			:     str   ,     A__			:     int  )					->   list[str]:





      """simple docstring"""



      return [sentence[i : i + ngram_size] for i in range(len(A__  ) - ngram_size + 1  )]


if __name__ == "__main__":
  from doctest import testmod

  testmod()


