






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


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

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

__UpperCAmelCase							:   Tuple							=  {"bertscore", "frugalscore", "perplexity"}
__UpperCAmelCase							:   str							=  importlib.util.find_spec("transformers") is not None





def 					lowercase_ (    __snake_case     :							str      )     -> str:





				'''simple docstring'''


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

				return wrapper





def 					lowercase_ (    __snake_case     :							str      )     -> Any:





				'''simple docstring'''


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

				return wrapper





def 					lowercase_ (    __snake_case     :							Optional[int]      )     -> List[Any]:





				'''simple docstring'''


				@wraps(__snake_case      )
				def wrapper(self     :							Optional[int]	,	__snake_case     :							Tuple      ):
								if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
												self.skipTest("\"test not supported on Windows\""      )
								else:
												test_case(self	,	__snake_case      )

				return wrapper





def 					lowercase_ (    )     -> Dict:





				'''simple docstring'''


				snake_case__      :List[str]         =   [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 					_snake_case						(			parameterized.TestCase ):
	_A          =   {}
	_A          =   None






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






	@contextmanager
	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase       )						->    Optional[int]:
					if metric_name in self.INTENSIVE_CALLS_PATCHER:
									with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCamelCase       ):
													yield
					else:
									yield






	@contextmanager
	def    lowerCAmelCase_							(		self       )						->    Dict:
					def load_local_metric(UpperCamelCase					,*UpperCamelCase					,**UpperCamelCase       ):
									return load_metric(os.path.join("metrics"					,UpperCamelCase       )					,*UpperCamelCase					,**UpperCamelCase       )

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






	@classmethod
	def    lowerCAmelCase_							(		cls					,UpperCamelCase       )						->    Any:
					def wrapper(UpperCamelCase       ):
									snake_case__      :Optional[Any]         =   contextmanager(UpperCamelCase       )
									snake_case__      :Optional[Any]         =   patcher
									return patcher

					return wrapper





@LocalMetricTest.register_intensive_calls_patcher("bleurt"      )
def 					lowercase_ (    __snake_case     :							List[Any]      )     -> 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						(			_A ):






					def    lowerCAmelCase_							(		self					,UpperCamelCase       )						->    List[str]:
									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__      :List[Any]         =   MockedPredictor()
								yield





@LocalMetricTest.register_intensive_calls_patcher("bertscore"      )
def 					lowercase_ (    __snake_case     :							Dict      )     -> Dict:





				'''simple docstring'''


				import torch

				def bert_cos_score_idf(__snake_case     :							List[Any]	,	__snake_case     :							Tuple	,	*__snake_case     :							Optional[int]	,	**__snake_case     :							List[Any]      ):
								return torch.tensor([[1.0, 1.0, 1.0]] * len(__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__      :Any         =   bert_cos_score_idf
								yield





@LocalMetricTest.register_intensive_calls_patcher("comet"      )
def 					lowercase_ (    __snake_case     :							Union[str, Any]      )     -> Optional[int]:





				'''simple docstring'''


				def load_from_checkpoint(__snake_case     :							List[Any]      ):


								class 					_snake_case						:






									def    lowerCAmelCase_							(		self					,UpperCamelCase					,*UpperCamelCase					,**UpperCamelCase       )						->    Dict:
													assert len(UpperCamelCase       ) == 2
													snake_case__      :int         =   [0.19, 0.92]
													return scores, sum(UpperCamelCase       ) / len(UpperCamelCase       )




								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__      :Union[str, Any]         =   None
								with patch("comet.load_from_checkpoint"      ) as mock_load_from_checkpoint:
												snake_case__      :Union[str, Any]         =   load_from_checkpoint
												yield





def 					lowercase_ (    )     -> List[str]:





				'''simple docstring'''


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







from typing import List, Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_herbert import HerbertTokenizer


__UpperCAmelCase							:   str							=  logging.get_logger(__name__)

__UpperCAmelCase							:   List[Any]							=  {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

__UpperCAmelCase							:   List[Any]							=  {
    "vocab_file": {
        "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json"
    },
    "merges_file": {
        "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt"
    },
}

__UpperCAmelCase							:   str							=  {"allegro/herbert-base-cased": 5_1_4}
__UpperCAmelCase							:   List[str]							=  {}


class 					_snake_case						(			_A ):
	_A          =   VOCAB_FILES_NAMES
	_A          =   PRETRAINED_VOCAB_FILES_MAP
	_A          =   PRETRAINED_INIT_CONFIGURATION
	_A          =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_A          =   HerbertTokenizer






	def __init__(		self					,UpperCamelCase=None					,UpperCamelCase=None					,UpperCamelCase=None					,UpperCamelCase="<s>"					,UpperCamelCase="<unk>"					,UpperCamelCase="<pad>"					,UpperCamelCase="<mask>"					,UpperCamelCase="</s>"					,**UpperCamelCase					,)						->    Dict:
					super().__init__(
					    UpperCamelCase					,UpperCamelCase					,tokenizer_file=UpperCamelCase					,cls_token=UpperCamelCase					,unk_token=UpperCamelCase					,pad_token=UpperCamelCase					,mask_token=UpperCamelCase					,sep_token=UpperCamelCase					,**UpperCamelCase					,)






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase = None       )						->    List[int]:
					snake_case__      :Optional[int]         =   [self.cls_token_id]
					snake_case__      :Any         =   [self.sep_token_id]
					if token_ids_a is None:
									return cls + token_ids_a + sep

					return cls + token_ids_a + sep + token_ids_a + sep






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase = None					,UpperCamelCase = False       )						->    List[int]:
					if already_has_special_tokens:
									return super().get_special_tokens_mask(
									    token_ids_a=UpperCamelCase					,token_ids_a=UpperCamelCase					,already_has_special_tokens=UpperCamelCase       )

					if token_ids_a is None:
									return [1] + ([0] * len(UpperCamelCase       )) + [1]
					return [1] + ([0] * len(UpperCamelCase       )) + [1] + ([0] * len(UpperCamelCase       )) + [1]






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase = None       )						->    List[int]:
					snake_case__      :Any         =   [self.sep_token_id]
					snake_case__      :Union[str, Any]         =   [self.cls_token_id]

					if token_ids_a is None:
									return len(cls + token_ids_a + sep       ) * [0]
					return len(cls + token_ids_a + sep       ) * [0] + len(token_ids_a + sep       ) * [1]






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase = None       )						->    Tuple[str]:
					snake_case__      :List[str]         =   self._tokenizer.model.save(UpperCamelCase					,name=UpperCamelCase       )
					return tuple(UpperCamelCase       )