



"""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_						:    Optional[Any]				=      pytest.mark.integration


A_						:    Optional[Any]				=      {'comet'}
A_						:    Any				=      importlib.util.find_spec('fairseq') is not None

A_						:    Optional[Any]				=      {'code_eval'}
A_						:    List[str]				=      os.name == 'nt'

A_						:    Optional[Any]				=      {'bertscore', 'frugalscore', 'perplexity'}
A_						:    List[Any]				=      importlib.util.find_spec('transformers') is not None
def  __snake_case							(	__A      :						str     )     ->       Tuple:






				'''simple docstring'''
				@wraps(__A     )
				def wrapper(self      :						Optional[int]							,		__A      :						Optional[Any]     ):
								if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
												self.skipTest('"test requires Fairseq"'     )
								else:
												test_case(self							,		__A     )

				return wrapper
def  __snake_case							(	__A      :						Optional[int]     )     ->       List[Any]:






				'''simple docstring'''
				@wraps(__A     )
				def wrapper(self      :						Optional[int]							,		__A      :						Dict     ):
								if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
												self.skipTest('"test requires transformers"'     )
								else:
												test_case(self							,		__A     )

				return wrapper
def  __snake_case							(	__A      :						str     )     ->       Tuple:






				'''simple docstring'''
				@wraps(__A     )
				def wrapper(self      :						List[str]							,		__A      :						Optional[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  __snake_case							(	)     ->       List[Any]:






				'''simple docstring'''
				SCREAMING_SNAKE_CASE						:							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(
    _lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase )
@local
class     lowerCAmelCase__						(	parameterized.TestCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		List[Any]  						= {}
	_SCREAMING_SNAKE_CASE	:		Any  						= None





	@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'    )
	@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'    )
	def 			_lowerCAmelCase     (      self				:       List[str]     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]    )						->	Optional[int]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							int							=     '[...]'
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     importlib.import_module(
					    datasets.load.metric_module_factory(os.path.join('metrics'     ,       _SCREAMING_SNAKE_CASE    )    ).module_path    )
					SCREAMING_SNAKE_CASE						:							int							=     datasets.load.import_main_class(metric_module.__name__     ,       dataset=_SCREAMING_SNAKE_CASE    )
					# check parameters
					SCREAMING_SNAKE_CASE						:							List[str]							=     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(_SCREAMING_SNAKE_CASE     ,       metric_module.__name__    ):
									with self.use_local_metrics():
													try:
																	SCREAMING_SNAKE_CASE						:							Any							=     doctest.testmod(_SCREAMING_SNAKE_CASE     ,       verbose=_SCREAMING_SNAKE_CASE     ,       raise_on_error=_SCREAMING_SNAKE_CASE    )
													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				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       int    )						->	int:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     '[...]'
					SCREAMING_SNAKE_CASE						:							Tuple							=     importlib.import_module(
					    datasets.load.metric_module_factory(os.path.join('metrics'     ,       _SCREAMING_SNAKE_CASE    )    ).module_path    )
					# run doctest
					with self.use_local_metrics():
									SCREAMING_SNAKE_CASE						:							Dict							=     doctest.testmod(_SCREAMING_SNAKE_CASE     ,       verbose=_SCREAMING_SNAKE_CASE     ,       raise_on_error=_SCREAMING_SNAKE_CASE    )
					self.assertEqual(results.failed     ,       0    )
					self.assertGreater(results.attempted     ,       1    )





	@contextmanager
	def 			_lowerCAmelCase     (      self				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       List[str]     ,       _SCREAMING_SNAKE_CASE				:       Optional[int]    )						->	Optional[int]:





					"""simple docstring"""


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





	@contextmanager
	def 			_lowerCAmelCase     (      self				:       str    )						->	List[str]:





					"""simple docstring"""


					def load_local_metric(_SCREAMING_SNAKE_CASE				:       int     ,       *_SCREAMING_SNAKE_CASE				:       Dict     ,       **_SCREAMING_SNAKE_CASE				:       int    ):
									return load_metric(os.path.join('metrics'     ,       _SCREAMING_SNAKE_CASE    )     ,       *_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE    )

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







	@classmethod
	def 			_lowerCAmelCase     (      cls				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       List[Any]    )						->	int:





					"""simple docstring"""


					def wrapper(_SCREAMING_SNAKE_CASE				:       Union[str, Any]    ):
									SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     contextmanager(_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							Any							=     patcher
									return patcher

					return wrapper




@LocalMetricTest.register_intensive_calls_patcher('bleurt'     )
def  __snake_case							(	__A      :						Union[str, Any]     )     ->       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     lowerCAmelCase__						(	_lowerCamelCase ):


					'''simple docstring'''







					def 			_lowerCAmelCase     (      self				:       Optional[int]     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]    )						->	Dict:





									"""simple docstring"""


									assert len(input_dict['input_ids']    ) == 2
									return np.array([1.0_3, 1.0_4]    )

    # 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:
								SCREAMING_SNAKE_CASE						:							Tuple							=     MockedPredictor()
								yield
@LocalMetricTest.register_intensive_calls_patcher('bertscore'     )
def  __snake_case							(	__A      :						Union[str, Any]     )     ->       str:






				'''simple docstring'''
				import torch

				def bert_cos_score_idf(__A      :						Dict							,		__A      :						Dict							,		*__A      :						int							,		**__A      :						List[str]     ):
								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:
								SCREAMING_SNAKE_CASE						:							List[Any]							=     bert_cos_score_idf
								yield
@LocalMetricTest.register_intensive_calls_patcher('comet'     )
def  __snake_case							(	__A      :						Optional[int]     )     ->       List[str]:






				'''simple docstring'''
				def load_from_checkpoint(__A      :						List[str]     ):
								class     lowerCAmelCase__						:


									'''simple docstring'''







									def 			_lowerCAmelCase     (      self				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       int     ,       *_SCREAMING_SNAKE_CASE				:       Tuple     ,       **_SCREAMING_SNAKE_CASE				:       List[str]    )						->	int:





													"""simple docstring"""


													assert len(_SCREAMING_SNAKE_CASE    ) == 2
													SCREAMING_SNAKE_CASE						:							Optional[int]							=     [0.1_9, 0.9_2]
													return scores, sum(_SCREAMING_SNAKE_CASE    ) / len(_SCREAMING_SNAKE_CASE    )




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







def  __snake_case							(	)     ->       int:






				'''simple docstring'''
				SCREAMING_SNAKE_CASE						:							Optional[int]							=     load_metric(os.path.join('metrics'							,		'seqeval'     )     )
				SCREAMING_SNAKE_CASE						:							Tuple							=     'ERROR'
				SCREAMING_SNAKE_CASE						:							List[Any]							=     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     )










"""simple docstring"""

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


A_						:    Optional[int]				=      {
    'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LlamaConfig'],
}

try:
							if not is_sentencepiece_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							A_						:    int				=      ['LlamaTokenizer']

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							A_						:    List[str]				=      ['LlamaTokenizerFast']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							A_						:    List[str]				=      [
							    'LlamaForCausalLM',
							    'LlamaModel',
							    'LlamaPreTrainedModel',
							    'LlamaForSequenceClassification',
							]


if TYPE_CHECKING:
							from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig

							try:
														if not is_sentencepiece_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_llama import LlamaTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_llama_fast import LlamaTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel


else:
							import sys

							A_						:    str				=      _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





