





"""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    : List[Any]							=							pytest.mark.integration


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

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

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

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						str    )  ->       Tuple:





     '''simple docstring'''

     @wraps(SCREAMING_SNAKE_CASE__    )
     def wrapper(self     :						Dict						,  SCREAMING_SNAKE_CASE__     :						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 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						int    )  ->       Tuple:





     '''simple docstring'''

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





     '''simple docstring'''

     @wraps(SCREAMING_SNAKE_CASE__    )
     def wrapper(self     :						Optional[int]						,  SCREAMING_SNAKE_CASE__     :						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 						__snake_case						(				)  ->       Any:





     '''simple docstring'''

     _UpperCAmelCase      :     Optional[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(
    _UpperCamelCase	,      _UpperCamelCase	,      _UpperCamelCase						)
@local
class      UpperCAmelCase_  (    parameterized.TestCase						):
      __SCREAMING_SNAKE_CASE						:       str								=			{}
      __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 						snake_case_ (					self					:     str					,     A					:     Union[str, Any]						):
           _UpperCAmelCase      :     Optional[int]        =   "[...]"
           _UpperCAmelCase      :     List[str]        =   importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("metrics"					,     A						)						).module_path						)
           _UpperCAmelCase      :     int        =   datasets.load.import_main_class(metric_module.__name__					,     dataset=A						)
           # check parameters
           _UpperCAmelCase      :     Optional[int]        =   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(A					,     metric_module.__name__						):
                with self.use_local_metrics():
                     try:
                          _UpperCAmelCase      :     str        =   doctest.testmod(A					,     verbose=A					,     raise_on_error=A						)
                     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 						snake_case_ (					self					:     Tuple					,     A					:     List[Any]						):
           _UpperCAmelCase      :     int        =   "[...]"
           _UpperCAmelCase      :     List[Any]        =   importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("metrics"					,     A						)						).module_path						)
           # run doctest
           with self.use_local_metrics():
                _UpperCAmelCase      :     int        =   doctest.testmod(A					,     verbose=A					,     raise_on_error=A						)
           self.assertEqual(results.failed					,     0						)
           self.assertGreater(results.attempted					,     1						)



      @contextmanager
      def 						snake_case_ (					self					:     Optional[int]					,     A					:     List[Any]					,     A					:     int						):
           if metric_name in self.INTENSIVE_CALLS_PATCHER:
                with self.INTENSIVE_CALLS_PATCHER[metric_name](A						):
                     yield
           else:
                yield



      @contextmanager
      def 						snake_case_ (					self					:     Tuple						):
           def load_local_metric(A					:     List[Any]					,     *A					:     str					,     **A					:     Any						):
                return load_metric(os.path.join("metrics"					,     A						)					,     *A					,     **A						)

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



      @classmethod
      def 						snake_case_ (					cls					:     List[Any]					,     A					:     Dict						):
           def wrapper(A					:     int						):
                _UpperCAmelCase      :     Tuple        =   contextmanager(A						)
                _UpperCAmelCase      :     int        =   patcher
                return patcher

           return wrapper







@LocalMetricTest.register_intensive_calls_patcher("bleurt"    )
def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						str    )  ->       List[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_  (    _UpperCamelCase						):



           def 						snake_case_ (					self					:     Tuple					,     A					:     Tuple						):
                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 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						int    )  ->       int:





     '''simple docstring'''

     import torch

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

@LocalMetricTest.register_intensive_calls_patcher("comet"    )
def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Any    )  ->       Tuple:





     '''simple docstring'''

     def load_from_checkpoint(SCREAMING_SNAKE_CASE__     :						Union[str, Any]    ):






          class      UpperCAmelCase_  :



                def 						snake_case_ (					self					:     Optional[Any]					,     A					:     Dict					,     *A					:     int					,     **A					:     Optional[int]						):
                     assert len(A						) == 2
                     _UpperCAmelCase      :     str        =   [0.19, 0.92]
                     return scores, sum(A						) / len(A						)







          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 						__snake_case						(				)  ->       Tuple:





     '''simple docstring'''

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




def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Dict=28_123    )  ->       List[str]:





     '''simple docstring'''

     _UpperCAmelCase      :     List[Any]        =   [1] * (limit + 1)

     for i in range(2						,  int(limit**0.5    ) + 1    ):
          sum_divs[i * i] += i
          for k in range(i + 1						,  limit // i + 1    ):
               sum_divs[k * i] += k + i

     _UpperCAmelCase      :     Any        =   set()
     _UpperCAmelCase      :     List[str]        =   0

     for n in range(1						,  limit + 1    ):
          if sum_divs[n] > n:
               abundants.add(SCREAMING_SNAKE_CASE__    )

          if not any((n - a in abundants) for a in abundants    ):
               res += n

     return res


if __name__ == "__main__":
 print(solution())
