



'''simple docstring'''




import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


a     :    int      						=					random.Random()

if is_torch_available():
							import torch



def    __lowerCamelCase						(      _lowercase			,       _lowercase=1.0			,       _lowercase=None			,       _lowercase=None	)   ->    int:
							if rng is None:
														UpperCAmelCase  :	Optional[Any]							  =	global_rng

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

							return values

class     UpperCamelCase_				(							unittest.TestCase    ):





	def __init__(						self	,	A	,	A=7	,	A=400	,	A=2000	,	A=1	,	A=0.0	,	A=16000	,	A=True	,	A=True	,	)    ->    Optional[int]:
								UpperCAmelCase  :	Optional[Any]							  =	parent
								UpperCAmelCase  :	int							  =	batch_size
								UpperCAmelCase  :	Any							  =	min_seq_length
								UpperCAmelCase  :	Any							  =	max_seq_length
								UpperCAmelCase  :	Tuple							  =	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								UpperCAmelCase  :	Union[str, Any]							  =	feature_size
								UpperCAmelCase  :	Union[str, Any]							  =	padding_value
								UpperCAmelCase  :	Union[str, Any]							  =	sampling_rate
								UpperCAmelCase  :	Optional[Any]							  =	return_attention_mask
								UpperCAmelCase  :	List[Any]							  =	do_normalize





	def 				_lowercase(						self					)    ->    Union[str, Any]:
								return {
								    "feature_size": self.feature_size,
								    "padding_value": self.padding_value,
								    "sampling_rate": self.sampling_rate,
								    "return_attention_mask": self.return_attention_mask,
								    "do_normalize": self.do_normalize,
								}






	def 				_lowercase(						self	,	A=False	,	A=False					)    ->    Any:
								def _flatten(A					):
															return list(itertools.chain(*A					)					)

								if equal_length:
															UpperCAmelCase  :	Optional[Any]							  =	floats_list((self.batch_size, self.max_seq_length)					)
								else:
															# make sure that inputs increase in size
															UpperCAmelCase  :	List[Any]							  =	[
															    _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:
															UpperCAmelCase  :	str							  =	[np.asarray(A					) for x in speech_inputs]

								return speech_inputs




@require_torch
@require_torchaudio
class     UpperCamelCase_				(							__magic_name__   ,  unittest.TestCase    ):
	lowercase    =				ASTFeatureExtractor





	def 				_lowercase(						self					)    ->    Dict:
								UpperCAmelCase  :	Any							  =	ASTFeatureExtractionTester(self					)





	def 				_lowercase(						self					)    ->    Any:
								# Tests that all call wrap to encode_plus and batch_encode_plus
								UpperCAmelCase  :	Optional[Any]							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								# create three inputs of length 800, 1000, and 1200
								UpperCAmelCase  :	Optional[Any]							  =	[floats_list((1, x)					)[0] for x in range(800	,	1400	,	200					)]
								UpperCAmelCase  :	int							  =	[np.asarray(A					) for speech_input in speech_inputs]

								# Test not batched input
								UpperCAmelCase  :	Union[str, Any]							  =	feat_extract(speech_inputs[0]	,	return_tensors="""np"""					).input_values
								UpperCAmelCase  :	int							  =	feat_extract(np_speech_inputs[0]	,	return_tensors="""np"""					).input_values
								self.assertTrue(np.allclose(A	,	A	,	atol=1e-3					)					)

								# Test batched
								UpperCAmelCase  :	Any							  =	feat_extract(A	,	padding=A	,	return_tensors="""np"""					).input_values
								UpperCAmelCase  :	Union[str, Any]							  =	feat_extract(A	,	padding=A	,	return_tensors="""np"""					).input_values
								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  :	Dict							  =	[floats_list((1, x)					)[0] for x in (800, 800, 800)]
								UpperCAmelCase  :	Tuple							  =	np.asarray(A					)
								UpperCAmelCase  :	Tuple							  =	feat_extract(A	,	return_tensors="""np"""					).input_values
								UpperCAmelCase  :	Dict							  =	feat_extract(A	,	return_tensors="""np"""					).input_values
								for enc_seq_a, enc_seq_a in zip(A	,	A					):
															self.assertTrue(np.allclose(A	,	A	,	atol=1e-3					)					)





	@require_torch
	def 				_lowercase(						self					)    ->    List[Any]:
								import torch

								UpperCAmelCase  :	List[str]							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								UpperCAmelCase  :	str							  =	np.random.rand(100					).astype(np.floataa					)
								UpperCAmelCase  :	Dict							  =	np_speech_inputs.tolist()

								for inputs in [py_speech_inputs, np_speech_inputs]:
															UpperCAmelCase  :	List[str]							  =	feature_extractor.pad([{"""input_values""": inputs}]	,	return_tensors="""np"""					)
															self.assertTrue(np_processed.input_values.dtype == np.floataa					)
															UpperCAmelCase  :	str							  =	feature_extractor.pad([{"""input_values""": inputs}]	,	return_tensors="""pt"""					)
															self.assertTrue(pt_processed.input_values.dtype == torch.floataa					)





	def 				_lowercase(						self	,	A					)    ->    List[Any]:
								from datasets import load_dataset

								UpperCAmelCase  :	Optional[int]							  =	load_dataset("""hf-internal-testing/librispeech_asr_dummy"""	,	"""clean"""	,	split="""validation"""					)
								# automatic decoding with librispeech
								UpperCAmelCase  :	Tuple							  =	ds.sort("""id"""					).select(range(A					)					)[:num_samples]["""audio"""]

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






	@require_torch
	def 				_lowercase(						self					)    ->    Tuple:
								# fmt: off
								UpperCAmelCase  :	Dict							  =	torch.tensor(
								    [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
								     -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
								     -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
								     -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]					)
								# fmt: on

								UpperCAmelCase  :	List[str]							  =	self._load_datasamples(1					)
								UpperCAmelCase  :	Union[str, Any]							  =	ASTFeatureExtractor()
								UpperCAmelCase  :	Optional[int]							  =	feature_extractor(A	,	return_tensors="""pt"""					).input_values
								self.assertEquals(input_values.shape	,	(1, 1024, 128)					)
								self.assertTrue(torch.allclose(input_values[0, 0, :30]	,	A	,	atol=1e-4					)					)






'''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]					)}

