
'''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
lowercase    :							str      =					pytest.mark.integration


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

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

lowercase    :							Optional[Any]      =					{"bertscore", "frugalscore", "perplexity"}
lowercase    :							str      =					importlib.util.find_spec("transformers") is not None







def 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	int:
	@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 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	Optional[int]:
	@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 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	Optional[int]:
	@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 				SCREAMING_SNAKE_CASE__	(   )       ->	Any:
	_snake_case   						=		[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(
    _lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase						)
@local
class 						__UpperCAmelCase      (					parameterized.TestCase						):
							__lowercase      		=       {}
							__lowercase      		=       None


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





								"""simple docstring"""






								_snake_case   						=		'[...]'
								_snake_case   						=		importlib.import_module(
								    datasets.load.metric_module_factory(os.path.join('metrics'    ,   lowerCAmelCase_  )  ).module_path  )
								_snake_case   						=		datasets.load.import_main_class(metric_module.__name__    ,   dataset=lowerCAmelCase_  )
								# check parameters
								_snake_case   						=		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:
											_snake_case   						=		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  lowerCamelCase				(       self    ,   lowerCAmelCase_  ):





								"""simple docstring"""






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


							@contextmanager
							def  lowerCamelCase				(       self    ,   lowerCAmelCase_    ,   lowerCAmelCase_  ):





								"""simple docstring"""






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


							@contextmanager
							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								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:
									_snake_case   						=		load_local_metric
									yield




							@classmethod
							def  lowerCamelCase				(       cls    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								def wrapper(lowerCAmelCase_  ):
									_snake_case   						=		contextmanager(lowerCAmelCase_  )
									_snake_case   						=		patcher
									return patcher

								return wrapper







@LocalMetricTest.register_intensive_calls_patcher('bleurt'	)
def 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	List[str]:
	import tensorflow.compat.va as tf
	from bleurt.score import Predictor

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


	class 						__UpperCAmelCase      (					_lowerCamelCase						):


								def  lowerCamelCase				(       self    ,   lowerCAmelCase_  ):





									"""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:
		_snake_case   						=		MockedPredictor()
		yield







@LocalMetricTest.register_intensive_calls_patcher('bertscore'	)
def 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	Dict:
	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:
		_snake_case   						=		bert_cos_score_idf
		yield







@LocalMetricTest.register_intensive_calls_patcher('comet'	)
def 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	Optional[int]:
	def load_from_checkpoint(__A	):


		class 						__UpperCAmelCase      :


									def  lowerCamelCase				(       self    ,   lowerCAmelCase_    ,   *lowerCAmelCase_    ,   **lowerCAmelCase_  ):





										"""simple docstring"""






										assert len(lowerCAmelCase_  ) == 2
										_snake_case   						=		[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:
		_snake_case   						=		None
		with patch('comet.load_from_checkpoint'	) as mock_load_from_checkpoint:
			_snake_case   						=		load_from_checkpoint
			yield







def 				SCREAMING_SNAKE_CASE__	(   )       ->	Union[str, Any]:
	_snake_case   						=		load_metric(os.path.join('metrics'			,				'seqeval'	)	)
	_snake_case   						=		'ERROR'
	_snake_case   						=		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	)








import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
				from sagemaker import Session, TrainingJobAnalytics
				from sagemaker.huggingface import HuggingFace

@pytest.mark.skipif(
    literal_eval(os.getenv('''TEST_SAGEMAKER'''     ,							'''False'''			)			) is not True     ,							reason='''Skipping test because should only be run when releasing minor transformers version'''     ,							)
@pytest.mark.usefixtures('''sm_env'''			)
@parameterized_class(
    [
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_glue.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.g4dn.xlarge''',
            '''results''': {'''train_runtime''': 6_5_0, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9},
        },
        {
            '''framework''': '''tensorflow''',
            '''script''': '''run_tf.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.g4dn.xlarge''',
            '''results''': {'''train_runtime''': 6_0_0, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9},
        },
    ]			)
class 	A_       (unittest.TestCase			):
	def      _lowercase				(    self		):






				'''simple docstring'''







				if self.framework == "pytorch":
							subprocess.run(
							    F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split()							,					encoding='''utf-8'''							,					check=_A							,					)
				assert hasattr(self							,					'''env'''		)
	def      _lowercase				(    self							,					_A=1		):






				'''simple docstring'''







				return HuggingFace(
				    entry_point=self.script							,					source_dir=self.env.test_path							,					role=self.env.role							,					image_uri=self.env.image_uri							,					base_job_name=F"""{self.env.base_job_name}-single"""							,					instance_count=_A							,					instance_type=self.instance_type							,					debugger_hook_config=_A							,					hyperparameters={**self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path}							,					metric_definitions=self.env.metric_definitions							,					py_version='''py36'''							,					)
	def      _lowercase				(    self							,					_A		):






				'''simple docstring'''







				TrainingJobAnalytics(_A		).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv"""		)







	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.create_estimator()

				# run training
				estimator.fit()

				# result dataframe
				UpperCAmelCase   		=				TrainingJobAnalytics(estimator.latest_training_job.name		).dataframe()

				# extract kpis
				UpperCAmelCase   		=				list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value''']		)
				UpperCAmelCase   		=				list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value''']		)
				# get train time from SageMaker job, this includes starting, preprocessing, stopping
				UpperCAmelCase   		=				(
				    Session().describe_training_job(estimator.latest_training_job.name		).get('''TrainingTimeInSeconds'''							,					9_9_9_9_9_9		)
				)

				# assert kpis
				assert train_runtime <= self.results["train_runtime"]
				assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy		)
				assert all(t <= self.results['''eval_loss'''] for t in eval_loss		)

				# dump tests result into json file to share in PR
				with open(F"""{estimator.latest_training_job.name}.json"""							,					'''w'''		) as outfile:
							json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss}							,					_A		)



