

"""simple docstring"""





def   _A  (  UpperCamelCase_					:	str)     ->						str:
   '''simple docstring'''


   if not all(char in "01" for char in bin_string):
      raise ValueError("Non-binary value was passed to the function")
   if not bin_string:
      raise ValueError("Empty string was passed to the function")
   __lowercase								=						""
   while len(UpperCamelCase_) % 3 != 0:
      __lowercase								=						"0" + bin_string
   __lowercase								=						[
       bin_string[index : index + 3]
       for index in range(len(UpperCamelCase_))
       if index % 3 == 0
   ]
   for bin_group in bin_string_in_3_list:
      __lowercase								=						0
      for index, val in enumerate(UpperCamelCase_):
         oct_val += int(2 ** (2 - index) * int(UpperCamelCase_))
      oct_string += str(UpperCamelCase_)
   return oct_string


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

   testmod()







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


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

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

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




def   _A  (  UpperCamelCase_					:	Dict)     ->						Any:
   '''simple docstring'''


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

   return wrapper




def   _A  (  UpperCamelCase_					:	Dict)     ->						int:
   '''simple docstring'''


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

   return wrapper




def   _A  (  UpperCamelCase_					:	Tuple)     ->						str:
   '''simple docstring'''


   @wraps(UpperCamelCase_)
   def wrapper(self					:	Optional[int],      UpperCamelCase_					:	Optional[Any]):
      if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
         self.skipTest("\"test not supported on Windows\"")
      else:
         test_case(self,      UpperCamelCase_)

   return wrapper




def   _A  (  )     ->						str:
   '''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(
    lowercase					,lowercase					,lowercase       )
@local
class  _lowerCAmelCase  (     parameterized.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : Optional[int]       		=     {}
 __UpperCAmelCase     : Tuple       		=     None


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


 @contextmanager
 def  _lowercase			(      self							:      List[Any], UpperCAmelCase__							:      Any, UpperCAmelCase__							:      Tuple     ):
    if metric_name in self.INTENSIVE_CALLS_PATCHER:
       with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase__     ):
          yield
    else:
       yield


 @contextmanager
 def  _lowercase			(      self							:      List[Any]     ):
    def load_local_metric(UpperCAmelCase__							:      Any, *UpperCAmelCase__							:      List[Any], **UpperCAmelCase__							:      Any     ):
       return load_metric(os.path.join("metrics", UpperCAmelCase__     ), *UpperCAmelCase__, **UpperCAmelCase__     )

    with patch("datasets.load_metric"     ) as mock_load_metric:
       __lowercase								=						load_local_metric
       yield



 @classmethod
 def  _lowercase			(      cls							:      Optional[Any], UpperCAmelCase__							:      List[Any]     ):
    def wrapper(UpperCAmelCase__							:      Tuple     ):
       __lowercase								=						contextmanager(UpperCAmelCase__     )
       __lowercase								=						patcher
       return patcher

    return wrapper







@LocalMetricTest.register_intensive_calls_patcher("bleurt")
def   _A  (  UpperCamelCase_					:	Any)     ->						Optional[Any]:
   '''simple docstring'''


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

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




   class  _lowerCAmelCase  (     lowercase       ):







    """simple docstring"""







    def  _lowercase			(      self							:      Tuple, UpperCAmelCase__							:      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:
      __lowercase								=						MockedPredictor()
      yield




@LocalMetricTest.register_intensive_calls_patcher("bertscore")
def   _A  (  UpperCamelCase_					:	Tuple)     ->						int:
   '''simple docstring'''


   import torch

   def bert_cos_score_idf(UpperCamelCase_					:	Tuple,      UpperCamelCase_					:	str,      *UpperCamelCase_					:	Optional[Any],      **UpperCamelCase_					:	Dict):
      return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_))

   # 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  (  UpperCamelCase_					:	Tuple)     ->						List[Any]:
   '''simple docstring'''


   def load_from_checkpoint(UpperCamelCase_					:	Tuple):




      class  _lowerCAmelCase  :







       """simple docstring"""







       def  _lowercase			(      self							:      str, UpperCAmelCase__							:      int, *UpperCAmelCase__							:      Dict, **UpperCAmelCase__							:      Dict     ):
          assert len(UpperCAmelCase__     ) == 2
          __lowercase								=						[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:
      __lowercase								=						None
      with patch("comet.load_from_checkpoint") as mock_load_from_checkpoint:
         __lowercase								=						load_from_checkpoint
         yield




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




