o
    
jC                     @   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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)	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NeuralhmmTTSao
  Neural HMM TTS model.

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

    Paper abstract::
        Neural sequence-to-sequence TTS has achieved significantly better output quality
    than statistical speech synthesis using HMMs.However, neural TTS is generally not probabilistic
    and uses non-monotonic attention. Attention failures increase training time and can make
    synthesis babble incoherently. This paper describes how the old and new paradigms can be
    combined to obtain the advantages of both worlds, by replacing attention in neural TTS with
    an autoregressive left-right no-skip hidden Markov model defined by a neural network.
    Based on this proposal, we modify Tacotron 2 to obtain an HMM-based neural TTS model with
    monotonic alignment, trained to maximise the full sequence likelihood without approximation.
    We also describe how to combine ideas from classical and contemporary TTS for best results.
    The resulting example system is smaller and simpler than Tacotron 2, and learns to speak with
    fewer iterations and less data, whilst achieving comparable naturalness prior to the post-net.
    Our approach also allows easy control over speaking rate. Audio examples and code
    are available at https://shivammehta25.github.io/Neural-HMM/ .

    Note:
        - This is a parameter efficient version of OverFlow (15.3M vs 28.6M). Since it has half the
        number of parameters as OverFlow the synthesis output quality is suboptimal (but comparable to Tacotron2
        without Postnet), but it learns to speak with even lesser amount of data and is still significantly faster
        than other attention-based methods.

        - 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.neuralhmm_tts_config.NeuralhmmTTSConfig` for class arguments.
    NconfigNeuralhmmTTSConfigapAudioProcessor	tokenizerr   speaker_managerc                    s   t  |||| || _|D ]
}t| |||  qt|j|j|j| _t	| j
| j| j| 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meanr   std   )super__init__r   setattrr   	num_charsstate_per_phoneencoder_in_out_featuresencoderr
   out_channelsr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   
neural_hmmregister_buffertorchtensor)selfr   r   r   r   key	__class__ O/home/kuhnn/.local/lib/python3.10/site-packages/TTS/tts/models/neuralhmm_tts.pyr-   A   s.   zNeuralhmmTTS.__init__statistics_dictc                 C   s(   t |d | j_t |d | j_d S )Nr)   r*   )r6   r7   r)   datar*   )r8   r>   r<   r<   r=   update_mean_stde   s   zNeuralhmmTTS.update_mean_stdc                 C   sH   | j  dks| j dkrt| j}| | | |}||||fS )Nr   r+   )r)   itemr*   r6   loadmel_statistics_parameter_pathr@   	normalize)r8   texttext_lenmelsmel_lenr>   r<   r<   r=   preprocess_batchi   s
   

zNeuralhmmTTS.preprocess_batchc                 C      | | j| jS N)subr)   divr*   r8   xr<   r<   r=   rD   q      zNeuralhmmTTS.normalizec                 C   rJ   rK   )mulr*   addr)   rN   r<   r<   r=   inverse_normalizet   rP   zNeuralhmmTTS.inverse_normalizec                 C   sZ   |  ||||\}}}}| ||\}}| |||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]`
        r+      )	log_probs
alignmentstransition_vectorsmeans)rI   r2   r4   	transpose)r8   rE   rF   rG   rH   encoder_outputsencoder_output_lenrU   fwd_alignmentsrW   rX   outputsr<   r<   r=   forwardw   s   zNeuralhmmTTS.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statsr<   r<   r=   _training_stats   s   $$zNeuralhmmTTS._training_statsrg   	criterionc           	      C   sf   |d }|d }|d }|d }| j ||||d}||d | |   }|| | ||fS )N
text_inputr_   	mel_inputra   )rE   rF   rG   rH   rU   )r^   sumupdateri   )	r8   rg   rj   rk   r_   rl   ra   r]   	loss_dictr<   r<   r=   
train_step   s   zNeuralhmmTTS.train_stepc                 C   s   |  ||S rK   )rp   )r8   rg   rj   r<   r<   r=   	eval_step   s   zNeuralhmmTTS.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)copyrn   rt   ru   rv   r   )r8   rr   default_input_dictr<   r<   r=   _format_aux_input   s   
zNeuralhmmTTS._format_aux_input)	x_lengthsrt   ru   rv   rE   c           	      C   s   dt j|dkddi}| ||}| j||d \}}| jj|||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.
        rz   r   r+   dimrt   ru   rv   rs   hmm_outputshmm_outputs_len)model_outputsmodel_outputs_lenrV   )
r6   rm   ry   r2   	inferencer4   rS   rn   r	   
double_pad)	r8   rE   rr   rx   rZ   r[   r]   rG   mel_outputs_lenr<   r<   r=   r      s    
zNeuralhmmTTS.inferencec                   C   s   t  S rK   )NLLLossr<   r<   r<   r=   get_criterion   s   zNeuralhmmTTS.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   r<   r<   r=   r      s
   
zNeuralhmmTTS.init_from_configFcheckpoint_pathevalstrictc                 C   s>   t |tdd}| |d  |r|   | jrJ d S d S )Ncpu)map_locationmodel)r   r6   deviceload_state_dictr   training)r8   r   r   r   r   cachestater<   r<   r=   load_checkpoint   s   
zNeuralhmmTTS.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)   r*   init_transition_probz  | > Data parameters found for: z). Loading mel normalization parameters...r)   r*   r   z( | > Data parameters loaded with value: transition_p)ospathisfiler   rC   force_generate_statisticsget_train_dataloadertrain_samplesprintr	   "get_data_parameters_for_flat_startr3   r0   rA   r6   saverB   	is_tensorr&   update_flat_start_transitionr   r@   )r8   trainer
dataloader	data_meandata_stdr   
statisticsr<   r<   r=   on_init_start  s>   


zNeuralhmmTTS.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 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 )"NrV   rW   rX   r+   r{   r   zForward alignment)   r   )titlefig_sizezForward log alignmentT)r   plot_logr   zTransition vectors)      )r   rl   )	alignmentlog_alignmentrW   mel_from_most_probable_state
mel_targetz) | > Synthesising audio from the model...rk   rz   r_   )rr   r   synthesisedc                 S   s   g | ]}|d  qS )r+   r<   .0pr<   r<   r=   
<listcomp>G  s    z-NeuralhmmTTS._create_logs.<locals>.<listcomp>input_parametersc                 S   s   g | ]
}|d     qS )rT   )r   numpyr   r<   r<   r=   r   H  s    output_parameters   z%synthesised_transition_probabilities/audios)r6   stackr   expr   r   r   r   	unsqueezerangelenr   inv_melspectrogramTr   r   )r8   rg   r]   r   rV   rW   rX   figuresinference_outputstates#transition_probability_synthesisingistartendaudior<   r<   r=   _create_logs/  s6   $zNeuralhmmTTS._create_logsr]   loggerLoggerassetsstepsc                 C   s6   |  ||| j\}}||| |||| jj dS )zLog training progress.N)r   r   train_figurestrain_audiossample_rate)r8   rg   r]   r   r   r   r   r   r<   r<   r=   	train_logT  s   zNeuralhmmTTS.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_histogramr?   r   r   r   r   eval_figureseval_audiosr   )
r8   rg   r]   r   r   r   tagvaluer   r   r<   r<   r=   eval_log\  s   
zNeuralhmmTTS.eval_logreturnc                 C   s*   | ||d | jj |||d  d S )Nr+   r   )test_audiosr   r   test_figures)r8   r]   r   r   r   r<   r<   r=   test_logk  s   zNeuralhmmTTS.test_log)NNN)NT)FTF)(__name__
__module____qualname____doc__r   r-   r   r@   rI   rD   rS   r^   staticmethodri   dictr   Modulerp   rq   ry   r6   no_gradTensorr   r   r   r   r   r   strboolr   r   inference_moder   intr   r   r   __classcell__r<   r<   r:   r=   r      s    ,$
&
&
	(
$

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)   )r8   r   return_dictr<   r<   r=   r^   u  s   
zNLLLoss.forwardN)r   r   r   r   r6   r   r   r^   r<   r<   r<   r=   r   r  s    r   )#r   typingr   r   r   r6   coqpitr   r   "trainer.logging.tensorboard_loggerr   %TTS.tts.layers.overflow.common_layersr   r	   "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   r<   r<   r<   r=   <module>   s&      ]