





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


SCREAMING_SNAKE_CASE_		  =			logging.get_logger(__name__)

class 						UpperCamelCase__					( lowerCAmelCase_  ):



     '''simple docstring'''

     __snake_case       :      Union[str, Any]						      =     ["input_values", "attention_mask"]






     def __init__(				self		:       List[str]		,lowerCamelCase__		:       Optional[Any]=1		,lowerCamelCase__		:       int=16000		,lowerCamelCase__		:       Any=0.0		,lowerCamelCase__		:       Union[str, Any]=False		,lowerCamelCase__		:       Optional[Any]=True		,**lowerCamelCase__		:       str		,)	->						Dict:




           '''simple docstring'''


           super().__init__(feature_size=lowerCamelCase__		,sampling_rate=lowerCamelCase__		,padding_value=lowerCamelCase__		,**lowerCamelCase__			)
           SCREAMING_SNAKE_CASE						=		return_attention_mask
           SCREAMING_SNAKE_CASE						=		do_normalize






     @staticmethod
     def 							SCREAMING_SNAKE_CASE__    (				lowerCamelCase__		:       List[np.ndarray]		,lowerCamelCase__		:       List[np.ndarray]		,lowerCamelCase__		:       float = 0.0			)	->						List[np.ndarray]:




           '''simple docstring'''


           if attention_mask is not None:
                 SCREAMING_SNAKE_CASE						=		np.array(lowerCamelCase__		,np.intaa			)
                 SCREAMING_SNAKE_CASE						=		[]

                 for vector, length in zip(lowerCamelCase__		,attention_mask.sum(-1			)			):
                       SCREAMING_SNAKE_CASE						=		(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7			)
                       if length < normed_slice.shape[0]:
                             SCREAMING_SNAKE_CASE						=		padding_value

                       normed_input_values.append(lowerCamelCase__			)
           else:
                 SCREAMING_SNAKE_CASE						=		[(x - x.mean()) / np.sqrt(x.var() + 1e-7			) for x in input_values]

           return normed_input_values






     def __call__(				self		:       Optional[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__		:       str		,)	->						BatchFeature:




           '''simple docstring'''


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

           SCREAMING_SNAKE_CASE						=		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}"""			)
           SCREAMING_SNAKE_CASE						=		is_batched_numpy or (
               isinstance(lowerCamelCase__		,(list, tuple)			) and (isinstance(raw_speech[0]		,(np.ndarray, tuple, list)			))
           )

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

           # convert into correct format for padding
           SCREAMING_SNAKE_CASE						=		BatchFeature({"""input_values""": raw_speech}			)

           SCREAMING_SNAKE_CASE						=		self.pad(
               lowerCamelCase__		,padding=lowerCamelCase__		,max_length=lowerCamelCase__		,truncation=lowerCamelCase__		,pad_to_multiple_of=lowerCamelCase__		,return_attention_mask=lowerCamelCase__		,)

           # convert input values to correct format
           SCREAMING_SNAKE_CASE						=		padded_inputs["""input_values"""]
           if not isinstance(input_values[0]		,np.ndarray			):
                 SCREAMING_SNAKE_CASE						=		[np.asarray(lowerCamelCase__		,dtype=np.floataa			) for array in input_values]
           elif (
               not isinstance(lowerCamelCase__		,np.ndarray			)
               and isinstance(input_values[0]		,np.ndarray			)
               and input_values[0].dtype is np.dtype(np.floataa			)
           ):
                 SCREAMING_SNAKE_CASE						=		[array.astype(np.floataa			) for array in input_values]
           elif isinstance(lowerCamelCase__		,np.ndarray			) and input_values.dtype is np.dtype(np.floataa			):
                 SCREAMING_SNAKE_CASE						=		input_values.astype(np.floataa			)

           # convert attention_mask to correct format
           SCREAMING_SNAKE_CASE						=		padded_inputs.get("""attention_mask"""			)
           if attention_mask is not None:
                 SCREAMING_SNAKE_CASE						=		[np.asarray(lowerCamelCase__		,dtype=np.intaa			) for array in attention_mask]

           # zero-mean and unit-variance normalization
           if self.do_normalize:
                 SCREAMING_SNAKE_CASE						=		(
                     attention_mask
                     if self._get_padding_strategies(lowerCamelCase__		,max_length=lowerCamelCase__			) is not PaddingStrategy.DO_NOT_PAD
                     else None
                 )
                 SCREAMING_SNAKE_CASE						=		self.zero_mean_unit_var_norm(
                     padded_inputs["""input_values"""]		,attention_mask=lowerCamelCase__		,padding_value=self.padding_value			)

           if return_tensors is not None:
                 SCREAMING_SNAKE_CASE						=		padded_inputs.convert_to_tensors(lowerCamelCase__			)

           return padded_inputs









import unittest
from dataclasses import dataclass
from typing import Optional

from transformers.utils import ModelOutput

@dataclass
class 						UpperCamelCase__					( lowerCAmelCase_  ):



     '''simple docstring'''

     __snake_case       :      float
     __snake_case       :      Optional[float]						      =     None
     __snake_case       :      Optional[float]						      =     None

class 						UpperCamelCase__					( unittest.TestCase  ):



     '''simple docstring'''

     def 							SCREAMING_SNAKE_CASE__    (				self		:       Any			)	->						Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30			)
           self.assertEqual(x.a		,30			)
           self.assertIsNone(x.b			)
           self.assertIsNone(x.c			)
           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		x.d






     def 							SCREAMING_SNAKE_CASE__    (				self		:       Optional[Any]			)	->						Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30		,b=10			)
           self.assertEqual(x[0]		,30			)
           self.assertEqual(x[1]		,10			)
           self.assertEqual(x[:2]		,(30, 10)			)
           self.assertEqual(x[:]		,(30, 10)			)

           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30		,c=10			)
           self.assertEqual(x[0]		,30			)
           self.assertEqual(x[1]		,10			)
           self.assertEqual(x[:2]		,(30, 10)			)
           self.assertEqual(x[:]		,(30, 10)			)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       str			)	->						Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30		,b=10			)
           self.assertEqual(x["""a"""]		,30			)
           self.assertEqual(x["""b"""]		,10			)
           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		x["""c"""]

           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30		,c=10			)
           self.assertEqual(x["""a"""]		,30			)
           self.assertEqual(x["""c"""]		,10			)
           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		x["""b"""]






     def 							SCREAMING_SNAKE_CASE__    (				self		:       List[Any]			)	->						Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30			)
           self.assertEqual(list(x.keys()			)		,["""a"""]			)
           self.assertEqual(list(x.values()			)		,[30]			)
           self.assertEqual(list(x.items()			)		,[("""a""", 30)]			)
           self.assertEqual(list(lowerCamelCase__			)		,["""a"""]			)

           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30		,b=10			)
           self.assertEqual(list(x.keys()			)		,["""a""", """b"""]			)
           self.assertEqual(list(x.values()			)		,[30, 10]			)
           self.assertEqual(list(x.items()			)		,[("""a""", 30), ("""b""", 10)]			)
           self.assertEqual(list(lowerCamelCase__			)		,["""a""", """b"""]			)

           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30		,c=10			)
           self.assertEqual(list(x.keys()			)		,["""a""", """c"""]			)
           self.assertEqual(list(x.values()			)		,[30, 10]			)
           self.assertEqual(list(x.items()			)		,[("""a""", 30), ("""c""", 10)]			)
           self.assertEqual(list(lowerCamelCase__			)		,["""a""", """c"""]			)

           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		x.update({"""d""": 20}			)
           with self.assertRaises(lowerCamelCase__			):
                 del x["a"]
           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		x.pop("""a"""			)
           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		x.setdefault("""d"""		,32			)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       int			)	->						List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30			)
           SCREAMING_SNAKE_CASE						=		10
           self.assertEqual(x.a		,10			)
           self.assertEqual(x["""a"""]		,10			)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       List[str]			)	->						Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=30			)
           SCREAMING_SNAKE_CASE						=		10
           self.assertEqual(x.a		,10			)
           self.assertEqual(x["""a"""]		,10			)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       List[Any]			)	->						Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest({"""a""": 30, """b""": 10}			)
           self.assertEqual(list(x.keys()			)		,["""a""", """b"""]			)
           self.assertEqual(x.a		,30			)
           self.assertEqual(x.b		,10			)






     def 							SCREAMING_SNAKE_CASE__    (				self		:       Optional[int]			)	->						Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE						=		ModelOutputTest([("""a""", 30), ("""b""", 10)]			)
           self.assertEqual(list(x.keys()			)		,["""a""", """b"""]			)
           self.assertEqual(x.a		,30			)
           self.assertEqual(x.b		,10			)

           with self.assertRaises(lowerCamelCase__			):
                 SCREAMING_SNAKE_CASE						=		ModelOutputTest([("""a""", 30), (10, 10)]			)

           SCREAMING_SNAKE_CASE						=		ModelOutputTest(a=(30, 30)			)
           self.assertEqual(list(x.keys()			)		,["""a"""]			)
           self.assertEqual(x.a		,(30, 30)			)


