Ë
    T^(h¹=  ã                   óÂ   — d Z ddlmZmZm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
é    )ÚListÚOptionalÚUnionNé   )Ú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ej                  ee   eej                     eee      f   dedee   deeeef      dee   dee   dee   dee   dee   dee   dee   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 overlaping windows for the STFT used to obtain the Mel Frequency coefficients.
        chunk_length (`int`, *optional*, defaults to 30):
            The maximum number of chuncks 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             €út/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/whisper/feature_extraction_whisper.pyr#   z WhisperFeatureExtractor.__init__H   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+   r0   r1   Úlog_spec_batchÚwaveformÚlog_specs         r.   Ú_np_extract_fbank_featuresz2WhisperFeatureExtractor._np_extract_fbank_featuresl   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/   rD   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.
        )r1   r   )Údtyper1   T)ÚwindowÚreturn_complex.Nr:   r   g»½×Ùß|Û=)Úmin)ÚdimÚkeepdimr   r   r;   r<   r4   )ÚtorchÚ
from_numpyÚtoÚfloat32Úhann_windowr$   r)   ÚrandnÚshaperH   r1   Ústftr%   Úabsr*   ÚTÚclampr6   rL   r@   r?   Údetachr4   Únumpy)
r+   rD   r1   rI   rU   Ú
magnitudesr*   Úmel_specrE   Ú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
        Nr:   gH¯¼šò×z>r   )
r>   rB   Úint32ÚzipÚsumÚmeanÚsqrtÚvarrT   rA   )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?Ú
max_lengthÚ
raw_speechÚ
truncationÚpad_to_multiple_ofÚreturn_tensorsr   Úpaddingr   Údo_normalizeÚreturn_token_timestampsc                 óh  — |�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<   |r|d   dd…dd| j>                  …f   |d<   |�)|D �cg c]  }t        |«      | j>                  z  ‘Œ c}|d<   |�|jA                  |«      }|S c c}w 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_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>

            return_tensors (`str` or [`~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 and allow automatic speech recognition
                pipeline.
            padding_value (`float`, *optional*, defaults to 0.0):
                The value that is used to fill the padding values / vectors.
            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")
            return_token_timestamps (`bool`, *optional*, defaults to `None`):
                Whether or not to return the number of frames of the input raw_speech.
                These num_frames can be used by the model to compute word level timestamps.
        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   )rH   r   )rs   rn   rp   rq   r   r`   )r`   r   )ÚaxisÚ
num_frames)!r   r=   r-   Ú__name__ÚloggerÚwarningÚ
isinstancer>   ÚndarrayÚlenrT   ÚlistÚtupleÚasarrayrQ   rW   rH   Úfloat64Úastyper   Úpadr'   rm   r   ÚstackÚgetÚ	transposer   r^   rF   r   r%   Úconvert_to_tensors)r+   ro   rp   rq   rr   r   rs   rn   r   rt   r1   ru   r,   Úis_batched_numpyÚ
is_batchedÚspeechÚbatched_speechÚpadded_inputsr   Úextract_fbank_featuresÚfeatureÚraw_speech_is                         r.   Ú__call__z WhisperFeatureExtractor.__call__À   s‘  € ðD Ð$Ø × 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Ð*Ñ+á à.;Ð<LÑ.MÊaÑQcÐTX×TcÑTcÐQcÐNcÑ.dˆMÐ*Ñ+à"Ð.ØdnÖ*oÐT`¬3¨|Ó+<ÀÇÁÓ+OÒ*oˆM˜,Ñ'àÐ%Ø)×<Ñ<¸^ÓLˆMàÐùòq ]ùòR /tùò +ps   Ä%7N%Ì,N*Í+N/)éP   i€>  é    é   i�  r   r   F)r4   )r   )
TNNNrn   NNNr4   N)rz   Ú
__module__Ú__qualname__Ú__doc__Úmodel_input_namesr#   r>   rB   Ústrr~   rF   r^   Ústaticmethodr   Úfloatrm   r   Úboolr   Úintr   r   r’   Ú__classcell__)r-   s   @r.   r   r   $   sÒ  ø„ ñðB *Ð*Ðð ØØØØØØØ#õ"
ðH¸¿¹ð È3ð ÐSU×S]ÑS]ó ñ< °b·h±hð  Èð  ÐXZ×XbÑXbó  ð> ð beñ#Ø˜2Ÿ:™:Ñ&ð#Ø8<¸R¿Z¹ZÑ8Hð#ØY^ð#à	ˆb�j‰jÑ	ò#ó ð#ð0  Ø,0Ø;?Ø04Ø!-Ø$(Ø'+Ø'+Ø %Ø26ñOà˜"Ÿ*™* d¨5¡k°4¸¿
¹
Ñ3CÀTÈ$ÈuÉ+ÑEVÐVÑWðOð ðOð % S™Mð	Oð
 !  s¨J Ñ!7Ñ8ðOð  (¨™~ðOð ˜#‘ðOð ˜S‘MðOð   ‘}ðOð ˜t‘nðOð ˜‘ðOð "*¨$¡ðOð 
÷Or/   r   )r˜   Útypingr   r   r   rZ   r>   Ú r   Úaudio_utilsr   r	   r
   Ú!feature_extraction_sequence_utilsr   Úfeature_extraction_utilsr   Úutilsr   r   rN   Ú
get_loggerrz   r{   r   Ú__all__r!   r/   r.   ú<module>r¨      s^   ðñ÷ )Ñ (ã å "ß HÑ HÝ IÝ 4ß (ñ ÔÛà	ˆ×	Ñ	˜HÓ	%€ôkÐ6ô kð\	 %Ð
%�r/   