



'''simple docstring'''




from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


a     :    Optional[Any]      						=					logging.get_logger(__name__)

class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				['input_values', 'padding_mask']





	def __init__(						self	,	A = 1	,	A = 24000	,	A = 0.0	,	A = None	,	A = None	,	**A	,	)    ->    Optional[int]:
								super().__init__(feature_size=A	,	sampling_rate=A	,	padding_value=A	,	**A					)
								UpperCAmelCase  :	Optional[int]							  =	chunk_length_s
								UpperCAmelCase  :	int							  =	overlap





	@property
	def 				_lowercase(						self					)    ->    Optional[int]:
								if self.chunk_length_s is None:
															return None
								else:
															return int(self.chunk_length_s * self.sampling_rate					)





	@property
	def 				_lowercase(						self					)    ->    Optional[int]:
								if self.chunk_length_s is None or self.overlap is None:
															return None
								else:
															return max(1	,	int((1.0 - self.overlap) * self.chunk_length					)					)






	def __call__(						self	,	A	,	A = None	,	A = False	,	A = None	,	A = None	,	A = None	,	)    ->    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 audio 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."""					)

								if padding and truncation:
															raise ValueError("""Both padding and truncation were set. Make sure you only set one."""					)
								elif padding is None:
															# by default let's pad the inputs
															UpperCAmelCase  :	str							  =	True

								UpperCAmelCase  :	int							  =	bool(
								    isinstance(A	,	(list, tuple)					) and (isinstance(raw_audio[0]	,	(np.ndarray, tuple, list)					))					)

								if is_batched:
															UpperCAmelCase  :	Optional[int]							  =	[np.asarray(A	,	dtype=np.floataa					).T for audio in raw_audio]
								elif not is_batched and not isinstance(A	,	np.ndarray					):
															UpperCAmelCase  :	str							  =	np.asarray(A	,	dtype=np.floataa					)
								elif isinstance(A	,	np.ndarray					) and raw_audio.dtype is np.dtype(np.floataa					):
															UpperCAmelCase  :	List[Any]							  =	raw_audio.astype(np.floataa					)

								# always return batch
								if not is_batched:
															UpperCAmelCase  :	Dict							  =	[np.asarray(A					).T]

								# verify inputs are valid
								for idx, example in enumerate(A					):
															if example.ndim > 2:
																						raise ValueError(f'''Expected input shape (channels, length) but got shape {example.shape}'''					)
															if self.feature_size == 1 and example.ndim != 1:
																						raise ValueError(f'''Expected mono audio but example has {example.shape[-1]} channels'''					)
															if self.feature_size == 2 and example.shape[-1] != 2:
																						raise ValueError(f'''Expected stereo audio but example has {example.shape[-1]} channels'''					)

								UpperCAmelCase  :	Optional[Any]							  =	None
								UpperCAmelCase  :	Dict							  =	BatchFeature({"""input_values""": raw_audio}					)
								if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
															if truncation:
																						UpperCAmelCase  :	Any							  =	min(array.shape[0] for array in raw_audio					)
																						UpperCAmelCase  :	Optional[int]							  =	int(np.floor(max_length / self.chunk_stride					)					)
																						UpperCAmelCase  :	Union[str, Any]							  =	(nb_step - 1) * self.chunk_stride + self.chunk_length
															elif padding:
																						UpperCAmelCase  :	str							  =	max(array.shape[0] for array in raw_audio					)
																						UpperCAmelCase  :	Optional[Any]							  =	int(np.ceil(max_length / self.chunk_stride					)					)
																						UpperCAmelCase  :	List[Any]							  =	(nb_step - 1) * self.chunk_stride + self.chunk_length
																						UpperCAmelCase  :	Optional[Any]							  =	"""max_length"""
															else:
																						UpperCAmelCase  :	Union[str, Any]							  =	input_values

        # normal padding on batch
								if padded_inputs is None:
															UpperCAmelCase  :	Dict							  =	self.pad(
															    A	,	max_length=A	,	truncation=A	,	padding=A	,	return_attention_mask=A	,	)
															if padding:
																						UpperCAmelCase  :	int							  =	padded_inputs.pop("""attention_mask"""					)

								UpperCAmelCase  :	List[str]							  =	[]
								for example in padded_inputs.pop("""input_values"""					):
															if self.feature_size == 1:
																						UpperCAmelCase  :	List[str]							  =	example[..., None]
															input_values.append(example.T					)

								UpperCAmelCase  :	List[str]							  =	input_values
								if return_tensors is not None:
															UpperCAmelCase  :	List[str]							  =	padded_inputs.convert_to_tensors(A					)

								return padded_inputs






'''simple docstring'''




from scipy.stats import pearsonr

import datasets


a     :    str      						=					"""
Pearson correlation coefficient and p-value for testing non-correlation.
The 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.
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.
"""


a     :    Dict      						=					"""
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    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.
    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.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


a     :    Optional[int]      						=					"""
@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, Ilhan 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, Antonio 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     UpperCamelCase_				(							datasets.Metric    ):





	def 				_lowercase(						self					)    ->    Optional[int]:
								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 				_lowercase(						self	,	A	,	A	,	A=False					)    ->    int:
								if return_pvalue:
															UpperCAmelCase  :	int							  =	pearsonr(A	,	A					)
															return {"pearsonr": results[0], "p-value": results[1]}
								else:
															return {"pearsonr": float(pearsonr(A	,	A					)[0]					)}

