o
    MeO                     @   s   d dl mZ d dlmZ d dlmZ d dlZd dlmZ d dlmZ ddl	m
Z
 ddl	mZ dd	l	mZ dd
lmZ G dd dejZG dd dejZG dd dejZG dd dejZdS )    )partial)Optional)UnionN)Tensor   )compute_fbank_matrix)
create_dct)power_to_db)
get_windowc                       sr   e Zd ZdZ								dd	ed
ee dee dedededededdf fddZ	de
de
fddZ  ZS )Spectrogramaa  Compute spectrogram of given signals, typically audio waveforms.
    The spectorgram is defined as the complex norm of the short-time Fourier transformation.

    Args:
        n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512.
        hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None.
        win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None.
        window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'.
        power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0.
        center (bool, optional): Whether to pad `x` to make that the :math:`t 	imes hop\_length` at the center of `t`-th frame. Defaults to True.
        pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'.
        dtype (str, optional): Data type of input and window. Defaults to 'float32'.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of Spectrogram.



    Examples:
        .. code-block:: python

            import paddle
            from paddle.audio.features import Spectrogram

            sample_rate = 16000
            wav_duration = 0.5
            num_channels = 1
            num_frames = sample_rate * wav_duration
            wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1
            waveform = wav_data.tile([num_channels, 1])

            feature_extractor = Spectrogram(n_fft=512, window = 'hann', power = 1.0)
            feats = feature_extractor(waveform)
       Nhann      ?Treflectfloat32n_fft
hop_length
win_lengthwindowpowercenterpad_modedtypereturnc	           	   	      sr   t t|   |dksJ d|| _|d u r|}t||d|d| _ttjj	|||| j||d| _
| d| j d S )Nr   z!Power of spectrogram must be > 0.T)Zfftbinsr   )r   r   r   r   r   r   
fft_window)superr   __init__r   r
   r   r   paddlesignalstft_stftregister_buffer)	selfr   r   r   r   r   r   r   r   	__class__ LD:\Projects\ConvertPro\env\Lib\site-packages\paddle/audio/features/layers.pyr   @   s&   	zSpectrogram.__init__xc                 C   s"   |  |}tt|| j}|S )z
        Args:
            x (Tensor): Tensor of waveforms with shape `(N, T)`

        Returns:
            Tensor: Spectrograms with shape `(N, n_fft//2 + 1, num_frames)`.
        )r    r   powabsr   )r"   r'   r   Zspectrogramr%   r%   r&   forward^   s   
zSpectrogram.forward)r   r   Nr   r   Tr   r   )__name__
__module____qualname____doc__intr   strfloatboolr   r   r*   __classcell__r%   r%   r#   r&   r      s<    $r   c                       s   e Zd ZdZ										
					d#dededee dee dededededededee dede	eef deddf fddZ
d edefd!d"Z  ZS )$MelSpectrograma	  Compute the melspectrogram of given signals, typically audio waveforms. It is computed by multiplying spectrogram with Mel filter bank matrix.

    Args:
        sr (int, optional): Sample rate. Defaults to 22050.
        n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512.
        hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None.
        win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None.
        window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'.
        power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0.
        center (bool, optional): Whether to pad `x` to make that the :math:`t 	imes hop\_length` at the center of `t`-th frame. Defaults to True.
        pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'.
        n_mels (int, optional): Number of mel bins. Defaults to 64.
        f_min (float, optional): Minimum frequency in Hz. Defaults to 50.0.
        f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None.
        htk (bool, optional): Use HTK formula in computing fbank matrix. Defaults to False.
        norm (Union[str, float], optional): Type of normalization in computing fbank matrix. Slaney-style is used by default. You can specify norm=1.0/2.0 to use customized p-norm normalization. Defaults to 'slaney'.
        dtype (str, optional): Data type of input and window. Defaults to 'float32'.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of MelSpectrogram.

    Examples:
        .. code-block:: python

            import paddle
            from paddle.audio.features import MelSpectrogram

            sample_rate = 16000
            wav_duration = 0.5
            num_channels = 1
            num_frames = sample_rate * wav_duration
            wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1
            waveform = wav_data.tile([num_channels, 1])

            feature_extractor = MelSpectrogram(sr=sample_rate, n_fft=512, window = 'hann', power = 1.0)
            feats = feature_extractor(waveform)
    "V     r   Nr          @Tr   @         I@Fslaneyr   srr   r   r   r   r   r   r   n_melsf_minf_maxhtknormr   r   c              
      s   t t|   t||||||||d| _|	| _|
| _|| _|| _|| _	|d u r+|d }t
|||	|
||||d| _| d| j d S )N)r   r   r   r   r   r   r   r   r   )r;   r   r<   r=   r>   r?   r@   r   fbank_matrix)r   r4   r   r   _spectrogramr<   r=   r>   r?   r@   r   rA   r!   )r"   r;   r   r   r   r   r   r   r   r<   r=   r>   r?   r@   r   r#   r%   r&   r      s6   zMelSpectrogram.__init__r'   c                 C   s   |  |}t| j|}|S )z
        Args:
            x (Tensor): Tensor of waveforms with shape `(N, T)`

        Returns:
            Tensor: Mel spectrograms with shape `(N, n_mels, num_frames)`.
        )rB   r   matmulrA   )r"   r'   Zspect_featuremel_featurer%   r%   r&   r*      s   
zMelSpectrogram.forward)r5   r6   r   Nr   r7   Tr   r8   r9   NFr:   r   r+   r,   r-   r.   r/   r   r0   r1   r2   r   r   r   r*   r3   r%   r%   r#   r&   r4   k   s`    '	

*r4   c                %       s   e Zd ZdZ											
							d'dededee dee dededededededee dede	eef dededee d ed!df$ fd"d#Z
d$ed!efd%d&Z  ZS )(LogMelSpectrograma	  Compute log-mel-spectrogram feature of given signals, typically audio waveforms.

    Args:
        sr (int, optional): Sample rate. Defaults to 22050.
        n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512.
        hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None.
        win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None.
        window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'.
        power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0.
        center (bool, optional): Whether to pad `x` to make that the :math:`t 	imes hop\_length` at the center of `t`-th frame. Defaults to True.
        pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'.
        n_mels (int, optional): Number of mel bins. Defaults to 64.
        f_min (float, optional): Minimum frequency in Hz. Defaults to 50.0.
        f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None.
        htk (bool, optional): Use HTK formula in computing fbank matrix. Defaults to False.
        norm (Union[str, float], optional): Type of normalization in computing fbank matrix. Slaney-style is used by default. You can specify norm=1.0/2.0 to use customized p-norm normalization. Defaults to 'slaney'.
        ref_value (float, optional): The reference value. If smaller than 1.0, the db level of the signal will be pulled up accordingly. Otherwise, the db level is pushed down. Defaults to 1.0.
        amin (float, optional): The minimum value of input magnitude. Defaults to 1e-10.
        top_db (Optional[float], optional): The maximum db value of spectrogram. Defaults to None.
        dtype (str, optional): Data type of input and window. Defaults to 'float32'.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of LogMelSpectrogram.

    Examples:
        .. code-block:: python

            import paddle
            from paddle.audio.features import LogMelSpectrogram

            sample_rate = 16000
            wav_duration = 0.5
            num_channels = 1
            num_frames = sample_rate * wav_duration
            wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1
            waveform = wav_data.tile([num_channels, 1])

            feature_extractor = LogMelSpectrogram(sr=sample_rate, n_fft=512, window = 'hann', power = 1.0)
            feats = feature_extractor(waveform)
    r5   r   Nr   r7   Tr   r8   r9   Fr:   r   绽|=r   r;   r   r   r   r   r   r   r   r<   r=   r>   r?   r@   	ref_valueamintop_dbr   r   c                    sJ   t t|   t|||||||||	|
||||d| _|| _|| _|| _d S )N)r;   r   r   r   r   r   r   r   r<   r=   r>   r?   r@   r   )r   rF   r   r4   _melspectrogramrH   rI   rJ   )r"   r;   r   r   r   r   r   r   r   r<   r=   r>   r?   r@   rH   rI   rJ   r   r#   r%   r&   r      s&   
zLogMelSpectrogram.__init__r'   c                 C   s$   |  |}t|| j| j| jd}|S )z
        Args:
            x (Tensor): Tensor of waveforms with shape `(N, T)`

        Returns:
            Tensor: Log mel spectrograms with shape `(N, n_mels, num_frames)`.
        )rH   rI   rJ   )rK   r	   rH   rI   rJ   )r"   r'   rD   log_mel_featurer%   r%   r&   r*     s   
zLogMelSpectrogram.forward)r5   r   NNr   r7   Tr   r8   r9   NFr:   r   rG   Nr   rE   r%   r%   r#   r&   rF      sr    *	

'rF   c                '       s   e Zd ZdZ											
								d)dedededee dee dededededededee dede	eef ded ed!ee d"ed#df& fd$d%Z
d&ed#efd'd(Z  ZS )*MFCCa  Compute mel frequency cepstral coefficients(MFCCs) feature of given waveforms.

    Args:
        sr (int, optional): Sample rate. Defaults to 22050.
        n_mfcc (int, optional): [description]. Defaults to 40.
        n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512.
        hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None.
        win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None.
        window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'.
        power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0.
        center (bool, optional): Whether to pad `x` to make that the :math:`t 	imes hop\_length` at the center of `t`-th frame. Defaults to True.
        pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'.
        n_mels (int, optional): Number of mel bins. Defaults to 64.
        f_min (float, optional): Minimum frequency in Hz. Defaults to 50.0.
        f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None.
        htk (bool, optional): Use HTK formula in computing fbank matrix. Defaults to False.
        norm (Union[str, float], optional): Type of normalization in computing fbank matrix. Slaney-style is used by default. You can specify norm=1.0/2.0 to use customized p-norm normalization. Defaults to 'slaney'.
        ref_value (float, optional): The reference value. If smaller than 1.0, the db level of the signal will be pulled up accordingly. Otherwise, the db level is pushed down. Defaults to 1.0.
        amin (float, optional): The minimum value of input magnitude. Defaults to 1e-10.
        top_db (Optional[float], optional): The maximum db value of spectrogram. Defaults to None.
        dtype (str, optional): Data type of input and window. Defaults to 'float32'.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of MFCC.

    Examples:
        .. code-block:: python

            import paddle
            from paddle.audio.features import MFCC

            sample_rate = 16000
            wav_duration = 0.5
            num_channels = 1
            num_frames = sample_rate * wav_duration
            wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1
            waveform = wav_data.tile([num_channels, 1])

            feature_extractor = MFCC(sr=sample_rate, n_fft=512, window = 'hann')
            feats = feature_extractor(waveform)
    r5   (   r   Nr   r7   Tr   r8   r9   Fr:   r   rG   r   r;   n_mfccr   r   r   r   r   r   r   r<   r=   r>   r?   r@   rH   rI   rJ   r   r   c                    s   t t|   ||
ksJ d||
f tdi d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|| _t||
|d| _| d| j d S )Nz-n_mfcc cannot be larger than n_mels: %d vs %dr;   r   r   r   r   r   r   r   r<   r=   r>   r?   r@   rH   rI   rJ   r   )rO   r<   r   
dct_matrixr%   )r   rM   r   rF   _log_melspectrogramr   rP   r!   )r"   r;   rO   r   r   r   r   r   r   r   r<   r=   r>   r?   r@   rH   rI   rJ   r   r#   r%   r&   r   U  sN   	
zMFCC.__init__r'   c                 C   s(   |  |}t|d| jd}|S )z
        Args:
            x (Tensor): Tensor of waveforms with shape `(N, T)`

        Returns:
            Tensor: Mel frequency cepstral coefficients with shape `(N, n_mfcc, num_frames)`.
        )r   r      )rQ   r   rC   Z	transposerP   )r"   r'   rL   Zmfccr%   r%   r&   r*     s   
zMFCC.forward)r5   rN   r   NNr   r7   Tr   r8   r9   NFr:   r   rG   Nr   rE   r%   r%   r#   r&   rM   *  sx    +	

*rM   )	functoolsr   typingr   r   r   Z	paddle.nnnnr   Z
functionalr   r   r	   Zfunctional.windowr
   ZLayerr   r4   rF   rM   r%   r%   r%   r&   <module>   s   O^a