


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(snake_case__     )
		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						,				snake_case__     )

		return wrapper
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		@wraps(snake_case__     )
		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						,				snake_case__     )

		return wrapper
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		@wraps(snake_case__     )
		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						,				snake_case__     )

		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	:			int        = None

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





									"""simple docstring"""







									lowercase__            =      '''[...]'''
									lowercase__            =      importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join('''metrics'''    ,						_a							)							).module_path							)
									lowercase__            =      datasets.load.import_main_class(metric_module.__name__    ,						dataset=_a							)
									# 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(_a    ,						metric_module.__name__							):
											with self.use_local_metrics():
													try:
															lowercase__            =      doctest.testmod(_a    ,						verbose=_a    ,						raise_on_error=_a							)
													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:	Tuple    ,						UpperCamelCase_:	Optional[Any]							)			->   Dict:





									"""simple docstring"""







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

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





									"""simple docstring"""







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

							@contextmanager
							def       lowerCamelCase_ (							self:	Dict							)			->   List[Any]:





									"""simple docstring"""







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

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


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





									"""simple docstring"""







									def wrapper(UpperCamelCase_:	Optional[Any]							):
											lowercase__            =      contextmanager(_a							)
											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]							)			->   Optional[int]:





											"""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(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:
				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:	Optional[Any]    ,						UpperCamelCase_:	Optional[Any]    ,						*UpperCamelCase_:	List[Any]    ,						**UpperCamelCase_:	int							)			->   Union[str, Any]:





													"""simple docstring"""







													assert len(_a							) == 2
													lowercase__            =      [0.19, 0.92]
													return scores, sum(_a							) / len(_a							)
				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(snake_case__						,				match=re.escape(snake_case__     )     ):
				metric.compute(predictions=[]						,				references=[]						,				scheme=snake_case__     )








"""simple docstring"""




from sklearn.metrics import recall_score

import datasets


lowerCAmelCase							:			Any     							=							"""
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


lowerCAmelCase							:			Any     							=							"""
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


lowerCAmelCase							:			Any     							=							"""
@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}
"""






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION				)
class     __magic_name__							(       datasets.Metric				):






				'''simple docstring'''





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							return datasets.MetricInfo(
							    description=_DESCRIPTION		, citation=_CITATION		, inputs_description=_KWARGS_DESCRIPTION		, features=datasets.Features(
							        {
							            """predictions""": datasets.Sequence(datasets.Value("""int32""" ) ),
							            """references""": datasets.Sequence(datasets.Value("""int32""" ) ),
							        }
							        if self.config_name == """multilabel"""
							        else {
							            """predictions""": datasets.Value("""int32""" ),
							            """references""": datasets.Value("""int32""" ),
							        } )		, reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]		, )





				def    _lowerCAmelCase				(       self		, _a		, _a		, _a=None		, _a=1		, _a="binary"		, _a=None		, _a="warn"		, ):





							"""simple docstring"""
							lowerCamelCase			      =					recall_score(
							    _a		, _a		, labels=_a		, pos_label=_a		, average=_a		, sample_weight=_a		, zero_division=_a		, )
							return {"recall": float(_a ) if score.size == 1 else score}



