

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


lowerCAmelCase__		      =       {"""comet"""}
lowerCAmelCase__		      =       importlib.util.find_spec("""fairseq""") is not None

lowerCAmelCase__		      =       {"""code_eval"""}
lowerCAmelCase__		      =       os.name == """nt"""

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



def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							List[Any]					)	->					int:




				'''simple docstring'''





				@wraps(SCREAMING_SNAKE_CASE_					)
				def wrapper(self:							Tuple		,				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     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							int					)	->					str:




				'''simple docstring'''





				@wraps(SCREAMING_SNAKE_CASE_					)
				def wrapper(self:							List[Any]		,				SCREAMING_SNAKE_CASE_:							Any					):
								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     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							List[Any]					)	->					Union[str, Any]:




				'''simple docstring'''





				@wraps(SCREAMING_SNAKE_CASE_					)
				def wrapper(self:							Any		,				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     lowerCAmelCase__							(		)	->					Any:




				'''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     a__  (    parameterized.TestCase	):
			"""simple docstring"""







			__lowerCamelCase       				=				{}
			__lowerCamelCase       				=				None


			@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"				)
			@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"				)
			def    UpperCamelCase						(			self					,					lowercase				)     ->  Union[str, Any]:
							'''simple docstring'''






							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					,					lowercase				)     ->  Optional[Any]:
							'''simple docstring'''






							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					,					lowercase					,					lowercase				)     ->  Optional[Any]:
							'''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(lowercase					,					*lowercase					,					**lowercase				):
											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					,					lowercase				)     ->  List[Any]:
							'''simple docstring'''






							def wrapper(lowercase				):
											A__						=	contextmanager(lowerCAmelCase__				)
											A__						=	patcher
											return patcher

							return wrapper



@LocalMetricTest.register_intensive_calls_patcher("bleurt"					)
def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							int					)	->					Any:




				'''simple docstring'''





				import tensorflow.compat.va as tf
				from bleurt.score import Predictor

				tf.flags.DEFINE_string("sv"		,				""		,				""					)  # handle pytest cli flags

				class     a__  (    __UpperCamelCase	):
							"""simple docstring"""







							def    UpperCamelCase						(			self					,					lowercase				)     ->  Dict:
											'''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:
								A__						=	MockedPredictor()
								yield



@LocalMetricTest.register_intensive_calls_patcher("bertscore"					)
def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							Optional[int]					)	->					Tuple:




				'''simple docstring'''





				import torch

				def bert_cos_score_idf(SCREAMING_SNAKE_CASE_:							Any		,				SCREAMING_SNAKE_CASE_:							Tuple		,				*SCREAMING_SNAKE_CASE_:							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:
								A__						=	bert_cos_score_idf
								yield



@LocalMetricTest.register_intensive_calls_patcher("comet"					)
def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							List[str]					)	->					Any:




				'''simple docstring'''





				def load_from_checkpoint(SCREAMING_SNAKE_CASE_:							int					):

								class     a__  :
											"""simple docstring"""







											def    UpperCamelCase						(			self					,					lowercase					,					*lowercase					,					**lowercase				)     ->  Optional[Any]:
															'''simple docstring'''






															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     lowerCAmelCase__							(		)	->					int:




				'''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(SCREAMING_SNAKE_CASE_		,				match=re.escape(SCREAMING_SNAKE_CASE_					)					):
								metric.compute(predictions=[]		,				references=[]		,				scheme=SCREAMING_SNAKE_CASE_					)





__lowerCAmelCase		       =							range(2, 20 + 1)
__lowerCAmelCase		       =							[10**k for k in range(ks[-1] + 1)]
__lowerCAmelCase		       =							{}




def    snake_case_     (  snake_case			,							snake_case			,							snake_case			,							snake_case     )  ->				Optional[int]:
       lowercase__:   str  			=   sum(a_i[j] for j in range(snake_case			,							len(snake_case     )     )     )
       lowercase__:   Optional[int]  			=   sum(a_i[j] * base[j] for j in range(min(len(snake_case     )			,							snake_case     )     )     )

       lowercase__			,						lowercase__:   str  			=   0, 0
       lowercase__:   Tuple  			=   n - i

       lowercase__:   Dict  			=   memo.get(snake_case     )

       if sub_memo is not None:
              lowercase__:   Optional[Any]  			=   sub_memo.get(snake_case     )

              if jumps is not None and len(snake_case     ) > 0:
                     # find and make the largest jump without going over
                     lowercase__:   int  			=   -1
                     for _k in range(len(snake_case     ) - 1			,							-1			,							-1     ):
                            if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
                                   lowercase__:   Union[str, Any]  			=   _k
                                   break

                     if max_jump >= 0:
                            lowercase__			,						lowercase__			,						lowercase__:   Any  			=   jumps[max_jump]
                            # since the difference between jumps is cached, add c
                            lowercase__:   str  			=   diff + c
                            for j in range(min(snake_case			,							len(snake_case     )     )     ):
                                   lowercase__			,						lowercase__:   Dict  			=   divmod(snake_case			,							10     )
                            if new_c > 0:
                                   add(snake_case			,							snake_case			,							snake_case     )

              else:
                     lowercase__:   List[Any]  			=   []
       else:
              lowercase__:   Optional[Any]  			=   {c: []}
              lowercase__:   Union[str, Any]  			=   sub_memo

       if dn >= max_dn or c + diff >= base[k]:
              return diff, dn

       if k > ks[0]:
              while True:
                     # keep doing smaller jumps
                     lowercase__			,						lowercase__:   Union[str, Any]  			=   next_term(snake_case			,							k - 1			,							i + dn			,							snake_case     )
                     diff += _diff
                     dn += terms_jumped

                     if dn >= max_dn or c + diff >= base[k]:
                            break
       else:
              # would be too small a jump, just compute sequential terms instead
              lowercase__			,						lowercase__:   Dict  			=   compute(snake_case			,							snake_case			,							i + dn			,							snake_case     )
              diff += _diff
              dn += terms_jumped

       lowercase__:   Any  			=   sub_memo[c]

       # keep jumps sorted by # of terms skipped
       lowercase__:   str  			=   0
       while j < len(snake_case     ):
              if jumps[j][1] > dn:
                     break
              j += 1

       # cache the jump for this value digitsum(b) and c
       sub_memo[c].insert(snake_case			,							(diff, dn, k)     )
       return (diff, dn)




def    snake_case_     (  snake_case			,							snake_case			,							snake_case			,							snake_case     )  ->				str:
       if i >= n:
              return 0, i
       if k > len(snake_case     ):
              a_i.extend([0 for _ in range(k - len(snake_case     )     )]     )

       # note: a_i -> b * 10^k + c
       # ds_b -> digitsum(b)
       # ds_c -> digitsum(c)
       lowercase__:   List[Any]  			=   i
       lowercase__			,						lowercase__			,						lowercase__:   Any  			=   0, 0, 0
       for j in range(len(snake_case     )     ):
              if j >= k:
                     ds_b += a_i[j]
              else:
                     ds_c += a_i[j]

       while i < n:
              i += 1
              lowercase__:   str  			=   ds_c + ds_b
              diff += addend
              lowercase__:   List[str]  			=   0
              for j in range(snake_case     ):
                     lowercase__:   Any  			=   a_i[j] + addend
                     lowercase__			,						lowercase__:   List[Any]  			=   divmod(snake_case			,							10     )

                     ds_c += a_i[j]

              if addend > 0:
                     break

       if addend > 0:
              add(snake_case			,							snake_case			,							snake_case     )
       return diff, i - start_i




def    snake_case_     (  snake_case			,							snake_case			,							snake_case     )  ->				int:
       for j in range(snake_case			,							len(snake_case     )     ):
              lowercase__:   str  			=   digits[j] + addend
              if s >= 10:
                     lowercase__			,						lowercase__:   Any  			=   divmod(snake_case			,							10     )
                     lowercase__:   Any  			=   addend // 10 + quotient
              else:
                     lowercase__:   Union[str, Any]  			=   s
                     lowercase__:   Union[str, Any]  			=   addend // 10

              if addend == 0:
                     break

       while addend > 0:
              lowercase__			,						lowercase__:   Union[str, Any]  			=   divmod(snake_case			,							10     )
              digits.append(snake_case     )




def    snake_case_     (  snake_case = 10**15     )  ->				int:
       lowercase__:   Optional[Any]  			=   [1]
       lowercase__:   int  			=   1
       lowercase__:   Tuple  			=   0
       while True:
              lowercase__			,						lowercase__:   str  			=   next_term(snake_case			,							20			,							i + dn			,							snake_case     )
              dn += terms_jumped
              if dn == n - i:
                     break

       lowercase__:   Dict  			=   0
       for j in range(len(snake_case     )     ):
              a_n += digits[j] * 10**j
       return a_n


if __name__ == "__main__":
 print(F'''{solution() = }''')


