




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		:				Union[str, Any]       			=		pytest.mark.integration


__lowerCAmelCase		:				List[Any]       			=		{'comet'}
__lowerCAmelCase		:				int       			=		importlib.util.find_spec('fairseq') is not None

__lowerCAmelCase		:				List[Any]       			=		{'code_eval'}
__lowerCAmelCase		:				int       			=		os.name == 'nt'

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




def 			__magic_name__				( A		:					List[str]   ):






			'''simple docstring'''







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

			return wrapper




def 			__magic_name__				( A		:					List[Any]   ):






			'''simple docstring'''







			@wraps(A   )
			def wrapper(self		:					Any,  A		:					Union[str, Any]   ):
						if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
									self.skipTest("\"test requires transformers\""   )
						else:
									test_case(self,  A   )

			return wrapper




def 			__magic_name__				( A		:					Union[str, Any]   ):






			'''simple docstring'''







			@wraps(A   )
			def wrapper(self		:					str,  A		:					int   ):
						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 			__magic_name__				( ):






			'''simple docstring'''







			a    =			[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   ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_       :							Any							 =					{}
				SCREAMING_SNAKE_CASE_       :							List[str]							 =					None





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





				@contextmanager
				def 							__UpperCAmelCase							(      self				:     Dict					,      __lowerCamelCase				:     Any					,      __lowerCamelCase				:     Optional[Any]							)					->     List[Any]:
							if metric_name in self.INTENSIVE_CALLS_PATCHER:
										with self.INTENSIVE_CALLS_PATCHER[metric_name](__lowerCamelCase							):
													yield
							else:
										yield





				@contextmanager
				def 							__UpperCAmelCase							(      self				:     int							)					->     Tuple:
							def load_local_metric(__lowerCamelCase				:     Tuple					,      *__lowerCamelCase				:     int					,      **__lowerCamelCase				:     Dict							):
										return load_metric(os.path.join("metrics"					,      __lowerCamelCase							)					,      *__lowerCamelCase					,      **__lowerCamelCase							)

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





				@classmethod
				def 							__UpperCAmelCase							(      cls				:     Dict					,      __lowerCamelCase				:     List[str]							)					->     Optional[Any]:
							def wrapper(__lowerCamelCase				:     Tuple							):
										a    =			contextmanager(__lowerCamelCase							)
										a    =			patcher
										return patcher

							return wrapper




@LocalMetricTest.register_intensive_calls_patcher("bleurt"   )
def 			__magic_name__				( A		:					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   ):
							"""simple docstring"""



							def 							__UpperCAmelCase							(      self				:     str					,      __lowerCamelCase				:     int							)					->     int:
										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:
						a    =			MockedPredictor()
						yield




@LocalMetricTest.register_intensive_calls_patcher("bertscore"   )
def 			__magic_name__				( A		:					Tuple   ):






			'''simple docstring'''







			import torch

			def bert_cos_score_idf(A		:					str,  A		:					List[str],  *A		:					Optional[int],  **A		:					Tuple   ):
						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:
						a    =			bert_cos_score_idf
						yield




@LocalMetricTest.register_intensive_calls_patcher("comet"   )
def 			__magic_name__				( A		:					int   ):






			'''simple docstring'''







			def load_from_checkpoint(A		:					Dict   ):




						class     snake_case__							:
										"""simple docstring"""



										def 							__UpperCAmelCase							(      self				:     List[Any]					,      __lowerCamelCase				:     Optional[Any]					,      *__lowerCamelCase				:     Optional[Any]					,      **__lowerCamelCase				:     Tuple							)					->     int:
													assert len(__lowerCamelCase							) == 2
													a    =			[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:
						a    =			None
						with patch("comet.load_from_checkpoint"   ) as mock_load_from_checkpoint:
									a    =			load_from_checkpoint
									yield






def 			__magic_name__				( ):






			'''simple docstring'''







			a    =			load_metric(os.path.join("metrics",  "seqeval"   )   )
			a    =			"ERROR"
			a    =			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 random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
		import os

		import jax.numpy as jnp
		from jax import jit

		from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
		from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

		__lowerCAmelCase		:				List[Any]       			=		'0.12'  # assumed parallelism: 8


if is_torch_available():
		import torch




def 			__magic_name__				( A		:					Dict,  A		:					Union[str, Any],  A		:					Optional[int]=None   ):






			'''simple docstring'''







			if rng is None:
						a    =			random.Random()

			a    =			1
			for dim in shape:
						total_dims *= dim

			a    =			[]
			for _ in range(A   ):
						values.append(rng.randint(0,  vocab_size - 1   )   )

			a    =			np.array(A,  dtype=jnp.intaa   ).reshape(A   )

			return output




def 			__magic_name__				( A		:					Dict,  A		:					Union[str, Any]=None   ):






			'''simple docstring'''







			a    =			ids_tensor(A,  vocab_size=2,  rng=A   )
			# make sure that at least one token is attended to for each batch
			a    =			1
			return attn_mask




@require_flax
class     snake_case__							:
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_       :							List[str]							 =					None
				SCREAMING_SNAKE_CASE_       :							Any							 =					()





				def 							__UpperCAmelCase							(      self				:     int							)					->     List[str]:
							a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()

							# cut to half length & take max batch_size 3
							a    =			2
							a    =			inputs["input_ids"].shape[-1] // 2
							a    =			inputs["input_ids"][:max_batch_size, :sequence_length]

							a    =			jnp.ones_like(__lowerCamelCase							)
							a    =			attention_mask[:max_batch_size, :sequence_length]

							# generate max 5 tokens
							a    =			input_ids.shape[-1] + 5
							if config.eos_token_id is not None and config.pad_token_id is None:
										# hack to allow generate for models such as GPT2 as is done in `generate()`
										a    =			config.eos_token_id
							return config, input_ids, attention_mask, max_length





				@is_pt_flax_cross_test
				def 							__UpperCAmelCase							(      self				:     Optional[Any]							)					->     int:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			False
							a    =			max_length
							a    =			0

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model_class.__name__[4:]  # Skip the "Flax" at the beginning
										a    =			getattr(__lowerCamelCase					,      __lowerCamelCase							)
										a    =			pt_model_class(__lowerCamelCase							).eval()
										a    =			load_flax_weights_in_pytorch_model(__lowerCamelCase					,      flax_model.params							)

										a    =			flax_model.generate(__lowerCamelCase							).sequences
										a    =			pt_model.generate(torch.tensor(__lowerCamelCase					,      dtype=torch.long							)							)

										if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
													a    =			flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

										self.assertListEqual(pt_generation_outputs.numpy().tolist()					,      flax_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     List[str]							)					->     Optional[int]:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			False
							a    =			max_length

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     Any:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			True
							a    =			max_length

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     int							)					->     Dict:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			False
							a    =			max_length
							a    =			2

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     Any							)					->     Union[str, Any]:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			False
							a    =			max_length
							a    =			2
							a    =			2

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[0]					,      input_ids.shape[0] * config.num_return_sequences							)





				def 							__UpperCAmelCase							(      self				:     Optional[Any]							)					->     Dict:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			True
							a    =			max_length
							a    =			0.8
							a    =			10
							a    =			0.3
							a    =			1
							a    =			8
							a    =			9

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     Optional[Any]							)					->     Optional[Any]:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			max_length
							a    =			1
							a    =			8
							a    =			9

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     List[str]							)					->     Union[str, Any]:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()
							a    =			max_length
							a    =			2
							a    =			1
							a    =			8
							a    =			9

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     Union[str, Any]							)					->     Dict:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()

							# pad attention mask on the left
							a    =			attention_mask.at[(0, 0)].set(0							)

							a    =			False
							a    =			max_length

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase					,      attention_mask=__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase					,      attention_mask=__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     Tuple							)					->     Tuple:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()

							# pad attention mask on the left
							a    =			attention_mask.at[(0, 0)].set(0							)

							a    =			True
							a    =			max_length

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase					,      attention_mask=__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase					,      attention_mask=__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)





				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     List[Any]:
							a    ,		a    ,		a    ,		a    =			self._get_input_ids_and_config()

							# pad attention mask on the left
							a    =			attention_mask.at[(0, 0)].set(0							)

							a    =			2
							a    =			max_length

							for model_class in self.all_generative_model_classes:
										a    =			model_class(__lowerCamelCase							)

										a    =			model.generate(__lowerCamelCase					,      attention_mask=__lowerCamelCase							).sequences
										self.assertEqual(generation_outputs.shape[-1]					,      __lowerCamelCase							)

										a    =			jit(model.generate							)
										a    =			jit_generate(__lowerCamelCase					,      attention_mask=__lowerCamelCase							).sequences

										self.assertListEqual(generation_outputs.tolist()					,      jit_generation_outputs.tolist()							)




@require_flax
class     snake_case__							(unittest.TestCase   ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(      self				:     Dict							)					->     Optional[Any]:
							a    =			AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert"							)
							a    =			FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only"							)

							a    =			"Hello world"
							a    =			tokenizer(__lowerCamelCase					,      return_tensors="np"							).input_ids

							# typos are quickly detected (the correct argument is `do_sample`)
							with self.assertRaisesRegex(__lowerCamelCase					,      "do_samples"							):
										model.generate(__lowerCamelCase					,      do_samples=__lowerCamelCase							)

							# arbitrary arguments that will not be used anywhere are also not accepted
							with self.assertRaisesRegex(__lowerCamelCase					,      "foo"							):
										a    =			{"foo": "bar"}
										model.generate(__lowerCamelCase					,      **__lowerCamelCase							)






