


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


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

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

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







def        _lowerCamelCase(	lowercase__	)						->	Optional[int]:

		'''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        _lowerCamelCase(	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        _lowerCamelCase(	lowercase__	)						->	Optional[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        _lowerCamelCase(	)						->	List[Any]:

		'''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(
    A_					,				A_					,				A_ )
@local
class       A    (   parameterized.TestCase ):
							UpperCamelCase_   :							Dict       ={}
							UpperCamelCase_   :							Optional[Any]       =None


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


							@contextmanager
							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase					):
									if metric_name in self.INTENSIVE_CALLS_PATCHER:
											with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCAmelCase					):
													yield
									else:
											yield


							@contextmanager
							def 			_A       (self					):
									def load_local_metric(lowerCAmelCase      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
											return load_metric(os.path.join('metrics'      ,				lowerCAmelCase					)      ,				*lowerCAmelCase      ,				**lowerCAmelCase					)

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







							@classmethod
							def 			_A       (cls      ,				lowerCAmelCase					):
									def wrapper(lowerCAmelCase					):
											__lowercase=			contextmanager(lowerCAmelCase					)
											__lowercase=			patcher
											return patcher

									return wrapper







@LocalMetricTest.register_intensive_calls_patcher('bleurt'	)
def        _lowerCamelCase(	lowercase__	)						->	Union[str, Any]:

		'''simple docstring'''







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

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





		class       A    (   A_ ):


									def 			_A       (self      ,				lowerCAmelCase					):
											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        _lowerCamelCase(	lowercase__	)						->	Any:

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







@LocalMetricTest.register_intensive_calls_patcher('comet'	)
def        _lowerCamelCase(	lowercase__	)						->	Tuple:

		'''simple docstring'''







		def load_from_checkpoint(lowercase__	):





				class       A    :


											def 			_A       (self      ,				lowerCAmelCase      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
													assert len(lowerCAmelCase					) == 2
													__lowercase=			[0.19, 0.92]
													return scores, sum(lowerCAmelCase					) / len(lowerCAmelCase					)


				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        _lowerCamelCase(	)						->	Union[str, Any]:

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










import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar





class       A    (   unittest.TestCase ):


							def 			_A       (self					):
									__lowercase=			logging.get_logger()

									# the current default level is logging.WARNING
									__lowercase=			logging.get_verbosity()

									logging.set_verbosity_error()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									logging.set_verbosity_warning()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									logging.set_verbosity_info()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									logging.set_verbosity_debug()
									self.assertEqual(logger.getEffectiveLevel()      ,				logging.get_verbosity()					)

									# restore to the original level
									logging.set_verbosity(lowerCAmelCase					)


							def 			_A       (self					):
									__lowercase=			logging.get_verbosity()

									__lowercase=			logging.get_logger('transformers.models.bart.tokenization_bart'					)
									__lowercase=			'Testing 1, 2, 3'

									# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
									if level_origin <= logging.WARNING:
											with CaptureLogger(lowerCAmelCase					) as cl:
													logger.warning(lowerCAmelCase					)
											self.assertEqual(cl.out      ,				msg + '\n'					)

									# this is setting the level for all of `transformers.*` loggers
									logging.set_verbosity_error()

									# should not be able to log warnings
									with CaptureLogger(lowerCAmelCase					) as cl:
											logger.warning(lowerCAmelCase					)
									self.assertEqual(cl.out      ,				''					)

									# should be able to log warnings again
									logging.set_verbosity_warning()
									with CaptureLogger(lowerCAmelCase					) as cl:
											logger.warning(lowerCAmelCase					)
									self.assertEqual(cl.out      ,				msg + '\n'					)

									# restore to the original level
									logging.set_verbosity(lowerCAmelCase					)


							@mockenv(TRANSFORMERS_VERBOSITY='error'					)
							def 			_A       (self					):
									# reset for the env var to take effect, next time some logger call is made
									transformers.utils.logging._reset_library_root_logger()
									# this action activates the env var
									__lowercase=			logging.get_logger('transformers.models.bart.tokenization_bart'					)

									__lowercase=			os.getenv('TRANSFORMERS_VERBOSITY'      ,				lowerCAmelCase					)
									__lowercase=			logging.log_levels[env_level_str]

									__lowercase=			logging.get_verbosity()
									self.assertEqual(
									    lowerCAmelCase      ,				lowerCAmelCase      ,				f'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}'      ,				)

									# restore to the original level
									__lowercase=			''
									transformers.utils.logging._reset_library_root_logger()


							@mockenv(TRANSFORMERS_VERBOSITY='super-error'					)
							def 			_A       (self					):
									# reset for the env var to take effect, next time some logger call is made
									transformers.utils.logging._reset_library_root_logger()
									__lowercase=			logging.logging.getLogger()
									with CaptureLogger(lowerCAmelCase					) as cl:
											# this action activates the env var
											logging.get_logger('transformers.models.bart.tokenization_bart'					)
									self.assertIn('Unknown option TRANSFORMERS_VERBOSITY=super-error'      ,				cl.out					)

									# no need to restore as nothing was changed







							def 			_A       (self					):
									# testing `logger.warning_advice()`
									transformers.utils.logging._reset_library_root_logger()

									__lowercase=			logging.get_logger('transformers.models.bart.tokenization_bart'					)
									__lowercase=			'Testing 1, 2, 3'

									with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='1'					):
											# nothing should be logged as env var disables this method
											with CaptureLogger(lowerCAmelCase					) as cl:
													logger.warning_advice(lowerCAmelCase					)
											self.assertEqual(cl.out      ,				''					)

									with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''					):
											# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
											with CaptureLogger(lowerCAmelCase					) as cl:
													logger.warning_advice(lowerCAmelCase					)
											self.assertEqual(cl.out      ,				msg + '\n'					)







def        _lowerCamelCase(	)						->	Optional[int]:

		'''simple docstring'''







		disable_progress_bar()
		assert are_progress_bars_disabled()

		enable_progress_bar()
		assert not are_progress_bars_disabled()






