




from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

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


lowerCamelCase_  						=   logging.get_logger(__name__)
class       __a					( __lowerCamelCase     ):


     """simple docstring"""


     _A				:    Any									=  ["input_values", "attention_mask"]




     def __init__(	self			: Tuple				,_UpperCamelCase			: Optional[int]=1				,_UpperCamelCase			: List[Any]=1_6_0_0_0				,_UpperCamelCase			: List[Any]=1_2_8				,_UpperCamelCase			: Dict=1_0_2_4				,_UpperCamelCase			: Optional[int]=0.0				,_UpperCamelCase			: Dict=True				,_UpperCamelCase			: List[str]=-4.267_7393				,_UpperCamelCase			: List[str]=4.568_9974				,_UpperCamelCase			: Union[str, Any]=False				,**_UpperCamelCase			: List[Any]				,)		->   List[str]:


         '''simple docstring'''





         super().__init__(feature_size=_UpperCamelCase				,sampling_rate=_UpperCamelCase				,padding_value=_UpperCamelCase				,**_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=num_mel_bins
         SCREAMING_SNAKE_CASE__								=max_length
         SCREAMING_SNAKE_CASE__								=do_normalize
         SCREAMING_SNAKE_CASE__								=mean
         SCREAMING_SNAKE_CASE__								=std
         SCREAMING_SNAKE_CASE__								=return_attention_mask




     def   __A				(	self			: Optional[int]				,_UpperCamelCase			: np.ndarray				,_UpperCamelCase			: int				,)		->   np.ndarray:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=torch.from_numpy(_UpperCamelCase						).unsqueeze(0						)
         SCREAMING_SNAKE_CASE__								=ta_kaldi.fbank(
             _UpperCamelCase				,htk_compat=_UpperCamelCase				,sample_frequency=self.sampling_rate				,use_energy=_UpperCamelCase				,window_type="""hanning"""				,num_mel_bins=self.num_mel_bins				,dither=0.0				,frame_shift=1_0				,)

         SCREAMING_SNAKE_CASE__								=fbank.shape[0]
         SCREAMING_SNAKE_CASE__								=max_length - n_frames

         # pad or truncate, depending on difference
         if difference > 0:
             SCREAMING_SNAKE_CASE__								=torch.nn.ZeroPadad((0, 0, 0, difference)						)
             SCREAMING_SNAKE_CASE__								=pad_module(_UpperCamelCase						)
         elif difference < 0:
             SCREAMING_SNAKE_CASE__								=fbank[0:max_length, :]

         SCREAMING_SNAKE_CASE__								=fbank.numpy()

         return fbank




     def   __A				(	self			: Optional[Any]				,_UpperCamelCase			: np.ndarray						)		->   np.ndarray:


         '''simple docstring'''





         return (input_values - (self.mean)) / (self.std * 2)




     def __call__(	self			: Union[str, Any]				,_UpperCamelCase			: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,_UpperCamelCase			: Optional[int] = None				,_UpperCamelCase			: Optional[Union[str, TensorType]] = None				,**_UpperCamelCase			: int				,)		->   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(_UpperCamelCase				,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(_UpperCamelCase				,(list, tuple)						) and (isinstance(raw_speech[0]				,(np.ndarray, tuple, list)						))
         )

         if is_batched:
             SCREAMING_SNAKE_CASE__								=[np.asarray(_UpperCamelCase				,dtype=np.floataa						) for speech in raw_speech]
         elif not is_batched and not isinstance(_UpperCamelCase				,np.ndarray						):
             SCREAMING_SNAKE_CASE__								=np.asarray(_UpperCamelCase				,dtype=np.floataa						)
         elif isinstance(_UpperCamelCase				,np.ndarray						) and raw_speech.dtype is np.dtype(np.floataa						):
             SCREAMING_SNAKE_CASE__								=raw_speech.astype(np.floataa						)

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

         # extract fbank features and pad/truncate to max_length
         SCREAMING_SNAKE_CASE__								=[self._extract_fbank_features(_UpperCamelCase				,max_length=self.max_length						) for waveform in raw_speech]

         # convert into BatchFeature
         SCREAMING_SNAKE_CASE__								=BatchFeature({"""input_values""": features}						)

         # make sure list is in array format
         SCREAMING_SNAKE_CASE__								=padded_inputs.get("""input_values"""						)
         if isinstance(input_values[0]				,_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=[np.asarray(_UpperCamelCase				,dtype=np.floataa						) for feature in input_values]

         # normalization
         if self.do_normalize:
             SCREAMING_SNAKE_CASE__								=[self.normalize(_UpperCamelCase						) for feature in input_values]

         if return_tensors is not None:
             SCREAMING_SNAKE_CASE__								=padded_inputs.convert_to_tensors(_UpperCamelCase						)

         return padded_inputs












import unittest
from dataclasses import dataclass
from typing import Optional

from transformers.utils import ModelOutput
@dataclass
class       __a					( __lowerCamelCase     ):


     """simple docstring"""


     _A				:    float
     _A				:    Optional[float]									=  None
     _A				:    Optional[float]									=  None






class       __a					( unittest.TestCase     ):


     """simple docstring"""


     def   __A				(	self			: Dict						)		->   Optional[int]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0						)
         self.assertEqual(x.a				,3_0						)
         self.assertIsNone(x.b						)
         self.assertIsNone(x.c						)
         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=x.d




     def   __A				(	self			: Tuple						)		->   Dict:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0				,b=1_0						)
         self.assertEqual(x[0]				,3_0						)
         self.assertEqual(x[1]				,1_0						)
         self.assertEqual(x[:2]				,(3_0, 1_0)						)
         self.assertEqual(x[:]				,(3_0, 1_0)						)

         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0				,c=1_0						)
         self.assertEqual(x[0]				,3_0						)
         self.assertEqual(x[1]				,1_0						)
         self.assertEqual(x[:2]				,(3_0, 1_0)						)
         self.assertEqual(x[:]				,(3_0, 1_0)						)




     def   __A				(	self			: List[str]						)		->   Dict:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0				,b=1_0						)
         self.assertEqual(x["""a"""]				,3_0						)
         self.assertEqual(x["""b"""]				,1_0						)
         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=x["""c"""]

         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0				,c=1_0						)
         self.assertEqual(x["""a"""]				,3_0						)
         self.assertEqual(x["""c"""]				,1_0						)
         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=x["""b"""]




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


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0						)
         self.assertEqual(list(x.keys()						)				,["""a"""]						)
         self.assertEqual(list(x.values()						)				,[3_0]						)
         self.assertEqual(list(x.items()						)				,[("""a""", 3_0)]						)
         self.assertEqual(list(_UpperCamelCase						)				,["""a"""]						)

         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0				,b=1_0						)
         self.assertEqual(list(x.keys()						)				,["""a""", """b"""]						)
         self.assertEqual(list(x.values()						)				,[3_0, 1_0]						)
         self.assertEqual(list(x.items()						)				,[("""a""", 3_0), ("""b""", 1_0)]						)
         self.assertEqual(list(_UpperCamelCase						)				,["""a""", """b"""]						)

         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0				,c=1_0						)
         self.assertEqual(list(x.keys()						)				,["""a""", """c"""]						)
         self.assertEqual(list(x.values()						)				,[3_0, 1_0]						)
         self.assertEqual(list(x.items()						)				,[("""a""", 3_0), ("""c""", 1_0)]						)
         self.assertEqual(list(_UpperCamelCase						)				,["""a""", """c"""]						)

         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=x.update({"""d""": 2_0}						)
         with self.assertRaises(_UpperCamelCase						):
             del x["a"]
         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=x.pop("""a"""						)
         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=x.setdefault("""d"""				,3_2						)




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


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0						)
         SCREAMING_SNAKE_CASE__								=1_0
         self.assertEqual(x.a				,1_0						)
         self.assertEqual(x["""a"""]				,1_0						)




     def   __A				(	self			: Union[str, Any]						)		->   Optional[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=3_0						)
         SCREAMING_SNAKE_CASE__								=1_0
         self.assertEqual(x.a				,1_0						)
         self.assertEqual(x["""a"""]				,1_0						)




     def   __A				(	self			: Dict						)		->   List[str]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest({"""a""": 3_0, """b""": 1_0}						)
         self.assertEqual(list(x.keys()						)				,["""a""", """b"""]						)
         self.assertEqual(x.a				,3_0						)
         self.assertEqual(x.b				,1_0						)




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


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=ModelOutputTest([("""a""", 3_0), ("""b""", 1_0)]						)
         self.assertEqual(list(x.keys()						)				,["""a""", """b"""]						)
         self.assertEqual(x.a				,3_0						)
         self.assertEqual(x.b				,1_0						)

         with self.assertRaises(_UpperCamelCase						):
             SCREAMING_SNAKE_CASE__								=ModelOutputTest([("""a""", 3_0), (1_0, 1_0)]						)

         SCREAMING_SNAKE_CASE__								=ModelOutputTest(a=(3_0, 3_0)						)
         self.assertEqual(list(x.keys()						)				,["""a"""]						)
         self.assertEqual(x.a				,(3_0, 3_0)						)






