Ë
    ÜÓ^j�A  ã                   ó®   — d Z ddlZddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZ ddlmZmZ  e«       rddlZ ej"                  e«      Z G d	„ d
e
«      Zd
gZy)z%
Feature extractor class for Whisper
é    Né   )Úis_torch_available)Úmel_filter_bankÚspectrogramÚwindow_function)ÚSequenceFeatureExtractor)ÚBatchFeature)Ú
TensorTypeÚloggingc                   óø  ‡ — e Zd ZdZdgZ	 	 	 	 	 	 	 	 dˆ fd„	Zdej                  dedej                  fd„Z	ddej                  dedej                  fd	„Z
e	 dd
eej                     deej                     dedeej                     fd„«       Z	 	 	 	 	 	 	 	 	 ddej                  ee   z  eej                     z  eee      z  dededz  deez  dz  dedz  dedz  dedz  dedz  dedz  dedz  defd„Zˆ xZS )ÚWhisperFeatureExtractoraŸ  
    Constructs a Whisper 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 class extracts mel-filter bank features from raw speech using a custom numpy implementation of the `Short Time
    Fourier Transform` which should match pytorch's `torch.stft` equivalent.

    Args:
        feature_size (`int`, *optional*, defaults to 80):
            The feature dimension of the extracted features.
        sampling_rate (`int`, *optional*, defaults to 16000):
            The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
        hop_length (`int`, *optional*, defaults to 160):
            Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
        chunk_length (`int`, *optional*, defaults to 30):
            The maximum number of chunks of `sampling_rate` samples used to trim and pad longer or shorter audio
            sequences.
        n_fft (`int`, *optional*, defaults to 400):
            Size of the Fourier transform.
        padding_value (`float`, *optional*, defaults to 0.0):
            Padding value used to pad the audio. Should correspond to silences.
        dither (`float`, *optional*, defaults to 0.0):
            Adds dithering. In other words, adds a small Gaussian noise to each frame.
            E.g. use 0.0001 to add dithering with a normal distribution centered
            around 0.0 with standard deviation 0.0001 (assuming [-1,+1] range of raw_speech).
            The value 0.0 means no dithering.
            Dithering has similar effect as `spectrogram(mel_floor=...)`. It reduces
            the high log_mel_fbank values for signals with hard-zero sections,
            when VAD cutoff is present in the signal.
    Úinput_featuresc	           	      óê   •— t        ‰
| �  d||||dœ|	¤Ž || _        || _        || _        ||z  | _        | j
                  |z  | _        || _        || _        t        d|dz  z   |dd|dd¬«      | _
        y )	N)Úfeature_sizeÚsampling_rateÚpadding_valueÚreturn_attention_maské   é   ç        g     @¿@Úslaney)Únum_frequency_binsÚnum_mel_filtersÚmin_frequencyÚmax_frequencyr   ÚnormÚ	mel_scale© )ÚsuperÚ__init__Ún_fftÚ
hop_lengthÚchunk_lengthÚ	n_samplesÚnb_max_framesr   Úditherr   Úmel_filters)Úselfr   r   r"   r#   r!   r   r&   r   ÚkwargsÚ	__class__s             €ú�/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/whisper/feature_extraction_whisper.pyr    z WhisperFeatureExtractor.__init__E   s›   ø€ ô 	‰Ñð 	
Ø%Ø'Ø'Ø"7ñ		
ð
 ò	
ð ˆŒ
Ø$ˆŒØ(ˆÔØ%¨Ñ5ˆŒØ!Ÿ^™^¨zÑ9ˆÔØ*ˆÔØˆŒÜ*Ø  5¨A¡:™~Ø(ØØ Ø'ØØô
ˆÕó    Úwaveform_batchÚdeviceÚreturnc                 óž  — |dk7  rt        d|› d�«      ‚g }|D ]œ  }t        |t        | j                  d«      | j                  | j                  d| j
                  | j                  d¬«      }|dd…dd	…f   }t        j                  ||j                  «       d
z
  «      }|dz   dz  }|j                  |«       Œž t        j                  |«      }|S )z¦
        Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch
        implementation with 1e-5 tolerance.
        ÚcpuzGot device `zñ` for feature extraction, but feature extraction on CUDA accelerator devices requires torch, which is not installed. Either set `device='cpu'`, or install torch according to the official instructions: https://pytorch.org/get-started/locally/Úhanng       @Úlog10)Úframe_lengthr"   Úpowerr&   r'   Úlog_melNéÿÿÿÿç       @ç      @)Ú
ValueErrorr   r   r!   r"   r&   r'   ÚnpÚmaximumÚmaxÚappendÚarray)r(   r-   r.   Úlog_spec_batchÚwaveformÚlog_specs         r+   Ú_np_extract_fbank_featuresz2WhisperFeatureExtractor._np_extract_fbank_featuresi   sá   € ð
 �UŠ?ÜØ˜v˜hð 'qð qóð ð
 ˆØ&ò 	,ˆHÜ"ØÜ §
¡
¨FÓ3Ø!ŸZ™ZØŸ?™?ØØ—{‘{Ø ×,Ñ,Øô	ˆHð  ¢ 3 B 3 Ñ'ˆHÜ—z‘z (¨H¯L©L«N¸SÑ,@ÓAˆHØ  3™¨#Ñ-ˆHØ×!Ñ! (Õ+ð	,ô Ÿ™ .Ó1ˆØÐr,   rA   c                 ó8  — t        j                  |«      j                  |t         j                  «      }t        j                  | j
                  |¬«      }| j                  dk7  rF|| j                  t        j                  |j                  |j                  |j                  ¬«      z  z  }t        j                  || j
                  | j                  |d¬«      }|ddd…f   j                  «       d	z  }t        j                  | j                  «      j                  |t         j                  «      }|j                  |z  }t        j                   |d
¬«      j#                  «       }|j%                  «       d	k(  rD|j'                  d	d¬«      d   j'                  dd¬«      d   }	t        j(                  ||	dz
  «      }n't        j(                  ||j'                  «       dz
  «      }|dz   dz  }|dk7  r|j+                  «       j-                  «       }|j/                  «       S )zÈ
        Compute the log-mel spectrogram of the audio using PyTorch's GPU-accelerated STFT implementation with batching,
        yielding results similar to cpu computing with 1e-5 tolerance.
        )r.   r   )Údtyper.   T)ÚwindowÚreturn_complex.Nr7   r   g»½×Ùß|Û=)Úmin)ÚdimÚkeepdimr   r   r8   r9   r1   )ÚtorchÚ
from_numpyÚtoÚfloat32Úhann_windowr!   r&   ÚrandnÚshaperE   r.   Ústftr"   Úabsr'   ÚTÚclampr3   rI   r=   r<   Údetachr1   Únumpy)
r(   rA   r.   rF   rR   Ú
magnitudesr'   Úmel_specrB   Úmax_vals
             r+   Ú_torch_extract_fbank_featuresz5WhisperFeatureExtractor._torch_extract_fbank_features‡   s¥  € ô
 ×#Ñ# HÓ-×0Ñ0°¼¿¹ÓGˆÜ×"Ñ" 4§:¡:°fÔ=ˆð
 �;‰;˜#ÒØ˜Ÿ™¤e§k¡k°(·.±.ÈÏÉÐ_g×_nÑ_nÔ&oÑoÑoˆHä�z‰z˜( D§J¡J°·±ÈÐ_cÔdˆØ˜#˜s ˜s˜(‘^×'Ñ'Ó)¨QÑ.ˆ
ä×&Ñ& t×'7Ñ'7Ó8×;Ñ;¸FÄEÇMÁMÓRˆØ—=‘= :Ñ-ˆä—;‘;˜x¨UÔ3×9Ñ9Ó;ˆØ�<‰<‹>˜QÒØ—l‘l q°$�lÓ7¸Ñ:×>Ñ>À1ÈdÐ>ÓSÐTUÑVˆGÜ—}‘} X¨w¸©}Ó=‰Hä—}‘} X¨x¯|©|«~ÀÑ/CÓDˆHØ˜s‘N cÑ)ˆØ�UŠ?Ø—‘Ó(×,Ñ,Ó.ˆHØ�~‰~ÓÐr,   Úinput_valuesÚattention_maskr   c                 ó  — |�³t        j                  |t         j                  «      }g }t        | |j	                  d«      «      D ]m  \  }}||d| j                  «       z
  t        j                  |d| j                  «       dz   «      z  }||j                  d   k  r|||d |j                  |«       Œo |S | D �cg c]<  }||j                  «       z
  t        j                  |j                  «       dz   «      z  ‘Œ> }}|S c c}w )z[
        Every array in the list is normalized to have zero mean and unit variance
        Nr7   gH¯¼šò×z>r   )
r;   r?   Úint32ÚzipÚsumÚmeanÚsqrtÚvarrQ   r>   )r\   r]   r   Únormed_input_valuesÚvectorÚlengthÚnormed_sliceÚxs           r+   Úzero_mean_unit_var_normz/WhisperFeatureExtractor.zero_mean_unit_var_norm¦   s  € ð Ð%ÜŸX™X n´b·h±hÓ?ˆNØ"$Ðä"% l°N×4FÑ4FÀrÓ4JÓ"Kò 9‘�˜Ø &¨°°¨×)=Ñ)=Ó)?Ñ ?Ä2Ç7Á7È6ÐRYÐSYÈ?×K^ÑK^ÓK`ÐcgÑKgÓChÑh�Ø˜L×.Ñ.¨qÑ1Ò1Ø,9�L  Ð)à#×*Ñ*¨<Õ8ð9ð #Ð"ð VbÖ"bÐPQ A¨¯©«¡L´B·G±G¸A¿E¹E»GÀd¹NÓ4KÓ#KÐ"bÐÐ"bà"Ð"ùò #cs   Â:AC?NÚ
max_lengthÚ
raw_speechÚ
truncationÚpad_to_multiple_ofÚreturn_tensorsr   Úpaddingr   Údo_normalizec                 óf  — |�O|| j                   k7  rmt        d| j                  j                  › d| j                   › d| j                   › d|› d�	«      ‚t        j                  d| j                  j                  › d�«       t        |t        j                  «      xr t        |j                  «      d	kD  }|r&t        |j                  «      d
kD  rt        d| › �«      ‚|xs@ t        |t        t        f«      xr( t        |d   t        j                  t        t        f«      }|r>|D �cg c]2  }t        j                  |gt        j                  ¬«      j                  ‘Œ4 }}nª|s@t        |t        j                  «      s&t        j                  |t        j                  ¬«      }nht        |t        j                  «      rN|j                   t        j                   t        j"                  «      u r|j%                  t        j                  «      }|s!t        j                  |g«      j                  g}t'        d|i«      }| j)                  |||r|n| j*                  |||xs |	¬«      }|	rD| j-                  |d   |d   | j.                  ¬«      |d<   t        j0                  |d   d¬«      |d<   |j3                  d«      j5                  d
dd	«      }t7        «       r| j8                  n| j:                  } ||d   |
«      }t        |d   t        «      r7|D �cg c]'  }t        j                  |t        j                  ¬«      ‘Œ) c}|d<   n||d<   |rK|d   dd…dd| j<                  …f   }|d   j                  d	   | j<                  z  dk7  r|dd…dd…f   }||d<   |�|j?                  |«      }|S c c}w c c}w )a]  Main method to featurize and prepare for the model one or several sequence(s). Implementation uses PyTorch
        for the STFT computation if available, otherwise a slower NumPy based one.

        Args:
            raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
                The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
                values, 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.
            truncation (`bool`, *optional*, default to `True`):
                Activates truncation to cut input sequences longer than *max_length* to *max_length*.
            pad_to_multiple_of (`int`, *optional*, defaults to None):
                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_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
            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)

                <Tip>

                For Whisper models, `attention_mask` should always be passed for batched inference, to avoid subtle
                bugs.

                </Tip>
            padding (`str` or [`~utils.PaddingStrategy`], *optional*, defaults to `'max_length'`):
                Activates and controls padding. Accepts the following values:

                - `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence is
                  provided).
                - `'max_length'` (default): 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.
                - `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
            max_length (`int`, *optional*):
                Controls the maximum length to use by one of the truncation/padding parameters.

                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
                is required by one of the truncation/padding parameters. If the model has no specific maximum input
                length (like XLNet) truncation/padding to a maximum length will be deactivated.
            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 and allow automatic speech recognition
                pipeline.
            do_normalize (`bool`, *optional*, defaults to `False`):
                Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
                improve the performance of the model.
            device (`str`, *optional*, defaults to `'cpu'`):
                Specifies the device for computation of the log-mel spectrogram of audio signals in the
                `_torch_extract_fbank_features` method. (e.g., "cpu", "cuda")
            **kwargs: Not supported by WhisperFeatureExtractor.__call__() and ignored.
        Nz3The model corresponding to this feature extractor: z& was trained using a sampling rate of zI. Please make sure that the provided `raw_speech` input was sampled with z	 and not ú.zDIt is strongly recommended to pass the `sampling_rate` argument to `zN()`. Failing to do so can result in silent errors that might be hard to debug.r   r   z2Only mono-channel audio is supported for input to r   )rE   r   )rp   rk   rm   rn   r   r]   )r]   r   )Úaxisr7   ) r   r:   r*   Ú__name__ÚloggerÚwarningÚ
isinstancer;   ÚndarrayÚlenrQ   ÚlistÚtupleÚasarrayrN   rT   rE   Úfloat64Úastyper	   Úpadr$   rj   r   ÚstackÚgetÚ	transposer   r[   rC   r"   Úconvert_to_tensors)r(   rl   rm   rn   ro   r   rp   rk   r   rq   r.   r)   Úis_batched_numpyÚ
is_batchedÚspeechÚbatched_speechÚpadded_inputsr   Úextract_fbank_featuresÚfeatureÚrescaled_attention_masks                        r+   Ú__call__z WhisperFeatureExtractor.__call__½   s›  € ðP Ð$Ø × 2Ñ 2Ò2Ü ØIÈ$Ï.É.×JaÑJaÐIbð c)Ø)-×);Ñ);Ð(<ð =)Ø)-×);Ñ);Ð(<¸IÀmÀ_ÐTUðWóð ô �N‰NØVÐW[×WeÑWe×WnÑWnÐVoð p\ð \ôô
 & j´"·*±*Ó=Ò[Ä#Àj×FVÑFVÓBWÐZ[ÑB[ÐÙ¤ J×$4Ñ$4Ó 5¸Ò 9ÜÐQÐRVÐQWÐXÓYÐYØ%ò 
Ü�z¤D¬% =Ó1Òl´zÀ*ÈQÁ-ÔRT×R\ÑR\Ô^cÔeiÐQjÓ7kð 	ñ ØQ[Ö\Àvœ"Ÿ*™* f X´R·Z±ZÔ@×BÓBÐ\ˆJÑ\Ù¤J¨z¼2¿:¹:Ô$FÜŸ™ J´b·j±jÔA‰JÜ˜
¤B§J¡JÔ/°J×4DÑ4DÌÏÉÔQS×Q[ÑQ[ÓH\Ñ4\Ø#×*Ñ*¬2¯:©:Ó6ˆJñ ÜŸ*™* j \Ó2×4Ñ4Ð5ˆJä%Ð'7¸Ð&DÓEˆð Ÿ™ØØÙ%/‘z°T·^±^Ø!Ø1Ø"7Ò"G¸<ð !ó 
ˆñ Ø.2×.JÑ.JØÐ.Ñ/Ø,Ð-=Ñ>Ø"×0Ñ0ð /Kó /ˆMÐ*Ñ+ô
 /1¯h©h°}ÐEUÑ7VÐ]^Ô._ˆMÐ*Ñ+ð '×*Ñ*Ð+;Ó<×FÑFÀqÈ!ÈQÓOˆô 3EÔ2FˆD×.Ò.ÈD×LkÑLkð 	ñ 0°¸qÑ0AÀ6ÓJˆä�n QÑ'¬Ô.ØdrÖ.sÐY`¬r¯z©z¸'ÌÏÉÖ/TÒ.sˆMÐ*Ò+ð /=ˆMÐ*Ñ+á à&3Ð4DÑ&EÂaÑI[ÈDÏOÉOÐI[ÐF[Ñ&\Ð#ð
 Ð-Ñ.×4Ñ4°QÑ7¸$¿/¹/ÑIÈQÒNØ*AÂ!ÀSÀbÀSÀ&Ñ*IÐ'Ø.EˆMÐ*Ñ+àÐ%Ø)×<Ñ<¸^ÓLˆMàÐùòy ]ùòR /ts   Ä%7N)Ì,N.)éP   i€>  é    é   i�  r   r   F)r1   )r   )	TNNNrk   NNNr1   )ru   Ú
__module__Ú__qualname__Ú__doc__Úmodel_input_namesr    r;   ry   ÚstrrC   r[   Ústaticmethodr{   Úfloatrj   ÚboolÚintr
   r	   r�   Ú__classcell__)r*   s   @r+   r   r   !   s½  ø„ ñðB *Ð*Ðð ØØØØØØØ#õ"
ðH¸¿¹ð ÈSð ÐUW×U_ÑU_ó ñ< °b·j±jð  È#ð  ÐZ\×ZdÑZdó  ð> ð beñ#Ø˜2Ÿ:™:Ñ&ð#Ø8<¸R¿Z¹ZÑ8Hð#ØY^ð#à	ˆb�j‰jÑ	ò#ó ð#ð0  Ø)-Ø26Ø-1Ø*Ø!%Ø$(Ø$(Ø"ñYà—J‘J  e¡Ñ,¨t°B·J±JÑ/?Ñ?À$ÀtÈEÁ{ÑBSÑSðYð ðYð   $™Jð	Yð
 ˜jÑ(¨4Ñ/ðYð  $ d™{ðYð �t‘ðYð ˜$‘JðYð ˜T‘zðYð ˜T‘kðYð �d‘
ðYð 
÷Yr,   r   )r“   rW   r;   Ú r   Úaudio_utilsr   r   r   Ú!feature_extraction_sequence_utilsr   Úfeature_extraction_utilsr	   Úutilsr
   r   rK   Ú
get_loggerru   rv   r   Ú__all__r   r,   r+   ú<module>r¢      sX   ðñó å "ß HÑ HÝ IÝ 4ß (ñ ÔÛà	ˆ×	Ñ	˜HÓ	%€ôuÐ6ô uðp	 %Ð
%�r,   