


'''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[str]					=						pytest.mark.integration


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

lowerCAmelCase    :     Optional[Any]					=						{"""code_eval"""}
lowerCAmelCase    :     Any					=						os.name == """nt"""

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






def 			lowercase				(_A					):







       """simple docstring"""







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

       return wrapper






def 			lowercase				(_A					):







       """simple docstring"""







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

       return wrapper






def 			lowercase				(_A					):







       """simple docstring"""







       @wraps(_A					)
       def wrapper(self   ,						_A					):
              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 			lowercase				():







       """simple docstring"""







       _lowerCAmelCase    :							Tuple   			=       [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(
    SCREAMING_SNAKE_CASE_    ,					SCREAMING_SNAKE_CASE_    ,					SCREAMING_SNAKE_CASE_	)
@local
class 	UpperCamelCase__					( parameterized.TestCase	):



     """simple docstring"""






     __magic_name__    			=    {}
     __magic_name__    			=    None







     @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'   )
     @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'   )
     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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

            '''simple docstring'''

            _lowerCAmelCase    :							List[Any]   			=       '[...]'
            _lowerCAmelCase    :							Any   			=       importlib.import_module(
                datasets.load.metric_module_factory(os.path.join('metrics'      ,	snake_case__   )   ).module_path   )
            # run doctest
            with self.use_local_metrics():
                   _lowerCAmelCase    :							str   			=       doctest.testmod(snake_case__      ,	verbose=snake_case__      ,	raise_on_error=snake_case__   )
            self.assertEqual(results.failed      ,	0   )
            self.assertGreater(results.attempted      ,	1   )







     @contextmanager
     def a	( self      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

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







     @contextmanager
     def a	( self   ):

            '''simple docstring'''

            def load_local_metric(snake_case__      ,	*snake_case__      ,	**snake_case__   ):
                   return load_metric(os.path.join('metrics'      ,	snake_case__   )      ,	*snake_case__      ,	**snake_case__   )

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







     @classmethod
     def a	( cls      ,	snake_case__   ):

            '''simple docstring'''

            def wrapper(snake_case__   ):
                   _lowerCAmelCase    :							Union[str, Any]   			=       contextmanager(snake_case__   )
                   _lowerCAmelCase    :							Optional[int]   			=       patcher
                   return patcher

            return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt'					)
def 			lowercase				(_A					):







       """simple docstring"""







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

       tf.flags.DEFINE_string('sv'   ,						''   ,						''					)  # handle pytest cli flags
       class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_	):



            """simple docstring"""






            def a	( self      ,	snake_case__   ):

                   '''simple docstring'''

                   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:
              _lowerCAmelCase    :							Tuple   			=       MockedPredictor()
              yield






@LocalMetricTest.register_intensive_calls_patcher('bertscore'					)
def 			lowercase				(_A					):







       """simple docstring"""







       import torch

       def bert_cos_score_idf(_A   ,						_A   ,						*_A   ,						**_A					):
              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:
              _lowerCAmelCase    :							List[Any]   			=       bert_cos_score_idf
              yield






@LocalMetricTest.register_intensive_calls_patcher('comet'					)
def 			lowercase				(_A					):







       """simple docstring"""







       def load_from_checkpoint(_A					):
              class 	UpperCamelCase__					:



                   """simple docstring"""






                   def a	( self      ,	snake_case__      ,	*snake_case__      ,	**snake_case__   ):

                          '''simple docstring'''

                          assert len(snake_case__   ) == 2
                          _lowerCAmelCase    :							Dict   			=       [0.19, 0.92]
                          return scores, sum(snake_case__   ) / len(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:
              _lowerCAmelCase    :							Optional[int]   			=       None
              with patch('comet.load_from_checkpoint'					) as mock_load_from_checkpoint:
                     _lowerCAmelCase    :							str   			=       load_from_checkpoint
                     yield






def 			lowercase				():







       """simple docstring"""







       _lowerCAmelCase    :							int   			=       load_metric(os.path.join('metrics'   ,						'seqeval'					)					)
       _lowerCAmelCase    :							Dict   			=       'ERROR'
       _lowerCAmelCase    :							Any   			=       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 unittest

from transformers import AutoTokenizer, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow


if is_flax_available():
       import jax.numpy as jnp

       from transformers import FlaxXLMRobertaModel
@require_sentencepiece
@require_tokenizers
@require_flax
class 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     @slow
     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base'   )
            _lowerCAmelCase    :							Optional[Any]   			=       AutoTokenizer.from_pretrained('xlm-roberta-base'   )
            _lowerCAmelCase    :							Dict   			=       'The dog is cute and lives in the garden house'
            _lowerCAmelCase    :							List[str]   			=       jnp.array([tokenizer.encode(snake_case__   )]   )

            _lowerCAmelCase    :							Optional[int]   			=       (1, 12, 768)  # batch_size, sequence_length, embedding_vector_dim
            _lowerCAmelCase    :							Tuple   			=       jnp.array(
                [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]]   )

            _lowerCAmelCase    :							Union[str, Any]   			=       model(snake_case__   )['last_hidden_state']
            self.assertEqual(output.shape      ,	snake_case__   )
            # compare the actual values for a slice of last dim
            self.assertTrue(jnp.allclose(output[:, :, -1]      ,	snake_case__      ,	atol=1E-3   )   )

