






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 							_a	(  UpperCamelCase_       :					List[str] )			-> Optional[Any]:
						"""simple docstring"""







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

						return wrapper


def 							_a	(  UpperCamelCase_       :					Dict )			-> str:
						"""simple docstring"""







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

						return wrapper


def 							_a	(  UpperCamelCase_       :					Optional[Any] )			-> Union[str, Any]:
						"""simple docstring"""







						@wraps(__lowercase )
						def wrapper(self       :					int     , UpperCamelCase_       :					Union[str, Any] ):
												if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
																		self.skipTest("\"test not supported on Windows\"" )
												else:
																		test_case(self     , __lowercase )

						return wrapper


def 							_a	(  )			-> Tuple:
						"""simple docstring"""







						lowerCAmelCase__			   =    [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   lowercase__  (      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 		UpperCAmelCase	(				self		,     __UpperCAmelCase							)->       str:







							'''simple docstring'''





							lowerCAmelCase__			   =    '[...]'
							lowerCAmelCase__			   =    importlib.import_module(
							    datasets.load.metric_module_factory(os.path.join("metrics"		,     _lowerCamelCase							)							).module_path							)
							lowerCAmelCase__			   =    datasets.load.import_main_class(metric_module.__name__		,     dataset=_lowerCamelCase							)
							# check parameters
							lowerCAmelCase__			   =    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:
																									lowerCAmelCase__			   =    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		,     __UpperCAmelCase							)->       List[str]:







							'''simple docstring'''





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

	@contextmanager
	def 		UpperCAmelCase	(				self		,     __UpperCAmelCase		,     __UpperCAmelCase							)->       int:







							'''simple docstring'''





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

	@contextmanager
	def 		UpperCAmelCase	(				self							)->       int:







							'''simple docstring'''





							def load_local_metric(__UpperCAmelCase		,     *__UpperCAmelCase		,     **__UpperCAmelCase							):
													return load_metric(os.path.join("metrics"		,     _lowerCamelCase							)		,     *_lowerCamelCase		,     **_lowerCamelCase							)

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


	@classmethod
	def 		UpperCAmelCase	(				cls		,     __UpperCAmelCase							)->       Dict:







							'''simple docstring'''





							def wrapper(__UpperCAmelCase							):
													lowerCAmelCase__			   =    contextmanager(_lowerCamelCase							)
													lowerCAmelCase__			   =    patcher
													return patcher

							return wrapper





@LocalMetricTest.register_intensive_calls_patcher("bleurt" )
def 							_a	(  UpperCamelCase_       :					Tuple )			-> Optional[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__  (      A__						):

							def 		UpperCAmelCase	(				self		,     __UpperCAmelCase							)->       Any:







													'''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:
												lowerCAmelCase__			   =    MockedPredictor()
												yield


@LocalMetricTest.register_intensive_calls_patcher("bertscore" )
def 							_a	(  UpperCamelCase_       :					Optional[Any] )			-> List[Any]:
						"""simple docstring"""







						import torch

						def bert_cos_score_idf(UpperCamelCase_       :					Optional[Any]     , UpperCamelCase_       :					Union[str, Any]     , *UpperCamelCase_       :					Optional[Any]     , **UpperCamelCase_       :					int ):
												return torch.tensor([[1.0, 1.0, 1.0]] * len(__lowercase ) )

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


@LocalMetricTest.register_intensive_calls_patcher("comet" )
def 							_a	(  UpperCamelCase_       :					Dict )			-> Any:
						"""simple docstring"""







						def load_from_checkpoint(UpperCamelCase_       :					List[str] ):


												class   lowercase__  :

													def 		UpperCAmelCase	(				self		,     __UpperCAmelCase		,     *__UpperCAmelCase		,     **__UpperCAmelCase							)->       List[Any]:







																			'''simple docstring'''





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





def 							_a	(  )			-> Union[str, Any]:
						"""simple docstring"""







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








"""simple docstring"""






import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer





class 				a__					(						A__       ):



     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=tempfile.mkdtemp()
      UpperCamelCase_     :					str   	=5

      # Realm tok
      UpperCamelCase_     :					List[Any]   	=[
          '[UNK]',
          '[CLS]',
          '[SEP]',
          '[PAD]',
          '[MASK]',
          'test',
          'question',
          'this',
          'is',
          'the',
          'first',
          'second',
          'third',
          'fourth',
          'fifth',
          'record',
          'want',
          '##want',
          '##ed',
          'wa',
          'un',
          'runn',
          '##ing',
          ',',
          'low',
          'lowest',
      ]
      UpperCamelCase_     :					List[str]   	=os.path.join(self.tmpdirname      ,  'realm_tokenizer'   )
      os.makedirs(_lowerCamelCase      ,  exist_ok=_lowerCamelCase   )
      UpperCamelCase_     :					int   	=os.path.join(_lowerCamelCase      ,  VOCAB_FILES_NAMES['vocab_file']   )
      with open(self.vocab_file      ,  'w'      ,  encoding='utf-8'   ) as vocab_writer:
       vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]   )   )

      UpperCamelCase_     :					str   	=os.path.join(self.tmpdirname      ,  'realm_block_records'   )
      os.makedirs(_lowerCamelCase      ,  exist_ok=_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Union[str, Any]   ):







      '''simple docstring'''



      return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname      ,  'realm_tokenizer'   )   )



     def  lowerCamelCase_						(							self :Dict   ):







      '''simple docstring'''



      shutil.rmtree(self.tmpdirname   )



     def  lowerCamelCase_						(							self :Dict   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=RealmConfig(num_block_records=self.num_block_records   )
      return config



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=Dataset.from_dict(
          {
              'id': ['0', '1'],
              'question': ['foo', 'bar'],
              'answers': [['Foo', 'Bar'], ['Bar']],
          }   )
      return dataset



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=np.array(
          [
              b'This is the first record',
              b'This is the second record',
              b'This is the third record',
              b'This is the fourth record',
              b'This is the fifth record',
              b'This is a longer longer longer record',
          ]      ,  dtype=_lowerCamelCase      ,  )
      return block_records



     def  lowerCamelCase_						(							self :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=RealmRetriever(
          block_records=self.get_dummy_block_records()      ,  tokenizer=self.get_tokenizer()      ,  )
      return retriever



     def  lowerCamelCase_						(							self :int   ):







      '''simple docstring'''



      UpperCamelCase_     :					Any   	=self.get_config()
      UpperCamelCase_     :					Tuple   	=self.get_dummy_retriever()
      UpperCamelCase_     :					Tuple   	=retriever.tokenizer

      UpperCamelCase_     :					List[str]   	=np.array([0, 3]      ,  dtype='long'   )
      UpperCamelCase_     :					Optional[Any]   	=tokenizer(['Test question']   ).input_ids
      UpperCamelCase_     :					Union[str, Any]   	=tokenizer(
          ['the fourth']      ,  add_special_tokens=_lowerCamelCase      ,  return_token_type_ids=_lowerCamelCase      ,  return_attention_mask=_lowerCamelCase      ,  ).input_ids
      UpperCamelCase_     :					Union[str, Any]   	=config.reader_seq_len

      UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_     :					Any   	=retriever(
          _lowerCamelCase      ,  _lowerCamelCase      ,  answer_ids=_lowerCamelCase      ,  max_length=_lowerCamelCase      ,  return_tensors='np'   )

      self.assertEqual(len(_lowerCamelCase   )      ,  2   )
      self.assertEqual(len(_lowerCamelCase   )      ,  2   )
      self.assertEqual(len(_lowerCamelCase   )      ,  2   )
      self.assertEqual(concat_inputs.input_ids.shape      ,  (2, 10)   )
      self.assertEqual(concat_inputs.attention_mask.shape      ,  (2, 10)   )
      self.assertEqual(concat_inputs.token_type_ids.shape      ,  (2, 10)   )
      self.assertEqual(concat_inputs.special_tokens_mask.shape      ,  (2, 10)   )
      self.assertEqual(
          tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]   )      ,  ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]']      ,  )
      self.assertEqual(
          tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]   )      ,  ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]']      ,  )



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=self.get_config()
      UpperCamelCase_     :					int   	=self.get_dummy_retriever()
      UpperCamelCase_     :					Any   	=retriever.tokenizer

      UpperCamelCase_     :					Optional[int]   	=np.array([0, 3, 5]      ,  dtype='long'   )
      UpperCamelCase_     :					Optional[int]   	=tokenizer(['Test question']   ).input_ids
      UpperCamelCase_     :					int   	=tokenizer(
          ['the fourth', 'longer longer']      ,  add_special_tokens=_lowerCamelCase      ,  return_token_type_ids=_lowerCamelCase      ,  return_attention_mask=_lowerCamelCase      ,  ).input_ids
      UpperCamelCase_     :					Union[str, Any]   	=config.reader_seq_len

      UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_	,     UpperCamelCase_     :					Union[str, Any]   	=retriever(
          _lowerCamelCase      ,  _lowerCamelCase      ,  answer_ids=_lowerCamelCase      ,  max_length=_lowerCamelCase      ,  return_tensors='np'   )

      self.assertEqual([False, True, True]      ,  _lowerCamelCase   )
      self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]      ,  _lowerCamelCase   )
      self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]      ,  _lowerCamelCase   )




     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=self.get_dummy_retriever()
      retriever.save_pretrained(os.path.join(self.tmpdirname      ,  'realm_block_records'   )   )

      # Test local path
      UpperCamelCase_     :					int   	=retriever.from_pretrained(os.path.join(self.tmpdirname      ,  'realm_block_records'   )   )
      self.assertEqual(retriever.block_records[0]      ,  b'This is the first record'   )

      # Test mocked remote path
      with patch('transformers.models.realm.retrieval_realm.hf_hub_download'   ) as mock_hf_hub_download:
       UpperCamelCase_     :					Dict   	=os.path.join(
           os.path.join(self.tmpdirname      ,  'realm_block_records'   )      ,  _REALM_BLOCK_RECORDS_FILENAME   )
       UpperCamelCase_     :					int   	=RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa'   )

      self.assertEqual(retriever.block_records[0]      ,  b'This is the first record'   )
