



'''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
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  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







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

     return wrapper






def  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







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

     return wrapper






def  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







     @wraps(lowercase__       )
     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       ,	lowercase__       )

     return wrapper






def  UpperCAmelCase_       (		):


     '''simple docstring'''







     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(
    __a					,	__a					,	__a)
@local
class 	UpperCAmelCase	(		parameterized.TestCase):


 '''simple docstring'''




 __magic_name__					: Any  =      {}
 __magic_name__					: Optional[int]  =      None




 @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning")
 @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning")
 def       lowercase_  (   self							,  lowerCAmelCase_) ->      List[str]:



      """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       lowercase_  (   self							,  lowerCAmelCase_) ->      Tuple:



      """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       lowercase_  (   self							,  lowerCAmelCase_							,  lowerCAmelCase_) ->      Tuple:



      """simple docstring"""







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




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



      """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:
           a_       		=load_local_metric
           yield




 @classmethod
 def       lowercase_  (   cls							,  lowerCAmelCase_) ->      List[Any]:



      """simple docstring"""







      def wrapper(lowerCAmelCase_):
           a_       		=contextmanager(lowerCAmelCase_)
           a_       		=patcher
           return patcher

      return wrapper






@LocalMetricTest.register_intensive_calls_patcher("bleurt"       )
def  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







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

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







     class 	UpperCAmelCase	(		__a):


      '''simple docstring'''




      def       lowercase_  (   self							,  lowerCAmelCase_) ->      Optional[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:
          a_       		=MockedPredictor()
          yield






@LocalMetricTest.register_intensive_calls_patcher("bertscore"       )
def  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







     import torch

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

     # 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_       (		lowercase__       ):


     '''simple docstring'''







     def load_from_checkpoint(lowercase__       ):







          class 	UpperCAmelCase	:


           '''simple docstring'''




           def       lowercase_  (   self							,  lowerCAmelCase_							,  *lowerCAmelCase_							,  **lowerCAmelCase_) ->      Dict:



                """simple docstring"""







                assert len(lowerCAmelCase_) == 2
                a_       		=[0.1_9, 0.9_2]
                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_       (		):


     '''simple docstring'''







     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(lowercase__       ,	match=re.escape(lowercase__       )       ):
          metric.compute(predictions=[]       ,	references=[]       ,	scheme=lowercase__       )







'''simple docstring'''


from __future__ import annotations






def  UpperCAmelCase_       (		lowercase__       ,	lowercase__       ):


     '''simple docstring'''







     if b == 0:
          return (1, 0)
     ((a_)		,						(a_))       		=extended_euclid(lowercase__       ,	a % b       )
     a_       		=a // b
     return (y, x - k * y)






def  UpperCAmelCase_       (		lowercase__       ,	lowercase__       ,	lowercase__       ,	lowercase__       ):


     '''simple docstring'''







     ((a_)		,						(a_))       		=extended_euclid(lowercase__       ,	lowercase__       )
     a_       		=na * na
     a_       		=ra * x * na + ra * y * na
     return (n % m + m) % m






def  UpperCAmelCase_       (		lowercase__       ,	lowercase__       ):


     '''simple docstring'''







     ((a_)		,						(a_))       		=extended_euclid(lowercase__       ,	lowercase__       )
     if b < 0:
          a_       		=(b % n + n) % n
     return b






def  UpperCAmelCase_       (		lowercase__       ,	lowercase__       ,	lowercase__       ,	lowercase__       ):


     '''simple docstring'''







     a_		,						a_       		=invert_modulo(lowercase__       ,	lowercase__       ), invert_modulo(lowercase__       ,	lowercase__       )
     a_       		=na * na
     a_       		=ra * x * na + ra * y * na
     return (n % m + m) % m


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

  testmod(name='''chinese_remainder_theorem''', verbose=True)
  testmod(name='''chinese_remainder_theorem2''', verbose=True)
  testmod(name='''invert_modulo''', verbose=True)
  testmod(name='''extended_euclid''', verbose=True)


