o
    
jD                     @   s   d dl Z d dlmZmZmZ d dlZd dlmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZ d dlmZ d d	lmZ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lmZ d dl m!Z! G dd deZ"G dd dej#Z$dS )    N)DictListUnion)Coqpit)nn)TensorboardLogger)EncoderOverflowUtils)Decoder)	NeuralHMM)!get_spec_from_most_probable_state&plot_transition_probabilities_to_numpy)BaseTTS)SpeakerManager)TTSTokenizer)plot_alignmentplot_spectrogram)format_aux_input)load_fsspecc                
       s  e Zd ZdZ			dBddddddd	ef fd
dZdefddZdd Zdd Z	dd Z
dd Zedd ZdedejfddZdedejfddZdefd d!Ze ddddd"fd#ejfd$d%Zed&d' ZedCddd)eee ee f fd*d+Z	,dDded-ed.ed/efd0d1Zd2d3 Z e! d4d5 Z"ded6ed7d8d9ed:e#f
d;d<Z$ded6ed7d8d9ed:e#f
d=d>Z%d6ed7d8d9ed:e#d?df
d@dAZ&  Z'S )EOverflowa  OverFlow TTS model.

    Paper::
        https://arxiv.org/abs/2211.06892

    Paper abstract::
        Neural HMMs are a type of neural transducer recently proposed for
    sequence-to-sequence modelling in text-to-speech. They combine the best features
    of classic statistical speech synthesis and modern neural TTS, requiring less
    data and fewer training updates, and are less prone to gibberish output caused
    by neural attention failures. In this paper, we combine neural HMM TTS with
    normalising flows for describing the highly non-Gaussian distribution of speech
    acoustics. The result is a powerful, fully probabilistic model of durations and
    acoustics that can be trained using exact maximum likelihood. Compared to
    dominant flow-based acoustic models, our approach integrates autoregression for
    improved modelling of long-range dependences such as utterance-level prosody.
    Experiments show that a system based on our proposal gives more accurate
    pronunciations and better subjective speech quality than comparable methods,
    whilst retaining the original advantages of neural HMMs. Audio examples and code
    are available at https://shivammehta25.github.io/OverFlow/.

    Note:
        - Neural HMMs uses flat start initialization i.e it computes the means and std and transition probabilities
        of the dataset and uses them to initialize the model. This benefits the model and helps with faster learning
        If you change the dataset or want to regenerate the parameters change the `force_generate_statistics` and
        `mel_statistics_parameter_path` accordingly.

        - To enable multi-GPU training, set the `use_grad_checkpointing=False` in config.
        This will significantly increase the memory usage.  This is because to compute
        the actual data likelihood (not an approximation using MAS/Viterbi) we must use
        all the states at the previous time step during the forward pass to decide the
        probability distribution at the current step i.e the difference between the forward
        algorithm and viterbi approximation.

    Check :class:`TTS.tts.configs.overflow.OverFlowConfig` for class arguments.
    NconfigOverFlowConfigapAudioProcessor	tokenizerr   speaker_managerc                    s   t  |||| || _|D ]
}t| |||  q|j| _t|j|j|j	| _
t| j| j| j| j	| j| j| j| j| j| j| j| j| j| jd| _t| j| j| j| j| j| j| j| j | j!| j"| j#d| _$| %dt&'d | %dt&'d d S )N)frame_channelsar_orderdeterministic_transitionencoder_dimprenet_type
prenet_dimprenet_n_layersprenet_dropoutprenet_dropout_at_inferencememory_rnn_dimoutputnet_sizeflat_start_params	std_flooruse_grad_checkpointing)	dropout_p
num_splitsnum_squeezesigmoid_scalec_in_channelsmeanr   std   )(super__init__r   setattrout_channelsdecoder_output_dimr   	num_charsstate_per_phoneencoder_in_out_featuresencoderr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   
neural_hmmr
   hidden_channels_deckernel_size_decdilation_ratenum_flow_blocks_decnum_block_layersdropout_p_decr+   r,   r-   r.   decoderregister_buffertorchtensor)selfr   r   r   r   key	__class__ J/home/kuhnn/.local/lib/python3.10/site-packages/TTS/tts/models/overflow.pyr3   >   sJ   zOverflow.__init__statistics_dictc                 C   s(   t |d | j_t |d | j_d S )Nr/   r0   )rD   rE   r/   datar0   )rF   rL   rJ   rJ   rK   update_mean_stdr   s   zOverflow.update_mean_stdc                 C   sH   | j  dks| j dkrt| j}| | | |}||||fS )Nr   r1   )r/   itemr0   rD   loadmel_statistics_parameter_pathrN   	normalize)rF   texttext_lenmelsmel_lenrL   rJ   rJ   rK   preprocess_batchv   s
   

zOverflow.preprocess_batchc                 C      | | j| jS N)subr/   divr0   rF   xrJ   rJ   rK   rR   ~      zOverflow.normalizec                 C   rX   rY   )mulr0   addr/   r\   rJ   rJ   rK   inverse_normalize   r^   zOverflow.inverse_normalizec                 C   sp   |  ||||\}}}}| ||\}}| |dd|\}}}	| ||||\}
}}}|
|	 |||d}|S )a  
        Forward pass for training and computing the log likelihood of a given batch.

        Shapes:
            Shapes:
            text: :math:`[B, T_in]`
            text_len: :math:`[B]`
            mels: :math:`[B, T_out, C]`
            mel_len: :math:`[B]`
        r1      )	log_probs
alignmentstransition_vectorsmeans)rW   r:   rB   	transposer;   )rF   rS   rT   rU   rV   encoder_outputsencoder_output_lenz	z_lengthslogdetrc   fwd_alignmentsre   rf   outputsrJ   rJ   rK   forward   s   zOverflow.forwardc                 C   sx   i }| d    |d< | d    |d< | d   | d      |d< | d   | d      |d< |S )Ntext_lengthsavg_text_lengthmel_lengthsavg_spec_lengthavg_text_batch_occupancyavg_spec_batch_occupancy)floatr/   max)batchstatsrJ   rJ   rK   _training_stats   s   $$zOverflow._training_statsrx   	criterionc           	      C   sf   |d }|d }|d }|d }| j ||||d}||d | |   }|| | ||fS )N
text_inputrp   	mel_inputrr   )rS   rT   rU   rV   rc   )ro   sumupdaterz   )	rF   rx   r{   r|   rp   r}   rr   rn   	loss_dictrJ   rJ   rK   
train_step   s   zOverflow.train_stepc                 C   s   |  ||S rY   )r   )rF   rx   r{   rJ   rJ   rK   	eval_step   s   zOverflow.eval_step	aux_inputc                 C   s2   |  }|| j| j| jd |rt||S |S )zSet missing fields to their default value.

        Args:
            aux_inputs (Dict): Dictionary containing the auxiliary inputs.
        sampling_tempmax_sampling_timeduration_threshold)copyr   r   r   r   r   )rF   r   default_input_dictrJ   rJ   rK   _format_aux_input   s   
zOverflow._format_aux_input)	x_lengthsr   r   r   rS   c           
      C   s   dt j|dkddi}| ||}| j||d \}}| jj|||d |d |d d}| j|d	 dd
|d dd\}}}	| |dd
}|	||d t
|d |d< |S )a  Sampling from the model

        Args:
            text (torch.Tensor): :math:`[B, T_in]`
            aux_inputs (_type_, optional): _description_. Defaults to None.

        Returns:
            outputs: Dictionary containing the following
                - mel (torch.Tensor): :math:`[B, T_out, C]`
                - hmm_outputs_len (torch.Tensor): :math:`[B]`
                - state_travelled (List[List[int]]): List of lists containing the state travelled for each sample in the batch.
                - input_parameters (list[torch.FloatTensor]): Input parameters to the neural HMM.
                - output_parameters (list[torch.FloatTensor]): Output parameters to the neural HMM.
        r   r   r1   dimr   r   r   r   hmm_outputsrb   hmm_outputs_lenT)reverse)model_outputsmodel_outputs_lenrd   )rD   r~   r   r:   	inferencer;   rB   rg   ra   r   r	   
double_pad)
rF   rS   r   r   rh   ri   rn   rU   mel_outputs_len_rJ   rJ   rK   r      s$   zOverflow.inferencec                   C   s   t  S rY   )NLLLossrJ   rJ   rJ   rK   get_criterion   s   zOverflow.get_criterionTsamplesc                 C   s@   ddl m} || |}t| \}}t| |}t||||S )a8  Initiate model from config

        Args:
            config (VitsConfig): Model config.
            samples (Union[List[List], List[Dict]]): Training samples to parse speaker ids for training.
                Defaults to None.
            verbose (bool): If True, print init messages. Defaults to True.
        r   )r   )TTS.utils.audior   init_from_configr   r   r   )r   r   verboser   r   r   
new_configr   rJ   rJ   rK   r      s
   
zOverflow.init_from_configFcheckpoint_pathevalstrictc                 C   sH   t |tdd}| |d  |r |   | j  | jr"J d S d S )Ncpu)map_locationmodel)r   rD   deviceload_state_dictr   rB   store_inversetraining)rF   r   r   r   r   cachestaterJ   rJ   rK   load_checkpoint  s   

zOverflow.load_checkpointc                 C   s0  t j|jjr|jjrQ|jd|jdd}td|jj d t	
||jj|jj\}}}td|jj d|||f  | | | d}t||jj n)td	|jj d
 t|jj}|d |d |d }}}td|||f  t|r| n||jjd< t	|j| |j| dS )zIf the current dataset does not have normalisation statistics and initialisation transition_probability it computes them otherwise loads.NF)training_assetsr   r   z$ | > Data parameters not found for: z+. Computing mel normalization parameters...z  | > Saving data parameters to: z	: value: )r/   r0   init_transition_probz  | > Data parameters found for: z). Loading mel normalization parameters...r/   r0   r   z( | > Data parameters loaded with value: transition_p)ospathisfiler   rQ   force_generate_statisticsget_train_dataloadertrain_samplesprintr	   "get_data_parameters_for_flat_startr5   r8   rO   rD   saverP   	is_tensorr'   update_flat_start_transitionr   rN   )rF   trainer
dataloader	data_meandata_stdr   
statisticsrJ   rJ   rK   on_init_start  s>   


zOverflow.on_init_startc                 C   s  |d |d }}t j|d dd}t|d  ddd	t|d  d
dddt|d ddd	tt|d |d | jddt|d d ddd}td | j|d d 	dd|d d 	did}t|d d dd|d< dd |d d D }	dd |d d D }
t
t|
d d D ]}|d }|d d }t|	|| |
|| |d | < q||d d j  }|d!|ifS )"Nrd   re   rf   r1   r   r   zForward alignment)   r   )titlefig_sizezForward log alignmentT)r   plot_logr   zTransition vectors)      )r   r}   )	alignmentlog_alignmentre   mel_from_most_probable_state
mel_targetz) | > Synthesising audio from the model...r|   r   rp   )r   r   synthesisedc                 S   s   g | ]}|d  qS )r1   rJ   .0prJ   rJ   rK   
<listcomp>W  s    z)Overflow._create_logs.<locals>.<listcomp>input_parametersc                 S   s   g | ]
}|d     qS )rb   )r   numpyr   rJ   rJ   rK   r   X  s    output_parameters   z%synthesised_transition_probabilities/audios)rD   stackr   expr   r   rB   r   r   	unsqueezerangelenr   inv_melspectrogramTr   r   )rF   rx   rn   r   rd   re   rf   figuresinference_outputstates#transition_probability_synthesisingistartendaudiorJ   rJ   rK   _create_logs?  s6   $zOverflow._create_logsrn   loggerLoggerassetsstepsc                 C   s6   |  ||| j\}}||| |||| jj dS )zLog training progress.N)r   r   train_figurestrain_audiossample_rate)rF   rx   rn   r   r   r   r   r   rJ   rJ   rK   	train_logd  s   zOverflow.train_logc           
      C   sx   t |tr!|  D ]\}}|dd}|j||j  | q	| 	||| j
\}}	||| |||	| j
j dS )z#Compute and log evaluation metrics../N)
isinstancer   named_parametersreplacewriteradd_histogramrM   r   r   r   r   eval_figureseval_audiosr   )
rF   rx   rn   r   r   r   tagvaluer   r   rJ   rJ   rK   eval_logl  s   
zOverflow.eval_logreturnc                 C   s*   | ||d | jj |||d  d S )Nr1   r   )test_audiosr   r   test_figures)rF   rn   r   r   r   rJ   rJ   rK   test_log{  s   zOverflow.test_log)NNN)NT)FTF)(__name__
__module____qualname____doc__r   r3   r   rN   rW   rR   ra   ro   staticmethodrz   dictr   Moduler   r   r   rD   no_gradTensorr   r   r   r   r   r   strboolr   r   inference_moder   intr   r   r   __classcell__rJ   rJ   rH   rK   r      s    (4
(
&

(
$

r   c                   @   s$   e Zd ZdZdejdefddZdS )r   zNegative log likelihood loss.log_probr   c                 C   s   i }|   |d< |S )z{Compute the loss.

        Args:
            logits (Tensor): [B, T, D]

        Returns:
            Tensor: [1]

        loss)r/   )rF   r
  return_dictrJ   rJ   rK   ro     s   
zNLLLoss.forwardN)r   r   r   r   rD   r  r  ro   rJ   rJ   rJ   rK   r     s    r   )%r   typingr   r   r   rD   coqpitr   r   "trainer.logging.tensorboard_loggerr   %TTS.tts.layers.overflow.common_layersr   r	   TTS.tts.layers.overflow.decoderr
   "TTS.tts.layers.overflow.neural_hmmr   &TTS.tts.layers.overflow.plotting_utilsr   r   TTS.tts.models.base_ttsr   TTS.tts.utils.speakersr   TTS.tts.utils.text.tokenizerr   TTS.tts.utils.visualr   r   TTS.utils.generic_utilsr   TTS.utils.ior   r   r  r   rJ   rJ   rJ   rK   <module>   s(      l