
    ^j*                         d dl Z d dlmZ ddlmZ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mZ  e       rd dlZd dlmc mZ  e       rd dlZ ej.                  e      Z G d	 d
e      Zd
gZy)    N)Any   )
AudioInputmake_list_of_audio)SequenceFeatureExtractor)BatchFeature)PaddingStrategy
TensorTypelogging)is_torch_availableis_torchaudio_availablec                        e Zd ZdZg dZ	 	 	 	 d fd	Z	 	 	 	 	 	 ddedeez  e	z  de
dz  ded	eez  dz  d
e
dz  dedefdZdeeef   fdZ xZS )Xcodec2FeatureExtractora  
    Constructs a Xcodec2 feature extractor, which computes mel-filter bank features for the semantic encoder and padded
    audio for the acoustic encoder.

    This feature extractor inherits from [`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.
        sampling_rate (`int`, *optional*, defaults to 16000):
            The sample rate at which the audio files should be digitalized expressed in hertz (Hz).
        padding_value (`float`, *optional*, defaults to 1.0):
            The value that is used to fill the padding vectors for the mel spectrogram.
        hop_length (`int`, *optional*, defaults to 320):
            Number of audio samples encoded per frame. Equivalent to product of downsampling ratios.
            Needed for acoustic encoder input padding.
    )input_featuresinput_valuespadding_maskinput_features_maskc                     t        |   d
|||d| || _        t        d|d      | _        ddg| j                  _        d| _        d| _        d| _        d	| _	        y )N)feature_sizesampling_ratepadding_value           audior      P   i      )
super__init__
hop_lengthr   acoustic_encoder_paddermodel_input_namesstridenum_mel_binsframe_lengthframe_shift)selfr   r   r   r!   kwargs	__class__s         /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/xcodec2/feature_extraction_xcodec2.pyr    z Xcodec2FeatureExtractor.__init__:   sv     	wl-_lwpvw %'?'(
$
 ;B>9R$$6     Nr   padding
max_length
truncationreturn_tensorsr   devicereturnc                 `   t               st        d      |;|| j                  k7  rYt        d|  d| j                   d| j                   d| d	      t        j                  d| j                  j                   d	       t        |      }|D ])  }	|	j                  d
kD  st        d|	j                          t        |      }
|D cg c]-  }t        j                  t        j                  |      dd      / }}| j                   j                  t#        d|i      ||||| j$                  d      }|j'                  d      }|d   dddddf   }g }t)        |
      D ]  }|*t+        ||   j-                         j/                               n|j                  d   }|| j$                  z   dz
  | j$                  z  | j$                  z  }t1        ||j                  d         }||ddd|f   }t        j                  || j$                  d
z  | j$                  d
z  fd      }|j3                  |      }t4        j6                  j8                  j;                  |dz  | j<                  | j>                  | j                  z  dz  | j@                  | j                  z  dz  | j                  dddddddd| j                  d
z        }||jC                  d      z
  t        jD                  |jG                  dd      dz         z  }|jI                  |        t#        d |i      }| j                  ||||| jJ                  |d!      }|d    }|jM                  d      }|j                  d   |j                  d   | jJ                  z  z
  }|ddd|ddf   jO                  |
|| jJ                  z  | j<                  | jJ                  z        }|M|ddd|f   jO                  |
|| jJ                  z  | jJ                        j1                  d"      jP                  }t#        ||||d#|$      S c c}w )%a  
        Args:
            audio (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
                Numpy array or torch tensor with shape (num_channels, sequence_length). A list of such arrays or
                tensors can also be provided for a batch of inputs.
            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
                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*.
            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 sample rate at which the `audio` input was sampled. It is strongly recommended to pass
                `sampling_rate` at the forward call to prevent silent errors.
            device (`str`, *optional*, defaults to `"cpu"`):
                Device for PyTorch tensors during mel-filter bank feature extraction.
            kwargs (*optional*):
                Remaining dictionary of keyword arguments that will be passed to the tokenizer or the feature
                extractor.
        z;PyTorch is required for mel-filter bank feature extraction.Nz3The model corresponding to this feature extractor: z& was trained using a sampling rate of zD. Please make sure that the provided `audio` 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   z6Expected input shape (channels, length) but got shape )r   r   r   )valuer   pt)r.   r/   r-   return_attention_maskpad_to_multiple_ofr0   attention_maskr   i   i  poveyg
ףp=
?TF   )r%   r&   r'   sample_frequencywindow_typepreemphasis_coefficientremove_dc_offsetuse_log_fbank
use_energydither
snip_edgeslow_freq	high_freqr   )unbiasedgHz>r   )r-   r.   r/   r8   r7   r0   )dim)r   r   r   r   )tensor_type))r   ImportErrorr   
ValueErrorloggerwarningr*   __name__r   ndimshapelenFpadtorch	as_tensorr"   r   r!   poprangeintsumitemminto
torchaudio
compliancekaldifbankr%   r&   r'   meansqrtvarappendr$   getreshapevalues)r(   r   r-   r.   r/   r0   r   r1   r)   example
batch_sizeapadded_inputsr   padded_audiomel_featuresiorig_lenper_sample_len	valid_lenwaveformfeaturesencoded_inputs
padded_melaudio_spectrogramspectrogram_masktrimmed_framess                              r+   __call__z Xcodec2FeatureExtractor.__call__T   st   Z "#[\\$ 2 22 I$ P**+ ,**+9]O1F  NNVW[WeWeWnWnVo p\ \
 #5) 	kG||a #YZaZgZgYh!ijj	k Z
 HMM!uq)6=MM4488'5)*!!")# 9 
 %(()9:$W-aqj9
 z" 	*A<H<Ts<?..05578ZfZlZlmoZpH'$//9A=$//QUYUdUddNNL,>,>r,BCI#Aq*9*$45HuuX1(<dooQR>R'S[^_H{{6*H!,,2288E"!..!..1C1CCdJ ,,t/A/AADH!%!3!3#(,!%" ,,1 9 H  !8==#33uzz(,,q[_,B`cgBg7hhH)1	*2 &'7&FGXX!!#{{")  

 ''78%>>*:;*0037H7N7Nq7QTXT_T_7_`-a.!.CDLL$++5t7H7H4;;7V
 ' O^O!34^t{{%BDKKP	   , ,"3'7	 '
 	
E Ns   2P+c                     t        j                  | j                        }| j                  j                  |d<   |j                  dd        |S )Nfeature_extractor_typer"   )copydeepcopy__dict__r*   rN   rV   )r(   outputs     r+   to_dictzXcodec2FeatureExtractor.to_dict   s=    t}}-+/>>+B+B'(

,d3r,   )r   i>  g      ?i@  )TNFNNcpu)rN   
__module____qualname____doc__r#   r    r   boolstrr	   rX   r
   r   ry   dictr   r   __classcell__)r*   s   @r+   r   r   $   s    & b : 15!% 26$(N
N
 o-N
 $J	N

 N
 j(4/N
 TzN
 N
 
N
`c3h r,   r   )r|   typingr   audio_utilsr   r   !feature_extraction_sequence_utilsr   feature_extraction_utilsr   utilsr	   r
   r   utils.import_utilsr   r   rT   torch.nn.functionalnn
functionalrR   r]   
get_loggerrN   rL   r   __all__r   r,   r+   <module>r      sg      9 I 4 9 9 M ## 
		H	%D6 DN %
%r,   