





"""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 					lowercase__    (					lowercase_			)					->		List[Any]:




      """simple docstring"""

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

      return wrapper




def 					lowercase__    (					lowercase_			)					->		int:




      """simple docstring"""

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

      return wrapper




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      @wraps(__A			)
      def wrapper(self		,lowercase_			):
            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 					lowercase__    (					)					->		List[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[int]						=       [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   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Optional[Any]	     =					{}
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					None

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

  @contextmanager
  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       Union[str, Any]					,   __a   :       Optional[Any]	)		->				Dict:
        if metric_name in self.INTENSIVE_CALLS_PATCHER:
              with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCAmelCase__	):
                    yield
        else:
              yield

  @contextmanager
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				int:
        def load_local_metric(__a   :       Tuple					,   *__a   :       str					,   **__a   :       Dict	):
              return load_metric(os.path.join("metrics"					,   lowerCAmelCase__	)					,   *lowerCAmelCase__					,   **lowerCAmelCase__	)

        with patch("datasets.load_metric"	) as mock_load_metric:
              _UpperCamelCase      :	Optional[Any]						=       load_local_metric
              yield


  @classmethod
  def    __SCREAMING_SNAKE_CASE				(		cls   :       List[Any]					,   __a   :       Any	)		->				str:
        def wrapper(__a   :       List[Any]	):
              _UpperCamelCase      :	List[str]						=       contextmanager(lowerCAmelCase__	)
              _UpperCamelCase      :	Tuple						=       patcher
              return patcher

        return wrapper





@LocalMetricTest.register_intensive_calls_patcher("bleurt"			)
def 					lowercase__    (					lowercase_			)					->		List[Any]:




      """simple docstring"""

      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   ):







        '''simple docstring'''


        def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       Any	)		->				int:
              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:
            _UpperCamelCase      :	Tuple						=       MockedPredictor()
            yield




@LocalMetricTest.register_intensive_calls_patcher("bertscore"			)
def 					lowercase__    (					lowercase_			)					->		Tuple:




      """simple docstring"""

      import torch

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




@LocalMetricTest.register_intensive_calls_patcher("comet"			)
def 					lowercase__    (					lowercase_			)					->		List[str]:




      """simple docstring"""

      def load_from_checkpoint(lowercase_			):



            class      __SCREAMING_SNAKE_CASE    :







              '''simple docstring'''


              def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]					,   __a   :       Optional[int]					,   *__a   :       Dict					,   **__a   :       str	)		->				Dict:
                    assert len(lowerCAmelCase__	) == 2
                    _UpperCamelCase      :	Optional[int]						=       [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:
            _UpperCamelCase      :	Optional[Any]						=       None
            with patch("comet.load_from_checkpoint"			) as mock_load_from_checkpoint:
                  _UpperCamelCase      :	List[Any]						=       load_from_checkpoint
                  yield




def 					lowercase__    (					)					->		List[Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       load_metric(os.path.join("metrics"		,"seqeval"			)			)
      _UpperCamelCase      :	List[Any]						=       "ERROR"
      _UpperCamelCase      :	List[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			)











"""simple docstring"""


import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(".")




def 					lowercase__    (					lowercase_			)					->		int:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       test_file.split(os.path.sep			)
      if components[0:2] != ["tests", "models"]:
            raise ValueError(
                "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got "
                F'''{test_file} instead.'''			)
      _UpperCamelCase      :	str						=       components[-1]
      if not test_fn.endswith("py"			):
            raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.'''			)
      if not test_fn.startswith("test_modeling_"			):
            raise ValueError(
                F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.'''			)

      _UpperCamelCase      :	Dict						=       components[:-1] + [test_fn.replace(".py"		,""			)]
      _UpperCamelCase      :	List[str]						=       ".".join(lowercase_			)

      return test_module_path




def 					lowercase__    (					lowercase_			)					->		List[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       get_module_path(lowercase_			)
      _UpperCamelCase      :	str						=       importlib.import_module(lowercase_			)

      return test_module




def 					lowercase__    (					lowercase_			)					->		Optional[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Union[str, Any]						=       []
      _UpperCamelCase      :	List[Any]						=       get_test_module(lowercase_			)
      for attr in dir(lowercase_			):
            if attr.endswith("ModelTester"			):
                  tester_classes.append(getattr(lowercase_		,lowercase_			)			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Tuple:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       []
      _UpperCamelCase      :	Any						=       get_test_module(lowercase_			)
      for attr in dir(lowercase_			):
            _UpperCamelCase      :	int						=       getattr(lowercase_		,lowercase_			)
            # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
            # `all_model_classes` is not empty (which also excludes other special classes).
            _UpperCamelCase      :	Optional[Any]						=       getattr(lowercase_		,"all_model_classes"		,[]			)
            if len(lowercase_			) > 0:
                  test_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Any:




      """simple docstring"""

      _UpperCamelCase      :	Dict						=       get_test_classes(lowercase_			)
      _UpperCamelCase      :	int						=       set()
      for test_class in test_classes:
            model_classes.update(test_class.all_model_classes			)

      # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Optional[Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       test_class()
      if hasattr(lowercase_		,"setUp"			):
            test.setUp()

      _UpperCamelCase      :	Tuple						=       None
      if hasattr(lowercase_		,"model_tester"			):
            # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
            if test.model_tester is not None:
                  _UpperCamelCase      :	Tuple						=       test.model_tester.__class__

      return model_tester




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	str						=       get_test_classes(lowercase_			)

      _UpperCamelCase      :	Dict						=       []
      for test_class in test_classes:
            if model_class in test_class.all_model_classes:
                  target_test_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Dict:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       get_test_classes_for_model(lowercase_		,lowercase_			)

      _UpperCamelCase      :	List[Any]						=       []
      for test_class in test_classes:
            _UpperCamelCase      :	List[Any]						=       get_model_tester_from_test_class(lowercase_			)
            if tester_class is not None:
                  tester_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       get_test_classes(lowercase_			)
      _UpperCamelCase      :	Tuple						=       {test_class: get_model_tester_from_test_class(lowercase_			) for test_class in test_classes}
      return test_tester_mapping




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       get_model_classes(lowercase_			)
      _UpperCamelCase      :	Optional[int]						=       {
          model_class: get_test_classes_for_model(lowercase_		,lowercase_			) for model_class in model_classes
      }
      return model_test_mapping




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       get_model_classes(lowercase_			)
      _UpperCamelCase      :	Tuple						=       {
          model_class: get_tester_classes_for_model(lowercase_		,lowercase_			) for model_class in model_classes
      }
      return model_to_tester_mapping




def 					lowercase__    (					lowercase_			)					->		Optional[int]:




      """simple docstring"""

      if isinstance(lowercase_		,lowercase_			):
            return o
      elif isinstance(lowercase_		,lowercase_			):
            return o.__name__
      elif isinstance(lowercase_		,(list, tuple)			):
            return [to_json(lowercase_			) for x in o]
      elif isinstance(lowercase_		,lowercase_			):
            return {to_json(lowercase_			): to_json(lowercase_			) for k, v in o.items()}
      else:
            return o
