



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


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

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

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







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[str]			):



					"""simple docstring"""





					@wraps(SCREAMING_SNAKE_CASE__			)
					def wrapper(self :  Any				,    SCREAMING_SNAKE_CASE__ :  List[str]			):
										if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
															self.skipTest("""\"test requires Fairseq\""""			)
										else:
															test_case(self				,    SCREAMING_SNAKE_CASE__			)

					return wrapper







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[int]			):



					"""simple docstring"""





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

					return wrapper







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Tuple			):



					"""simple docstring"""





					@wraps(SCREAMING_SNAKE_CASE__			)
					def wrapper(self :  List[str]				,    SCREAMING_SNAKE_CASE__ :  Dict			):
										if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
															self.skipTest("""\"test not supported on Windows\""""			)
										else:
															test_case(self				,    SCREAMING_SNAKE_CASE__			)

					return wrapper







def 							SCREAMING_SNAKE_CASE__      (		):



					"""simple docstring"""





					snake_case_					:		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    __lowercase     (					parameterized.TestCase):







						"""simple docstring"""







						_A		:							Optional[Any]							       =		{}
						_A		:							Any							       =		None







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







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







						@contextmanager
						def 						__UpperCamelCase							(self       ):
											def load_local_metric(lowercase__   ,		*lowercase__   ,		**lowercase__       ):
																return load_metric(os.path.join("""metrics"""   ,		lowercase__       )   ,		*lowercase__   ,		**lowercase__       )

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







						@classmethod
						def 						__UpperCamelCase							(cls   ,		lowercase__       ):
											def wrapper(lowercase__       ):
																snake_case_					:		List[str] 					=					contextmanager(lowercase__       )
																snake_case_					:		int 					=					patcher
																return patcher

											return wrapper







@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""			)
def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  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    __lowercase     (					_UpperCAmelCase):







											"""simple docstring"""







											def 						__UpperCamelCase							(self   ,		lowercase__       ):
																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_					:		Optional[int] 					=					MockedPredictor()
										yield







@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""			)
def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[Any]			):



					"""simple docstring"""





					import torch

					def bert_cos_score_idf(SCREAMING_SNAKE_CASE__ :  str				,    SCREAMING_SNAKE_CASE__ :  Dict				,    *SCREAMING_SNAKE_CASE__ :  List[Any]				,    **SCREAMING_SNAKE_CASE__ :  str			):
										return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_SNAKE_CASE__			)			)

					# 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_					:		int 					=					bert_cos_score_idf
										yield







@LocalMetricTest.register_intensive_calls_patcher("""comet"""			)
def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[Any]			):



					"""simple docstring"""





					def load_from_checkpoint(SCREAMING_SNAKE_CASE__ :  int			):







										class    __lowercase     :







																"""simple docstring"""







																def 						__UpperCamelCase							(self   ,		lowercase__   ,		*lowercase__   ,		**lowercase__       ):
																					assert len(lowercase__       ) == 2
																					snake_case_					:		List[str] 					=					[0.19, 0.92]
																					return scores, sum(lowercase__       ) / len(lowercase__       )
										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_					:		List[Any] 					=					None
										with patch("""comet.load_from_checkpoint"""			) as mock_load_from_checkpoint:
															snake_case_					:		List[Any] 					=					load_from_checkpoint
															yield







def 							SCREAMING_SNAKE_CASE__      (		):



					"""simple docstring"""





					snake_case_					:		str 					=					load_metric(os.path.join("""metrics"""				,    """seqeval"""			)			)
					snake_case_					:		Optional[Any] 					=					"""ERROR"""
					snake_case_					:		Dict 					=					f'Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'
					with pytest.raises(SCREAMING_SNAKE_CASE__				,    match=re.escape(SCREAMING_SNAKE_CASE__			)			):
										metric.compute(predictions=[]				,    references=[]				,    scheme=SCREAMING_SNAKE_CASE__			)









"""simple docstring"""

import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import BatchEncoding, MarianTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available


if is_sentencepiece_available():
			from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json

from ...test_tokenization_common import TokenizerTesterMixin


a_			   =					get_tests_dir('''fixtures/test_sentencepiece.model''')

a_			   =					{'''target_lang''': '''fi''', '''source_lang''': '''en'''}
a_			   =					'''>>zh<<'''
a_			   =					'''Helsinki-NLP/'''

if is_torch_available():
			a_			   =					'''pt'''
elif is_tf_available():
			a_			   =					'''tf'''
else:
			a_			   =					'''jax'''







@require_sentencepiece
class    __lowercase     (					_UpperCAmelCase					,    unittest.TestCase):







						"""simple docstring"""







						_A		:							str							       =		MarianTokenizer
						_A		:							List[str]							       =		False
						_A		:							List[str]							       =		True







						def 						__UpperCamelCase							(self       ):
											super().setUp()
											snake_case_					:		Optional[int] 					=					["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""]
											snake_case_					:		Any 					=					dict(zip(lowercase__   ,		range(len(lowercase__       )       )       )       )
											snake_case_					:		Any 					=					Path(self.tmpdirname       )
											save_json(lowercase__   ,		save_dir / VOCAB_FILES_NAMES["""vocab"""]       )
											save_json(lowercase__   ,		save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""]       )
											if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists():
																copyfile(lowercase__   ,		save_dir / VOCAB_FILES_NAMES["""source_spm"""]       )
																copyfile(lowercase__   ,		save_dir / VOCAB_FILES_NAMES["""target_spm"""]       )

											snake_case_					:		Optional[Any] 					=					MarianTokenizer.from_pretrained(self.tmpdirname       )
											tokenizer.save_pretrained(self.tmpdirname       )







						def 						__UpperCamelCase							(self   ,		**lowercase__       ):
											return MarianTokenizer.from_pretrained(self.tmpdirname   ,		**lowercase__       )







						def 						__UpperCamelCase							(self   ,		lowercase__       ):
											return (
											    "This is a test",
											    "This is a test",
											)







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Union[str, Any] 					=					"""</s>"""
											snake_case_					:		Tuple 					=					0

											self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase__       )   ,		lowercase__       )
											self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase__       )   ,		lowercase__       )







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		List[str] 					=					list(self.get_tokenizer().get_vocab().keys()       )

											self.assertEqual(vocab_keys[0]   ,		"""</s>"""       )
											self.assertEqual(vocab_keys[1]   ,		"""<unk>"""       )
											self.assertEqual(vocab_keys[-1]   ,		"""<pad>"""       )
											self.assertEqual(len(lowercase__       )   ,		9       )







						def 						__UpperCamelCase							(self       ):
											self.assertEqual(self.get_tokenizer().vocab_size   ,		9       )







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Any 					=					MarianTokenizer.from_pretrained(f'{ORG_NAME}opus-mt-en-de'       )
											snake_case_					:		Tuple 					=					en_de_tokenizer(["""I am a small frog"""]   ,		return_tensors=lowercase__       )
											self.assertIsInstance(lowercase__   ,		lowercase__       )
											snake_case_					:		Dict 					=					[38, 1_21, 14, 6_97, 3_88_48, 0]
											self.assertListEqual(lowercase__   ,		batch.input_ids[0]       )

											snake_case_					:		Tuple 					=					tempfile.mkdtemp()
											en_de_tokenizer.save_pretrained(lowercase__       )
											snake_case_					:		str 					=					[x.name for x in Path(lowercase__       ).glob("""*"""       )]
											self.assertIn("""source.spm"""   ,		lowercase__       )
											MarianTokenizer.from_pretrained(lowercase__       )







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Union[str, Any] 					=					self.get_tokenizer()

											snake_case_					:		List[str] 					=					tok(
											    ["""I am a small frog""" * 10_00, """I am a small frog"""]   ,		padding=lowercase__   ,		truncation=lowercase__   ,		return_tensors=lowercase__       )
											self.assertIsInstance(lowercase__   ,		lowercase__       )
											self.assertEqual(batch.input_ids.shape   ,		(2, 5_12)       )







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Tuple 					=					self.get_tokenizer()
											snake_case_					:		Tuple 					=					tok(["""I am a tiny frog""", """I am a small frog"""]   ,		padding=lowercase__   ,		return_tensors=lowercase__       )
											self.assertIsInstance(lowercase__   ,		lowercase__       )
											self.assertEqual(batch_smaller.input_ids.shape   ,		(2, 10)       )







						@slow
						def 						__UpperCamelCase							(self       ):
											# fmt: off
											snake_case_					:		str 					=					{"""input_ids""": [[4_34_95, 4_62, 20, 4_21_64, 13_69, 52, 4_64, 1_32, 17_03, 4_92, 13, 74_91, 3_89_99, 6, 8, 4_64, 1_32, 17_03, 4_92, 13, 46_69, 3_78_67, 13, 75_25, 27, 15_93, 9_88, 13, 3_39_72, 70_29, 6, 20, 82_51, 3_83, 2, 2_70, 58_66, 37_88, 2, 23_53, 82_51, 1_23_38, 2, 1_39_58, 3_87, 2, 36_29, 69_53, 1_88, 29_00, 2, 1_39_58, 80_11, 1_15_01, 23, 84_60, 40_73, 3_40_09, 20, 4_35, 1_14_39, 27, 8, 84_60, 40_73, 60_04, 20, 99_88, 3_75, 27, 33, 2_66, 19_45, 10_76, 13_50, 3_78_67, 32_88, 5, 5_77, 10_76, 43_74, 8, 50_82, 5, 2_64_53, 2_57, 5_56, 4_03, 2, 2_42, 1_32, 3_83, 3_16, 4_92, 8, 1_07_67, 6, 3_16, 3_04, 42_39, 3, 0], [1_48, 1_57_22, 19, 18_39, 12, 13_50, 13, 2_23_27, 50_82, 54_18, 4_75_67, 3_59_38, 59, 3_18, 1_95_52, 1_08, 21_83, 54, 1_49_76, 48_35, 32, 5_47, 11_14, 8, 3_15, 24_17, 5, 92, 1_90_88, 3, 0, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00], [36, 63_95, 1_25_70, 3_91_47, 1_15_97, 6, 2_66, 4, 4_54_05, 72_96, 3, 0, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
											# fmt: on

											self.tokenizer_integration_test_util(
											    expected_encoding=lowercase__   ,		model_name="""Helsinki-NLP/opus-mt-en-de"""   ,		revision="""1a8c2263da11e68e50938f97e10cd57820bd504c"""   ,		decode_kwargs={"""use_source_tokenizer""": True}   ,		)







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Any 					=					MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs"""       )

											snake_case_					:		Dict 					=					"""Tämä on testi"""
											snake_case_					:		List[Any] 					=					"""This is a test"""

											snake_case_					:		Optional[int] 					=					[76, 7, 20_47, 2]
											snake_case_					:		List[str] 					=					[69, 12, 11, 9_40, 2]

											snake_case_					:		Any 					=					tokenizer(lowercase__       ).input_ids
											self.assertListEqual(lowercase__   ,		lowercase__       )

											snake_case_					:		str 					=					tokenizer(text_target=lowercase__       ).input_ids
											self.assertListEqual(lowercase__   ,		lowercase__       )

											snake_case_					:		int 					=					tokenizer.decode(lowercase__   ,		skip_special_tokens=lowercase__       )
											self.assertEqual(lowercase__   ,		lowercase__       )




