
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__     :		Dict        = {"""comet"""}
lowerCamelCase__     :		Optional[int]        = importlib.util.find_spec("""fairseq""") is not None

lowerCamelCase__     :		Tuple        = {"""code_eval"""}
lowerCamelCase__     :		str        = os.name == """nt"""

lowerCamelCase__     :		int        = {"""bertscore""", """frugalscore""", """perplexity"""}
lowerCamelCase__     :		Tuple        = importlib.util.find_spec("""transformers""") is not None

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


  '''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_ )		->						Any:


  '''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_ )		->						Any:


  '''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						(   )		->						List[str]:


  '''simple docstring'''






  lowercase__	: Union[str, 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    _snake_case (						parameterized.TestCase				):
 __lowerCAmelCase	:  Any	   =      {}
 __lowerCAmelCase	:  str	   =      None


 @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""")
 @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""")
 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: int     		=   """[...]"""
   lowercase__	: Optional[Any]     		=   importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("""metrics"""       ,	SCREAMING_SNAKE_CASE_)).module_path)
   lowercase__	: List[str]     		=   datasets.load.import_main_class(metric_module.__name__       ,	dataset=SCREAMING_SNAKE_CASE_)
   # check parameters
   lowercase__	: 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(SCREAMING_SNAKE_CASE_       ,	metric_module.__name__):
     with self.use_local_metrics():
       try:
         lowercase__	: int     		=   doctest.testmod(SCREAMING_SNAKE_CASE_       ,	verbose=SCREAMING_SNAKE_CASE_       ,	raise_on_error=SCREAMING_SNAKE_CASE_)
       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       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   """[...]"""
   lowercase__	: Union[str, Any]     		=   importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("""metrics"""       ,	SCREAMING_SNAKE_CASE_)).module_path)
   # run doctest
   with self.use_local_metrics():
     lowercase__	: Union[str, Any]     		=   doctest.testmod(SCREAMING_SNAKE_CASE_       ,	verbose=SCREAMING_SNAKE_CASE_       ,	raise_on_error=SCREAMING_SNAKE_CASE_)
   self.assertEqual(results.failed       ,	0)
   self.assertGreater(results.attempted       ,	1)


 @contextmanager
 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




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


 @contextmanager
 def   lowercase__  (       self):


   '''simple docstring'''




   def load_local_metric(SCREAMING_SNAKE_CASE_       ,	*SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_):
     return load_metric(os.path.join("""metrics"""       ,	SCREAMING_SNAKE_CASE_)       ,	*SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_)

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



 @classmethod
 def   lowercase__  (       cls       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   def wrapper(SCREAMING_SNAKE_CASE_):
     lowercase__	: Any     		=   contextmanager(SCREAMING_SNAKE_CASE_)
     lowercase__	: Union[str, Any]     		=   patcher
     return patcher

   return wrapper

@LocalMetricTest.register_intensive_calls_patcher("""bleurt""" )
def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






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

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



  class    _snake_case (						UpperCAmelCase_				):


   def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


     '''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:
    lowercase__	: str     		=   MockedPredictor()
    yield

@LocalMetricTest.register_intensive_calls_patcher("""bertscore""" )
def 		UpperCamelCase						(   lowercase_ )		->						int:


  '''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:
    lowercase__	: int     		=   bert_cos_score_idf
    yield

@LocalMetricTest.register_intensive_calls_patcher("""comet""" )
def 		UpperCamelCase						(   lowercase_ )		->						Dict:


  '''simple docstring'''






  def load_from_checkpoint(lowercase_ ):



    class    _snake_case :


     def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	*SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_):


       '''simple docstring'''




       assert len(SCREAMING_SNAKE_CASE_) == 2
       lowercase__	: Optional[Any]     		=   [0.1_9, 0.9_2]
       return scores, sum(SCREAMING_SNAKE_CASE_) / len(SCREAMING_SNAKE_CASE_)

    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__	: Union[str, Any]     		=   None
    with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint:
      lowercase__	: List[Any]     		=   load_from_checkpoint
      yield



def 		UpperCamelCase						(   )		->						List[Any]:


  '''simple docstring'''






  lowercase__	: Optional[Any]     		=   load_metric(os.path.join("""metrics"""			,			"""seqeval""" ) )
  lowercase__	: int     		=   """ERROR"""
  lowercase__	: Tuple     		=   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 typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


if is_sentencepiece_available():
    from ..ta.tokenization_ta import TaTokenizer
else:
    from ...utils.dummy_sentencepiece_objects import TaTokenizer

_UpperCamelCase		     =    TaTokenizer

if is_tokenizers_available():
    from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
    from ...utils.dummy_tokenizers_objects import TaTokenizerFast

_UpperCamelCase		     =    TaTokenizerFast

_UpperCamelCase		     =    {"""configuration_mt5""": ["""MT5Config""", """MT5OnnxConfig"""]}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _UpperCamelCase		     =    [
        """MT5EncoderModel""",
        """MT5ForConditionalGeneration""",
        """MT5ForQuestionAnswering""",
        """MT5Model""",
        """MT5PreTrainedModel""",
        """MT5Stack""",
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _UpperCamelCase		     =    ["""TFMT5EncoderModel""", """TFMT5ForConditionalGeneration""", """TFMT5Model"""]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _UpperCamelCase		     =    ["""FlaxMT5EncoderModel""", """FlaxMT5ForConditionalGeneration""", """FlaxMT5Model"""]


if TYPE_CHECKING:
    from .configuration_mta import MTaConfig, MTaOnnxConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_mta import (
            MTaEncoderModel,
            MTaForConditionalGeneration,
            MTaForQuestionAnswering,
            MTaModel,
            MTaPreTrainedModel,
            MTaStack,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel

else:
    import sys

    _UpperCamelCase		     =    _LazyModule(
        __name__,
        globals()["""__file__"""],
        _import_structure,
        extra_objects={"""MT5Tokenizer""": MTaTokenizer, """MT5TokenizerFast""": MTaTokenizerFast},
        module_spec=__spec__,
    )






