o
    
jb                     @   st  d dl Z d dlZd dlmZmZ d dlmZmZmZ d dl	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 d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dl m!Z! d dl"m#Z# d dl$m%Z%m&Z& d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-eG dd deZ.G dd de#Z/dS )     N)	dataclassfield)DictListTuple)Coqpit)nn)
DataLoader)DistributedSampler)plot_spectrogram)AudioProcessor)mulaw_decode)load_fsspec)WaveRNNDataset)WaveRNNLoss)BaseVocoder)$sample_from_discretized_mix_logisticsample_from_gaussianc                 C   s   t jd|  |  d S )N)sysstdoutwrite)string	variables r   M/home/kuhnn/.local/lib/python3.10/site-packages/TTS/vocoder/models/wavernn.pystream   s   r   c                       $   e Zd Z fddZdd Z  ZS )ResBlockc                    sN   t    tj||ddd| _tj||ddd| _t|| _t|| _d S )N   Fkernel_sizebias)	super__init__r   Conv1dconv1conv2BatchNorm1dbatch_norm1batch_norm2)selfdims	__class__r   r   r$      s
   
zResBlock.__init__c                 C   s>   |}|  |}| |}t|}| |}| |}|| S N)r&   r)   Frelur'   r*   )r+   xresidualr   r   r   forward&   s   




zResBlock.forward__name__
__module____qualname__r$   r4   __classcell__r   r   r-   r   r      s    r   c                       r   )	MelResNetc                    st   t    |d d }tj|||dd| _t|| _t | _t	|D ]
}| j
t| q$tj||dd| _d S )N   r   Fr    )r!   )r#   r$   r   r%   conv_inr(   
batch_norm
ModuleListlayersrangeappendr   conv_out)r+   num_res_blocksin_dimscompute_dimsres_out_dimspadk_size_r-   r   r   r$   1   s   

zMelResNet.__init__c                 C   s@   |  |}| |}t|}| jD ]}||}q| |}|S r/   )r<   r=   r0   r1   r?   rB   )r+   r2   fr   r   r   r4   ;   s   





zMelResNet.forwardr5   r   r   r-   r   r:   0   s    
r:   c                       r   )	Stretch2dc                    s   t    || _|| _d S r/   )r#   r$   x_scaley_scale)r+   rL   rM   r-   r   r   r$   F   s   

zStretch2d.__init__c                 C   sT   |  \}}}}|dd}|ddd| jd| j}||||| j || j S )N   r   )size	unsqueezerepeatrM   rL   view)r+   r2   bchwr   r   r   r4   K   s   zStretch2d.forwardr5   r   r   r-   r   rK   E   s    rK   c                       r   )UpsampleNetworkc                    s   t    t|d | _|| j | _|| _|r(t|||||| _t	| jd| _
t | _|D ]4}d|d d f}	d|f}
t	|d}tjdd|	|
dd}|jjd|	d   | j| | j| q/d S )NrN   r   r;   r   F)r!   paddingr"         ?)r#   r$   np
cumproducttotal_scaleindentuse_aux_netr:   resnetrK   resnet_stretchr   r>   	up_layersConv2dweightdatafill_rA   )r+   	feat_dimsupsample_scalesrE   rC   rF   rG   r_   scalerH   rY   stretchconvr-   r   r   r$   S   s"   



zUpsampleNetwork.__init__c                 C   s   | j r| |d}| |}|d}|dd}nd }|d}| jD ]}||}q&|dd d d d | j| j f }|dd|fS )Nr   r;   )r_   r`   rQ   ra   squeeze	transposerb   r^   )r+   mauxrJ   r   r   r   r4   n   s   




&zUpsampleNetwork.forwardr5   r   r   r-   r   rX   R   s    rX   c                       r   )Upsamplec                    s<   t    || _|| _|| | _|| _t|||||| _d S r/   )r#   r$   ri   rG   r^   r_   r:   r`   )r+   ri   rG   rC   rg   rE   rF   r_   r-   r   r   r$   ~   s   

zUpsample.__init__c                 C   s   | j r| |}tjjj|| jddd}|dd}nd }tjjj|| jddd}|d d d d | j| j f }|d }|dd|fS )NlinearT)scale_factormodealign_cornersr   r;   g
ףp=
?)	r_   r`   torchr   
functionalinterpolateri   rm   r^   )r+   rn   ro   r   r   r   r4      s   
 zUpsample.forwardr5   r   r   r-   r   rp   }   s    rp   c                   @   s   e Zd ZU dZdZeed< dZeed< dZeed< dZ	eed< dZ
eed	< d
Zeed< d
Zeed< edd dZee ed< dZeed< d
Zeed< dZeed< dZeed< dS )WavernnArgsuh  🐸 WaveRNN model arguments.

    rnn_dims (int):
        Number of hidden channels in RNN layers. Defaults to 512.
    fc_dims (int):
        Number of hidden channels in fully-conntected layers. Defaults to 512.
    compute_dims (int):
        Number of hidden channels in the feature ResNet. Defaults to 128.
    res_out_dim (int):
        Number of hidden channels in the feature ResNet output. Defaults to 128.
    num_res_blocks (int):
        Number of residual blocks in the ResNet. Defaults to 10.
    use_aux_net (bool):
        enable/disable the feature ResNet. Defaults to True.
    use_upsample_net (bool):
        enable/ disable the upsampling networl. If False, basic upsampling is used. Defaults to True.
    upsample_factors (list):
        Upsampling factors. The multiply of the values must match the `hop_length`. Defaults to ```[4, 8, 8]```.
    mode (str):
        Output mode of the WaveRNN vocoder. `mold` for Mixture of Logistic Distribution, `gauss` for a single
        Gaussian Distribution and `bits` for quantized bits as the model's output.
    mulaw (bool):
        enable / disable the use of Mulaw quantization for training. Only applicable if `mode == 'bits'`. Defaults
        to `True`.
    pad (int):
            Padding applied to the input feature frames against the convolution layers of the feature network.
            Defaults to 2.
    i   rnn_dimsfc_dims   rE   rF   
   rC   Tr_   use_upsample_netc                   C   s   g dS )N)      r   r   r   r   r   r   <lambda>   s    zWavernnArgs.<lambda>)default_factoryupsample_factorsmoldrs   mulawr;   rG   P   rg   N)r6   r7   r8   __doc__ry   int__annotations__rz   rE   rF   rC   r_   boolr}   r   r   r   rs   strr   rG   rg   r   r   r   r   rx      s   
 rx   c                       sR  e Zd Zdef fddZdd Zd8ddZd	d
 Zdd Ze	dd Z
e	d9ddZe	dd Z	d:ddZdededeeef fddZdededeeef fddZe dedd d!edeeef fd"d#Zd$ed%d&ded'edeeejf f
d(d)Ze	dedefd*d+Zdeded,d-d.ed/ed0efd1d2Zd3d4 Ze	d;d6d7Z  ZS )<Wavernnconfigc                    sX  t  | t| jjtrd| jj | _n| jjdkrd| _n| jjdkr)d| _ntd| jjtdi |j	
 | _| jjd | _| jjrqt| jjd |j	jksWJ dt| jj| jj| jj| jj| jj| jj| jj| _nt|j	j| jj| jj| jj| jj| jj| jj| _| jjrt| jj| j d	 | jj| _tj| jj| jjd
d| _ tj| jj| j | jjd
d| _!t| jj| j | jj"| _#t| jj"| j | jj"| _$t| jj"| j| _%dS t| jjd	 | jj| _tj| jj| jjd
d| _ tj| jj| jjd
d| _!t| jj| jj"| _#t| jj"| jj"| _$t| jj"| j| _%dS )u  🐸 WaveRNN model.
        Original paper - https://arxiv.org/abs/1802.08435
        Official implementation - https://github.com/fatchord/WaveRNN

        Args:
            config (Coqpit): [description]

        Raises:
            RuntimeError: [description]

        Examples:
            >>> from TTS.vocoder.configs import WavernnConfig
            >>> config = WavernnConfig()
            >>> model = Wavernn(config)

        Paper Abstract:
            Sequential models achieve state-of-the-art results in audio, visual and textual domains with respect to
            both estimating the data distribution and generating high-quality samples. Efficient sampling for this
            class of models has however remained an elusive problem. With a focus on text-to-speech synthesis, we
            describe a set of general techniques for reducing sampling time while maintaining high output quality.
            We first describe a single-layer recurrent neural network, the WaveRNN, with a dual softmax layer that
            matches the quality of the state-of-the-art WaveNet model. The compact form of the network makes it
            possible to generate 24kHz 16-bit audio 4x faster than real time on a GPU. Second, we apply a weight
            pruning technique to reduce the number of weights in the WaveRNN. We find that, for a constant number of
            parameters, large sparse networks perform better than small dense networks and this relationship holds for
            sparsity levels beyond 96%. The small number of weights in a Sparse WaveRNN makes it possible to sample
            high-fidelity audio on a mobile CPU in real time. Finally, we propose a new generation scheme based on
            subscaling that folds a long sequence into a batch of shorter sequences and allows one to generate multiple
            samples at once. The Subscale WaveRNN produces 16 samples per step without loss of quality and offers an
            orthogonal method for increasing sampling efficiency.
        r;   r      gaussUnknown model mode value - r~   rN   z4 [!] upsample scales needs to be equal to hop_lengthr   T)batch_firstNr   )&r#   r$   
isinstanceargsrs   r   	n_classesRuntimeErrorr   audioto_dictaprF   aux_dimsr}   r[   r\   r   
hop_lengthrX   rg   rE   rC   rG   r_   upsamplerp   r   Linearry   IGRUrnn1rnn2rz   fc1fc2fc3)r+   r   r-   r   r   r$      sZ    
	  zWavernn.__init__c                    s  | d}td| jj|j}td| jj|j} |\}} jjry 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 } jjrtj
|d	||gdd
ntj
|d	|gdd
} |}|} j   ||\}}|| }|} jjrtj
||	gdd
n|} j   ||\}}|| } jjrtj
||
gdd
n|}t |} jjrtj
||gdd
n|}t |} |S )Nr   r   c                    s   g | ]} j | qS r   )r   .0ir+   r   r   
<listcomp>  s    z#Wavernn.forward.<locals>.<listcomp>   r;   rO   r~   rN   dim)rP   ru   zerosr   ry   todevicer   r_   r@   catrQ   r   r   flatten_parametersr   r0   r1   r   r   r   )r+   r2   melsbsizeh1h2ro   aux_idxa1a2a3a4resrI   r   r   r   r4     s:   
""""



zWavernn.forwardNc                    s  |    g }t }| | j}| | j}t  t|tj	r1t
|tt|  j}|jdkr;|d}|dd | jjj }	| j|dd| jjdd}| |dd\} |rt| |||} d urt|  || | \}
}}t|
| jj|}t|
| jj|}t|
d|}| jjr| j  fddt!d	D }t!|D ]|d d d d f }| jjrЇfd
d|D \}}}}| jjrtj"|||gddntj"||gdd}| #|}|||}|| }| jjrtj"||gddn|}|||}|| }| jjrtj"||gddn|}t$%| &|}| jjr4tj"||gddn|}t$%| '|}| (|}| jj)dkrgt*|ddd}|+|,d |dd|}nZ| jj)dkrt-|ddd}|+|,d |dd|}n6t| jj)t.rt$j/|dd}tj01|}d|2 3  | j4d  d }|+| |d}nt5d| jj)d dkr| 6||
| qW d    n	1 sw   Y  t7|dd}|8 }|r|9 }|:tj;}| <|||}n|d }| jj=rt| jj)t.rt>|| jj)d}t?ddd| jjj }|d |	 }|	t@|krD|d| jjj d   |9  < | A  |S )Nr;   r   rN   r   both)rG   sidec              	      s2   g | ]} d d d d | |d  f qS )Nr   r   r   )ro   dr   r   r   Z  s   2 z%Wavernn.inference.<locals>.<listcomp>r~   c                 3   s&    | ]}|d d  d d f V  qd S r/   r   )r   a)r   r   r   	<genexpr>`  s   $ z$Wavernn.inference.<locals>.<genexpr>r   r   r   rZ   r   d   )wavmulaw_qc   i)Bevaltimeget_gru_cellr   r   ru   no_gradr   r[   ndarrayFloatTensorr   r   next
parametersr   ndimrQ   rP   r   r   r   
pad_tensorrm   r   rG   r   fold_with_overlapr   ry   type_asr_   r   r@   r   r   r0   r1   r   r   r   rs   r   rA   rS   r   r   softmaxdistributionsCategoricalsamplefloatr   r   gen_displaystackcpunumpyastypefloat64xfade_and_unfoldr   r   linspacelentrain)r+   r   batchedtargetoverlapoutputstartr   r   wave_lenb_sizeseq_lenrI   r   r   r2   	aux_splitm_ta1_ta2_ta3_ta4_tinplogitsr   	posteriordistribfade_outr   )ro   r   r   r   	inference;  s   

.

 
  

FzWavernn.inferencec                 C   sN   |d t   |  | d }|d | jjj }td|| || |||f d S )Nr   i  zC%i/%i -- batch_size: %i -- gen_rate: %.1f kHz -- x_realtime: %.1f  )r   r   r   sample_rater   )r+   r   r   r   r   gen_raterealtime_ratior   r   r   r     s   zWavernn.gen_displayc                 C   s   |  \}}}|| ||  }|||  | }|| }	|	dkr3|d7 }|d|  |	 }
| j||
dd}t||d|  ||j}t|D ]}|||  }|| d|  }|dd||ddf ||< qF|S )a  Fold the tensor with overlap for quick batched inference.
            Overlap will be used for crossfading in xfade_and_unfold()
        Args:
            x (tensor)    : Upsampled conditioning features.
                            shape=(1, timesteps, features)
            target (int)  : Target timesteps for each index of batch
            overlap (int) : Timesteps for both xfade and rnn warmup
        Return:
            (tensor) : shape=(num_folds, target + 2 * overlap, features)
        Details:
            x = [[h1, h2, ... hn]]
            Where each h is a vector of conditioning features
            Eg: target=2, overlap=1 with x.size(1)=10
            folded = [[h1, h2, h3, h4],
                      [h4, h5, h6, h7],
                      [h7, h8, h9, h10]]
        r   r   r;   after)r   N)rP   r   ru   r   r   r   r@   )r+   r2   r   r   rI   	total_lenfeatures	num_foldsextended_len	remainingrY   foldedr   r   endr   r   r   r     s    zWavernn.fold_with_overlapc                 C   sD   t | j| j}| jj|j_| jj|j_| j	j|j
_| jj|j_|S r/   )r   GRUCell
input_sizehidden_sizeweight_hh_l0re   	weight_hhweight_ih_l0	weight_ih
bias_hh_l0bias_hh
bias_ih_l0bias_ih)grugru_cellr   r   r   r     s   zWavernn.get_gru_cellr   c                 C   s   |   \}}}|dkr|d|  n|| }t|||| j}|dv r5| |d d ||| d d f< |S |dkrF| |d d d |d d f< |S )Nr   r;   )beforer   r   )rP   ru   r   r   r   )r2   rG   r   rT   trU   totalpaddedr   r   r   r     s   zWavernn.pad_tensorc                 C   s*  | j \}}|d|  }|||  | }|d }|| }tj|tjd}tjdd|tjd}	tdd|	  }
tdd|	  }t||
g}
t||g}| ddd|f  |
9  < | dd| df  |9  < tj|tjd}t|D ]}|||  }|| d|  }|||  | | 7  < qv|S )a  Applies a crossfade and unfolds into a 1d array.
        Args:
            y (ndarry)    : Batched sequences of audio samples
                            shape=(num_folds, target + 2 * overlap)
                            dtype=np.float64
            overlap (int) : Timesteps for both xfade and rnn warmup
        Return:
            (ndarry) : audio samples in a 1d array
                       shape=(total_len)
                       dtype=np.float64
        Details:
            y = [[seq1],
                 [seq2],
                 [seq3]]
            Apply a gain envelope at both ends of the sequences
            y = [[seq1_in, seq1_target, seq1_out],
                 [seq2_in, seq2_target, seq2_out],
                 [seq3_in, seq3_target, seq3_out]]
            Stagger and add up the groups of samples:
            [seq1_in, seq1_target, (seq1_out + seq2_in), seq2_target, ...]
        r;   )dtyperN   r   g      ?N)shaper[   r   r   r   sqrtconcatenater@   )yr   r   r   lengthr   silence_lenfade_lensilencer  fade_inr   unfoldedr   r   r   r   r   r   r     s&   
zWavernn.xfade_and_unfoldFc                 C   s@   t |td|d}| |d  |r|   | jrJ d S d S )Nr   )map_locationcachemodel)r   ru   r   load_state_dictr   training)r+   r   checkpoint_pathr   r  stater   r   r   load_checkpoint  s   
zWavernn.load_checkpointbatch	criterionreturnc                 C   sn   |d }|d }|d }|  ||}t| jjtr#|ddd}n| }|d}|||}d|i|fS )Ninputwaveformwaveform_coarser   r;   rN   model_output)r4   r   r   rs   r   rm   rQ   r   )r+   r!  r"  r   r%  r&  y_hat	loss_dictr   r   r   
train_step(  s   

zWavernn.train_stepc                 C   s   |  ||S r/   )r*  )r+   r!  r"  r   r   r   	eval_step7  s   zWavernn.eval_stepassetstest_loaderr	   r   c                 C   s   | j }i }i }|jd}t|D ]J\}}	t|	d }
|
t|  j	}
| 
|
| jj| jj| jj}||}|d| dt|
jd| dt|ji |d| d|i q||fS )Nr   r   test_z/ground_truthz/predictionz/audio)r   datasetload_test_samples	enumerateru   r   r   r   r   r   r   r   r   target_samplesoverlap_samplesmelspectrogramupdater   T)r+   r,  r-  r   r   figuresaudiossamplesidxr   r2   r(  x_hatr   r   r   test:  s    
zWavernn.testoutputsloggerLoggerstepsc                 C   s*   |\}}| || |||| jj d S r/   )eval_figureseval_audiosr   r   )r+   r=  r>  r,  r@  r7  r8  r   r   r   test_logQ  s   zWavernn.test_logc                 C   s$   | d }| d }| d }|||dS )Nr   r   r;   )r$  r%  r&  r   )r!  r%  r   r&  r   r   r   format_batchX  s   zWavernn.format_batchis_evalTr9  verbosenum_gpusc                 C   s   | j }t|||j|j|jj|jj|jj| |d	}|dkr#t|ddnd }	t	||r+dn|j
|dk|j|	|r8|jn|jdd}
|
S )N)	r   itemsr   hop_lenrG   rs   r   is_trainingrF  r   T)shuffler   )
batch_sizerK  
collate_fnsamplernum_workers
pin_memory)r   r   r   r   
model_argsrG   rs   r   r
   r	   rL  collatenum_eval_loader_workersnum_loader_workers)r+   r   r,  rE  r9  rF  rG  r   r/  rN  loaderr   r   r   get_data_loader_  s.   		zWavernn.get_data_loaderc                 C   s   t | jjS r/   )r   r   rs   r   r   r   r   get_criterion  s   zWavernn.get_criterionWavernnConfigc                 C   s   t | S r/   )r   )r   r   r   r   init_from_config  s   zWavernn.init_from_config)NNN)r   )FF)r   rX  ) r6   r7   r8   r   r$   r4   r   r   r   staticmethodr   r   r   r   r   r   r*  r+  ru   r   r<  r   r[   r   rC  rD  r   r   rV  rW  rY  r9   r   r   r-   r   r      sn    T
%d*

8
	


!r   )0r   r   dataclassesr   r   typingr   r   r   r   r[   ru   torch.nn.functionalr   rv   r0   coqpitr   torch.utils.datar	   torch.utils.data.distributedr
   TTS.tts.utils.visualr   TTS.utils.audior    TTS.utils.audio.numpy_transformsr   TTS.utils.ior   $TTS.vocoder.datasets.wavernn_datasetr   TTS.vocoder.layers.lossesr   TTS.vocoder.models.base_vocoderr   TTS.vocoder.utils.distributionr   r   r   Moduler   r:   rK   rX   rp   rx   r   r   r   r   r   <module>   s8    +,