





import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
    from transformers import WhisperFeatureExtractor

if is_torch_available():
    import torch

__lowerCamelCase	:					List[str]			  =					random.Random()



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase=1.0							,       _lowerCAmelCase=None							,       _lowerCAmelCase=None					)						->			str:
 if rng is None:
  UpperCamelCase     : List[Any]	     =       global_rng

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

 return values



@require_torch
@require_torchaudio
class  A__       (	unittest.TestCase      ):





      def __init__(			self	,							A_	,							A_=7	,							A_=400	,							A_=2000	,							A_=10	,							A_=160	,							A_=8	,							A_=0.0	,							A_=4000	,							A_=False	,							A_=True	,							):
       '''simple docstring'''




       UpperCamelCase     : str	     =       parent
       UpperCamelCase     : Optional[int]	     =       batch_size
       UpperCamelCase     : int	     =       min_seq_length
       UpperCamelCase     : Any	     =       max_seq_length
       UpperCamelCase     : List[Any]	     =       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
       UpperCamelCase     : Tuple	     =       padding_value
       UpperCamelCase     : Dict	     =       sampling_rate
       UpperCamelCase     : Optional[int]	     =       return_attention_mask
       UpperCamelCase     : Optional[Any]	     =       do_normalize
       UpperCamelCase     : List[Any]	     =       feature_size
       UpperCamelCase     : Union[str, Any]	     =       chunk_length
       UpperCamelCase     : str	     =       hop_length





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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





      def 	__UpperCamelCase(			self	,							A_=False	,							A_=False       ):
       '''simple docstring'''




       def _flatten(A_       ):
        return list(itertools.chain(*A_       )       )

       if equal_length:
        UpperCamelCase     : List[str]	     =       [floats_list((self.max_seq_length, self.feature_size)       ) for _ in range(self.batch_size       )]
       else:
        # make sure that inputs increase in size
        UpperCamelCase     : List[Any]	     =       [
            floats_list((x, self.feature_size)       )
            for x in range(self.min_seq_length	,							self.max_seq_length	,							self.seq_length_diff       )
        ]
       if numpify:
        UpperCamelCase     : Dict	     =       [np.asarray(A_       ) for x in speech_inputs]
       return speech_inputs



@require_torch
@require_torchaudio
class  A__       (	__snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :List[str]						   =       WhisperFeatureExtractor if is_speech_available() else None





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       WhisperFeatureExtractionTester(self       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       self.feature_extraction_class(**self.feat_extract_dict       )

       with tempfile.TemporaryDirectory() as tmpdirname:
        UpperCamelCase     : List[str]	     =       feat_extract_first.save_pretrained(A_       )[0]
        check_json_file_has_correct_format(A_       )
        UpperCamelCase     : str	     =       self.feature_extraction_class.from_pretrained(A_       )

       UpperCamelCase     : Any	     =       feat_extract_first.to_dict()
       UpperCamelCase     : Optional[Any]	     =       feat_extract_second.to_dict()
       UpperCamelCase     : List[str]	     =       feat_extract_first.mel_filters
       UpperCamelCase     : List[str]	     =       feat_extract_second.mel_filters
       self.assertTrue(np.allclose(A_	,							A_       )       )
       self.assertEqual(A_	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       self.feature_extraction_class(**self.feat_extract_dict       )

       with tempfile.TemporaryDirectory() as tmpdirname:
        UpperCamelCase     : Optional[Any]	     =       os.path.join(A_	,							"feat_extract.json"       )
        feat_extract_first.to_json_file(A_       )
        UpperCamelCase     : Tuple	     =       self.feature_extraction_class.from_json_file(A_       )

       UpperCamelCase     : Tuple	     =       feat_extract_first.to_dict()
       UpperCamelCase     : Tuple	     =       feat_extract_second.to_dict()
       UpperCamelCase     : Optional[int]	     =       feat_extract_first.mel_filters
       UpperCamelCase     : Tuple	     =       feat_extract_second.mel_filters
       self.assertTrue(np.allclose(A_	,							A_       )       )
       self.assertEqual(A_	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       # create three inputs of length 800, 1000, and 1200
       UpperCamelCase     : Union[str, Any]	     =       [floats_list((1, x)       )[0] for x in range(800	,							1400	,							200       )]
       UpperCamelCase     : List[str]	     =       [np.asarray(A_       ) for speech_input in speech_inputs]

       # Test feature size
       UpperCamelCase     : List[str]	     =       feature_extractor(A_	,							padding="max_length"	,							return_tensors="np"       ).input_features
       self.assertTrue(input_features.ndim == 3       )
       self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames       )
       self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size       )

       # Test not batched input
       UpperCamelCase     : str	     =       feature_extractor(speech_inputs[0]	,							return_tensors="np"       ).input_features
       UpperCamelCase     : Optional[int]	     =       feature_extractor(np_speech_inputs[0]	,							return_tensors="np"       ).input_features
       self.assertTrue(np.allclose(A_	,							A_	,							atol=1e-3       )       )

       # Test batched
       UpperCamelCase     : Tuple	     =       feature_extractor(A_	,							return_tensors="np"       ).input_features
       UpperCamelCase     : int	     =       feature_extractor(A_	,							return_tensors="np"       ).input_features
       for enc_seq_a, enc_seq_a in zip(A_	,							A_       ):
        self.assertTrue(np.allclose(A_	,							A_	,							atol=1e-3       )       )

       # Test 2-D numpy arrays are batched.
       UpperCamelCase     : Optional[Any]	     =       [floats_list((1, x)       )[0] for x in (800, 800, 800)]
       UpperCamelCase     : List[Any]	     =       np.asarray(A_       )
       UpperCamelCase     : Optional[int]	     =       feature_extractor(A_	,							return_tensors="np"       ).input_features
       UpperCamelCase     : List[Any]	     =       feature_extractor(A_	,							return_tensors="np"       ).input_features
       for enc_seq_a, enc_seq_a in zip(A_	,							A_       ):
        self.assertTrue(np.allclose(A_	,							A_	,							atol=1e-3       )       )

       # Test truncation required
       UpperCamelCase     : str	     =       [floats_list((1, x)       )[0] for x in range(200	,							(feature_extractor.n_samples + 500)	,							200       )]
       UpperCamelCase     : List[Any]	     =       [np.asarray(A_       ) for speech_input in speech_inputs]

       UpperCamelCase     : str	     =       [x[: feature_extractor.n_samples] for x in speech_inputs]
       UpperCamelCase     : str	     =       [np.asarray(A_       ) for speech_input in speech_inputs_truncated]

       UpperCamelCase     : int	     =       feature_extractor(A_	,							return_tensors="np"       ).input_features
       UpperCamelCase     : List[Any]	     =       feature_extractor(A_	,							return_tensors="np"       ).input_features
       for enc_seq_a, enc_seq_a in zip(A_	,							A_       ):
        self.assertTrue(np.allclose(A_	,							A_	,							atol=1e-3       )       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       import torch

       UpperCamelCase     : Optional[Any]	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : Optional[int]	     =       np.random.rand(100	,							32       ).astype(np.floataa       )
       UpperCamelCase     : Tuple	     =       np_speech_inputs.tolist()

       for inputs in [py_speech_inputs, np_speech_inputs]:
        UpperCamelCase     : Union[str, Any]	     =       feature_extractor.pad([{"input_features": inputs}]	,							return_tensors="np"       )
        self.assertTrue(np_processed.input_features.dtype == np.floataa       )
        UpperCamelCase     : Tuple	     =       feature_extractor.pad([{"input_features": inputs}]	,							return_tensors="pt"       )
        self.assertTrue(pt_processed.input_features.dtype == torch.floataa       )





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       load_dataset("hf-internal-testing/librispeech_asr_dummy"	,							"clean"	,							split="validation"       )
       # automatic decoding with librispeech
       UpperCamelCase     : List[str]	     =       ds.sort("id"       ).select(range(A_       )       )[:num_samples]["audio"]

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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       torch.tensor(
           [
               0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51,
               0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78,
               0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54,
               -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54
           ]       )
       # fmt: on

       UpperCamelCase     : Dict	     =       self._load_datasamples(1       )
       UpperCamelCase     : List[str]	     =       WhisperFeatureExtractor()
       UpperCamelCase     : Optional[int]	     =       feature_extractor(A_	,							return_tensors="pt"       ).input_features
       self.assertEqual(input_features.shape	,							(1, 80, 3000)       )
       self.assertTrue(torch.allclose(input_features[0, 0, :30]	,							A_	,							atol=1e-4       )       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : Optional[int]	     =       self._load_datasamples(1       )[0]
       UpperCamelCase     : List[str]	     =       ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535  # Rescale to [0, 65535] to show issue
       UpperCamelCase     : int	     =       feat_extract.zero_mean_unit_var_norm([audio]	,							attention_mask=A_       )[0]

       self.assertTrue(np.all(np.mean(A_       ) < 1e-3       )       )
       self.assertTrue(np.all(np.abs(np.var(A_       ) - 1       ) < 1e-3       )       )







from scipy.stats import spearmanr

import datasets


__lowerCamelCase	:					List[str]			  =					"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

__lowerCamelCase	:					List[Any]			  =					"""
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

__lowerCamelCase	:					Optional[int]			  =					r"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
"""



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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return datasets.MetricInfo(
           description=_DESCRIPTION	,							citation=_CITATION	,							inputs_description=_KWARGS_DESCRIPTION	,							features=datasets.Features(
               {
                   "predictions": datasets.Value("float"       ),
                   "references": datasets.Value("float"       ),
               }       )	,							reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"]	,							)





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       spearmanr(A_	,							A_       )
       if return_pvalue:
        return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
       else:
        return {"spearmanr": results[0]}
