



"""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


lowerCAmelCase__        =				random.Random()






def        snake_case_  (      A_					:		Tuple,				A_					:		List[str]=1.0,				A_					:		Optional[int]=None,				A_					:		List[str]=None						):


       '''simple docstring'''





       if rng is None:
              _lowerCamelCase						:				Union[str, Any]    			= global_rng

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

       return values






class        __snake_case       (	unittest.TestCase):




  def __init__( self     :						str						,					__lowerCAmelCase     :						List[Any]						,					__lowerCAmelCase     :						Dict=7						,					__lowerCAmelCase     :						str=4_0_0						,					__lowerCAmelCase     :						Optional[Any]=2_0_0_0						,					__lowerCAmelCase     :						str=1						,					__lowerCAmelCase     :						List[str]=0.0						,					__lowerCAmelCase     :						Dict=1_6_0_0_0						,					__lowerCAmelCase     :						List[str]=True						,					__lowerCAmelCase     :						str=True						,					):






         """simple docstring"""






         _lowerCamelCase						:				int    			= parent
         _lowerCamelCase						:				Dict    			= batch_size
         _lowerCamelCase						:				str    			= min_seq_length
         _lowerCamelCase						:				List[str]    			= max_seq_length
         _lowerCamelCase						:				Dict    			= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         _lowerCamelCase						:				List[Any]    			= feature_size
         _lowerCamelCase						:				Dict    			= padding_value
         _lowerCamelCase						:				int    			= sampling_rate
         _lowerCamelCase						:				int    			= return_attention_mask
         _lowerCamelCase						:				List[Any]    			= do_normalize




  def 						SCREAMING_SNAKE_CASE				( self     :						Any		):






         """simple docstring"""






         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 						SCREAMING_SNAKE_CASE				( self     :						Optional[Any]						,					__lowerCAmelCase     :						Union[str, Any]=False						,					__lowerCAmelCase     :						Tuple=False		):






         """simple docstring"""






         def _flatten(__lowerCAmelCase     :						int		):
                return list(itertools.chain(*__lowerCAmelCase		)		)

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

         return speech_inputs






class        __snake_case       (	_lowercase  ,     unittest.TestCase):
  snake_case__				:   Tuple  			=						WavaVecaFeatureExtractor




  def 						SCREAMING_SNAKE_CASE				( self     :						int		):






         """simple docstring"""






         _lowerCamelCase						:				Any    			= WavaVecaFeatureExtractionTester(self		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Union[str, Any]						,					__lowerCAmelCase     :						int		):






         """simple docstring"""






         self.assertTrue(np.all(np.mean(__lowerCAmelCase						,					axis=0		) < 1E-3		)		)
         self.assertTrue(np.all(np.abs(np.var(__lowerCAmelCase						,					axis=0		) - 1		) < 1E-3		)		)




  def 						SCREAMING_SNAKE_CASE				( self     :						List[Any]		):






         """simple docstring"""






         _lowerCamelCase						:				Tuple    			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
         # create three inputs of length 800, 1000, and 1200
         _lowerCamelCase						:				int    			= [floats_list((1, x)		)[0] for x in range(8_0_0						,					1_4_0_0						,					2_0_0		)]
         _lowerCamelCase						:				int    			= [np.asarray(__lowerCAmelCase		) for speech_input in speech_inputs]

         # Test not batched input
         _lowerCamelCase						:				List[Any]    			= feat_extract(speech_inputs[0]						,					return_tensors='''np'''		).input_values
         _lowerCamelCase						:				Optional[Any]    			= feat_extract(np_speech_inputs[0]						,					return_tensors='''np'''		).input_values
         self.assertTrue(np.allclose(__lowerCAmelCase						,					__lowerCAmelCase						,					atol=1E-3		)		)

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

         # Test 2-D numpy arrays are batched.
         _lowerCamelCase						:				List[str]    			= [floats_list((1, x)		)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
         _lowerCamelCase						:				Optional[int]    			= np.asarray(__lowerCAmelCase		)
         _lowerCamelCase						:				Tuple    			= feat_extract(__lowerCAmelCase						,					return_tensors='''np'''		).input_values
         _lowerCamelCase						:				Any    			= feat_extract(__lowerCAmelCase						,					return_tensors='''np'''		).input_values
         for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase						,					__lowerCAmelCase		):
                self.assertTrue(np.allclose(__lowerCAmelCase						,					__lowerCAmelCase						,					atol=1E-3		)		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Tuple		):






         """simple docstring"""






         _lowerCamelCase						:				Optional[int]    			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
         _lowerCamelCase						:				Dict    			= [floats_list((1, x)		)[0] for x in range(8_0_0						,					1_4_0_0						,					2_0_0		)]

         _lowerCamelCase						:				List[str]    			= ['''longest''', '''max_length''', '''do_not_pad''']
         _lowerCamelCase						:				Tuple    			= [None, 1_6_0_0, None]
         for max_length, padding in zip(__lowerCAmelCase						,					__lowerCAmelCase		):
                _lowerCamelCase						:				str    			= feat_extract(__lowerCAmelCase						,					padding=__lowerCAmelCase						,					max_length=__lowerCAmelCase						,					return_tensors='''np'''		)
                _lowerCamelCase						:				Optional[int]    			= processed.input_values

                self._check_zero_mean_unit_variance(input_values[0][:8_0_0]		)
                self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6		)
                self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]		)
                self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6		)
                self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]		)




  def 						SCREAMING_SNAKE_CASE				( self     :						str		):






         """simple docstring"""






         _lowerCamelCase						:				str    			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
         _lowerCamelCase						:				Dict    			= range(8_0_0						,					1_4_0_0						,					2_0_0		)
         _lowerCamelCase						:				Tuple    			= [floats_list((1, x)		)[0] for x in lengths]

         _lowerCamelCase						:				Optional[Any]    			= ['''longest''', '''max_length''', '''do_not_pad''']
         _lowerCamelCase						:				str    			= [None, 1_6_0_0, None]

         for max_length, padding in zip(__lowerCAmelCase						,					__lowerCAmelCase		):
                _lowerCamelCase						:				Tuple    			= feat_extract(__lowerCAmelCase						,					max_length=__lowerCAmelCase						,					padding=__lowerCAmelCase		)
                _lowerCamelCase						:				Any    			= processed.input_values

                self._check_zero_mean_unit_variance(input_values[0][:8_0_0]		)
                self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]		)
                self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Dict		):






         """simple docstring"""






         _lowerCamelCase						:				Tuple    			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
         _lowerCamelCase						:				Optional[int]    			= [floats_list((1, x)		)[0] for x in range(8_0_0						,					1_4_0_0						,					2_0_0		)]
         _lowerCamelCase						:				str    			= feat_extract(
             __lowerCAmelCase						,					truncation=__lowerCAmelCase						,					max_length=1_0_0_0						,					padding='''max_length'''						,					return_tensors='''np'''		)
         _lowerCamelCase						:				List[Any]    			= processed.input_values

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




  def 						SCREAMING_SNAKE_CASE				( self     :						int		):






         """simple docstring"""






         _lowerCamelCase						:				int    			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
         _lowerCamelCase						:				List[Any]    			= [floats_list((1, x)		)[0] for x in range(8_0_0						,					1_4_0_0						,					2_0_0		)]
         _lowerCamelCase						:				Union[str, Any]    			= feat_extract(
             __lowerCAmelCase						,					truncation=__lowerCAmelCase						,					max_length=1_0_0_0						,					padding='''longest'''						,					return_tensors='''np'''		)
         _lowerCamelCase						:				int    			= processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]		)
         self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]		)
         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, 1_0_0_0)		)

         _lowerCamelCase						:				Union[str, Any]    			= [floats_list((1, x)		)[0] for x in range(8_0_0						,					1_4_0_0						,					2_0_0		)]
         _lowerCamelCase						:				List[str]    			= feat_extract(
             __lowerCAmelCase						,					truncation=__lowerCAmelCase						,					max_length=2_0_0_0						,					padding='''longest'''						,					return_tensors='''np'''		)
         _lowerCamelCase						:				Dict    			= processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]		)
         self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]		)
         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, 1_2_0_0)		)




  @require_torch
  def 						SCREAMING_SNAKE_CASE				( self     :						Tuple		):






         """simple docstring"""






         import torch

         _lowerCamelCase						:				Tuple    			= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
         _lowerCamelCase						:				Tuple    			= np.random.rand(1_0_0		).astype(np.floataa		)
         _lowerCamelCase						:				Dict    			= np_speech_inputs.tolist()

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




  @slow
  @require_torch
  def 						SCREAMING_SNAKE_CASE				( self     :						List[Any]		):






         """simple docstring"""






         for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
                _lowerCamelCase						:				Optional[Any]    			= WavaVecaConfig.from_pretrained(__lowerCAmelCase		)
                _lowerCamelCase						:				Any    			= WavaVecaFeatureExtractor.from_pretrained(__lowerCAmelCase		)

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



from __future__ import annotations





def    __lowercase     (						lowerCamelCase					:     Optional[Any]  ,  lowerCamelCase					:     Dict  ,  lowerCamelCase					:     Union[str, Any]  ,  lowerCamelCase					:     List[str]	):  # noqa: E741
 while r - l > 1:
  UpperCamelCase_					:						Union[str, Any] =					(l + r) // 2
  if v[m] >= key:
   UpperCamelCase_					:						str =					m
  else:
   UpperCamelCase_					:						List[Any] =					m  # noqa: E741
 return r





def    __lowercase     (						lowerCamelCase					:     list[int]	):
 if len(lowerCamelCase	) == 0:
  return 0

 UpperCamelCase_					:						Tuple =					[0] * len(lowerCamelCase	)
 UpperCamelCase_					:						int =					1

 UpperCamelCase_					:						Dict =					v[0]

 for i in range(1  ,  len(lowerCamelCase	)	):
  if v[i] < tail[0]:
   UpperCamelCase_					:						Any =					v[i]
  elif v[i] > tail[length - 1]:
   UpperCamelCase_					:						Dict =					v[i]
   length += 1
  else:
   UpperCamelCase_					:						List[str] =					v[i]

 return length


if __name__ == "__main__":
   import doctest

   doctest.testmod()



