
from scipy.stats import pearsonr

import datasets


_snake_case      :							Tuple     	=    "\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n"


_snake_case      :							str     	=    "\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results['pearsonr'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        ['p-value', 'pearsonr']\n        >>> print(round(results['pearsonr'], 2))\n        -0.74\n        >>> print(round(results['p-value'], 2))\n        0.15\n"


_snake_case      :							int     	=    "\n@article{2020SciPy-NMeth,\nauthor  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n      Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n      Kern, Robert and Larson, Eric and Carey, C J and\n      Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n      Harris, Charles R. and Archibald, Anne M. and\n      Ribeiro, Antonio H. and Pedregosa, Fabian and\n      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n      Computing in Python}},\njournal = {Nature Methods},\nyear    = {2020},\nvolume  = {17},\npages   = {261--272},\nadsurl  = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n"





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







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->Union[str, Any]:
										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.pearsonr.html"]		,    )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]		,    lowerCAmelCase__							:int		,    lowerCAmelCase__							:Any		,    lowerCAmelCase__							:Optional[int]=False     )  ->int:
										if return_pvalue:
														lowercase         =      pearsonr(lowerCAmelCase__		,    lowerCAmelCase__     )
														return {"pearsonr": results[0], "p-value": results[1]}
										else:
														return {"pearsonr": float(pearsonr(lowerCAmelCase__		,    lowerCAmelCase__     )[0]     )}


from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


_snake_case      :							Any     	=    logging.get_logger(__name__)





class   UpperCamelCase_      (      __a		):







						'''simple docstring'''



						UpperCamelCase      :  Any				   =					['''input_features''', '''attention_mask''']





						def __init__(			self							:List[Any]		,    lowerCAmelCase__							:List[Any]=80		,    lowerCAmelCase__							:int=16000		,    lowerCAmelCase__							:str=0.0		,    lowerCAmelCase__							:int=10		,    lowerCAmelCase__							:List[Any]=25		,    lowerCAmelCase__							:List[str]="hamming_window"		,    lowerCAmelCase__							:int=3_27_68.0		,    lowerCAmelCase__							:str=0.97		,    lowerCAmelCase__							:List[str]=1.0		,    lowerCAmelCase__							:Optional[int]=True		,    lowerCAmelCase__							:Tuple=True		,    lowerCAmelCase__							:str=False		,    **lowerCAmelCase__							:Optional[Any]		,    )  ->Union[str, Any]:
										super().__init__(feature_size=lowerCAmelCase__		,    sampling_rate=lowerCAmelCase__		,    padding_value=lowerCAmelCase__		,    **lowerCAmelCase__     )

										lowercase         =      feature_size
										lowercase         =      sampling_rate
										lowercase         =      padding_value
										lowercase         =      hop_length
										lowercase         =      win_length
										lowercase         =      frame_signal_scale
										lowercase         =      preemphasis_coeff
										lowercase         =      mel_floor
										lowercase         =      normalize_means
										lowercase         =      normalize_vars
										lowercase         =      win_function
										lowercase         =      return_attention_mask

										lowercase         =      win_length * sampling_rate // 1000
										lowercase         =      hop_length * sampling_rate // 1000

										lowercase         =      optimal_fft_length(self.sample_size     )
										lowercase         =      (self.n_fft // 2) + 1





						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]		,    lowerCAmelCase__							:np.array     )  ->np.ndarray:
										if self.win_function == "hamming_window":
														lowercase         =      window_function(window_length=self.sample_size		,    name=self.win_function		,    periodic=lowerCAmelCase__     )
										else:
														lowercase         =      window_function(window_length=self.sample_size		,    name=self.win_function     )

										lowercase         =      mel_filter_bank(
										    num_frequency_bins=self.n_freqs		,    num_mel_filters=self.feature_size		,    min_frequency=0.0		,    max_frequency=self.sampling_rate / 2.0		,    sampling_rate=self.sampling_rate		,    )

										lowercase         =      spectrogram(
										    one_waveform * self.frame_signal_scale		,    window=lowerCAmelCase__		,    frame_length=self.sample_size		,    hop_length=self.sample_stride		,    fft_length=self.n_fft		,    center=lowerCAmelCase__		,    preemphasis=self.preemphasis_coeff		,    mel_filters=lowerCAmelCase__		,    mel_floor=self.mel_floor		,    log_mel="log"		,    )
										return msfc_features.T





						def        SCREAMING_SNAKE_CASE(			self							:Tuple		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Dict     )  ->int:
										# make sure we normalize float32 arrays
										if self.normalize_means:
														lowercase         =      x[:input_length].mean(axis=0     )
														lowercase         =      np.subtract(lowerCAmelCase__		,    lowerCAmelCase__     )
										if self.normalize_vars:
														lowercase         =      x[:input_length].std(axis=0     )
														lowercase         =      np.divide(lowerCAmelCase__		,    lowerCAmelCase__     )

										if input_length < x.shape[0]:
														lowercase         =      padding_value

										# make sure array is in float32
										lowercase         =      x.astype(np.floataa     )

										return x





						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]		,    lowerCAmelCase__							:List[np.ndarray]		,    lowerCAmelCase__							:Optional[np.ndarray] = None     )  ->List[np.ndarray]:
										lowercase         =      attention_mask.sum(-1     ) if attention_mask is not None else [x.shape[0] for x in input_features]
										return [self._normalize_one(lowerCAmelCase__		,    lowerCAmelCase__		,    self.padding_value     ) for x, n in zip(lowerCAmelCase__		,    lowerCAmelCase__     )]





						def __call__(			self							:Any		,    lowerCAmelCase__							:Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]		,    lowerCAmelCase__							:Union[bool, str, PaddingStrategy] = False		,    lowerCAmelCase__							:Optional[int] = None		,    lowerCAmelCase__							:bool = False		,    lowerCAmelCase__							:Optional[int] = None		,    lowerCAmelCase__							:Optional[bool] = None		,    lowerCAmelCase__							:Optional[Union[str, TensorType]] = None		,    lowerCAmelCase__							:Optional[int] = None		,    **lowerCAmelCase__							:Union[str, Any]		,    )  ->BatchFeature:

										if sampling_rate is not None:
														if sampling_rate != self.sampling_rate:
																		raise ValueError(
																		    F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
																		    F''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
																		    F''' {self.sampling_rate} and not {sampling_rate}.'''     )
										else:
														logger.warning(
														    "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
														    "Failing to do so can result in silent errors that might be hard to debug."     )

										lowercase         =      isinstance(lowerCAmelCase__		,    np.ndarray     ) and len(raw_speech.shape     ) > 1
										if is_batched_numpy and len(raw_speech.shape     ) > 2:
														raise ValueError(F'''Only mono-channel audio is supported for input to {self}'''     )
										lowercase         =      is_batched_numpy or (
										    isinstance(lowerCAmelCase__		,    (list, tuple)     ) and (isinstance(raw_speech[0]		,    (np.ndarray, tuple, list)     ))
										)

										if is_batched:
														lowercase         =      [np.asarray(lowerCAmelCase__		,    dtype=np.floataa     ) for speech in raw_speech]
										elif not is_batched and not isinstance(lowerCAmelCase__		,    np.ndarray     ):
														lowercase         =      np.asarray(lowerCAmelCase__		,    dtype=np.floataa     )
										elif isinstance(lowerCAmelCase__		,    np.ndarray     ) and raw_speech.dtype is np.dtype(np.floataa     ):
														lowercase         =      raw_speech.astype(np.floataa     )

										# always return batch
										if not is_batched:
														lowercase         =      [raw_speech]

										# extract fbank features
										lowercase         =      [self._extract_mfsc_features(lowerCAmelCase__     ) for one_waveform in raw_speech]

										# convert into correct format for padding
										lowercase         =      BatchFeature({"input_features": features}     )

										lowercase         =      self.pad(
										    lowerCAmelCase__		,    padding=lowerCAmelCase__		,    max_length=lowerCAmelCase__		,    truncation=lowerCAmelCase__		,    pad_to_multiple_of=lowerCAmelCase__		,    return_attention_mask=lowerCAmelCase__		,    **lowerCAmelCase__		,    )
										# make sure list is in array format
										lowercase         =      padded_inputs.get("input_features"     )
										if isinstance(input_features[0]		,    lowerCAmelCase__     ):
														lowercase         =      [np.asarray(lowerCAmelCase__		,    dtype=np.floataa     ) for feature in input_features]

										lowercase         =      padded_inputs.get("attention_mask"     )
										if attention_mask is not None:
														lowercase         =      [np.asarray(lowerCAmelCase__		,    dtype=np.intaa     ) for array in attention_mask]

										if self.normalize_means or self.normalize_vars:
														lowercase         =      (
														    np.array(lowerCAmelCase__		,    dtype=np.intaa     )
														    if self._get_padding_strategies(lowerCAmelCase__		,    max_length=lowerCAmelCase__     ) is not PaddingStrategy.DO_NOT_PAD
														    and padding
														    else None
														)
														lowercase         =      self.normalize(
														    padded_inputs["input_features"]		,    attention_mask=lowerCAmelCase__     )

										if return_tensors is not None:
														lowercase         =      padded_inputs.convert_to_tensors(lowerCAmelCase__     )

										return padded_inputs
