





"""simple docstring"""





import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


_UpperCamelCase					      =   random.Random()



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				Dict     ,    SCREAMING_SNAKE_CASE							:				Union[str, Any]=1.0     ,    SCREAMING_SNAKE_CASE							:				Optional[Any]=None     ,    SCREAMING_SNAKE_CASE							:				Tuple=None ):


							'''simple docstring'''







							if rng is None:
														__lowerCamelCase   :   Optional[Any]       =global_rng

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

							return values
class 		SCREAMING_SNAKE_CASE_				(     unittest.TestCase ):
				"""simple docstring"""




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




				def        __lowercase	(  self	:List[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	:List[str]    ,     __lowercase	:Optional[Any]=False    ,     __lowercase	:Dict=False      ):
											def _flatten(__lowercase	:List[Any]      ):
																		return list(itertools.chain(*__lowercase      )      )

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

											return speech_inputs

class 		SCREAMING_SNAKE_CASE_				(     snake_case__							,	unittest.TestCase ):
				"""simple docstring"""
				__snake_case :							Optional[Any]									=		WavaVecaFeatureExtractor




				def        __lowercase	(  self	:Any      ):
											__lowerCamelCase   :   int       =WavaVecaFeatureExtractionTester(self      )




				def        __lowercase	(  self	:Any    ,     __lowercase	:str      ):
											self.assertTrue(np.all(np.mean(__lowercase    ,     axis=0      ) < 1e-3      )      )
											self.assertTrue(np.all(np.abs(np.var(__lowercase    ,     axis=0      ) - 1      ) < 1e-3      )      )




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

											# Test not batched input
											__lowerCamelCase   :   Optional[Any]       =feat_extract(speech_inputs[0]    ,     return_tensors='''np'''      ).input_values
											__lowerCamelCase   :   Union[str, Any]       =feat_extract(np_speech_inputs[0]    ,     return_tensors='''np'''      ).input_values
											self.assertTrue(np.allclose(__lowercase    ,     __lowercase    ,     atol=1e-3      )      )

											# Test batched
											__lowerCamelCase   :   List[Any]       =feat_extract(__lowercase    ,     return_tensors='''np'''      ).input_values
											__lowerCamelCase   :   Optional[Any]       =feat_extract(__lowercase    ,     return_tensors='''np'''      ).input_values
											for enc_seq_a, enc_seq_a in zip(__lowercase    ,     __lowercase      ):
																		self.assertTrue(np.allclose(__lowercase    ,     __lowercase    ,     atol=1e-3      )      )

											# Test 2-D numpy arrays are batched.
											__lowerCamelCase   :   Optional[int]       =[floats_list((1, x)      )[0] for x in (800, 800, 800)]
											__lowerCamelCase   :   Optional[int]       =np.asarray(__lowercase      )
											__lowerCamelCase   :   Dict       =feat_extract(__lowercase    ,     return_tensors='''np'''      ).input_values
											__lowerCamelCase   :   int       =feat_extract(__lowercase    ,     return_tensors='''np'''      ).input_values
											for enc_seq_a, enc_seq_a in zip(__lowercase    ,     __lowercase      ):
																		self.assertTrue(np.allclose(__lowercase    ,     __lowercase    ,     atol=1e-3      )      )




				def        __lowercase	(  self	:Union[str, Any]      ):
											__lowerCamelCase   :   Optional[int]       =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
											__lowerCamelCase   :   Optional[int]       =[floats_list((1, x)      )[0] for x in range(800    ,     1400    ,     200      )]

											__lowerCamelCase   :   Dict       =['''longest''', '''max_length''', '''do_not_pad''']
											__lowerCamelCase   :   Dict       =[None, 1600, None]
											for max_length, padding in zip(__lowercase    ,     __lowercase      ):
																		__lowerCamelCase   :   List[Any]       =feat_extract(__lowercase    ,     padding=__lowercase    ,     max_length=__lowercase    ,     return_tensors='''np'''      )
																		__lowerCamelCase   :   List[Any]       =processed.input_values

																		self._check_zero_mean_unit_variance(input_values[0][:800]      )
																		self.assertTrue(input_values[0][800:].sum() < 1e-6      )
																		self._check_zero_mean_unit_variance(input_values[1][:1000]      )
																		self.assertTrue(input_values[0][1000:].sum() < 1e-6      )
																		self._check_zero_mean_unit_variance(input_values[2][:1200]      )




				def        __lowercase	(  self	:List[Any]      ):
											__lowerCamelCase   :   str       =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
											__lowerCamelCase   :   Union[str, Any]       =range(800    ,     1400    ,     200      )
											__lowerCamelCase   :   Tuple       =[floats_list((1, x)      )[0] for x in lengths]

											__lowerCamelCase   :   Optional[int]       =['''longest''', '''max_length''', '''do_not_pad''']
											__lowerCamelCase   :   List[str]       =[None, 1600, None]

											for max_length, padding in zip(__lowercase    ,     __lowercase      ):
																		__lowerCamelCase   :   int       =feat_extract(__lowercase    ,     max_length=__lowercase    ,     padding=__lowercase      )
																		__lowerCamelCase   :   Any       =processed.input_values

																		self._check_zero_mean_unit_variance(input_values[0][:800]      )
																		self._check_zero_mean_unit_variance(input_values[1][:1000]      )
																		self._check_zero_mean_unit_variance(input_values[2][:1200]      )




				def        __lowercase	(  self	:Optional[int]      ):
											__lowerCamelCase   :   str       =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
											__lowerCamelCase   :   List[Any]       =[floats_list((1, x)      )[0] for x in range(800    ,     1400    ,     200      )]
											__lowerCamelCase   :   int       =feat_extract(
											    __lowercase    ,     truncation=__lowercase    ,     max_length=1000    ,     padding='''max_length'''    ,     return_tensors='''np'''      )
											__lowerCamelCase   :   Optional[int]       =processed.input_values

											self._check_zero_mean_unit_variance(input_values[0, :800]      )
											self._check_zero_mean_unit_variance(input_values[1]      )
											self._check_zero_mean_unit_variance(input_values[2]      )




				def        __lowercase	(  self	:Dict      ):
											__lowerCamelCase   :   str       =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
											__lowerCamelCase   :   str       =[floats_list((1, x)      )[0] for x in range(800    ,     1400    ,     200      )]
											__lowerCamelCase   :   Optional[Any]       =feat_extract(
											    __lowercase    ,     truncation=__lowercase    ,     max_length=1000    ,     padding='''longest'''    ,     return_tensors='''np'''      )
											__lowerCamelCase   :   Union[str, Any]       =processed.input_values

											self._check_zero_mean_unit_variance(input_values[0, :800]      )
											self._check_zero_mean_unit_variance(input_values[1, :1000]      )
											self._check_zero_mean_unit_variance(input_values[2]      )

											# make sure that if max_length < longest -> then pad to max_length
											self.assertTrue(input_values.shape == (3, 1000)      )

											__lowerCamelCase   :   Any       =[floats_list((1, x)      )[0] for x in range(800    ,     1400    ,     200      )]
											__lowerCamelCase   :   Any       =feat_extract(
											    __lowercase    ,     truncation=__lowercase    ,     max_length=2000    ,     padding='''longest'''    ,     return_tensors='''np'''      )
											__lowerCamelCase   :   Dict       =processed.input_values

											self._check_zero_mean_unit_variance(input_values[0, :800]      )
											self._check_zero_mean_unit_variance(input_values[1, :1000]      )
											self._check_zero_mean_unit_variance(input_values[2]      )

											# make sure that if max_length > longest -> then pad to longest
											self.assertTrue(input_values.shape == (3, 1200)      )




				@require_torch
				def        __lowercase	(  self	:Union[str, Any]      ):
											import torch

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

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




				@slow
				@require_torch
				def        __lowercase	(  self	:Optional[Any]      ):
											# this test makes sure that models that are using
											# group norm don't have their feature extractor return the
											# attention_mask
											for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
																		__lowerCamelCase   :   Tuple       =WavaVecaConfig.from_pretrained(__lowercase      )
																		__lowerCamelCase   :   str       =WavaVecaFeatureExtractor.from_pretrained(__lowercase      )

																		# only "layer" feature extraction norm should make use of
																		# attention_mask
																		self.assertEqual(feat_extract.return_attention_mask    ,     config.feat_extract_norm == '''layer'''      )











"""simple docstring"""





import numpy as np



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				np.array ):


							'''simple docstring'''







							return 1 / (1 + np.exp(-vector ))


if __name__ == "__main__":
							import doctest

							doctest.testmod()




