codingutf8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license feature extractor class for mctct modelinputnames inputfeatures attentionmask def init self featuresize80 samplingrate16000 paddingvalue0 0 hoplength10 winlength25 winfunctionhammingwindow framesignalscale32768 0 preemphasiscoeff0 97 melfloor1 0 normalizemeanstrue normalizevarstrue returnattentionmaskfalse kwargs super initfeaturesizefeaturesize samplingratesamplingrate paddingvaluepaddingvalue kwargs self featuresize featuresize self samplingrate samplingrate self paddingvalue paddingvalue self hoplength hoplength self winlength winlength self framesignalscale framesignalscale self preemphasiscoeff preemphasiscoeff self melfloor melfloor self normalizemeans normalizemeans self normalizevars normalizevars self winfunction winfunction self returnattentionmask returnattentionmask self samplesize winlength samplingrate 1000 self samplestride hoplength samplingrate 1000 self nfft optimalfftlengthself samplesize self nfreqs self nfft 2 1 def extractmfscfeaturesself onewaveform np array np ndarray if self winfunction hammingwindow window windowfunctionwindowlengthself samplesize nameself winfunction periodicfalse else window windowfunctionwindowlengthself samplesize nameself winfunction fbanks melfilterbank numfrequencybinsself nfreqs nummelfiltersself featuresize minfrequency0 0 maxfrequencyself samplingrate 2 0 samplingrateself samplingrate msfcfeatures spectrogram onewaveform self framesignalscale windowwindow framelengthself samplesize hoplengthself samplestride fftlengthself nfft centerfalse preemphasisself preemphasiscoeff melfiltersfbanks melfloorself melfloor logmellog return msfcfeatures t def normalizeoneself x inputlength paddingvalue make sure we normalize float32 arrays if self normalizemeans mean x inputlength meanaxis0 x np subtractx mean if self normalizevars std x inputlength stdaxis0 x np dividex std if inputlength x shape0 xinputlength paddingvalue make sure array is in float32 x x astypenp float32 return x def normalize self inputfeatures listnp ndarray attentionmask optionalnp ndarray none listnp ndarray lengths attentionmask sum1 if attentionmask is not none else x shape0 for x in inputfeatures return self normalizeonex n self paddingvalue for x n in zipinputfeatures lengths def call self rawspeech unionnp ndarray listfloat listnp ndarray listlistfloat padding unionbool str paddingstrategy false maxlength optionalint none truncation bool false padtomultipleof optionalint none returnattentionmask optionalbool none returntensors optionalunionstr tensortype none samplingrate optionalint none kwargs batchfeature if samplingrate is not none if samplingrate self samplingrate raise valueerror fthe model corresponding to this feature extractor self was trained using a sampling rate of f self samplingrate please make sure that the provided rawspeech input was sampled with f self samplingrate and not samplingrate else logger warning it is strongly recommended to pass the samplingrate argument to this function failing to do so can result in silent errors that might be hard to debug isbatchednumpy isinstancerawspeech np ndarray and lenrawspeech shape 1 if isbatchednumpy and lenrawspeech shape 2 raise valueerrorfonly monochannel audio is supported for input to self isbatched isbatchednumpy or isinstancerawspeech list tuple and isinstancerawspeech0 np ndarray tuple list if isbatched rawspeech np asarrayspeech dtypenp float32 for speech in rawspeech elif not isbatched and not isinstancerawspeech np ndarray rawspeech np asarrayrawspeech dtypenp float32 elif isinstancerawspeech np ndarray and rawspeech dtype is np dtypenp float64 rawspeech rawspeech astypenp float32 always return batch if not isbatched rawspeech rawspeech extract fbank features features self extractmfscfeaturesonewaveform for onewaveform in rawspeech convert into correct format for padding encodedinputs batchfeatureinputfeatures features paddedinputs self pad encodedinputs paddingpadding maxlengthmaxlength truncationtruncation padtomultipleofpadtomultipleof returnattentionmasktrue kwargs make sure list is in array format inputfeatures paddedinputs getinputfeatures if isinstanceinputfeatures0 list paddedinputsinputfeatures np asarrayfeature dtypenp float32 for feature in inputfeatures attentionmask paddedinputs getattentionmask if attentionmask is not none paddedinputsattentionmask np asarrayarray dtypenp int32 for array in attentionmask if self normalizemeans or self normalizevars attentionmask np arrayattentionmask dtypenp int32 if self getpaddingstrategiespadding maxlengthmaxlength is not paddingstrategy donotpad and padding else none paddedinputsinputfeatures self normalize paddedinputsinputfeatures attentionmaskattentionmask if returntensors is not none paddedinputs paddedinputs converttotensorsreturntensors return paddedinputs coding utf 8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license feature extractor class for m ctc t constructs a m ctc t feature extractor this feature extractor inherits from feature_extraction_sequence_utils sequencefeatureextractor which contains most of the main methods users should refer to this superclass for more information regarding those methods this code has been adapted from flashlight s c code for more information about the implementation one can refer to this notebook https colab research google com drive 1gltinkkhzms isdcgy_ tvckv0qnf gt scrollto pmcrgmmuc_an that takes the user step by step in the implementation args feature_size int defaults to 80 the feature dimension of the extracted features this is the number of mel_frequency sampling_rate int defaults to 16000 the sampling rate at which the audio files should be digitalized expressed in hertz hz padding_value float defaults to 0 0 the value that is used to fill the padding values hop_length int defaults to 10 number of audio samples between windows otherwise referred to as shift in many papers win_length int defaults to 25 number of ms per window win_function str defaults to hamming_window name for the window function used for windowing must be accessible via torch win_function frame_signal_scale float defaults to 32768 0 constant multiplied in creating the frames before applying dft preemphasis_coeff float defaults to 0 97 constant multiplied in applying pre emphasis before dft mel_floor float defaults to 1 0 minimum value of mel frequency banks normalize_means bool optional defaults to true whether or not to zero mean normalize the extracted features normalize_vars bool optional defaults to true whether or not to unit variance normalize the extracted features extracts mfsc features for one waveform vector unbatched adapted from flashlight s c mfsc code make sure we normalize float32 arrays make sure array is in float32 main method to featurize and prepare for the model one or several sequence s sequences it returns the log mel spectrogram of the input audio as implemented in the original flashlight mfsc feature extraction code args raw_speech torch tensor np ndarray list float list torch tensor list np ndarray list list float the sequence or batch of sequences to be padded each sequence can be a tensor a numpy array a list of float values a list of tensors a list of numpy arrays or a list of list of float values must be mono channel audio not stereo i e single float per timestep padding bool str or file_utils paddingstrategy optional defaults to false select a strategy to pad the returned sequences according to the model s padding side and padding index among true or longest pad to the longest sequence in the batch or no padding if only a single sequence if provided max_length pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided false or do_not_pad default no padding i e can output a batch with sequences of different lengths max_length int optional maximum length of the returned list and optionally padding length see above truncation bool activates truncation to cut input sequences longer than max_length to max_length pad_to_multiple_of int optional if set will pad the sequence to a multiple of the provided value this is especially useful to enable the use of tensor cores on nvidia hardware with compute capability 7 5 volta or on tpus which benefit from having sequence lengths be a multiple of 128 return_attention_mask bool optional whether to return the attention mask if left to the default will return the attention mask according to the specific feature_extractor s default what are attention masks glossary attention mask return_tensors str or file_utils tensortype optional if set will return tensors instead of list of python integers acceptable values are tf return tensorflow tf constant objects pt return pytorch torch tensor objects np return numpy np ndarray objects sampling_rate int optional the sampling rate at which the raw_speech input was sampled it is strongly recommended to pass sampling_rate at the forward call to prevent silent errors padding_value float defaults to 0 0 always return batch extract fbank features convert into correct format for padding make sure list is in array format
from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


logger = logging.get_logger(__name__)


class MCTCTFeatureExtractor(SequenceFeatureExtractor):
    r

    model_input_names = ["input_features", "attention_mask"]

    def __init__(
        self,
        feature_size=80,
        sampling_rate=16000,
        padding_value=0.0,
        hop_length=10,
        win_length=25,
        win_function="hamming_window",
        frame_signal_scale=32768.0,
        preemphasis_coeff=0.97,
        mel_floor=1.0,
        normalize_means=True,
        normalize_vars=True,
        return_attention_mask=False,
        **kwargs,
    ):
        super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)

        self.feature_size = feature_size
        self.sampling_rate = sampling_rate
        self.padding_value = padding_value
        self.hop_length = hop_length
        self.win_length = win_length
        self.frame_signal_scale = frame_signal_scale
        self.preemphasis_coeff = preemphasis_coeff
        self.mel_floor = mel_floor
        self.normalize_means = normalize_means
        self.normalize_vars = normalize_vars
        self.win_function = win_function
        self.return_attention_mask = return_attention_mask

        self.sample_size = win_length * sampling_rate // 1000
        self.sample_stride = hop_length * sampling_rate // 1000

        self.n_fft = optimal_fft_length(self.sample_size)
        self.n_freqs = (self.n_fft // 2) + 1

    def _extract_mfsc_features(self, one_waveform: np.array) -> np.ndarray:
        
        if self.win_function == "hamming_window":
            window = window_function(window_length=self.sample_size, name=self.win_function, periodic=False)
        else:
            window = window_function(window_length=self.sample_size, name=self.win_function)

        fbanks = mel_filter_bank(
            num_frequency_bins=self.n_freqs,
            num_mel_filters=self.feature_size,
            min_frequency=0.0,
            max_frequency=self.sampling_rate / 2.0,
            sampling_rate=self.sampling_rate,
        )

        msfc_features = spectrogram(
            one_waveform * self.frame_signal_scale,
            window=window,
            frame_length=self.sample_size,
            hop_length=self.sample_stride,
            fft_length=self.n_fft,
            center=False,
            preemphasis=self.preemphasis_coeff,
            mel_filters=fbanks,
            mel_floor=self.mel_floor,
            log_mel="log",
        )
        return msfc_features.T

    def _normalize_one(self, x, input_length, padding_value):
        
        if self.normalize_means:
            mean = x[:input_length].mean(axis=0)
            x = np.subtract(x, mean)
        if self.normalize_vars:
            std = x[:input_length].std(axis=0)
            x = np.divide(x, std)

        if input_length < x.shape[0]:
            x[input_length:] = padding_value

        
        x = x.astype(np.float32)

        return x

    def normalize(
        self, input_features: List[np.ndarray], attention_mask: Optional[np.ndarray] = None
    ) -> List[np.ndarray]:
        lengths = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
        return [self._normalize_one(x, n, self.padding_value) for x, n in zip(input_features, lengths)]

    def __call__(
        self,
        raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
        padding: Union[bool, str, PaddingStrategy] = False,
        max_length: Optional[int] = None,
        truncation: bool = False,
        pad_to_multiple_of: Optional[int] = None,
        return_attention_mask: Optional[bool] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        sampling_rate: Optional[int] = None,
        **kwargs,
    ) -> BatchFeature:
        

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

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

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

        
        if not is_batched:
            raw_speech = [raw_speech]

        
        features = [self._extract_mfsc_features(one_waveform) for one_waveform in raw_speech]

        
        encoded_inputs = BatchFeature({"input_features": features})

        padded_inputs = self.pad(
            encoded_inputs,
            padding=padding,
            max_length=max_length,
            truncation=truncation,
            pad_to_multiple_of=pad_to_multiple_of,
            return_attention_mask=True,
            **kwargs,
        )
        
        input_features = padded_inputs.get("input_features")
        if isinstance(input_features[0], list):
            padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features]

        attention_mask = padded_inputs.get("attention_mask")
        if attention_mask is not None:
            padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]

        if self.normalize_means or self.normalize_vars:
            attention_mask = (
                np.array(attention_mask, dtype=np.int32)
                if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
                and padding
                else None
            )
            padded_inputs["input_features"] = self.normalize(
                padded_inputs["input_features"], attention_mask=attention_mask
            )

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

        return padded_inputs