
    ^j".              	           d dl Z d dlZd dlZd dlmc mZ ddlm	Z	 ddl
mZ ddlmZ ddlmZmZmZ ddlmZ  ej(                  e      Zdded	ed
edefdZ ed       G d de             ZdgZy)    N   )mel_filter_bank)SequenceFeatureExtractor)BatchFeature)PaddingStrategy
TensorTypelogging)requiresvaluename	tolerancereturnc                 p    t        |       }t        | |z
        |kD  rt        | d|        t        |      S )Nz. must resolve to an integer sample count, got )roundabs
ValueErrorint)r   r   r   roundeds       /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/inkling/feature_extraction_inkling.py_to_exact_intr      s>    ElG
57?i'D6!OPUwWXXw<    )torch)backendsc                   `    e Zd ZdZddgZ	 	 	 	 	 	 ddedededed	ed
edz  f fdZddej                  de
dej                  fdZ	 	 	 	 	 	 	 	 ddej                  ee   z  eej                     z  eee      z  dedz  dee
z  ez  dedz  dededz  dedz  de
ez  dz  de
dz  defdZ xZS )InklingFeatureExtractora  
    Constructs a TML audio feature extractor, which converts raw audio waveforms into log-mel spectrogram
    features (mel filterbank energies in log10 space). The quantization of these features into discrete
    dMel bins is performed downstream by [`InklingProcessor`].

    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.

    Args:
        feature_size (`int`, *optional*, defaults to 80):
            The feature dimension of the extracted features, i.e. the number of mel filterbanks.
        sampling_rate (`int`, *optional*, defaults to 16000):
            The sampling rate at which the audio files should be digitized, expressed in hertz (Hz).
        padding_value (`float`, *optional*, defaults to 0.0):
            The value used to pad the log-mel spectrograms to the same length in a batch.
        audio_token_duration_s (`float`, *optional*, defaults to 0.05):
            Duration, in seconds, represented by a single audio token, i.e. the STFT hop length.
        window_size_multiplier (`float`, *optional*, defaults to 2.0):
            Multiplier applied to `audio_token_duration_s` to obtain the STFT window length.
        n_fft (`int`, *optional*):
            FFT size. Defaults to the window length (`audio_token_duration_s * window_size_multiplier *
            sampling_rate`) when not provided.
    input_featuresinput_features_maskNfeature_sizesampling_ratepadding_valueaudio_token_duration_swindow_size_multipliern_fftc           	      z   t        	|   d|||d| || _        || _        t	        ||z  d      | _        t	        ||z  |z  d      | _        |xs | j                  | _        | j
                  dk  s| j                  dk  s| j                  dk  rt        d      t        j                  | j                  dt        j                        | _        t        | j                  dz  d	z   |d
|dz  |dd      }t        j                  t        j                   |j"                  t        j                              | _        y )N)r   r   r    z&audio_token_duration_s * sampling_ratez?audio_token_duration_s * window_size_multiplier * sampling_rater   z7hop_length, window_size, and n_fft must all be positiveT)periodicdtype                     @slaney)num_frequency_binsnum_mel_filtersmin_frequencymax_frequencyr   norm	mel_scale)r&    )super__init__r!   r"   r   
hop_lengthwindow_sizer#   r   r   hann_windowfloat32windowr   
from_numpynpascontiguousarrayTmel_filters)
selfr   r   r    r!   r"   r#   kwargsr>   	__class__s
            r   r4   z InklingFeatureExtractor.__init__B   s8    	 	
%''	
 		
 '=#&<#'"]24\
 )"%;;mKM
 .d..
??a4#3#3q#8DJJ!OVWW ''(8(84u}}] &#zzQ2('#-'
 !++B,@,@VXV`V`,abr   waveformdevicer   c           	         t        j                  |j                  d   | j                  z        | j                  z  |j                  d   z
  }t	        | j
                  | j                  z
  d      }t        j                  |||f      }t        j                  || j
                  | j                  | j                  | j                  j                  |      dd      }t        j                  |      }|j                  d      j                  d      j!                  d      j#                         }| j$                  j                  |      }||z  }|j!                  d      j'                         }|j)                  dd      S )	Nr   FT)r5   
win_lengthr9   centerreturn_complexr'   g|=r(   )mathceilshaper5   maxr#   Fpadr   stftr6   r9   toview_as_realpowsum	clamp_minsqrtr>   log10	transpose)	r?   rB   rC   	right_padleft_padrO   
magnitudesr>   mel_specs	            r   _torch_extract_fbank_featuresz5InklingFeatureExtractor._torch_extract_fbank_featureso   s6   IIhnnR04??BCdooUX`XfXfgiXjj	tzzDOO3Q755Hi#89zzJJ'';;>>&)
 ''-
^^A&**2.88?DDF
&&))&1+%%e,224 !!!Q''r   
raw_speechpadding
max_length
truncationpad_to_multiple_ofreturn_attention_maskreturn_tensorsc
           	      b   |8|| j                   k7  r>t        d| j                    d| j                    d| d      t        j                  d       | j                  j
                  ddd	t        j                  ffd
}t        |t        j                        rt        j                  |      }t        |t        j                        r,|j                  dkD  rt        d|j                   d      |g}nt        |t        t        f      r`t        |      dk(  rt        d      t        |d   t         t"        t        j$                  t        j&                  f      r|g}n&t        |      }nt)        d dt+        |             |D cg c]  } ||      dddf    }}|D cg c]  }t        |       }}t-        ||d      }| j/                  |||||d      }|j0                  j3                  d      }| j5                  ||	      }t        j6                  |j8                  | j:                  z   dz
  | j:                  d      }t        j<                  |j>                  d   |	      dddf   |dddf   k  }||jA                  d      z  }d|i}|r||d<   t-        ||      S c c}w c c}w )a  
        Extract log-mel spectrogram features from one or several audio clip(s).

        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 at `self.sampling_rate`, not stereo, i.e. single float per timestep. Decoding
                and resampling of raw audio (bytes / paths / URLs) is handled upstream by the processor's
                `apply_chat_template`, not here.
            sampling_rate (`int`, *optional*):
                The sampling rate of `raw_speech`, used only to validate against `self.sampling_rate`.
            device (`str`, *optional*, defaults to `"cpu"`):
                The device on which the log-mel spectrogram is computed in `_torch_extract_fbank_features`.
        NzWThe model corresponding to this feature extractor was trained using a sampling rate of zB. Please make sure that the provided audio input was sampled with z	 and not .zIt 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.clipz np.ndarray | torch.Tensor | listr   c                    t        | t        j                        r| n't        j                  t	        j
                  |             }|j                  t        j                        }|j                  dk(  r-t        j                  d d       |j                  d      }|S |j                  dk7  r"t        dt        |j                         d      |S )	Nr'   z2Only mono-channel audio is supported for input to zB. Taking the mean over the channel (last) axis to convert to mono.rE   )dimr(   zDEach audio clip must be 1-D (mono) or 2-D (multichannel), got shape re   )
isinstancer   Tensor	as_tensorr;   asarrayrP   r8   ndimloggerwarning_oncemeanr   tuplerK   )rf   tensorcls_names     r   _to_monoz2InklingFeatureExtractor.__call__.<locals>._to_mono   s    'ell;TQSQ[Q[\`QaAbFYYu}}-F{{a##H
 SW W  ,
 M	 ! Z[`agamam[nZoopq  Mr   r'   zCA single array input must be 1-D (mono) or 2-D (multichannel); got z2 dims. Pass a list of arrays for a batch of clips.r   zReceived an empty audio input.z!Unsupported audio input type for z: )r   audio_lengthspt)r^   r_   r`   ra   rc   rE   r(   floor)rounding_mode)rC   r   r   )datatensor_type)!r   r   rn   ro   rA   __name__r   rj   ri   r;   ndarrayr:   rm   listrq   lenr   floatintegerfloating	TypeErrortyper   rN   r   squeezer\   divru   r5   arangerK   	unsqueeze)r?   r]   r   r^   r_   r`   ra   rb   rc   rC   r@   rt   clipsrf   speechru   batched_speechpadded_inputsinput_waveformsr   
num_framesr   ry   rs   s                          @r   __call__z InklingFeatureExtractor.__call__   s   8 $ 2 22 #112 3((,(:(:';9]OSTV  \
 >>**	= 	%,, 	 j"**-))*5Jj%,,/" YZdZiZiYj kB B   LE
T5M2:!# !ABB*Q-#ubjj"++)NO#Z(?zDQ[L\K]^__:?@$htnQW-@
@ 4>>V>>%Vc&de!!1 ! 
 (66>>rB;;OVT YY''$//9A=t^e

 $ll>+?+?+B6RSWYZSZ[^hijlpip^qq'*=*G*G*KK .1  +>D&'>BB? A ?s   J'$J,)P   i>  r)   g?r*   N)cpu)NTNFNTNr   )r{   
__module____qualname____doc__model_input_namesr   r   r4   r   rj   strr\   r;   r|   r}   boolr   r   r   r   __classcell__)rA   s   @r   r   r   %   s   2 *+@A #"(,(+ +c+c +c 	+c
 !&+c !&+c Tz+cZ(ell (C (\a\h\h (6 %)04!% )--126"nCJJe,tBJJ/??$tE{BSSnC TznC o-	nC
 $JnC nC  $JnC  $d{nC j(4/nC d
nC 
nCr   r   )gư>)rI   numpyr;   r   torch.nn.functionalnn
functionalrM   audio_utilsr   !feature_extraction_sequence_utilsr   feature_extraction_utilsr   utilsr   r   r	   utils.import_utilsr
   
get_loggerr{   rn   r   r   r   r   r   __all__r2   r   r   <module>r      s         * I 4 9 9 * 
		H	% c e s  
:OC6 OC OCd %
%r   