o
    Oôj
/  ã                   @   s°   d dl Z d dl mZ d dlZd dlm  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G dd„ dejƒZdS )é    N)ÚList)ÚAudioSignal©Ú
STFTParams)Únnc                       sB   e Zd ZdZddedef‡ fdd„Zded	ef‡ fd
d„Z‡  Z	S )ÚL1Lossaî  L1 Loss between AudioSignals. Defaults
    to comparing ``audio_data``, but any
    attribute of an AudioSignal can be used.

    Parameters
    ----------
    attribute : str, optional
        Attribute of signal to compare, defaults to ``audio_data``.
    weight : float, optional
        Weight of this loss, defaults to 1.0.

    Implementation copied from: https://github.com/descriptinc/lyrebird-audiotools/blob/961786aa1a9d628cca0c0486e5885a457fe70c1a/audiotools/metrics/distance.py
    Ú
audio_dataç      ð?Ú	attributeÚweightc                    s"   || _ || _tƒ jdi |¤Ž d S )N© )r
   r   ÚsuperÚ__init__)Úselfr
   r   Úkwargs©Ú	__class__r   ú\/var/www/html/academy/tools/voices/clone/sv-venv/lib/python3.10/site-packages/dac/nn/loss.pyr      s   zL1Loss.__init__ÚxÚyc                    s0   t |tƒrt|| jƒ}t|| jƒ}tƒ  ||¡S )a  
        Parameters
        ----------
        x : AudioSignal
            Estimate AudioSignal
        y : AudioSignal
            Reference AudioSignal

        Returns
        -------
        torch.Tensor
            L1 loss between AudioSignal attributes.
        )Ú
isinstancer   Úgetattrr
   r   Úforward)r   r   r   r   r   r   r      s   
zL1Loss.forward)r   r	   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚstrÚfloatr   r   r   Ú__classcell__r   r   r   r   r      s    r   c                       sT   e Zd ZdZ					ddededed	ed
ef
‡ fdd„Zdedefdd„Z	‡  Z
S )Ú	SISDRLossaÆ  
    Computes the Scale-Invariant Source-to-Distortion Ratio between a batch
    of estimated and reference audio signals or aligned features.

    Parameters
    ----------
    scaling : int, optional
        Whether to use scale-invariant (True) or
        signal-to-noise ratio (False), by default True
    reduction : str, optional
        How to reduce across the batch (either 'mean',
        'sum', or none).], by default ' mean'
    zero_mean : int, optional
        Zero mean the references and estimates before
        computing the loss, by default True
    clip_min : int, optional
        The minimum possible loss value. Helps network
        to not focus on making already good examples better, by default None
    weight : float, optional
        Weight of this loss, defaults to 1.0.

    Implementation copied from: https://github.com/descriptinc/lyrebird-audiotools/blob/961786aa1a9d628cca0c0486e5885a457fe70c1a/audiotools/metrics/distance.py
    TÚmeanNr	   ÚscalingÚ	reductionÚ	zero_meanÚclip_minr   c                    s,   || _ || _|| _|| _|| _tƒ  ¡  d S ©N)r"   r#   r$   r%   r   r   r   )r   r"   r#   r$   r%   r   r   r   r   r   L   s   zSISDRLoss.__init__r   r   c                 C   sf  d}t |tƒr|j}|j}n|}|}|jd }| |dd¡ ddd¡}| |dd¡ ddd¡}| jrA|jddd�}|jddd�}nd}d}|| }	|| }
|	d jdd	�| }|
|	 jdd	�| }| j	rk||  
d¡nd}||	 }|
| }|d jdd	�}|d jdd	�}d
t || | ¡ }| jd ur�tj|| jd�}| jdkr¨| ¡ }|S | jdkr±| ¡ }|S )Ng:Œ0âŽyE>r   é   éÿÿÿÿé   T)ÚdimÚkeepdiméþÿÿÿ)r*   iöÿÿÿ)Úminr!   Úsum)r   r   r   ÚshapeÚreshapeÚpermuter$   r!   r.   r"   Ú	unsqueezeÚtorchÚlog10r%   Úclampr#   )r   r   r   ÚepsÚ
referencesÚ	estimatesÚnbÚmean_referenceÚmean_estimateÚ_referencesÚ
_estimatesÚreferences_projectionÚreferences_on_estimatesÚscaleÚe_trueÚe_resÚsignalÚnoiseÚsdrr   r   r   r   [   sF   

ÿý


þzSISDRLoss.forward)Tr!   TNr	   )r   r   r   r   Úintr   r   r   r   r   r   r   r   r   r   r    3   s&    úþýüûúr    c                       sz   e Zd ZdZddge ¡ dddddddf	d	ee d
ej	de
de
de
de
de
dedef‡ fdd„Zdedefdd„Z‡  ZS )ÚMultiScaleSTFTLossaÆ  Computes the multi-scale STFT loss from [1].

    Parameters
    ----------
    window_lengths : List[int], optional
        Length of each window of each STFT, by default [2048, 512]
    loss_fn : typing.Callable, optional
        How to compare each loss, by default nn.L1Loss()
    clamp_eps : float, optional
        Clamp on the log magnitude, below, by default 1e-5
    mag_weight : float, optional
        Weight of raw magnitude portion of loss, by default 1.0
    log_weight : float, optional
        Weight of log magnitude portion of loss, by default 1.0
    pow : float, optional
        Power to raise magnitude to before taking log, by default 2.0
    weight : float, optional
        Weight of this loss, by default 1.0
    match_stride : bool, optional
        Whether to match the stride of convolutional layers, by default False

    References
    ----------

    1.  Engel, Jesse, Chenjie Gu, and Adam Roberts.
        "DDSP: Differentiable Digital Signal Processing."
        International Conference on Learning Representations. 2019.

    Implementation copied from: https://github.com/descriptinc/lyrebird-audiotools/blob/961786aa1a9d628cca0c0486e5885a457fe70c1a/audiotools/metrics/spectral.py
    é   é   çñhãˆµøä>r	   ç       @FNÚwindow_lengthsÚloss_fnÚ	clamp_epsÚ
mag_weightÚ
log_weightÚpowr   Úmatch_strideÚwindow_typec
           
         sH   t ƒ  ¡  ‡ ‡fdd„|D ƒ| _|| _|| _|| _|| _|| _|| _d S )Nc                    ó    g | ]}t ||d  ˆ ˆd�‘qS ©é   )Úwindow_lengthÚ
hop_lengthrR   rS   r   ©Ú.0Úw©rR   rS   r   r   Ú
<listcomp>»   ó    úüÿz/MultiScaleSTFTLoss.__init__.<locals>.<listcomp>)	r   r   Ústft_paramsrM   rP   rO   rN   r   rQ   )
r   rL   rM   rN   rO   rP   rQ   r   rR   rS   r   r\   r   r   ®   s   
ù	
zMultiScaleSTFTLoss.__init__r   r   c              	   C   s˜   d}| j D ]D}| |j|j|j¡ | |j|j|j¡ || j|  |j | j	¡ 
| j
¡ ¡ |j | j	¡ 
| j
¡ ¡ ¡ 7 }|| j|  |j|j¡ 7 }q|S )a?  Computes multi-scale STFT between an estimate and a reference
        signal.

        Parameters
        ----------
        x : AudioSignal
            Estimate signal
        y : AudioSignal
            Reference signal

        Returns
        -------
        torch.Tensor
            Multi-scale STFT loss.
        ç        )r_   ÚstftrW   rX   rS   rP   rM   Ú	magnituder5   rN   rQ   r4   rO   )r   r   r   ÚlossÚsr   r   r   r   Ë   s   

þzMultiScaleSTFTLoss.forward©r   r   r   r   r   r   r   rF   ÚtypingÚCallabler   Úboolr   r   r   r   r   r   r   r   r   rG   Ž   s>    !öþýüûúùø	÷
örG   c                       s¤   e Zd ZdZddgddge ¡ dddddd	d
d
gddgdfdee dee dej	de
de
de
de
de
dedee
 dee
 def‡ fdd„Zdedefdd„Z‡  ZS )ÚMelSpectrogramLossaf  Compute distance between mel spectrograms. Can be used
    in a multi-scale way.

    Parameters
    ----------
    n_mels : List[int]
        Number of mels per STFT, by default [150, 80],
    window_lengths : List[int], optional
        Length of each window of each STFT, by default [2048, 512]
    loss_fn : typing.Callable, optional
        How to compare each loss, by default nn.L1Loss()
    clamp_eps : float, optional
        Clamp on the log magnitude, below, by default 1e-5
    mag_weight : float, optional
        Weight of raw magnitude portion of loss, by default 1.0
    log_weight : float, optional
        Weight of log magnitude portion of loss, by default 1.0
    pow : float, optional
        Power to raise magnitude to before taking log, by default 2.0
    weight : float, optional
        Weight of this loss, by default 1.0
    match_stride : bool, optional
        Whether to match the stride of convolutional layers, by default False

    Implementation copied from: https://github.com/descriptinc/lyrebird-audiotools/blob/961786aa1a9d628cca0c0486e5885a457fe70c1a/audiotools/metrics/spectral.py
    é–   éP   rH   rI   rJ   r	   rK   Fr`   NÚn_melsrL   rM   rN   rO   rP   rQ   r   rR   Úmel_fminÚmel_fmaxrS   c                    sZ   t ƒ  ¡  ‡ ‡fdd„|D ƒ| _|| _|| _|| _|| _|| _|| _|
| _	|| _
|| _d S )Nc                    rT   rU   r   rY   r\   r   r   r]     r^   z/MelSpectrogramLoss.__init__.<locals>.<listcomp>)r   r   r_   rl   rM   rN   rP   rO   r   rm   rn   rQ   )r   rl   rL   rM   rN   rO   rP   rQ   r   rR   rm   rn   rS   r   r\   r   r     s   
ù	
zMelSpectrogramLoss.__init__r   r   c              	   C   sÂ   d}t | j| j| j| jƒD ]Q\}}}}|j|j|jdœ}|j|f||dœ|¤Ž}	|j|f||dœ|¤Ž}
|| j	|  
|	 | j¡ | j¡ ¡ |
 | j¡ | j¡ ¡ ¡ 7 }|| j|  
|	|
¡ 7 }q|S )a*  Computes mel loss between an estimate and a reference
        signal.

        Parameters
        ----------
        x : AudioSignal
            Estimate signal
        y : AudioSignal
            Reference signal

        Returns
        -------
        torch.Tensor
            Mel loss.
        r`   )rW   rX   rS   )rm   rn   )Úziprl   rm   rn   r_   rW   rX   rS   Úmel_spectrogramrP   rM   r5   rN   rQ   r4   rO   )r   r   r   rc   rl   ÚfminÚfmaxrd   r   Úx_melsÚy_melsr   r   r   r   &  s    ÿý
þzMelSpectrogramLoss.forwardre   r   r   r   r   ri   ç   sP    óþýüûúùø	÷
öõôó#ri   c                       s8   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Z‡  ZS )
ÚGANLosszõ
    Computes a discriminator loss, given a discriminator on
    generated waveforms/spectrograms compared to ground truth
    waveforms/spectrograms. Computes the loss for both the
    discriminator and the generator in separate functions.
    c                    s   t ƒ  ¡  || _d S r&   )r   r   Údiscriminator)r   rv   r   r   r   r   R  s   

zGANLoss.__init__c                 C   s    |   |j¡}|   |j¡}||fS r&   )rv   r   )r   ÚfakeÚrealÚd_fakeÚd_realr   r   r   r   V  s   zGANLoss.forwardc                 C   sd   |   | ¡  ¡ |¡\}}d}t||ƒD ]\}}|t |d d ¡7 }|t d|d  d ¡7 }q|S )Nr   r(   r)   r'   )r   ÚcloneÚdetachro   r3   r!   )r   rw   rx   ry   rz   Zloss_dÚx_fakeÚx_realr   r   r   Údiscriminator_loss[  s   zGANLoss.discriminator_lossc           
      C   s”   |   ||¡\}}d}|D ]}|t d|d  d ¡7 }qd}tt|ƒƒD ]!}tt|| ƒd ƒD ]}	|t || |	 || |	  ¡ ¡7 }q0q$||fS )Nr   r'   r(   r)   )r   r3   r!   ÚrangeÚlenÚFÚl1_lossr|   )
r   rw   rx   ry   rz   Zloss_gr}   Zloss_featureÚiÚjr   r   r   Úgenerator_lossd  s   &ÿzGANLoss.generator_loss)	r   r   r   r   r   r   r   r†   r   r   r   r   r   ru   J  s    	ru   )rf   r   r3   Ztorch.nn.functionalr   Ú
functionalr‚   Ú
audiotoolsr   r   r   ÚModuler    rG   ri   ru   r   r   r   r   Ú<module>   s    ([Yc