U
    ,:%ev                 %   @   s  d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	 d dl
Z
d dlZd dl
mZ d dlmZ ddlmZmZ dd	d
dddddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*g%Zdeeeeeeee e	eef eeeee ed-d.dZdeee eeeeee	eef eeeed/d0d	Ze	eef d1d2d3Ze
jd4d5d6Zeeeeeeeeee eed7d8d
Zdeeeeee ed9d:dZeeeed;d<dZdeeed>d?d@ZdeeedAdBdCZ eeedDdEdFZ!deeeeeee eedGdHdZ"eeeeeedIdJdZ#eeee edKdLdZ$eeedMdNdZ%eeedOdPdZ&eeeedQdRdZ'eeeedSdTdUZ(deeeeeedWdXdZ)deeeeeedYdZdZ*deeeed]d^dZ+eeeeed_d`daZ,deeef eeef eeeef dcdddeZ-eeeedfdgdhZ.eeedidjdkZ/deeeeeeedpdqdZ0deeeeeedudvdZ1eeeeeeeedwdxdZ2ej3j4edydtdzdeeeeee ee ee ed{d|dZ5e
6d}Z7d~dbdde7dfeeeeeeee e
j6ee
j d	ddZ8eeeeeedddZ9deeeeeeee edddZ:e
j;j<eeedddZ=eedddZ>deeeeeee ee ee ed	ddZ?deeeeee ee ee edddZ@eee edddZAdeeeeeeeedddZBdeee eeedddZCde
jeee
jdddZDde
jeee
jdddZEe
je
jddddZFdeee	eef eeeeddd ZGdeeee	eef  eeeeddd!ZHeeddd"ZIdeee	eef eeeeddd#ZJeeeddd$ZKe
je
jddddZLeddddZMe
jeeee
jdddZNde
je
jee
jddd%ZOde
je
jee
jddd&ZPde
je
je
jee
j e
jddd'ZQde
jeeee
j ee
jee
j f dÜdd(ZRdee
jdƜdd)ZSdee
jdƜdd*ZTddʄ ZUdS )    N)Sequence)ListOptionalTupleUnion)Tensor)
deprecated   )highpass_biquadtreble_biquadspectrograminverse_spectrogram
griffinlimamplitude_to_DBDB_to_amplitudecompute_deltasmelscale_fbankslinear_fbanks
create_dctdetect_pitch_frequencymu_law_encodingmu_law_decodingphase_vocodermask_along_axismask_along_axis_iidsliding_window_cmnspectral_centroidapply_codecresampleedit_distanceloudnesspitch_shift	rnnt_losspsdmvdr_weights_soudenmvdr_weights_rtfrtf_evd	rtf_powerapply_beamformingfftconvolveconvolve	add_noisespeedpreemphasis
deemphasisTreflect)waveformpadwindown_fft
hop_length
win_lengthpower
normalizedcenterpad_modeonesidedreturn_complexreturnc                 C   s   |dk	rt d |dkr0tjj| ||fd} t|\}}|  }| d|d } tj	| ||||||	||
dd
}||dd |j
dd  }|r||d	   }|dk	r|d
kr| S | |S |S )a  Create a spectrogram or a batch of spectrograms from a raw audio signal.
    The spectrogram can be either magnitude-only or complex.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        waveform (Tensor): Tensor of audio of dimension `(..., time)`
        pad (int): Two sided padding of signal
        window (Tensor): Window tensor that is applied/multiplied to each frame/window
        n_fft (int): Size of FFT
        hop_length (int): Length of hop between STFT windows
        win_length (int): Window size
        power (float or None): Exponent for the magnitude spectrogram,
            (must be > 0) e.g., 1 for magnitude, 2 for power, etc.
            If None, then the complex spectrum is returned instead.
        normalized (bool or str): Whether to normalize by magnitude after stft. If input is str, choices are
            ``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to
            ``"window"``. When normalized on ``"window"``, waveform is normalized upon the window's L2 energy. If
            normalized on ``"frame_length"``, waveform is normalized by dividing by
            :math:`(\text{frame\_length})^{0.5}`.
        center (bool, optional): whether to pad :attr:`waveform` on both sides so
            that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
            Default: ``True``
        pad_mode (string, optional): controls the padding method used when
            :attr:`center` is ``True``. Default: ``"reflect"``
        onesided (bool, optional): controls whether to return half of results to
            avoid redundancy. Default: ``True``
        return_complex (bool, optional):
            Deprecated and not used.

    Returns:
        Tensor: Dimension `(..., freq, time)`, freq is
        ``n_fft // 2 + 1`` and ``n_fft`` is the number of
        Fourier bins, and time is the number of window hops (n_frame).
    Nz`return_complex` argument is now deprecated and is not effective.`torchaudio.functional.spectrogram(power=None)` always returns a tensor with complex dtype. Please remove the argument in the function call.r   constantT
inputr3   r4   r5   r2   r8   r9   r7   r:   r;          @      ?)warningswarntorchnn
functionalr1   _get_spec_normssizereshapestftshapepowsumsqrtabs)r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   frame_length_normwindow_normrM   spec_f rU   _/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torchaudio/functional/functional.pyr   9   s:    3 )r   lengthr1   r2   r3   r4   r5   r7   r8   r9   r:   r<   c                 C   s   t |\}}|  std|r6| |d   } |  }| d|d |d } tj	| |||||||
|dk	r||d|  nddd
}|dk	r|d	kr|dd|| f }||dd |j
dd  }|S )
a0  Create an inverse spectrogram or a batch of inverse spectrograms from the provided
    complex-valued spectrogram.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        spectrogram (Tensor): Complex tensor of audio of dimension (..., freq, time).
        length (int or None): The output length of the waveform.
        pad (int): Two sided padding of signal. It is only effective when ``length`` is provided.
        window (Tensor): Window tensor that is applied/multiplied to each frame/window
        n_fft (int): Size of FFT
        hop_length (int): Length of hop between STFT windows
        win_length (int): Window size
        normalized (bool or str): Whether the stft output was normalized by magnitude. If input is str, choices are
            ``"window"`` and ``"frame_length"``, dependent on normalization mode. ``True`` maps to
            ``"window"``.
        center (bool, optional): whether the waveform was padded on both sides so
            that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
            Default: ``True``
        pad_mode (string, optional): controls the padding method used when
            :attr:`center` is ``True``. This parameter is provided for compatibility with the
            spectrogram function and is not used. Default: ``"reflect"``
        onesided (bool, optional): controls whether spectrogram was done in onesided mode.
            Default: ``True``

    Returns:
        Tensor: Dimension `(..., time)`. Least squares estimation of the original signal.
    z+Expected `spectrogram` to be complex dtype.rB   r>   rA   N   F)
r@   r3   r4   r5   r2   r8   r7   r:   rW   r;   r   )rI   
is_complex
ValueErrorrN   rO   rP   rJ   rK   rF   istftrM   )r   rW   r1   r2   r3   r4   r5   r7   r8   r9   r:   rR   rS   rM   r0   rU   rU   rV   r      s.    , )r7   c                 C   sp   d\}}t j| trH| dkr,td| | dkr:d}qh| dkrhd}n t j| tr`| rhd}ntd||fS )N)FF)frame_lengthr2   z Invalid normalized parameter: {}r\   Tr2   zInput type not supported)rF   jit
isinstancestrrZ   formatbool	TypeError)r7   rR   rS   rU   rU   rV   rI      s    rI   
real_dtypec                 C   sB   | t jkrt jS | t jkr t jS | t jkr0t jS td|  d S )NzUnexpected dtype )rF   doubleZcdoublefloatZcfloathalfZ	complex32rZ   rc   rU   rU   rV   _get_complex_dtype   s    


rh   )specgramr2   r3   r4   r5   r6   n_itermomentumrW   	rand_initr<   c
                 C   sj  d|  krdk s$n t d||d|  }|  }
| dgt|
dd  } | d| } |	rtj|  t| j	| j
d}ntj|  dt| j	| j
d}tjd| j	| j
d}t|D ]l}tj| | |||||d	}tj|||||d
ddd
d
d
}|}|r||| }|| d}|}qtj| | |||||d	}||
dd |jdd  }|S )a  Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Implementation ported from
    *librosa* :cite:`brian_mcfee-proc-scipy-2015`, *A fast Griffin-Lim algorithm* :cite:`6701851`
    and *Signal estimation from modified short-time Fourier transform* :cite:`1172092`.

    Args:
        specgram (Tensor): A magnitude-only STFT spectrogram of dimension `(..., freq, frames)`
            where freq is ``n_fft // 2 + 1``.
        window (Tensor): Window tensor that is applied/multiplied to each frame/window
        n_fft (int): Size of FFT, creates ``n_fft // 2 + 1`` bins
        hop_length (int): Length of hop between STFT windows. (
            Default: ``win_length // 2``)
        win_length (int): Window size. (Default: ``n_fft``)
        power (float): Exponent for the magnitude spectrogram,
            (must be > 0) e.g., 1 for magnitude, 2 for power, etc.
        n_iter (int): Number of iteration for phase recovery process.
        momentum (float): The momentum parameter for fast Griffin-Lim.
            Setting this to 0 recovers the original Griffin-Lim method.
            Values near 1 can lead to faster convergence, but above 1 may not converge.
        length (int or None): Array length of the expected output.
        rand_init (bool): Initializes phase randomly if True, to zero otherwise.

    Returns:
        Tensor: waveform of `(..., time)`, where time equals the ``length`` parameter if given.
    r   r	   z+momentum must be in range [0, 1). Found: {}r>   rA   Ndtypedevice        r3   r4   r5   r2   rW   Tr/   Fr?   gؗҜ<)rZ   r`   rJ   rK   listrN   rF   randrh   rn   ro   fulltensorranger[   rL   Zmul_divrQ   addrM   )ri   r2   r3   r4   r5   r6   rj   rk   rW   rl   rM   ZanglesZtprev_ZinverseZrebuiltr0   rU   rU   rV   r     s\    *           )x
multiplieramindb_multipliertop_dbr<   c              	   C   s   |t t j| |d }||| 8 }|dk	r| }| dkrH|d nd}|d||d |d }t ||jdd	| dddd}||}|S )
a   Turn a spectrogram from the power/amplitude scale to the decibel scale.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    The output of each tensor in a batch depends on the maximum value of that tensor,
    and so may return different values for an audio clip split into snippets vs. a full clip.

    Args:

        x (Tensor): Input spectrogram(s) before being converted to decibel scale.
            The expected shapes are ``(freq, time)``, ``(channel, freq, time)`` or
            ``(..., batch, channel, freq, time)``.

            .. note::

               When ``top_db`` is specified, cut-off values are computed for each audio
               in the batch. Therefore if the input shape is 4D (or larger), different
               cut-off values are used for audio data in the batch.
               If the input shape is 2D or 3D, a single cutoff value is used.

        multiplier (float): Use 10. for power and 20. for amplitude
        amin (float): Number to clamp ``x``
        db_multiplier (float): Log10(max(reference value and amin))
        top_db (float or None, optional): Minimum negative cut-off in decibels. A reasonable number
            is 80. (Default: ``None``)

    Returns:
        Tensor: Output tensor in decibel scale
    )minNrX   r	   r>   rA   )r   rA   r>   dim)	rF   log10clamprJ   r   rK   maxZamaxview)rz   r{   r|   r}   r~   Zx_dbrM   Zpacked_channelsrU   rU   rV   r   g  s    "$
)rz   refr6   r<   c                 C   s   |t t dd|  | S )a  Turn a tensor from the decibel scale to the power/amplitude scale.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    Args:
        x (Tensor): Input tensor before being converted to power/amplitude scale.
        ref (float): Reference which the output will be scaled by.
        power (float): If power equals 1, will compute DB to power. If 0.5, will compute DB to amplitude.

    Returns:
        Tensor: Output tensor in power/amplitude scale.
          $@g?)rF   rN   )rz   r   r6   rU   rU   rV   r     s    htk)freq	mel_scaler<   c                 C   s   |dkrt d|dkr.dtd| d   S d}d}| | | }d	}|| | }td
d }| |kr~|t| | |  }|S )zConvert Hz to Mels.

    Args:
        freqs (float): Frequencies in Hz
        mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)

    Returns:
        mels (float): Frequency in Mels
    slaneyr   -mel_scale should be one of "htk" or "slaney".r        F@rC        @rp   竪P@     @@皙@      ;@)rZ   mathr   log)r   r   f_minf_spmels
min_log_hzmin_log_mellogsteprU   rU   rV   
_hz_to_mel  s    r   )r   r   r<   c           	      C   s   |dkrt d|dkr,dd| d  d  S d}d	}|||   }d
}|| | }tdd }| |k}|t|| | |   ||< |S )zConvert mel bin numbers to frequencies.

    Args:
        mels (Tensor): Mel frequencies
        mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)

    Returns:
        freqs (Tensor): Mels converted in Hz
    r   r   r   r   r   r   rC   rp   r   r   r   r   )rZ   r   r   rF   exp)	r   r   r   r   freqsr   r   r   Zlog_trU   rU   rV   
_mel_to_hz  s    r   )	all_freqsf_ptsr<   c                 C   s   |dd |dd  }| d|  d }td}d|ddddf  |dd  }|ddddf |dd  }t|t||}|S )a  Create a triangular filter bank.

    Args:
        all_freqs (Tensor): STFT freq points of size (`n_freqs`).
        f_pts (Tensor): Filter mid points of size (`n_filter`).

    Returns:
        fb (Tensor): The filter bank of size (`n_freqs`, `n_filter`).
    r	   Nr>   r   g      rA   rX   )	unsqueezerF   zerosr   r   )r   r   Zf_diffZslopeszeroZdown_slopesZ	up_slopesfbrU   rU   rV   _create_triangular_filterbank  s    
$ r   )n_freqsr   f_maxn_melssample_ratenormr   r<   c                 C   s   |dk	r|dkrt dtd|d | }t||d}t||d}	t||	|d }
t|
|d}t||}|dk	r|dkrd|d|d  |d|   }||d9 }|jddjd	k	 rt
d
| d|  d |S )a"  Create a frequency bin conversion matrix.

    .. devices:: CPU

    .. properties:: TorchScript

    Note:
        For the sake of the numerical compatibility with librosa, not all the coefficients
        in the resulting filter bank has magnitude of 1.

        .. image:: https://download.pytorch.org/torchaudio/doc-assets/mel_fbanks.png
           :alt: Visualization of generated filter bank

    Args:
        n_freqs (int): Number of frequencies to highlight/apply
        f_min (float): Minimum frequency (Hz)
        f_max (float): Maximum frequency (Hz)
        n_mels (int): Number of mel filterbanks
        sample_rate (int): Sample rate of the audio waveform
        norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band
            (area normalization). (Default: ``None``)
        mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)

    Returns:
        Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_mels``)
        meaning number of frequencies to highlight/apply to x the number of filterbanks.
        Each column is a filterbank so that assuming there is a matrix A of
        size (..., ``n_freqs``), the applied result would be
        ``A @ melscale_fbanks(A.size(-1), ...)``.

    Nr   z$norm must be one of None or "slaney"r   rX   )r   rB   r   rp   zIAt least one mel filterbank has all zero values. The value for `n_mels` (z4) may be set too high. Or, the value for `n_freqs` (z) may be set too low.)rZ   rF   linspacer   r   r   r   r   valuesanyrD   rE   )r   r   r   r   r   r   r   r   Zm_minZm_maxZm_ptsr   r   ZenormrU   rU   rV   r   	  s     )
 )r   r   r   n_filterr   r<   c                 C   s2   t d|d | }t |||d }t||}|S )a)  Creates a linear triangular filterbank.

    .. devices:: CPU

    .. properties:: TorchScript

    Note:
        For the sake of the numerical compatibility with librosa, not all the coefficients
        in the resulting filter bank has magnitude of 1.

        .. image:: https://download.pytorch.org/torchaudio/doc-assets/lin_fbanks.png
           :alt: Visualization of generated filter bank

    Args:
        n_freqs (int): Number of frequencies to highlight/apply
        f_min (float): Minimum frequency (Hz)
        f_max (float): Maximum frequency (Hz)
        n_filter (int): Number of (linear) triangular filter
        sample_rate (int): Sample rate of the audio waveform

    Returns:
        Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_filter``)
        meaning number of frequencies to highlight/apply to x the number of filterbanks.
        Each column is a filterbank so that assuming there is a matrix A of
        size (..., ``n_freqs``), the applied result would be
        ``A * linear_fbanks(A.size(-1), ...)``.
    r   rX   )rF   r   r   )r   r   r   r   r   r   r   r   rU   rU   rV   r   Q  s    #
)n_mfccr   r   r<   c                 C   s   |dk	r|dkrt dtt|}tt| d}ttjt| |d  | }|dkrl|d9 }n0|d  dtd 9  < |tdt| 9 }|	 S )	a  Create a DCT transformation matrix with shape (``n_mels``, ``n_mfcc``),
    normalized depending on norm.

    .. devices:: CPU

    .. properties:: TorchScript

    Args:
        n_mfcc (int): Number of mfc coefficients to retain
        n_mels (int): Number of mel filterbanks
        norm (str or None): Norm to use (either "ortho" or None)

    Returns:
        Tensor: The transformation matrix, to be right-multiplied to
        row-wise data of size (``n_mels``, ``n_mfcc``).
    NZorthoz#norm must be either "ortho" or Noner	         ?rB   r   rC   )
rZ   rF   arangerf   r   cosr   pirP   t)r   r   r   nkdctrU   rU   rV   r     s     
)rz   quantization_channelsr<   c                 C   s~   |d }|   s&td | tj} tj|| jd}t| t	|t
|   t	| }|d d | d tj}|S )a  Encode signal based on mu-law companding.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    For more info see the
    `Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_

    This algorithm expects the signal has been scaled to between -1 and 1 and
    returns a signal encoded with values from 0 to quantization_channels - 1.

    Args:
        x (Tensor): Input tensor
        quantization_channels (int): Number of channels

    Returns:
        Tensor: Input after mu-law encoding
    rC   zbThe input Tensor must be of floating type.             This will be an error in the v0.12 release.rn   r	   rX   r   )is_floating_pointrD   rE   torF   rf   ru   rn   signlog1prQ   Zint64)rz   r   mux_murU   rU   rV   r     s    ()r   r   r<   c                 C   sl   |d }|   s| tj} tj|| jd}| | d d }t|tt|t	| d  | }|S )a  Decode mu-law encoded signal.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    For more info see the
    `Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_

    This expects an input with values between 0 and quantization_channels - 1
    and returns a signal scaled between -1 and 1.

    Args:
        x_mu (Tensor): Input tensor
        quantization_channels (int): Number of channels

    Returns:
        Tensor: Input after mu-law decoding
    rC   r   rX   )
r   r   rF   rf   ru   rn   r   r   rQ   r   )r   r   r   rz   rU   rU   rV   r     s    ,)complex_specgramsratephase_advancer<   c                 C   sp  |dkr| S |   }| dgt|dd  } t| j}tjd|  d|| j|d}|d }| dddf  }tj	j
| dd	g} | d| }| d|d  }	| }
|	 }| }|	 }||
 | }|d	tj t|d	tj    }|| }tj||dddf gdd
}t|d}|| d| |  }t||}||dd |jdd  }|S )aF  Given a STFT tensor, speed up in time without modifying pitch by a factor of ``rate``.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        complex_specgrams (Tensor):
            A tensor of dimension `(..., freq, num_frame)` with complex dtype.
        rate (float): Speed-up factor
        phase_advance (Tensor): Expected phase advance in each bin. Dimension of `(freq, 1)`

    Returns:
        Tensor:
            Stretched spectrogram. The resulting tensor is of the same dtype as the input
            spectrogram, but the number of frames is changed to ``ceil(num_frame / rate)``.

    Example
        >>> freq, hop_length = 1025, 512
        >>> # (channel, freq, time)
        >>> complex_specgrams = torch.randn(2, freq, 300, dtype=torch.cfloat)
        >>> rate = 1.3 # Speed up by 30%
        >>> phase_advance = torch.linspace(
        >>>    0, math.pi * hop_length, freq)[..., None]
        >>> x = phase_vocoder(complex_specgrams, rate, phase_advance)
        >>> x.shape # with 231 == ceil(300 / 1.3)
        torch.Size([2, 1025, 231])
    rC   r>   rA   Nr   ro   rn   .r	   rX   r   )rJ   rK   rr   rF   realrn   r   ro   ZanglerG   rH   r1   Zindex_selectlongrQ   r   r   roundcatcumsumZpolarrM   )r   r   r   rM   rd   Z
time_stepsalphasZphase_0Zcomplex_specgrams_0Zcomplex_specgrams_1Zangle_0Zangle_1Znorm_0Znorm_1ZphaseZ	phase_accmagZcomplex_specgrams_stretchrU   rU   rV   r     s0    " )
mask_parampaxis_lengthr<   c                 C   s"   |dkr| S t | t|| S d S )NrC   )r   int)r   r   r   rU   rU   rV   _get_mask_param)  s    r   rC   )	specgramsr   
mask_valueaxisr   r<   c                 C   sb  |   }|dk r td| d||d |d fkrXtd|d  d|d  d| dd	|  krld
ks~n td| dt||| j| }|dk r| S | j}| j}tj| jd|d  ||d| }tj| jd|d  ||d| ||  }	|		 d }
|		 |	  d }tj
d| |||d}| |d} | ||
k||k @ |} | |d} | S )a  Apply a mask along ``axis``.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Mask will be applied from indices ``[v_0, v_0 + v)``,
    where ``v`` is sampled from ``uniform(0, max_v)`` and
    ``v_0`` from ``uniform(0, specgrams.size(axis) - v)``,
    with ``max_v = mask_param`` when ``p = 1.0`` and
    ``max_v = min(mask_param, floor(specgrams.size(axis) * p))`` otherwise.

    Args:
        specgrams (Tensor): Real spectrograms `(..., freq, time)`, with at least 3 dimensions.
        mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param]
        mask_value (float): Value to assign to the masked columns
        axis (int): Axis to apply masking on, which should be the one of the last two dimensions.
        p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0)

    Returns:
        Tensor: Masked spectrograms with the same dimensions as input specgrams Tensor`
       z1Spectrogram must have at least three dimensions ( given).rX   r	   4Only Frequency and Time masking are supported (axis 
 and axis  supported; rp   rC   ,The value of p must be between 0.0 and 1.0 (Nr   .NNr   r>   )r   rZ   r   rM   ro   rn   rF   rs   rJ   r   r   	transposemasked_fill)r   r   r   r   r   r   ro   rn   value	min_value
mask_startmask_endmaskrU   rU   rV   r   0  s.    ",)ri   r   r   r   r   r<   c                 C   s  |   }|dk r td| d||d |d fkrXtd|d  d|d  d| dd|  krld	ks~n td
| dt||| j| }|dk r| S |  }| dgt|dd  } td| }td| || d |  }|	 
 }	|	 |	  
 }
tjd| j|| d  | j| jd}||	k||
k @ }||d krZ|d}|
|	 |krptd| ||} | |dd | jdd  } | S )a  Apply a mask along ``axis``.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Mask will be applied from indices ``[v_0, v_0 + v)``,
    where ``v`` is sampled from ``uniform(0, max_v)`` and
    ``v_0`` from ``uniform(0, specgram.size(axis) - v)``, with
    ``max_v = mask_param`` when ``p = 1.0`` and
    ``max_v = min(mask_param, floor(specgram.size(axis) * p))``
    otherwise.
    All examples will have the same mask interval.

    Args:
        specgram (Tensor): Real spectrograms `(..., freq, time)`, with at least 2 dimensions.
        mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param]
        mask_value (float): Value to assign to the masked columns
        axis (int): Axis to apply masking on, which should be the one of the last two dimensions.
        p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0)

    Returns:
        Tensor: Masked spectrograms with the same dimensions as input specgram Tensor
    rX   zDSpectrogram must have at least two dimensions (time and frequency) (r   r	   r   r   r   rp   rC   r   r>   rA   Nr   r   r   z=Number of columns to be masked should be less than mask_param)r   rZ   r   rM   rJ   rK   rr   rF   rs   r   squeezer   ro   rn   r   r   )ri   r   r   r   r   r   rM   r   r   r   r   r   rU   rU   rV   r   r  s6     $
    	replicate)ri   r5   moder<   c           
      C   s   | j }| j}|  }| dd|d } |dk r<td| |d d }||d  d| d  d }tjjj| ||f|d} tj	| |d d||d
| jd dd}tjjj| || jd d| }	|	|}	|	S )	a  Compute delta coefficients of a tensor, usually a spectrogram:

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    .. math::
       d_t = \frac{\sum_{n=1}^{\text{N}} n (c_{t+n} - c_{t-n})}{2 \sum_{n=1}^{\text{N}} n^2}

    where :math:`d_t` is the deltas at time :math:`t`,
    :math:`c_t` is the spectrogram coeffcients at time :math:`t`,
    :math:`N` is ``(win_length-1)//2``.

    Args:
        specgram (Tensor): Tensor of audio of dimension `(..., freq, time)`
        win_length (int, optional): The window length used for computing delta (Default: ``5``)
        mode (str, optional): Mode parameter passed to padding (Default: ``"replicate"``)

    Returns:
        Tensor: Tensor of deltas of dimension `(..., freq, time)`

    Example
        >>> specgram = torch.randn(1, 40, 1000)
        >>> delta = compute_deltas(specgram)
        >>> delta2 = compute_deltas(delta)
    r	   r>   r   zEWindow length should be greater than or equal to 3. Found win_length rX   )r   r   )groups)ro   rn   rJ   rK   rZ   rF   rG   rH   r1   r   repeatrM   conv1d)
ri   r5   r   ro   rn   rM   r   denomkerneloutputrU   rU   rV   r     s    *
)r0   r   
frame_timefreq_lowr<   c                 C   sB  d}t t|| }t t|| }|  d }t t|| }|||  | }	tjj| d|	f} g }
td|d D ]}| dd| f 	d||dd|ddf }| d|df 	d||dd|ddf }|| 
d|tjj|ddd d |tjj|ddd d }|
|d q|t|
d}|S )	a  
    Compute Normalized Cross-Correlation Function (NCCF).

    .. math::
        \phi_i(m) = \frac{\sum_{n=b_i}^{b_i + N-1} w(n) w(m+n)}{\sqrt{E(b_i) E(m+b_i)}},

    where
    :math:`\phi_i(m)` is the NCCF at frame :math:`i` with lag :math:`m`,
    :math:`w` is the waveform,
    :math:`N` is the length of a frame,
    :math:`b_i` is the beginning of frame :math:`i`,
    :math:`E(j)` is the energy :math:`\sum_{n=j}^{j+N-1} w^2(n)`.
    &.>r>   r   r	   .NrX   ordr   )r   r   ceilrJ   rF   rG   rH   r1   rv   unfoldrO   linalgvector_normrN   appendr   r   )r0   r   r   r   EPSILONZlags
frame_sizeZwaveform_lengthZnum_of_framesr   Z
output_lagZlags1s2Zoutput_framesnccfrU   rU   rV   _compute_nccf  s(    .,r   Gz?)abthreshr<   c                 C   sP   | d ||d  k}|| d  | |d   }|| d  | |d   }||fS )zb
    Take value from first if bigger than a multiplicative factor of the second, elementwise.
    r   r	   rU   )r   r   r   r   r   indicesrU   rU   rV   _combine_max"  s    r  )r   r   	freq_highr<   c                 C   sv   t t|| }t| d|df d}| jd d }t| d||f d}t||}|d }||7 }|d7 }|S )z
    For each frame, take the highest value of NCCF,
    apply centered median smoothing, and convert to frequency.

    Note: If the max among all the lags is very close
    to the first half of lags, then the latter is taken.
    .Nr>   rX   r	   )r   r   r   rF   r   rM   r  )r   r   r  Zlag_minbestZ	half_sizerg   r  rU   rU   rV   _find_max_per_frame,  s    	
r  )r  r5   r<   c                 C   sv   |d d }t jjj| |dfddd} t j|| d|f dg dd	| dd
|f< | d|d}t |d\}}|S )zH
    Apply median smoothing to the 1D tensor over the given window.
    r	   rX   r   r=   rp   )r   r   .r>   r   N)rF   rG   rH   r1   r   r   r   Zmedian)r  r5   Z
pad_lengthZrollr   ry   rU   rU   rV   _median_smoothingI  s    .r  {Gz?   U   H  )r0   r   r   r5   r   r  r<   c                 C   s   t |  }| dg|dd  } t| |||}t|||}t||}d}	||	|tj  }
|
|dd t |
j	dd  }
|
S )a  Detect pitch frequency.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    It is implemented using normalized cross-correlation function and median smoothing.

    Args:
        waveform (Tensor): Tensor of audio of dimension `(..., freq, time)`
        sample_rate (int): The sample rate of the waveform (Hz)
        frame_time (float, optional): Duration of a frame (Default: ``10 ** (-2)``).
        win_length (int, optional): The window length for median smoothing (in number of frames) (Default: ``30``).
        freq_low (int, optional): Lowest frequency that can be detected (Hz) (Default: ``85``).
        freq_high (int, optional): Highest frequency that can be detected (Hz) (Default: ``3400``).

    Returns:
        Tensor: Tensor of freq of dimension `(..., frame)`
    r>   Nr   )
rr   rJ   rK   r   r  r  r   rF   rf   rM   )r0   r   r   r5   r   r  rM   r   r  r   r   rU   rU   rV   r   [  s    
$X  d   F)ri   
cmn_windowmin_cmn_windowr8   	norm_varsr<   c                 C   s  | j }|dd \}}| d||} | j d }| j}	| j}
d }}tj|||	|
d}tj|||	|
d}tj||||	|
d}t|D ]$}d}d}|r||d  }|| }n|| }|d }|dk r||8 }d}|s||krt|d |}||kr||| 8 }|}|dk rd}|dkrv| dd||| ddf }|t|d7 }|r|t	|d ddddddf 7 }nt||kr| dd|ddf }||8 }|r||d 8 }||kr| dd|ddf }||7 }|r||d 7 }|| }|}|}| dd|ddf ||  |dd|ddf< |r|dkr^tj|||	|
d|dd|ddf< q|}|| }||d |d  8 }t
|d}|dd|ddf  |9  < q||dd ||f }t|dkr|d}|S )	a  
    Apply sliding-window cepstral mean (and optionally variance) normalization per utterance.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    Args:
        specgram (Tensor): Tensor of spectrogram of dimension `(..., time, freq)`
        cmn_window (int, optional): Window in frames for running average CMN computation (int, default = 600)
        min_cmn_window (int, optional):  Minimum CMN window used at start of decoding (adds latency only at start).
            Only applicable if center == false, ignored if center==true (int, default = 100)
        center (bool, optional): If true, use a window centered on the current frame
            (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false)
        norm_vars (bool, optional): If true, normalize variance to one. (bool, default = false)

    Returns:
        Tensor: Tensor matching input shape `(..., freq, time)`
    rA   Nr>   r   rm   rX   r	   g      )rM   r   rn   ro   rF   r   rv   r   rO   r   rN   lenr   )ri   r  r  r8   r  Zinput_shapeZ
num_framesZ	num_featsZnum_channelsrn   ro   Zlast_window_startZlast_window_endZcur_sumZ	cur_sumsqZcmn_specgramr   Zwindow_startZ
window_endZ
input_partZframe_to_removeZframe_to_addZwindow_framesZvariancerU   rU   rV   r     sx    




(

0
& 
)r0   r   r1   r2   r3   r4   r5   r<   c           
   
   C   s^   t | |||||ddd}tjd|d d|d  |jdd}d	}	|| j|	d
|j|	d
 S )a  Compute the spectral centroid for each channel along the time axis.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    The spectral centroid is defined as the weighted average of the
    frequency values, weighted by their magnitude.

    Args:
        waveform (Tensor): Tensor of audio of dimension `(..., time)`
        sample_rate (int): Sample rate of the audio waveform
        pad (int): Two sided padding of signal
        window (Tensor): Window tensor that is applied/multiplied to each frame/window
        n_fft (int): Size of FFT
        hop_length (int): Length of hop between STFT windows
        win_length (int): Window size

    Returns:
        Tensor: Dimension `(..., time)`
    rC   F)r1   r2   r3   r4   r5   r6   r7   r   rX   r	   )Zstepsro   )r>   r	   rA   r   )r   rF   r   ro   rK   rO   )
r0   r   r1   r2   r3   r4   r5   ri   r   Zfreq_dimrU   rU   rV   r     s    
&z:Please migrate to :py:class:`torchaudio.io.AudioEffector`.)remove)r0   r   r`   channels_firstcompressionencodingbits_per_sampler<   c           
      C   sd   t  >}tjj|j| |||||| tjjj|j||d\}}	W 5 Q R X |	|kr`t||	|}|S )a^  
    Apply codecs as a form of augmentation.

    .. devices:: CPU

    Args:
        waveform (Tensor): Audio data. Must be 2 dimensional. See also ```channels_first```.
        sample_rate (int): Sample rate of the audio waveform.
        format (str): File format.
        channels_first (bool, optional):
            When True, both the input and output Tensor have dimension `(channel, time)`.
            Otherwise, they have dimension `(time, channel)`.
        compression (float or None, optional): Used for formats other than WAV.
            For more details see :py:func:`torchaudio.backend.sox_io_backend.save`.
        encoding (str or None, optional): Changes the encoding for the supported formats.
            For more details see :py:func:`torchaudio.backend.sox_io_backend.save`.
        bits_per_sample (int or None, optional): Changes the bit depth for the supported formats.
            For more details see :py:func:`torchaudio.backend.sox_io_backend.save`.

    Returns:
        Tensor: Resulting Tensor.
        If ``channels_first=True``, it has `(channel, time)` else `(time, channel)`.
    )r  r`   )	tempfileNamedTemporaryFile
torchaudiobackendZsox_io_backendsavenameloadr   )
r0   r   r`   r  r  r  r  fZ	augmentedsrrU   rU   rV   r     s    "
       $cpu   sinc_interp_hann)		orig_freqnew_freqgcdlowpass_filter_widthrolloffresampling_methodbetaro   rn   c	                 C   s  t | | krt ||ks td|dkrPddd}	td| d|	|  d n|dkrftd	|t | | } t || }|d
krtdt| |}
|
|9 }
t||  |
 }|d k	r|nt	j
}t	j| ||  ||dd |  }t	jd
| d||dd d d d f | | }||
9 }|| |}|dkrNt	|tj | d d }nF|d kr\d}t	t|}t	|t	d|| d   t	| }|tj9 }|
|  }t	|d
kt	d|| | }||| 9 }|d kr|jt	jd}||fS )Na  Frequencies must be of integer type to ensure quality resampling computation. To work around this, manually convert both frequencies to integer values that maintain their resampling rate ratio before passing them into the function. Example: To downsample a 44100 hz waveform by a factor of 8, use `orig_freq=8` and `new_freq=1` instead of `orig_freq=44100` and `new_freq=5512.5`. For more information, please refer to https://github.com/pytorch/audio/issues/1487.)Zsinc_interpolationZkaiser_windowr!  sinc_interp_kaiser"z>" resampling method name is being deprecated and replaced by "z>" in the next release. The default behavior remains unchanged.)r!  r)  zInvalid resampling method: {}r   z)Low pass filter width should be positive.rm   )NNr>   rX   gQaTi-@r	   rC   r   )r   	ExceptionrD   rE   rZ   r`   r   r   r   rF   Zfloat64r   Zclamp_r   r   ru   rf   Zi0rP   wherer   sinZfloat32)r"  r#  r$  r%  r&  r'  r(  ro   rn   Z
method_mapZ	base_freqwidthZ	idx_dtypeidxr   r2   Zbeta_tensorscaleZkernelsrU   rU   rV   _get_sinc_resample_kernelA  sL    	
 ,

*
&
r1  )r0   r"  r#  r$  r   r.  c                 C   s   |   std| j dt|| }t|| }|  }| d|d } | j\}}tjj	
| ||| f} tjj	j| d d d f ||d}	|	dd|d}	tt|| |  }
|	dd |
f }	|	|d d |	jdd   }	|	S )Nz?Expected floating point type for waveform tensor, but received .r>   )strider	   rX   .)r   rb   rn   r   rJ   r   rM   rF   rG   rH   r1   r   r   rK   r   Z	as_tensorr   )r0   r"  r#  r$  r   r.  rM   Znum_wavsrW   	resampledtarget_lengthrU   rU   rV   _apply_sinc_resample_kernel  s    
  r6  )r0   r"  r#  r%  r&  r'  r(  r<   c              
   C   sn   |dks|dkrt d||kr$| S tt|t|}t|||||||| j| j	\}}	t| |||||	}
|
S )a  Resamples the waveform at the new frequency using bandlimited interpolation. :cite:`RESAMPLE`.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Note:
        ``transforms.Resample`` precomputes and reuses the resampling kernel, so using it will result in
        more efficient computation if resampling multiple waveforms with the same resampling parameters.

    Args:
        waveform (Tensor): The input signal of dimension `(..., time)`
        orig_freq (int): The original frequency of the signal
        new_freq (int): The desired frequency
        lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper
            but less efficient. (Default: ``6``)
        rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist.
            Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``)
        resampling_method (str, optional): The resampling method to use.
            Options: [``"sinc_interp_hann"``, ``"sinc_interp_kaiser"``] (Default: ``"sinc_interp_hann"``)
        beta (float or None, optional): The shape parameter used for kaiser window.

    Returns:
        Tensor: The waveform at the new frequency of dimension `(..., time).`
    rp   z:Original frequency and desired frequecy should be positive)rZ   r   r$  r   r1  ro   rn   r6  )r0   r"  r#  r%  r&  r'  r(  r$  r   r.  r4  rU   rU   rV   r     s$    #)seq1seq2r<   c           
      C   s   t |}tt|d }dd t|d D }tdt | d D ]}||d< td|d D ]j}| |d  ||d  kr||d  ||< qZ||d  d }||d  d }|| d }	t|||	||< qZ|| }}q@t|d S )a4  
    Calculate the word level edit (Levenshtein) distance between two sequences.

    .. devices:: CPU

    The function computes an edit distance allowing deletion, insertion and
    substitution. The result is an integer.

    For most applications, the two input sequences should be the same type. If
    two strings are given, the output is the edit distance between the two
    strings (character edit distance). If two lists of strings are given, the
    output is the edit distance between sentences (word edit distance). Users
    may want to normalize the output by the length of the reference sequence.

    Args:
        seq1 (Sequence): the first sequence to compare.
        seq2 (Sequence): the second sequence to compare.
    Returns:
        int: The distance between the first and second sequences.
    r	   c                 S   s   g | ]}d qS )r   rU   ).0ry   rU   rU   rV   
<listcomp>  s     z!edit_distance.<locals>.<listcomp>r   r>   )r  rr   rv   r   r   )
r7  r8  Z	len_sent2ZdoldZdnewijZsubstitutionZ	insertionZdeletionrU   rU   rV   r     s    )r0   r   c              	   C   s  |  ddkrtdd}d}d}d}tt|| }tt|d|  }t| |d	d
dtd } t| |dd} t	| 
d||}tj|dd}tjdddddg| j| jd}	|	d| d }	tj|	d| dd}
ddt|
  }||k}|d}tj|| ddtj|dd }tj|	| dd}
|dt|
  d }t|d||dk}|d}tj|| ddtj|dd }tj|	| dd}
|dt|
  }|S )a  Measure audio loudness according to the ITU-R BS.1770-4 recommendation.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    Args:
        waveform(torch.Tensor): audio waveform of dimension `(..., channels, time)`
        sample_rate (int): sampling rate of the waveform

    Returns:
        Tensor: loudness estimates (LKFS)

    Reference:
        - https://www.itu.int/rec/R-REC-BS.1770-4-201510-I/en
    rA   r   z$Only up to 5 channels are supported.g?g      ?g     Qg&1r	   g      @g     p@rX   g      C@r   r>   r   rC   g(\?rm   N
   )rJ   rZ   r   r   r   r   rP   r
   rF   squarer   meanru   rn   ro   rO   r   r   Zcount_nonzerological_andr   )r0   r   Zgate_durationoverlapZ	gamma_absZkweight_biasZgate_samplesstepZenergygZenergy_weightedr    Zgated_blocksZenergy_filteredZ	gamma_relZLKFSrU   rU   rV   r    &  s6    
 
       )	r0   r   n_stepsbins_per_octaver3   r5   r4   r2   r<   c                 C   sH   t | ||||||}dt| |  }	t|t||	 |}
t|
|  S )a#  
    Shift the pitch of a waveform by ``n_steps`` steps.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    Args:
        waveform (Tensor): The input waveform of shape `(..., time)`.
        sample_rate (int): Sample rate of `waveform`.
        n_steps (int): The (fractional) steps to shift `waveform`.
        bins_per_octave (int, optional): The number of steps per octave (Default: ``12``).
        n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins (Default: ``512``).
        win_length (int or None, optional): Window size. If None, then ``n_fft`` is used. (Default: ``None``).
        hop_length (int or None, optional): Length of hop between STFT windows. If None, then
            ``win_length // 4`` is used (Default: ``None``).
        window (Tensor or None, optional): Window tensor that is applied/multiplied to each frame/window.
            If None, then ``torch.hann_window(win_length)`` is used (Default: ``None``).


    Returns:
        Tensor: The pitch-shifted audio waveform of shape `(..., time)`.
    rB   )_stretch_waveformrf   r   r   _fix_waveform_shaperJ   )r0   r   rF  rG  r3   r5   r4   r2   waveform_stretchr   waveform_shiftrU   rU   rV   r!   c  s    !	)r0   rF  rG  r3   r5   r4   r2   r<   c                 C   s   |dkr|d }|dkr|}|dkr4t j|| jd}|  }| d|d } |d }dt| |  }	t j| ||||dddddd	
}
t jd
tj	| |
j
d |
jdd }t|
|	|}tt||	 }t j||||||d}|S )z
    Pitch shift helper function to preprocess and stretch waveform before resampling step.

    Args:
        See pitch_shift arg descriptions.

    Returns:
        Tensor: The preprocessed waveform stretched prior to resampling.
    N   )Zwindow_lengthro   r>   rB   Tr/   Fr?   r   rA   ro   .Nrq   )rF   Zhann_windowro   rJ   rK   rf   rL   r   r   r   rM   r   r   r   r[   )r0   rF  rG  r3   r5   r4   r2   rM   ori_lenr   rT   r   Zspec_stretchZlen_stretchrJ  rU   rU   rV   rH    sD    $     rH  )rK  rM   r<   c                 C   sj   |d }|   d }||kr.| dd|f } ntjj| d|| g} | |dd | jdd  } | S )a?  
    PitchShift helper function to process after resampling step to fix the shape back.

    Args:
        waveform_shift(Tensor): The waveform after stretch and resample
        shape (List[int]): The shape of initial waveform

    Returns:
        Tensor: The pitch-shifted audio waveform of shape `(..., time)`.
    r>   .Nr   )rJ   rF   rG   rH   r1   r   rM   )rK  rM   rO  Z	shift_lenrU   rU   rV   rI    s     rI  r>   r?  )logitstargetslogit_lengthstarget_lengthsblankr   	reductionfused_log_softmaxc           
   	   C   sj   |dkrt d|dk r&| jd | }tjjj| ||||||d\}}	|dkrV| S |dkrf| S |S )a  Compute the RNN Transducer loss from *Sequence Transduction with Recurrent Neural Networks*
    :cite:`graves2012sequence`.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    The RNN Transducer loss extends the CTC loss by defining a distribution over output
    sequences of all lengths, and by jointly modelling both input-output and output-output
    dependencies.

    Args:
        logits (Tensor): Tensor of dimension `(batch, max seq length, max target length + 1, class)`
            containing output from joiner
        targets (Tensor): Tensor of dimension `(batch, max target length)` containing targets with zero padded
        logit_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of each sequence from encoder
        target_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of targets for each sequence
        blank (int, optional): blank label (Default: ``-1``)
        clamp (float, optional): clamp for gradients (Default: ``-1``)
        reduction (string, optional): Specifies the reduction to apply to the output:
            ``"none"`` | ``"mean"`` | ``"sum"``. (Default: ``"mean"``)
        fused_log_softmax (bool): set to False if calling log_softmax outside of loss (Default: ``True``)
    Returns:
        Tensor: Loss with the reduction option applied. If ``reduction`` is  ``"none"``, then size `(batch)`,
        otherwise scalar.
    )noner?  rO   z3reduction should be one of "none", "mean", or "sum"r   r>   )rP  rQ  rR  rS  rT  r   rV  r?  rO   )rZ   rM   rF   Zopsr  r"   r?  rO   )
rP  rQ  rR  rS  rT  r   rU  rV  Zcostsry   rU   rU   rV   r"     s$    $

绽|=)ri   r   	normalizeepsr<   c                 C   s   |  dd} td| |  g}|dk	r|jdd | jdd ksX|jd | jd krrtd|j d| j d|r||jdd	d
|  }||d  }|jdd}|S )a/  Compute cross-channel power spectral density (PSD) matrix.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        specgram (torch.Tensor): Multi-channel complex-valued spectrum.
            Tensor with dimensions `(..., channel, freq, time)`.
        mask (torch.Tensor or None, optional): Time-Frequency mask for normalization.
            Tensor with dimensions `(..., freq, time)`. (Default: ``None``)
        normalize (bool, optional): If ``True``, normalize the mask along the time dimension. (Default: ``True``)
        eps (float, optional): Value to add to the denominator in mask normalization. (Default: ``1e-15``)

    Returns:
        torch.Tensor: The complex-valued PSD matrix of the input spectrum.
        Tensor with dimensions `(..., freq, channel, channel)`
    r   rA   z...ct,...et->...tceNr>   zYThe dimensions of mask except the channel dimension should be the same as specgram.Found z for mask and  for specgram.T)r   Zkeepdimr   r   )r   rF   einsumconjrM   rZ   rO   )ri   r   rY  rZ  r#   rU   rU   rV   r#     s    0rA   )r@   dim1dim2r<   c                 C   sL   | j dk rtd| j| | j| kr.tdtj| d||d} | jddS )a  Compute the trace of a Tensor along ``dim1`` and ``dim2`` dimensions.

    Args:
        input (torch.Tensor): Tensor with dimensions `(..., channel, channel)`.
        dim1 (int, optional): The first dimension of the diagonal matrix.
            (Default: ``-1``)
        dim2 (int, optional): The second dimension of the diagonal matrix.
            (Default: ``-2``)

    Returns:
        Tensor: The trace of the input Tensor.
    rX   z/The dimension of the tensor must be at least 2.z3The size of ``dim1`` and ``dim2`` must be the same.r   )r^  r_  r>   r   )ndimrZ   rM   rF   ZdiagonalrO   )r@   r^  r_  rU   rU   rV   _compute_mat_traceJ  s    
ra  Hz>:0yE>)matregrZ  r<   c                 C   sZ   |  d}tj|| j| jd}t| jd | }|| }| ||dddddf   } | S )a  Perform Tikhonov regularization (only modifying real part).

    Args:
        mat (torch.Tensor): Input matrix with dimensions `(..., channel, channel)`.
        reg (float, optional): Regularization factor. (Default: 1e-8)
        eps (float, optional): Value to avoid the correlation matrix is all-zero. (Default: ``1e-8``)

    Returns:
        Tensor: Regularized matrix with dimensions `(..., channel, channel)`.
    r>   rm   r   .N)rJ   rF   eyern   ro   ra  r   )rd  re  rZ  Crf  epsilonrU   rU   rV   _tik_reg_  s    
ri  )psd_spsd_nr<   c                 C   s   | j dk s|j dk r.td| j d|j d|  r>| sXtd| j d|j d| j|jkr~td| j d|j d| jd	 | jd
 krtd| j ddS )a  Assertion checks of the PSD matrices of target speech and noise.

    Args:
        psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
            Tensor with dimensions `(..., freq, channel, channel)`.
        psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
            Tensor with dimensions `(..., freq, channel, channel)`.
    r   zUExpected at least 3D Tensor (..., freq, channel, channel) for psd_s and psd_n. Found z for psd_s and  for psd_n.zQThe type of psd_s and psd_n must be ``torch.cfloat`` or ``torch.cdouble``. Found z<The dimensions of psd_s and psd_n should be the same. Found  and r2  r>   rA   ;The last two dimensions of psd_s should be the same. Found N)r`  rZ   rM   rY   rb   rn   )rj  rk  rU   rU   rV   _assert_psd_matricest  s    	ro  )rj  rk  reference_channeldiagonal_loadingdiag_epsrZ  r<   c           	   
   C   s   t | | |rt||d}tj|| }|t|d |  }tj|tr^|ddd|f }nPtj|t	r|
|j}td||dddddf g}ntdt| d|S )a  Compute the Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) beamforming weights
    by the method proposed by *Souden et, al.* :cite:`souden2009optimal`.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Given the power spectral density (PSD) matrix of target speech :math:`\bf{\Phi}_{\textbf{SS}}`,
    the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and a one-hot vector that represents the
    reference channel :math:`\bf{u}`, the method computes the MVDR beamforming weight martrix
    :math:`\textbf{w}_{\text{MVDR}}`. The formula is defined as:

    .. math::
        \textbf{w}_{\text{MVDR}}(f) =
        \frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bf{\Phi}_{\textbf{SS}}}}(f)}
        {\text{Trace}({{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f) \bf{\Phi}_{\textbf{SS}}}(f))}}\bm{u}

    Args:
        psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
            Tensor with dimensions `(..., freq, channel, channel)`.
        psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
            Tensor with dimensions `(..., freq, channel, channel)`.
        reference_channel (int or torch.Tensor): Specifies the reference channel.
            If the dtype is ``int``, it represents the reference channel index.
            If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
            is one-hot.
        diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
            (Default: ``True``)
        diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
            It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
        eps (float, optional): Value to add to the denominator in the beamforming weight formula.
            (Default: ``1e-8``)

    Returns:
        torch.Tensor: The complex-valued MVDR beamforming weight matrix with dimensions `(..., freq, channel)`.
    re  r   .N...c,...c->...9Expected "int" or "Tensor" for reference_channel. Found: r2  )ro  ri  rF   r   solvera  r]   r^   r   r   r   rn   r\  rb   type)	rj  rk  rp  rq  rr  rZ  	numeratorwsbeamform_weightsrU   rU   rV   r$     s    ,
")rtfrk  rp  rq  rr  rZ  r<   c           
   	   C   s  | j dk rtd| j d|j dk r8td|j d|  rH| sbtd| j d|j d| j|jd	d
 krtd| j d|j d|jd
 |jd krtd|j d|rt||d}tj	|| 
d
d
}td|  |g}||j
d
|  }|d	k	rtj|tr4| d|f  }	nTtj|trt||j}td|  |dd	d	d	f g}	ntdt| d||	d  }|S )aM  Compute the Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) beamforming weights
    based on the relative transfer function (RTF) and power spectral density (PSD) matrix of noise.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Given the relative transfer function (RTF) matrix or the steering vector of target speech :math:`\bm{v}`,
    the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and a one-hot vector that represents the
    reference channel :math:`\bf{u}`, the method computes the MVDR beamforming weight martrix
    :math:`\textbf{w}_{\text{MVDR}}`. The formula is defined as:

    .. math::
        \textbf{w}_{\text{MVDR}}(f) =
        \frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}}
        {{\bm{v}^{\mathsf{H}}}(f){\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}

    where :math:`(.)^{\mathsf{H}}` denotes the Hermitian Conjugate operation.

    Args:
        rtf (torch.Tensor): The complex-valued RTF vector of target speech.
            Tensor with dimensions `(..., freq, channel)`.
        psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
            Tensor with dimensions `(..., freq, channel, channel)`.
        reference_channel (int or torch.Tensor): Specifies the reference channel.
            If the dtype is ``int``, it represents the reference channel index.
            If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
            is one-hot.
        diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
            (Default: ``True``)
        diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
            It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
        eps (float, optional): Value to add to the denominator in the beamforming weight formula.
            (Default: ``1e-8``)

    Returns:
        torch.Tensor: The complex-valued MVDR beamforming weight matrix with dimensions `(..., freq, channel)`.
    rX   z@Expected at least 2D Tensor (..., freq, channel) for rtf. Found r2  r   zKExpected at least 3D Tensor (..., freq, channel, channel) for psd_n. Found zOThe type of rtf and psd_n must be ``torch.cfloat`` or ``torch.cdouble``. Found z for rtf and rl  Nr>   zfThe dimensions of rtf and the dimensions withou the last dimension of psd_n should be the same. Found rA   z;The last two dimensions of psd_n should be the same. Found rs  z...d,...d->....rt  ru  rN  )r`  rZ   rM   rY   rb   rn   ri  rF   r   rv  r   r   r\  r]  r   r]   r^   r   r   r   rw  )
r{  rk  rp  rq  rr  rZ  rx  denominatorrz  r0  rU   rU   rV   r%     s8    .


$)rj  r<   c                 C   s\   |   std| j d| jd | jd kr@td| j dtj| \}}|d }|S )a  Estimate the relative transfer function (RTF) or the steering vector by eigenvalue decomposition.

    .. devices:: CPU CUDA

    .. properties:: TorchScript

    Args:
        psd_s (Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
            Tensor of dimension `(..., freq, channel, channel)`

    Returns:
        Tensor: The estimated complex-valued RTF of target speech.
        Tensor of dimension `(..., freq, channel)`
    zGThe type of psd_s must be ``torch.cfloat`` or ``torch.cdouble``. Found r2  r>   rA   rn  ).r>   )rY   rb   rn   rM   rZ   rF   r   Zeigh)rj  ry   vr{  rU   rU   rV   r&   #  s    r   )rj  rk  rp  rj   rq  rr  r<   c           	   
   C   s   t | | |dkrtd|r*t||d}tj|| }tj|trT|d|f }nPtj|t	r|
|j}td||dddddf g}ntdt| d|d	}|d
krt|d
 D ]}t||}qt| |}nt||}|d	S )a  Estimate the relative transfer function (RTF) or the steering vector by the power method.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
            Tensor with dimensions `(..., freq, channel, channel)`.
        psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
            Tensor with dimensions `(..., freq, channel, channel)`.
        reference_channel (int or torch.Tensor): Specifies the reference channel.
            If the dtype is ``int``, it represents the reference channel index.
            If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
            is one-hot.
        diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
            (Default: ``True``)
        diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
            It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)

    Returns:
        torch.Tensor: The estimated complex-valued RTF of target speech.
        Tensor of dimension `(..., freq, channel)`.
    r   z/The number of iteration must be greater than 0.rs  .rt  Nru  r2  r>   rX   )ro  rZ   ri  rF   r   rv  r]   r^   r   r   r   rn   r\  rb   rw  r   rv   matmulr   )	rj  rk  rp  rj   rq  rr  phir{  ry   rU   rU   rV   r'   ;  s&     
"
)rz  ri   r<   c                 C   sx   | j dd |j dd kr6td| j  d|j  d|  rF| s`td| j d|j dtd|  |g}|S )	a  Apply the beamforming weight to the multi-channel noisy spectrum to obtain the single-channel enhanced spectrum.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    .. math::
        \hat{\textbf{S}}(f) = \textbf{w}_{\text{bf}}(f)^{\mathsf{H}} \textbf{Y}(f)

    where :math:`\textbf{w}_{\text{bf}}(f)` is the beamforming weight for the :math:`f`-th frequency bin,
    :math:`\textbf{Y}` is the multi-channel spectrum for the :math:`f`-th frequency bin.

    Args:
        beamform_weights (Tensor): The complex-valued beamforming weight matrix.
            Tensor of dimension `(..., freq, channel)`
        specgram (Tensor): The multi-channel complex-valued noisy spectrum.
            Tensor of dimension `(..., channel, freq, time)`

    Returns:
        Tensor: The single-channel complex-valued enhanced spectrum.
            Tensor of dimension `(..., freq, time)`
    NrA   r   zThe dimensions except the last two dimensions of beamform_weights should be the same as the dimensions except the last three dimensions of specgram. Found z for beamform_weights and r[  z_The type of beamform_weights and specgram must be ``torch.cfloat`` or ``torch.cdouble``. Found z...fc,...cft->...ft)rM   rZ   rY   rb   rn   rF   r\  r]  )rz  ri   Zspecgram_enhancedrU   rU   rV   r(   z  s    )rz   yr<   c                 C   s   | j |j kr&td| j  d|j  dt| j d D ]L}| |}||}||ks4|dks4|dkrfq4td| j d|j dq4d S )Nz-The operands must be the same dimension (got rm  ).r	   z9Leading dimensions of x and y are not broadcastable (got )r`  rZ   rv   rJ   rM   )rz   r  r;  xiyirU   rU   rV   _check_shape_compatible  s    

r  )r   r<   c                 C   s,   dddg}| |kr(t d|  d| dd S )Nrt   validsameUnrecognized mode value ''. Please specify one of r2  )rZ   )r   valid_convolve_modesrU   rU   rV   _check_convolve_mode  s    
r  )conv_resultx_lengthy_lengthr   r<   c                 C   s   dddg}|dkr| S |dkr\t ||t|| d }| d| d }| d||| f S |dkr| d| d }| d||| f S td| d	| d
d S )Nrt   r  r  r	   r>   rX   .r  r  r2  )r   r   rJ   rZ   )r  r  r  r   r  r5  Z	start_idxrU   rU   rV   _apply_convolve_mode  s    
r  rt   )rz   r  r   r<   c                 C   st   t | | t| | d|d d }tjj| |dtjj||d }tjj||d}t|| d|d|S )a  
    Convolves inputs along their last dimension using FFT. For inputs with large last dimensions, this function
    is generally much faster than :meth:`convolve`.
    Note that, in contrast to :meth:`torch.nn.functional.conv1d`, which actually applies the valid cross-correlation
    operator, this function applies the true `convolution`_ operator.
    Also note that this function can only output float tensors (int tensor inputs will be cast to float).

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        x (torch.Tensor): First convolution operand, with shape `(..., N)`.
        y (torch.Tensor): Second convolution operand, with shape `(..., M)`
            (leading dimensions must be broadcast-able with those of ``x``).
        mode (str, optional): Must be one of ("full", "valid", "same").

            * "full": Returns the full convolution result, with shape `(..., N + M - 1)`. (Default)
            * "valid": Returns the segment of the full convolution result corresponding to where
              the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
            * "same": Returns the center segment of the full convolution result, with shape `(..., N)`.

    Returns:
        torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
        the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.

    .. _convolution:
        https://en.wikipedia.org/wiki/Convolution
    r>   r	   )r   )r  r  rJ   rF   ZfftZrfftZirfftr  )rz   r  r   r   ZfresultresultrU   rU   rV   r)     s    
 c                 C   s\  t | | t| | d|d }}| d|dk rF||  } }| jdd |jdd krdd t| jdd |jdd D }| || jd g } |||jd g }t| jdd  }| 	t
|| df}|	t
||df}tjjj||ddd|d|dd d}	| jdd d }
|		|
}t||||S )	a  
    Convolves inputs along their last dimension using the direct method.
    Note that, in contrast to :meth:`torch.nn.functional.conv1d`, which actually applies the valid cross-correlation
    operator, this function applies the true `convolution`_ operator.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        x (torch.Tensor): First convolution operand, with shape `(..., N)`.
        y (torch.Tensor): Second convolution operand, with shape `(..., M)`
            (leading dimensions must be broadcast-able with those of ``x``).
        mode (str, optional): Must be one of ("full", "valid", "same").

            * "full": Returns the full convolution result, with shape `(..., N + M - 1)`. (Default)
            * "valid": Returns the segment of the full convolution result corresponding to where
              the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
            * "same": Returns the center segment of the full convolution result, with shape `(..., N)`.

    Returns:
        torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
        the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.

    .. _convolution:
        https://en.wikipedia.org/wiki/Convolution
    r>   Nc                 S   s   g | ]\}}t ||qS rU   )r   )r9  r;  r<  rU   rU   rV   r:  	  s     zconvolve.<locals>.<listcomp>r	   r   )r@   weightr3  r   padding)r>   )r  r  rJ   rM   zipZbroadcast_torF   ru   prodrK   r   rG   rH   r   flipr   r  )rz   r  r   Zx_sizeZy_sizeZ	new_shapeZnum_signalsZ
reshaped_xZ
reshaped_yr   Zoutput_shaper  rU   rU   rV   r*     s,    

(
)r0   noisesnrlengthsr<   c                 C   s&  | j d |j d   kr"|j kr:n n|dksB|j |j ksBtd| d}||dkrvtd| d|d d|dk	rtjd||jd	| j|dk }| | }|| }n| }|}tj	j
|d
ddd
 }tj	j
|d
ddd
 }	dt|t|	  }
d|
| d  }|d| }| | S )a  Scales and adds noise to waveform per signal-to-noise ratio.

    Specifically, for each pair of waveform vector :math:`x \in \mathbb{R}^L` and noise vector
    :math:`n \in \mathbb{R}^L`, the function computes output :math:`y` as

    .. math::
        y = x + a n \, \text{,}

    where

    .. math::
        a = \sqrt{ \frac{ ||x||_{2}^{2} }{ ||n||_{2}^{2} } \cdot 10^{-\frac{\text{SNR}}{10}} } \, \text{,}

    with :math:`\text{SNR}` being the desired signal-to-noise ratio between :math:`x` and :math:`n`, in dB.

    Note that this function broadcasts singleton leading dimensions in its inputs in a manner that is
    consistent with the above formulae and PyTorch's broadcasting semantics.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        waveform (torch.Tensor): Input waveform, with shape `(..., L)`.
        noise (torch.Tensor): Noise, with shape `(..., L)` (same shape as ``waveform``).
        snr (torch.Tensor): Signal-to-noise ratios in dB, with shape `(...,)`.
        lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform`` and ``noise``, with shape
            `(...,)` (leading dimensions must match those of ``waveform``). If ``None``, all elements in ``waveform``
            and ``noise`` are treated as valid. (Default: ``None``)

    Returns:
        torch.Tensor: Result of scaling and adding ``noise`` to ``waveform``, with shape `(..., L)`
        (same shape as ``waveform``).
    r	   Nz%Input leading dimensions don't match.r>   z9Length dimensions of waveform and noise don't match (got rm  r  r   rM  rX   r   r=  g      4@)r`  rZ   rJ   rF   r   ro   expandrM   r   r   r   r   )r0   r  r  r  Lr   Zmasked_waveformZmasked_noiseZenergy_signalZenergy_noiseZoriginal_snr_dbr0  Zscaled_noiserU   rU   rV   r+   #	  s&    &:

)r0   r"  factorr  r<   c                 C   sh   t || }t |}t||}|| }|| }|dkr>d}nt|| | |j}t| |||fS )a  Adjusts waveform speed.

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        waveform (torch.Tensor): Input signals, with shape `(..., time)`.
        orig_freq (int): Original frequency of the signals in ``waveform``.
        factor (float): Factor by which to adjust speed of input. Values greater than 1.0
            compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time.
        lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`.
            If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``)

    Returns:
        (torch.Tensor, torch.Tensor or None):
            torch.Tensor
                Speed-adjusted waveform, with shape `(..., new_time).`
            torch.Tensor or None
                If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform,
                with shape `(...)`; otherwise, ``None``.
    N)r   r   r$  rF   r   r   rn   r   )r0   r"  r  r  Zsource_sample_rateZtarget_sample_rater$  Zout_lengthsrU   rU   rV   r,   g	  s    
ףp=
?)coeffr<   c                 C   s4   |   } | dddf  || dddf  8  < | S )a*  Pre-emphasizes a waveform along its last dimension, i.e.
    for each signal :math:`x` in ``waveform``, computes
    output :math:`y` as

    .. math::
        y[i] = x[i] - \text{coeff} \cdot x[i - 1]

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        waveform (torch.Tensor): Waveform, with shape `(..., N)`.
        coeff (float, optional): Pre-emphasis coefficient. Typically between 0.0 and 1.0.
            (Default: 0.97)

    Returns:
        torch.Tensor: Pre-emphasized waveform, with shape `(..., N)`.
    .r	   Nr>   )clone)r0   r  rU   rU   rV   r-   	  s    (c                 C   sD   t jd| g| j| jd}t jddg| j| jd}tjj| ||dS )aN  De-emphasizes a waveform along its last dimension.
    Inverse of :meth:`preemphasis`. Concretely, for each signal
    :math:`x` in ``waveform``, computes output :math:`y` as

    .. math::
        y[i] = x[i] + \text{coeff} \cdot y[i - 1]

    .. devices:: CPU CUDA

    .. properties:: Autograd TorchScript

    Args:
        waveform (torch.Tensor): Waveform, with shape `(..., N)`.
        coeff (float, optional): De-emphasis coefficient. Typically between 0.0 and 1.0.
            (Default: 0.97)

    Returns:
        torch.Tensor: De-emphasized waveform, with shape `(..., N)`.
    rC   rm   rp   )a_coeffsb_coeffs)rF   ru   rn   ro   r  rH   Zlfilter)r0   r  r  r  rU   rU   rV   r.   	  s    c                 C   s(  t |  dkr(tdt |   dt | dkrPtdt |  d|d|d  krv| dkrn ntd|  | krtd|   d	|  d| | krtd
|  d	|  d| |   }| |  }tj|| 	 j
 }|| d|  S )u  Computes the Fréchet distance between two multivariate normal distributions :cite:`dowson1982frechet`.

    Concretely, for multivariate Gaussians :math:`X(\mu_X, \Sigma_X)`
    and :math:`Y(\mu_Y, \Sigma_Y)`, the function computes and returns :math:`F` as

    .. math::
        F(X, Y) = || \mu_X - \mu_Y ||_2^2
        + \text{Tr}\left( \Sigma_X + \Sigma_Y - 2 \sqrt{\Sigma_X \Sigma_Y} \right)

    Args:
        mu_x (torch.Tensor): mean :math:`\mu_X` of multivariate Gaussian :math:`X`, with shape `(N,)`.
        sigma_x (torch.Tensor): covariance matrix :math:`\Sigma_X` of :math:`X`, with shape `(N, N)`.
        mu_y (torch.Tensor): mean :math:`\mu_Y` of multivariate Gaussian :math:`Y`, with shape `(N,)`.
        sigma_y (torch.Tensor): covariance matrix :math:`\Sigma_Y` of :math:`Y`, with shape `(N, N)`.

    Returns:
        torch.Tensor: the Fréchet distance between :math:`X` and :math:`Y`.
    r	   z2Input mu_x must be one-dimensional; got dimension r2  rX   z5Input sigma_x must be two-dimensional; got dimension r   z4Each of sigma_x's dimensions must match mu_x's size.z3Inputs mu_x and mu_y must have the same shape; got rm  z9Inputs sigma_x and sigma_y must have the same shape; got )r  rJ   rZ   r>  rO   tracerF   r   ZeigvalsrP   r   )Zmu_xZsigma_xZmu_yZsigma_yr   r   crU   rU   rV   frechet_distance	  s     *r  )Tr/   TN)Tr/   T)N)r   )r   )Nr   )rC   )rC   )r   r   )r   )r  r  r	  r
  )r  r  FF)TNNN)r   r   r!  N)rD  rE  NNN)rD  rE  NNN)r>   r>   r?  T)NTrX  )r>   rA   )rb  rc  )Trb  rc  )NTrb  rc  )r   Trb  )rt   )rt   )N)N)r  )r  )Vr   r  rD   collections.abcr   typingr   r   r   r   rF   r  r   Z!torchaudio._internal.module_utilsr   Z	filteringr
   r   __all__r   rf   ra   r_   r   r   rI   rn   rh   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r   r   
_extensionZfail_if_no_soxr   ro   Z_CPUr1  r6  r   r]   Zunusedr   r    r!   rH  rI  r"   r#   ra  ri  ro  r$   r%   r&   r'   r(   r  r  r  r)   r*   r+   r,   r-   r.   r  rU   rU   rU   rV   <module>   s  2    
g   
Pf     3""   I."!J G K6/.
    /    ^-
    *
d"    :)A     3     5    >   -   
B    U   
?)'9    E    )