


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 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		@wraps(lowerCAmelCase_     )
		def wrapper(self						,				SCREAMING_SNAKE_CASE     ):
				if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
						self.skipTest('''"test requires Fairseq"'''     )
				else:
						test_case(self						,				lowerCAmelCase_     )

		return wrapper
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




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

		return wrapper
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		@wraps(lowerCAmelCase_     )
		def wrapper(self						,				SCREAMING_SNAKE_CASE     ):
				if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
						self.skipTest('''"test not supported on Windows"'''     )
				else:
						test_case(self						,				lowerCAmelCase_     )

		return wrapper
def 			_a (      ):


		"""simple docstring"""




		lowercase__            =      [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			):
							_lowercase	:			int        = {}
							_lowercase	:			Any        = None

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





									"""simple docstring"""







									lowercase__            =      '''[...]'''
									lowercase__            =      importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join('''metrics'''    ,						lowerCAmelCase_							)							).module_path							)
									lowercase__            =      datasets.load.import_main_class(metric_module.__name__    ,						dataset=lowerCAmelCase_							)
									# check parameters
									lowercase__            =      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:
															lowercase__            =      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       lowerCamelCase_ (							self:	Any    ,						UpperCamelCase_:	Tuple							)			->   List[str]:





									"""simple docstring"""







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

							@contextmanager
							def       lowerCamelCase_ (							self:	str    ,						UpperCamelCase_:	Tuple    ,						UpperCamelCase_:	List[str]							)			->   int:





									"""simple docstring"""







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

							@contextmanager
							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   List[str]:





									"""simple docstring"""







									def load_local_metric(UpperCamelCase_:	Any    ,						*UpperCamelCase_:	str    ,						**UpperCamelCase_:	List[str]							):
											return load_metric(os.path.join('''metrics'''    ,						lowerCAmelCase_							)    ,						*lowerCAmelCase_    ,						**lowerCAmelCase_							)

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


							@classmethod
							def       lowerCamelCase_ (							cls:	List[str]    ,						UpperCamelCase_:	List[Any]							)			->   List[str]:





									"""simple docstring"""







									def wrapper(UpperCamelCase_:	str							):
											lowercase__            =      contextmanager(lowerCAmelCase_							)
											lowercase__            =      patcher
											return patcher

									return wrapper
@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''     )
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""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			):

									def       lowerCamelCase_ (							self:	List[str]    ,						UpperCamelCase_:	Optional[Any]							)			->   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:
				lowercase__            =      MockedPredictor()
				yield
@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''     )
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		import torch

		def bert_cos_score_idf(SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE						,				*SCREAMING_SNAKE_CASE						,				**SCREAMING_SNAKE_CASE     ):
				return torch.tensor([[1.0, 1.0, 1.0]] * len(lowerCAmelCase_     )     )

		# 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:
				lowercase__            =      bert_cos_score_idf
				yield
@LocalMetricTest.register_intensive_calls_patcher('''comet'''     )
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		def load_from_checkpoint(SCREAMING_SNAKE_CASE     ):


				class        _a							:

											def       lowerCamelCase_ (							self:	Any    ,						UpperCamelCase_:	Any    ,						*UpperCamelCase_:	Any    ,						**UpperCamelCase_:	List[Any]							)			->   Optional[Any]:





													"""simple docstring"""







													assert len(lowerCAmelCase_							) == 2
													lowercase__            =      [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:
				lowercase__            =      None
				with patch('''comet.load_from_checkpoint'''     ) as mock_load_from_checkpoint:
						lowercase__            =      load_from_checkpoint
						yield
def 			_a (      ):


		"""simple docstring"""




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









from ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
)


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_pt_objects import *  # noqa F403
else:
     from .scheduling_consistency_models import CMStochasticIterativeScheduler
     from .scheduling_ddim import DDIMScheduler
     from .scheduling_ddim_inverse import DDIMInverseScheduler
     from .scheduling_ddim_parallel import DDIMParallelScheduler
     from .scheduling_ddpm import DDPMScheduler
     from .scheduling_ddpm_parallel import DDPMParallelScheduler
     from .scheduling_deis_multistep import DEISMultistepScheduler
     from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
     from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
     from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
     from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
     from .scheduling_euler_discrete import EulerDiscreteScheduler
     from .scheduling_heun_discrete import HeunDiscreteScheduler
     from .scheduling_ipndm import IPNDMScheduler
     from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
     from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
     from .scheduling_karras_ve import KarrasVeScheduler
     from .scheduling_pndm import PNDMScheduler
     from .scheduling_repaint import RePaintScheduler
     from .scheduling_sde_ve import ScoreSdeVeScheduler
     from .scheduling_sde_vp import ScoreSdeVpScheduler
     from .scheduling_unclip import UnCLIPScheduler
     from .scheduling_unipc_multistep import UniPCMultistepScheduler
     from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
     from .scheduling_vq_diffusion import VQDiffusionScheduler

try:
     if not is_flax_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_flax_objects import *  # noqa F403
else:
     from .scheduling_ddim_flax import FlaxDDIMScheduler
     from .scheduling_ddpm_flax import FlaxDDPMScheduler
     from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
     from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
     from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
     from .scheduling_pndm_flax import FlaxPNDMScheduler
     from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
     from .scheduling_utils_flax import (
         FlaxKarrasDiffusionSchedulers,
         FlaxSchedulerMixin,
         FlaxSchedulerOutput,
         broadcast_to_shape_from_left,
     )


try:
     if not (is_torch_available() and is_scipy_available()):
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
     from .scheduling_lms_discrete import LMSDiscreteScheduler

try:
     if not (is_torch_available() and is_torchsde_available()):
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
     from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler

