



from sklearn.metrics import roc_auc_score

import datasets


__snake_case		:Dict 						=	'''
This metric computes the area under the curve (AUC) for the Receiver Operating Characteristic Curve (ROC). The return values represent how well the model used is predicting the correct classes, based on the input data. A score of `0.5` means that the model is predicting exactly at chance, i.e. the model\'s predictions are correct at the same rate as if the predictions were being decided by the flip of a fair coin or the roll of a fair die. A score above `0.5` indicates that the model is doing better than chance, while a score below `0.5` indicates that the model is doing worse than chance.

This metric has three separate use cases:
    - binary: The case in which there are only two different label classes, and each example gets only one label. This is the default implementation.
    - multiclass: The case in which there can be more than two different label classes, but each example still gets only one label.
    - multilabel: The case in which there can be more than two different label classes, and each example can have more than one label.
'''

__snake_case		:int 						=	'''
Args:
- references (array-like of shape (n_samples,) or (n_samples, n_classes)): Ground truth labels. Expects different input based on use case:
    - binary: expects an array-like of shape (n_samples,)
    - multiclass: expects an array-like of shape (n_samples,)
    - multilabel: expects an array-like of shape (n_samples, n_classes)
- prediction_scores (array-like of shape (n_samples,) or (n_samples, n_classes)): Model predictions. Expects different inputs based on use case:
    - binary: expects an array-like of shape (n_samples,)
    - multiclass: expects an array-like of shape (n_samples, n_classes)
    - multilabel: expects an array-like of shape (n_samples, n_classes)
- average (`str`): Type of average, and is ignored in the binary use case. Defaults to \'macro\'. Options are:
    - `\'micro\'`: Calculates metrics globally by considering each element of the label indicator matrix as a label. Only works with the multilabel use case.
    - `\'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 (i.e. the number of true instances for each label).
    - `\'samples\'`: Calculate metrics for each instance, and find their average. Only works with the multilabel use case.
    - `None`:  No average is calculated, and scores for each class are returned. Only works with the multilabels use case.
- sample_weight (array-like of shape (n_samples,)): Sample weights. Defaults to None.
- max_fpr (`float`): If not None, the standardized partial AUC over the range [0, `max_fpr`] is returned. Must be greater than `0` and less than or equal to `1`. Defaults to `None`. Note: For the multiclass use case, `max_fpr` should be either `None` or `1.0` as ROC AUC partial computation is not currently supported for `multiclass`.
- multi_class (`str`): Only used for multiclass targets, where it is required. Determines the type of configuration to use. Options are:
    - `\'ovr\'`: Stands for One-vs-rest. Computes the AUC of each class against the rest. This treats the multiclass case in the same way as the multilabel case. Sensitive to class imbalance even when `average == \'macro\'`, because class imbalance affects the composition of each of the \'rest\' groupings.
    - `\'ovo\'`: Stands for One-vs-one. Computes the average AUC of all possible pairwise combinations of classes. Insensitive to class imbalance when `average == \'macro\'`.
- labels (array-like of shape (n_classes,)): Only used for multiclass targets. List of labels that index the classes in
    `prediction_scores`. If `None`, the numerical or lexicographical order of the labels in
    `prediction_scores` is used. Defaults to `None`.
Returns:
    roc_auc (`float` or array-like of shape (n_classes,)): Returns array if in multilabel use case and `average=\'None\'`. Otherwise, returns `float`.
Examples:
    Example 1:
        >>> roc_auc_score = datasets.load_metric("roc_auc")
        >>> refs = [1, 0, 1, 1, 0, 0]
        >>> pred_scores = [0.5, 0.2, 0.99, 0.3, 0.1, 0.7]
        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores)
        >>> print(round(results[\'roc_auc\'], 2))
        0.78

    Example 2:
        >>> roc_auc_score = datasets.load_metric("roc_auc", "multiclass")
        >>> refs = [1, 0, 1, 2, 2, 0]
        >>> pred_scores = [[0.3, 0.5, 0.2],
        ...                 [0.7, 0.2, 0.1],
        ...                 [0.005, 0.99, 0.005],
        ...                 [0.2, 0.3, 0.5],
        ...                 [0.1, 0.1, 0.8],
        ...                 [0.1, 0.7, 0.2]]
        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores, multi_class=\'ovr\')
        >>> print(round(results[\'roc_auc\'], 2))
        0.85

    Example 3:
        >>> roc_auc_score = datasets.load_metric("roc_auc", "multilabel")
        >>> refs = [[1, 1, 0],
        ...         [1, 1, 0],
        ...         [0, 1, 0],
        ...         [0, 0, 1],
        ...         [0, 1, 1],
        ...         [1, 0, 1]]
        >>> pred_scores = [[0.3, 0.5, 0.2],
        ...                 [0.7, 0.2, 0.1],
        ...                 [0.005, 0.99, 0.005],
        ...                 [0.2, 0.3, 0.5],
        ...                 [0.1, 0.1, 0.8],
        ...                 [0.1, 0.7, 0.2]]
        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores, average=None)
        >>> print([round(res, 2) for res in results[\'roc_auc\']])
        [0.83, 0.38, 0.94]
'''

__snake_case		:List[str] 						=	'''\
@article{doi:10.1177/0272989X8900900307,
author = {Donna Katzman McClish},
title ={Analyzing a Portion of the ROC Curve},
journal = {Medical Decision Making},
volume = {9},
number = {3},
pages = {190-195},
year = {1989},
doi = {10.1177/0272989X8900900307},
    note ={PMID: 2668680},
URL = {https://doi.org/10.1177/0272989X8900900307},
eprint = {https://doi.org/10.1177/0272989X8900900307}
}


@article{10.1023/A:1010920819831,
author = {Hand, David J. and Till, Robert J.},
title = {A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems},
year = {2001},
issue_date = {November 2001},
publisher = {Kluwer Academic Publishers},
address = {USA},
volume = {45},
number = {2},
issn = {0885-6125},
url = {https://doi.org/10.1023/A:1010920819831},
doi = {10.1023/A:1010920819831},
journal = {Mach. Learn.},
month = {oct},
pages = {171–186},
numpages = {16},
keywords = {Gini index, AUC, error rate, ROC curve, receiver operating characteristic}
}


@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        _A			(      datasets.Metric       ):



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


           '''simple docstring'''

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





       def 						_lowerCamelCase     (						self				:	Union[str, Any]	,						__SCREAMING_SNAKE_CASE				:	List[Any]	,						__SCREAMING_SNAKE_CASE				:	List[str]	,						__SCREAMING_SNAKE_CASE				:	Optional[Any]="macro"	,						__SCREAMING_SNAKE_CASE				:	int=None	,						__SCREAMING_SNAKE_CASE				:	int=None	,						__SCREAMING_SNAKE_CASE				:	List[Any]="raise"	,						__SCREAMING_SNAKE_CASE				:	List[Any]=None	,						):


           '''simple docstring'''

           return {
               "roc_auc": roc_auc_score(
                   __SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						average=__SCREAMING_SNAKE_CASE	,						sample_weight=__SCREAMING_SNAKE_CASE	,						max_fpr=__SCREAMING_SNAKE_CASE	,						multi_class=__SCREAMING_SNAKE_CASE	,						labels=__SCREAMING_SNAKE_CASE	,						)
           }










import itertools
import random
import unittest

import numpy as np

from transformers import EncodecFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
 import torch


__snake_case		:Any 						=	random.Random()





def 	__snake_case      (     _UpperCAmelCase  ,					_UpperCAmelCase=1.0  ,					_UpperCAmelCase=None  ,					_UpperCAmelCase=None							):
    if rng is None:
        __a					=							global_rng

    __a					=							[]
    for batch_idx in range(shape[0]							):
        values.append([]							)
        for _ in range(shape[1]							):
            values[-1].append(rng.random() * scale							)

    return values

@require_torch
class        _A			(      unittest.TestCase       ):



       def __init__(						self				:	Dict	,						__SCREAMING_SNAKE_CASE				:	str	,						__SCREAMING_SNAKE_CASE				:	Tuple=7	,						__SCREAMING_SNAKE_CASE				:	Any=400	,						__SCREAMING_SNAKE_CASE				:	Any=2_000	,						__SCREAMING_SNAKE_CASE				:	int=1	,						__SCREAMING_SNAKE_CASE				:	Dict=0.0	,						__SCREAMING_SNAKE_CASE				:	Optional[int]=24_000	,						__SCREAMING_SNAKE_CASE				:	Dict=True	,						):


           '''simple docstring'''

           __a					=							parent
           __a					=							batch_size
           __a					=							min_seq_length
           __a					=							max_seq_length
           __a					=							(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
           __a					=							feature_size
           __a					=							padding_value
           __a					=							sampling_rate
           __a					=							return_attention_mask



       def 						_lowerCamelCase     (						self				:	List[str]):


           '''simple docstring'''

           return {
               "feature_size": self.feature_size,
               "padding_value": self.padding_value,
               "sampling_rate": self.sampling_rate,
               "return_attention_mask": self.return_attention_mask,
           }





       def 						_lowerCamelCase     (						self				:	List[Any]	,						__SCREAMING_SNAKE_CASE				:	Union[str, Any]=False	,						__SCREAMING_SNAKE_CASE				:	Optional[Any]=False):


           '''simple docstring'''

           def _flatten(__SCREAMING_SNAKE_CASE				:	List[str]):
               return list(itertools.chain(*__SCREAMING_SNAKE_CASE))

           if equal_length:
               __a					=							floats_list((self.batch_size, self.max_seq_length))
           else:
               # make sure that inputs increase in size
               __a					=							[
                   _flatten(floats_list((x, self.feature_size)))
                   for x in range(self.min_seq_length	,						self.max_seq_length	,						self.seq_length_diff)
               ]

           if numpify:
               __a					=							[np.asarray(__SCREAMING_SNAKE_CASE) for x in audio_inputs]

           return audio_inputs


@require_torch
class        _A			(      __UpperCAmelCase ,unittest.TestCase       ):
       UpperCamelCase__    :       str		   =		EncodecFeatureExtractor



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


           '''simple docstring'''

           __a					=							EnCodecFeatureExtractionTester(self)



       def 						_lowerCamelCase     (						self				:	Optional[int]):


           '''simple docstring'''

           __a					=							self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
           # create three inputs of length 800, 1000, and 1200
           __a					=							[floats_list((1, x))[0] for x in range(800	,						1_400	,						200)]
           __a					=							[np.asarray(__SCREAMING_SNAKE_CASE) for audio_input in audio_inputs]

           # Test not batched input
           __a					=							feat_extract(audio_inputs[0]	,						return_tensors='''np''').input_values
           __a					=							feat_extract(np_audio_inputs[0]	,						return_tensors='''np''').input_values
           self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						atol=1E-3))

           # Test batched
           __a					=							feat_extract(__SCREAMING_SNAKE_CASE	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''np''').input_values
           __a					=							feat_extract(__SCREAMING_SNAKE_CASE	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''np''').input_values
           for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE):
               self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						atol=1E-3))



       def 						_lowerCamelCase     (						self				:	Optional[Any]):


           '''simple docstring'''

           __a					=							self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
           __a					=							np.random.rand(100).astype(np.floataa)
           __a					=							np_audio_inputs.tolist()

           for inputs in [py_audio_inputs, np_audio_inputs]:
               __a					=							feature_extractor.pad([{'''input_values''': inputs}]	,						return_tensors='''np''')
               self.assertTrue(np_processed.input_values.dtype == np.floataa)
               __a					=							feature_extractor.pad([{'''input_values''': inputs}]	,						return_tensors='''pt''')
               self.assertTrue(pt_processed.input_values.dtype == torch.floataa)



       def 						_lowerCamelCase     (						self				:	Tuple	,						__SCREAMING_SNAKE_CASE				:	str):


           '''simple docstring'''

           from datasets import load_dataset

           __a					=							load_dataset('''hf-internal-testing/librispeech_asr_dummy'''	,						'''clean'''	,						split='''validation''')
           # automatic decoding with librispeech
           __a					=							ds.sort('''id''').select(range(__SCREAMING_SNAKE_CASE))[:num_samples]['''audio''']

           return [x["array"] for x in audio_samples]



       def 						_lowerCamelCase     (						self				:	int):


           '''simple docstring'''

           __a					=							torch.tensor(
               [2.3804E-03, 2.0752E-03, 1.9836E-03, 2.1057E-03, 1.6174E-03,
                3.0518E-04, 9.1553E-05, 3.3569E-04, 9.7656E-04, 1.8311E-03,
                2.0142E-03, 2.1057E-03, 1.7395E-03, 4.5776E-04, -3.9673E-04,
                4.5776E-04, 1.0071E-03, 9.1553E-05, 4.8828E-04, 1.1597E-03,
                7.3242E-04, 9.4604E-04, 1.8005E-03, 1.8311E-03, 8.8501E-04,
                4.2725E-04, 4.8828E-04, 7.3242E-04, 1.0986E-03, 2.1057E-03])
           # fmt: on
           __a					=							self._load_datasamples(1)
           __a					=							EncodecFeatureExtractor()
           __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(input_values.shape	,						(1, 1, 93_680))
           self.assertTrue(torch.allclose(input_values[0, 0, :30]	,						__SCREAMING_SNAKE_CASE	,						atol=1E-6))



       def 						_lowerCamelCase     (						self				:	Optional[int]):


           '''simple docstring'''

           __a					=							torch.tensor(
               [2.3804E-03, 2.0752E-03, 1.9836E-03, 2.1057E-03, 1.6174E-03,
                3.0518E-04, 9.1553E-05, 3.3569E-04, 9.7656E-04, 1.8311E-03,
                2.0142E-03, 2.1057E-03, 1.7395E-03, 4.5776E-04, -3.9673E-04,
                4.5776E-04, 1.0071E-03, 9.1553E-05, 4.8828E-04, 1.1597E-03,
                7.3242E-04, 9.4604E-04, 1.8005E-03, 1.8311E-03, 8.8501E-04,
                4.2725E-04, 4.8828E-04, 7.3242E-04, 1.0986E-03, 2.1057E-03])
           # fmt: on
           __a					=							self._load_datasamples(1)
           __a					=							[np.tile(input_audio[0][None]	,						reps=(2, 1))]
           input_audio[0][1] *= 0.5
           __a					=							EncodecFeatureExtractor(feature_size=2)
           __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(input_values.shape	,						(1, 2, 93_680))
           self.assertTrue(torch.allclose(input_values[0, 0, :30]	,						__SCREAMING_SNAKE_CASE	,						atol=1E-6))
           self.assertTrue(torch.allclose(input_values[0, 1, :30]	,						EXPECTED_INPUT_VALUES * 0.5	,						atol=1E-6))





       def 						_lowerCamelCase     (						self				:	Any):


           '''simple docstring'''

           __a					=							self._load_datasamples(2)
           # would be easier if the stride was like
           __a					=							EncodecFeatureExtractor(feature_size=1	,						chunk_length_s=1	,						overlap=0.01)

           # pad and trunc raise an error ?
           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE	,						'''^Both padding and truncation were set. Make sure you only set one.$'''	,						):
               __a					=							feature_extractor(
                   __SCREAMING_SNAKE_CASE	,						padding='''max_length'''	,						truncation=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values

           # truncate to chunk
           __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						truncation=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(2, 1, 71_520))  # 2 chunks

           # force truncate to max_length
           __a					=							feature_extractor(
               __SCREAMING_SNAKE_CASE	,						truncation=__SCREAMING_SNAKE_CASE	,						max_length=48_000	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(2, 1, 48_000))

           # pad to chunk
           __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(padded_outputs.shape	,						(2, 1, 95_280))

           # pad to chunk
           __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(2, 1, 95_280))

           # force pad to max length
           __a					=							feature_extractor(
               __SCREAMING_SNAKE_CASE	,						padding='''max_length'''	,						max_length=100_000	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(2, 1, 100_000))

           # force no pad
           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE	,						'''^Unable to create tensor, you should probably activate padding with \'padding=True\' to have batched tensors with the same length.$'''	,						):
               __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values

           __a					=							feature_extractor(input_audio[0]	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(1, 1, 93_680))

           # no pad if no chunk_length_s
           __a					=							None
           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE	,						'''^Unable to create tensor, you should probably activate padding with \'padding=True\' to have batched tensors with the same length.$'''	,						):
               __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values

           __a					=							feature_extractor(input_audio[0]	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(1, 1, 93_680))

           # no pad if no overlap
           __a					=							2
           __a					=							None
           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE	,						'''^Unable to create tensor, you should probably activate padding with \'padding=True\' to have batched tensors with the same length.$'''	,						):
               __a					=							feature_extractor(__SCREAMING_SNAKE_CASE	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values

           __a					=							feature_extractor(input_audio[0]	,						padding=__SCREAMING_SNAKE_CASE	,						return_tensors='''pt''').input_values
           self.assertEquals(truncated_outputs.shape	,						(1, 1, 93_680))





