




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


UpperCAmelCase_					=   {"comet"}
UpperCAmelCase_					=   importlib.util.find_spec("fairseq") is not None

UpperCAmelCase_					=   {"code_eval"}
UpperCAmelCase_					=   os.name == "nt"

UpperCAmelCase_					=   {"bertscore", "frugalscore", "perplexity"}
UpperCAmelCase_					=   importlib.util.find_spec("transformers") is not None


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

  return wrapper


def     SCREAMING_SNAKE_CASE							(   a_						:				Tuple      ):
  @wraps(a_      )
  def wrapper(self						:				List[str]					,       a_						:				List[Any]      ):
    if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
      self.skipTest('"test requires transformers"'      )
    else:
      test_case(self					,       a_      )

  return wrapper


def     SCREAMING_SNAKE_CASE							(   a_						:				List[str]      ):
  @wraps(a_      )
  def wrapper(self						:				Dict					,       a_						:				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     SCREAMING_SNAKE_CASE							(   ):
  __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(
    __magic_name__							,				__magic_name__							,				__magic_name__			)
@local
class  __lowercase    (	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 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     str:
     __a								=       '[...]'
     __a								=       importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('metrics'   ,				UpperCamelCase   )   ).module_path   )
     __a								=       datasets.load.import_main_class(metric_module.__name__   ,				dataset=UpperCamelCase   )
     # 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(UpperCamelCase   ,				metric_module.__name__   ):
       with self.use_local_metrics():
         try:
           __a								=       doctest.testmod(UpperCamelCase   ,				verbose=UpperCamelCase   ,				raise_on_error=UpperCamelCase   )
         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   ,				UpperCamelCase   )					->     Union[str, Any]:
     __a								=       '[...]'
     __a								=       importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('metrics'   ,				UpperCamelCase   )   ).module_path   )
     # run doctest
     with self.use_local_metrics():
       __a								=       doctest.testmod(UpperCamelCase   ,				verbose=UpperCamelCase   ,				raise_on_error=UpperCamelCase   )
     self.assertEqual(results.failed   ,				0   )
     self.assertGreater(results.attempted   ,				1   )







   @contextmanager
   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Any:
     if metric_name in self.INTENSIVE_CALLS_PATCHER:
       with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCamelCase   ):
         yield
     else:
       yield







   @contextmanager
   def 		UpperCamelCase__      (						self   )					->     Optional[int]:
     def load_local_metric(UpperCamelCase   ,				*UpperCamelCase   ,				**UpperCamelCase   ):
       return load_metric(os.path.join('metrics'   ,				UpperCamelCase   )   ,				*UpperCamelCase   ,				**UpperCamelCase   )

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







   @classmethod
   def 		UpperCamelCase__      (						cls   ,				UpperCamelCase   )					->     Optional[Any]:
     def wrapper(UpperCamelCase   ):
       __a								=       contextmanager(UpperCamelCase   )
       __a								=       patcher
       return patcher

     return wrapper


@LocalMetricTest.register_intensive_calls_patcher('bleurt'      )
def     SCREAMING_SNAKE_CASE							(   a_						:				Any      ):
  import tensorflow.compat.va as tf
  from bleurt.score import Predictor

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





  class  __lowercase    (	__magic_name__			):







     def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Dict:
       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:
    __a								=       MockedPredictor()
    yield


@LocalMetricTest.register_intensive_calls_patcher('bertscore'      )
def     SCREAMING_SNAKE_CASE							(   a_						:				Dict      ):
  import torch

  def bert_cos_score_idf(a_						:				Dict					,       a_						:				Tuple					,       *a_						:				Dict					,       **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:
    __a								=       bert_cos_score_idf
    yield


@LocalMetricTest.register_intensive_calls_patcher('comet'      )
def     SCREAMING_SNAKE_CASE							(   a_						:				Dict      ):
  def load_from_checkpoint(a_						:				List[str]      ):





    class  __lowercase    :







       def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				*UpperCamelCase   ,				**UpperCamelCase   )					->     Union[str, Any]:
         assert len(UpperCamelCase   ) == 2
         __a								=       [0.19, 0.92]
         return scores, sum(UpperCamelCase   ) / len(UpperCamelCase   )

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









'''simple docstring'''


import inspect
import os
import unittest

import torch

import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
    execute_subprocess_async,
    require_cpu,
    require_huggingface_suite,
    require_multi_gpu,
    require_single_gpu,
)
from accelerate.utils import patch_environment





@require_huggingface_suite
class  __lowercase    (	unittest.TestCase			):







   def 		UpperCamelCase__      (						self   )					->     Tuple:
     __a								=       inspect.getfile(accelerate.test_utils   )
     __a								=       os.path.sep.join(
         mod_file.split(os.path.sep   )[:-1] + ['scripts', 'external_deps', 'test_metrics.py']   )

     from accelerate.test_utils.scripts.external_deps import test_metrics  # noqa: F401

     __a								=       test_metrics







   @require_cpu
   def 		UpperCamelCase__      (						self   )					->     Tuple:
     debug_launcher(self.test_metrics.main   ,				num_processes=1   )







   @require_cpu
   def 		UpperCamelCase__      (						self   )					->     str:
     debug_launcher(self.test_metrics.main   )







   @require_single_gpu
   def 		UpperCamelCase__      (						self   )					->     Dict:
     self.test_metrics.main()







   @require_multi_gpu
   def 		UpperCamelCase__      (						self   )					->     int:
     print(f"Found {torch.cuda.device_count()} devices."   )
     __a								=       ['torchrun', f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path]
     with patch_environment(omp_num_threads=1   ):
       execute_subprocess_async(UpperCamelCase   ,				env=os.environ.copy()   )



