a
    âñh„0  ã                   @   s–   d dl mZmZ d dlZd dlmZ d dlmZ g d¢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 )é    )ÚListÚTupleN)ÚTensor)Únn)ÚResBlockÚ	MelResNetÚ	Stretch2dÚUpsampleNetworkÚWaveRNNc                       s:   e Zd ZdZd
eddœ‡ fdd„Zeedœdd	„Z‡  ZS )r   aŒ  ResNet block based on "Deep Residual Learning for Image Recognition"

    The paper link is https://arxiv.org/pdf/1512.03385.pdf.

    Args:
        n_freq: the number of bins in a spectrogram. (Default: ``128``)

    Examples
        >>> resblock = ResBlock()
        >>> input = torch.rand(10, 128, 512)  # a random spectrogram
        >>> output = resblock(input)  # shape: (10, 128, 512)
    é€   N)Ún_freqÚreturnc                    sR   t ƒ  ¡  t tj||ddd�t |¡tjdd�tj||ddd�t |¡¡| _d S )Né   F©Úin_channelsÚout_channelsÚkernel_sizeÚbiasT©Zinplace)ÚsuperÚ__init__r   Ú
SequentialÚConv1dÚBatchNorm1dÚReLUÚresblock_model)Úselfr   ©Ú	__class__© úY/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchaudio/models/wavernn.pyr      s    

ûzResBlock.__init__©Úspecgramr   c                 C   s   |   |¡| S )zéPass the input through the ResBlock layer.
        Args:
            specgram (Tensor): the input sequence to the ResBlock layer (n_batch, n_freq, n_time).

        Return:
            Tensor shape: (n_batch, n_freq, n_time)
        )r   ©r   r"   r   r   r    Úforward#   s    	zResBlock.forward)r   ©	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úintr   r   r$   Ú__classcell__r   r   r   r    r   
   s   r   c                       sB   e Zd ZdZdeeeeeddœ‡ fdd„Zeed	œd
d„Z‡  ZS )r   a�  MelResNet layer uses a stack of ResBlocks on spectrogram.

    Args:
        n_res_block: the number of ResBlock in stack. (Default: ``10``)
        n_freq: the number of bins in a spectrogram. (Default: ``128``)
        n_hidden: the number of hidden dimensions of resblock. (Default: ``128``)
        n_output: the number of output dimensions of melresnet. (Default: ``128``)
        kernel_size: the number of kernel size in the first Conv1d layer. (Default: ``5``)

    Examples
        >>> melresnet = MelResNet()
        >>> input = torch.rand(10, 128, 512)  # a random spectrogram
        >>> output = melresnet(input)  # shape: (10, 128, 508)
    é
   r   é   N)Ún_res_blockr   Ún_hiddenÚn_outputr   r   c                    sh   t ƒ  ¡  ‡ fdd„t|ƒD ƒ}tjtj|ˆ |dd�t ˆ ¡tjdd�g|¢tjˆ |dd�‘R Ž | _d S )	Nc                    s   g | ]}t ˆ ƒ‘qS r   )r   )Ú.0Ú_©r/   r   r    Ú
<listcomp>G   ó    z&MelResNet.__init__.<locals>.<listcomp>Fr   Tr   r   )r   r   r   )	r   r   Úranger   r   r   r   r   Úmelresnet_model)r   r.   r   r/   r0   r   Z	ResBlocksr   r3   r    r   ?   s    

ýüûzMelResNet.__init__r!   c                 C   s
   |   |¡S )zÿPass the input through the MelResNet layer.
        Args:
            specgram (Tensor): the input sequence to the MelResNet layer (n_batch, n_freq, n_time).

        Return:
            Tensor shape: (n_batch, n_output, n_time - kernel_size + 1)
        )r7   r#   r   r   r    r$   Q   s    	zMelResNet.forward)r,   r   r   r   r-   r%   r   r   r   r    r   /   s        ûûr   c                       s:   e Zd ZdZeeddœ‡ fdd„Zeedœdd„Z‡  ZS )	r   a‘  Upscale the frequency and time dimensions of a spectrogram.

    Args:
        time_scale: the scale factor in time dimension
        freq_scale: the scale factor in frequency dimension

    Examples
        >>> stretch2d = Stretch2d(time_scale=10, freq_scale=5)

        >>> input = torch.rand(10, 100, 512)  # a random spectrogram
        >>> output = stretch2d(input)  # shape: (10, 500, 5120)
    N)Ú
time_scaleÚ
freq_scaler   c                    s   t ƒ  ¡  || _|| _d S )N)r   r   r9   r8   )r   r8   r9   r   r   r    r   k   s    
zStretch2d.__init__r!   c                 C   s   |  | jd¡  | jd¡S )zþPass the input through the Stretch2d layer.

        Args:
            specgram (Tensor): the input sequence to the Stretch2d layer (..., n_freq, n_time).

        Return:
            Tensor shape: (..., n_freq * freq_scale, n_time * time_scale)
        éþÿÿÿéÿÿÿÿ)Zrepeat_interleaver9   r8   r#   r   r   r    r$   s   s    
zStretch2d.forwardr%   r   r   r   r    r   ]   s
   þr   c                	       sP   e Zd ZdZdee eeeeeddœ‡ fdd„Zeeeef d	œd
d„Z	‡  Z
S )r	   añ  Upscale the dimensions of a spectrogram.

    Args:
        upsample_scales: the list of upsample scales.
        n_res_block: the number of ResBlock in stack. (Default: ``10``)
        n_freq: the number of bins in a spectrogram. (Default: ``128``)
        n_hidden: the number of hidden dimensions of resblock. (Default: ``128``)
        n_output: the number of output dimensions of melresnet. (Default: ``128``)
        kernel_size: the number of kernel size in the first Conv1d layer. (Default: ``5``)

    Examples
        >>> upsamplenetwork = UpsampleNetwork(upsample_scales=[4, 4, 16])
        >>> input = torch.rand(10, 128, 10)  # a random spectrogram
        >>> output = upsamplenetwork(input)  # shape: (10, 1536, 128), (10, 1536, 128)
    r,   r   r-   N)Úupsample_scalesr.   r   r/   r0   r   r   c                    sÊ   t ƒ  ¡  d}|D ]}||9 }q|d d | | _t|||||ƒ| _t|dƒ| _g }	|D ]`}
t|
dƒ}tjddd|
d d fd|
fdd�}|j	j
 d|
d d  ¡ |	 |¡ |	 |¡ qXtj|	Ž | _d S )Nr   é   r   F)r   r   r   Úpaddingr   g      ð?)r   r   Úindentr   Úresnetr   Úresnet_stretchr   ZConv2dZweightÚdataZfill_Úappendr   Úupsample_layers)r   r<   r.   r   r/   r0   r   Útotal_scaleÚupsample_scaleZ	up_layersZscaleZstretchÚconvr   r   r    r   ‘   s(    


ü
zUpsampleNetwork.__init__r!   c                 C   sf   |   |¡ d¡}|  |¡}| d¡}| d¡}|  |¡}| d¡dd…dd…| j| j …f }||fS )a¿  Pass the input through the UpsampleNetwork layer.

        Args:
            specgram (Tensor): the input sequence to the UpsampleNetwork layer (n_batch, n_freq, n_time)

        Return:
            Tensor shape: (n_batch, n_freq, (n_time - kernel_size + 1) * total_scale),
                          (n_batch, n_output, (n_time - kernel_size + 1) * total_scale)
        where total_scale is the product of all elements in upsample_scales.
        r   N)r@   Ú	unsqueezerA   ÚsqueezerD   r?   )r   r"   Zresnet_outputZupsampling_outputr   r   r    r$   ¯   s    



&zUpsampleNetwork.forward)r,   r   r   r   r-   )r&   r'   r(   r)   r   r*   r   r   r   r$   r+   r   r   r   r    r	   €   s        úúr	   c                       sR   e Zd ZdZdee eeeeeeeeeddœ‡ fdd	„Zeeed
œdd„Z‡  Z	S )r
   aB  WaveRNN model based on the implementation from `fatchord <https://github.com/fatchord/WaveRNN>`_.

    The original implementation was introduced in
    `"Efficient Neural Audio Synthesis" <https://arxiv.org/pdf/1802.08435.pdf>`_.
    The input channels of waveform and spectrogram have to be 1. The product of
    `upsample_scales` must equal `hop_length`.

    Args:
        upsample_scales: the list of upsample scales.
        n_classes: the number of output classes.
        hop_length: the number of samples between the starts of consecutive frames.
        n_res_block: the number of ResBlock in stack. (Default: ``10``)
        n_rnn: the dimension of RNN layer. (Default: ``512``)
        n_fc: the dimension of fully connected layer. (Default: ``512``)
        kernel_size: the number of kernel size in the first Conv1d layer. (Default: ``5``)
        n_freq: the number of bins in a spectrogram. (Default: ``128``)
        n_hidden: the number of hidden dimensions of resblock. (Default: ``128``)
        n_output: the number of output dimensions of melresnet. (Default: ``128``)

    Example
        >>> wavernn = WaveRNN(upsample_scales=[5,5,8], n_classes=512, hop_length=200)
        >>> waveform, sample_rate = torchaudio.load(file)
        >>> # waveform shape: (n_batch, n_channel, (n_time - kernel_size + 1) * hop_length)
        >>> specgram = MelSpectrogram(sample_rate)(waveform)  # shape: (n_batch, n_channel, n_freq, n_time)
        >>> output = wavernn(waveform, specgram)
        >>> # output shape: (n_batch, n_channel, (n_time - kernel_size + 1) * hop_length, n_classes)
    r,   é   r-   r   N)r<   Ú	n_classesÚ
hop_lengthr.   Ún_rnnÚn_fcr   r   r/   r0   r   c                    s  t ƒ  ¡  || _|| _|
d | _|| _|| _d}|D ]}||9 }q4|| jkr`td|› d|› �ƒ‚t||||	|
|ƒ| _	t
 || j d |¡| _t
j||dd�| _t
j|| j |dd�| _t
jdd�| _t
jdd�| _t
 || j |¡| _t
 || j |¡| _t
 || j¡| _d S )Né   r   z/Expected: total_scale == hop_length, but found z != T)Zbatch_firstr   )r   r   r   rM   Ún_auxrL   rK   Ú
ValueErrorr	   Úupsampler   ZLinearÚfcZGRUÚrnn1Úrnn2r   Úrelu1Úrelu2Úfc1Úfc2Úfc3)r   r<   rK   rL   r.   rM   rN   r   r   r/   r0   rE   rF   r   r   r    r   ã   s4    



ûzWaveRNN.__init__)Úwaveformr"   r   c                    s  |  d¡dksJ dƒ‚|  d¡dks,J dƒ‚| d¡| d¡ }}|  d¡}tjd|ˆ j|j|jd�}tjd|ˆ j|j|jd�}ˆ  |¡\}}| dd¡}| dd¡}‡ fdd„t	d	ƒD ƒ}|d
d
…d
d
…|d |d …f }|d
d
…d
d
…|d |d …f }	|d
d
…d
d
…|d |d …f }
|d
d
…d
d
…|d |d …f }tj
| d¡||gdd�}ˆ  |¡}|}ˆ  ||¡\}}|| }|}tj
||	gdd�}ˆ  ||¡\}}|| }tj
||
gdd�}ˆ  |¡}ˆ  |¡}tj
||gdd�}ˆ  |¡}ˆ  |¡}ˆ  |¡}| d¡S )a  Pass the input through the WaveRNN model.

        Args:
            waveform: the input waveform to the WaveRNN layer (n_batch, 1, (n_time - kernel_size + 1) * hop_length)
            specgram: the input spectrogram to the WaveRNN layer (n_batch, 1, n_freq, n_time)

        Return:
            Tensor shape: (n_batch, 1, (n_time - kernel_size + 1) * hop_length, n_classes)
        r   z*Require the input channel of waveform is 1z*Require the input channel of specgram is 1r   )ÚdtypeÚdevicer=   c                    s   g | ]}ˆ j | ‘qS r   )rP   )r1   Úi©r   r   r    r4   (  r5   z#WaveRNN.forward.<locals>.<listcomp>r-   Né   rO   r;   )Zdim)ÚsizerI   ÚtorchÚzerosrM   r\   r]   rR   Z	transposer6   ÚcatrH   rS   rT   rU   rX   rV   rY   rW   rZ   )r   r[   r"   Z
batch_sizeÚh1Úh2ZauxZaux_idxZa1Za2Úa3Za4ÚxÚresr2   r   r_   r    r$     s>    
""""





zWaveRNN.forward)r,   rJ   rJ   r-   r   r   r   )
r&   r'   r(   r)   r   r*   r   r   r$   r+   r   r   r   r    r
   Æ   s*           öö+r
   )Útypingr   r   rb   r   r   Ú__all__ÚModuler   r   r   r	   r
   r   r   r   r    Ú<module>   s   %.#F