o
    
jM                     @   s  d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlZd dlm	  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mZ d d	lmZ d d
lmZ d dlmZ d dlmZ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, dd Z-d0ddZ.					d1ddZ/d2d d!Z0d3d"d#Z1		d4d$d%Z2d&d' Z3d(d) Z4eG d*d+ d+eZ5eG d,d- d-eZ6G d.d/ d/e,Z7dS )5    N)contextmanager)	dataclass)time)Coqpit)tqdm)TorchMelSpectrogram)denormalize_tacotron_mel
load_voicewav_to_univnet_mel)UnifiedVoice)"AudioMiniEncoderWithClassifierHead)CLVP)SpacedDiffusionget_named_beta_schedulespace_timesteps)DiffusionTts)RandomLatentConverter)VoiceBpeTokenizer)VocConfVocType)Wav2VecAlignment)BaseTTSc                 C   sR   | dd|f }| j d |kr| }|S | j d |k r't| d|| j d  f}|S )z
    Utility function for forcing <t> to have the specified sequence length, whether by clipping it or padding it with 0s.
    .Nr   )shapeFpad)tlengthtp r   J/home/kuhnn/.local/lib/python3.10/site-packages/TTS/tts/models/tortoise.pypad_or_truncate   s   r!   c                 C   s.   | du r	t t n| } t|  t|  | S )z
    Sets the random seeds that tortoise uses to the current time() and returns that seed so results can be
    reproduced.
    N)intr   torchmanual_seedrandomseedr&   r   r   r    deterministic_state'   s   

r(        T   ddimc              
   C   s&   t t| |gdddtd| |||dS )z_
    Helper function to load a GaussianDiffusion instance configured for use as a vocoder.
    epsilonlearned_rangemselinear)use_timestepsmodel_mean_typemodel_var_type	loss_typebetasconditioning_freeconditioning_free_ksampler)r   r   r   )trained_diffusion_stepsdesired_diffusion_steps	cond_freecond_free_kr8   r   r   r    load_discrete_vocoder_diffuser5   s   

r=    cudac                 K   s   | j d | }|dk rtj| dt|fd} n|dkr-td|}| dd||| f } tdi || dd}|d	|S )zm
    Converts the given conditioning signal to a MEL spectrogram and clips it as expected by the models.
    r   r   )r   Nr   )
r   r   r   absr%   randintr   	unsqueezesqueezeto)clipcond_lengthdevicekwargsgap
rand_startmel_clipr   r   r    format_conditioningK   s   rL   c                 C   sv   | |k  }t|dkr|rtd | S d| |< |  }d| |d< |d | jd k r9d| d< d| d< d	| d
< | S )a]  
    This function performs some padding on coded audio that fixes a mismatch issue between what the diffusion model was
    trained on and what the autoregressive code generator creates (which has no padding or end).
    This is highly specific to the DVAE being used, so this particular coding will not necessarily work if used with
    a different DVAE. This can be inferred by feeding a audio clip padded with lots of zeros on the end through the DVAE
    and copying out the last few codes.

    Failing to do this padding will produce speech with a harsh end that sounds like "BLAH" or similar.
    r   zNo stop tokens found in one of the generated voice clips. This typically means the spoken audio is too long. In some cases, the output will still be good, though. Listen to it and if it is missing words, try breaking up your input text.S   N   -      r   )nonzerolenprintminitemr   )codes
stop_tokencomplainstop_token_indicesstmr   r   r    fix_autoregressive_outputY   s   r]   c                 C   s   t  H |jd d d d }|jd d|f}| |||d}t j||jd| }	|j| ||	d	|i|d
}
t|
ddddd|f W  d   S 1 sOw   Y  dS )zZ
    Uses the specified diffusion model to convert discrete codes into a spectrogram.
    r+      ]  "V  r   d   FrG   precomputed_aligned_embeddings)noisemodel_kwargsprogressN)r#   no_gradr   timestep_independentrandnrG   sample_loopr   )diffusion_modeldiffuserlatentsconditioning_latentstemperatureverboseoutput_seq_lenoutput_shapeprecomputed_embeddingsrd   melr   r   r    do_spectrogram_diffusionw   s"   
$ru   c                 C   sp   t ddddddddddddd	}|tjtj|d
tdd |  	d} t
j|| dd}|d d S )a#  
    Returns whether or not Tortoises' classifier thinks the given clip came from Tortoise.
    :param clip: torch tensor containing audio waveform data (get it from load_audio)
    :return: True if the clip was classified as coming from Tortoise and false if it was classified as real.
       r+   i      r^       r   F)spec_dimembedding_dimdepthdownsample_factorresnet_blocksattn_blocksnum_attn_headsbase_channelsdropoutkernel_sizedistribute_zero_labelzclassifier.pthcpumap_locationr   dim)r   load_state_dictr#   loadospathjoinrG   r   rB   r   softmax)rE   	model_dir
classifierresultsr   r   r    classify_audio_clip   s$   $r   c                  C   sT   t j r(t j \} }|d }d}|dkrd}|S |dkr"d}|S |dkr(d}|S )	z
    Tries to pick a batch size that will fit in your GPU. These sizes aren't guaranteed to work, but they should give
    you a good shot.
    i   @r+         
         r^   )r#   r?   is_availablemem_get_info)_	availableavailableGb
batch_sizer   r   r    pick_best_batch_size_for_gpu   s   
r   c                   @   s2   e Zd ZU dZeed< dZeed< dZeed< dS )TortoiseAudioConfigr`   sample_rater_   diffusion_sample_rateoutput_sample_rateN)__name__
__module____qualname__r   r"   __annotations__r   r   r   r   r   r    r      s   
 r   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< dZeed< ej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< 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$< 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.< d*Z(eed/< d0Z)eed1< d0Z*eed2< d0Z+eed3< d4Z,eed5< d6Z-eed7< d8Z.eed9< d:Z/eed;< d<Z0eed=< d6Z1eed>< d:Z2eed?< d@Z3eedA< dZ4eedB< dCZ5eedD< d	S )ETortoiseArgsa  A dataclass to represent Tortoise model arguments that define the model structure.

    Args:
        autoregressive_batch_size (int): The size of the auto-regressive batch.
        enable_redaction (bool, optional): Whether to enable redaction. Defaults to True.
        high_vram (bool, optional): Whether to use high VRAM. Defaults to False.
        kv_cache (bool, optional): Whether to use the kv_cache. Defaults to True.
        ar_checkpoint (str, optional): The checkpoint for the autoregressive model. Defaults to None.
        clvp_checkpoint (str, optional): The checkpoint for the ConditionalLatentVariablePerseq model. Defaults to None.
        diff_checkpoint (str, optional): The checkpoint for the DiffTTS model. Defaults to None.
        num_chars (int, optional): The maximum number of characters to generate. Defaults to 255.
        vocoder (VocType, optional): The vocoder to use for synthesis. Defaults to VocConf.Univnet.

        For UnifiedVoice model:
        ar_max_mel_tokens (int, optional): The maximum mel tokens for the autoregressive model. Defaults to 604.
        ar_max_text_tokens (int, optional): The maximum text tokens for the autoregressive model. Defaults to 402.
        ar_max_conditioning_inputs (int, optional): The maximum conditioning inputs for the autoregressive model. Defaults to 2.
        ar_layers (int, optional): The number of layers for the autoregressive model. Defaults to 30.
        ar_model_dim (int, optional): The model dimension for the autoregressive model. Defaults to 1024.
        ar_heads (int, optional): The number of heads for the autoregressive model. Defaults to 16.
        ar_number_text_tokens (int, optional): The number of text tokens for the autoregressive model. Defaults to 255.
        ar_start_text_token (int, optional): The start text token for the autoregressive model. Defaults to 255.
        ar_checkpointing (bool, optional): Whether to use checkpointing for the autoregressive model. Defaults to False.
        ar_train_solo_embeddings (bool, optional): Whether to train embeddings for the autoregressive model. Defaults to False.

        For DiffTTS model:
        diff_model_channels (int, optional): The number of channels for the DiffTTS model. Defaults to 1024.
        diff_num_layers (int, optional): The number of layers for the DiffTTS model. Defaults to 10.
        diff_in_channels (int, optional): The input channels for the DiffTTS model. Defaults to 100.
        diff_out_channels (int, optional): The output channels for the DiffTTS model. Defaults to 200.
        diff_in_latent_channels (int, optional): The input latent channels for the DiffTTS model. Defaults to 1024.
        diff_in_tokens (int, optional): The input tokens for the DiffTTS model. Defaults to 8193.
        diff_dropout (int, optional): The dropout percentage for the DiffTTS model. Defaults to 0.
        diff_use_fp16 (bool, optional): Whether to use fp16 for the DiffTTS model. Defaults to False.
        diff_num_heads (int, optional): The number of heads for the DiffTTS model. Defaults to 16.
        diff_layer_drop (int, optional): The layer dropout percentage for the DiffTTS model. Defaults to 0.
        diff_unconditioned_percentage (int, optional): The percentage of unconditioned inputs for the DiffTTS model. Defaults to 0.

        For ConditionalLatentVariablePerseq model:
        clvp_dim_text (int): The dimension of the text input for the CLVP module. Defaults to 768.
        clvp_dim_speech (int): The dimension of the speech input for the CLVP module. Defaults to 768.
        clvp_dim_latent (int): The dimension of the latent representation for the CLVP module. Defaults to 768.
        clvp_num_text_tokens (int): The number of text tokens used by the CLVP module. Defaults to 256.
        clvp_text_enc_depth (int): The depth of the text encoder in the CLVP module. Defaults to 20.
        clvp_text_seq_len (int): The maximum sequence length of the text input for the CLVP module. Defaults to 350.
        clvp_text_heads (int): The number of attention heads used by the text encoder in the CLVP module. Defaults to 12.
        clvp_num_speech_tokens (int): The number of speech tokens used by the CLVP module. Defaults to 8192.
        clvp_speech_enc_depth (int): The depth of the speech encoder in the CLVP module. Defaults to 20.
        clvp_speech_heads (int): The number of attention heads used by the speech encoder in the CLVP module. Defaults to 12.
        clvp_speech_seq_len (int): The maximum sequence length of the speech input for the CLVP module. Defaults to 430.
        clvp_use_xformers (bool): A flag indicating whether the model uses transformers in the CLVP module. Defaults to True.
        duration_const (int): A constant value used in the model. Defaults to 102400.
    r+   autoregressive_batch_sizeFenable_redaction	high_vramTkv_cacheNar_checkpointclvp_checkpointdiff_checkpoint   	num_charsvocoderi\  ar_max_mel_tokensi  ar_max_text_tokensrv   ar_max_conditioning_inputs   	ar_layers   ar_model_dimr   ar_headsar_number_text_tokensar_start_text_tokenar_checkpointingar_train_solo_embeddingsdiff_model_channelsr   diff_num_layersra   diff_in_channelsr*   diff_out_channelsdiff_in_latent_channelsi   diff_in_tokensr   diff_dropoutdiff_use_fp16diff_num_headsdiff_layer_dropdiff_unconditioned_percentagei   clvp_dim_textclvp_dim_speechclvp_dim_latent   clvp_num_text_tokens   clvp_text_enc_depthi^  clvp_text_seq_len   clvp_text_headsi    clvp_num_speech_tokensclvp_speech_enc_depthclvp_speech_headsi  clvp_speech_seq_lenclvp_use_xformersi  duration_const)6r   r   r   __doc__r   r"   r   r   boolr   r   r   strr   r   r   r   Univnetr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r      sZ   
 6r   c                       s   e Zd ZdZdef fddZedd Z			d*d	d
Zdd Z	d+ddZ
dd Z																				d,ddZdd  Zd!d" Zed-d$d%Z						d.d&d'Zd(d) Z  ZS )/Tortoisea  Tortoise model class.

    Currently only supports inference.

    Examples:
        >>> from TTS.tts.configs.tortoise_config import TortoiseConfig
        >>> from TTS.tts.models.tortoise import Tortoise
        >>> config = TortoiseConfig()
        >>> model = Tortoise.inif_from_config(config)
        >>> model.load_checkpoint(config, checkpoint_dir="paths/to/models_dir/", eval=True)
    configc                    s  t  j|d d d d | _|| _| jj| _| jj| _|j| _| jj	d u r&t
 n| jj	| _	| jj| _ttj r9dnd| _| jrDt | _t | _t| jj| jj| jj| 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j'| jj(| jj)| jj*| jj+| jj,d | _-t.| jj/| jj0| jj1| jj2| jj3| jj4| jj5| jj6| jj7| jj8| jj9| jj:d | _;| jj<j=>  | _<d | _?d | _@| jjAr| j B| j| _ | j-B| j| _-| j;B| j| _;| j<B| j| _<| jjA| _Ad S )N)ap	tokenizerr?   r   )
max_mel_tokensmax_text_tokensmax_conditioning_inputslayers	model_dimheadsnumber_text_tokensstart_text_tokencheckpointingtrain_solo_embeddings)model_channels
num_layersin_channelsout_channelsin_latent_channels	in_tokensr   use_fp16	num_heads
layer_dropunconditioned_percentage)dim_text
dim_speech
dim_latentnum_text_tokenstext_enc_depthtext_seq_len
text_headsnum_speech_tokensspeech_enc_depthspeech_headsspeech_seq_lenuse_xformers)Csuper__init__mel_norm_pathr   argsr   r   r   
models_dirr   r   r   r#   rG   r?   r   r   alignerr   r   r   r   r   r   r   r   r   r   r   r   r   r   autoregressiver   r   r   r   r   r   r   r   r   r   r   r   	diffusionr   r   r   r   r   r   r   r   r   r   r   r   r   clvpr   valueconstructorrlg_autorlg_diffusionr   rD   )selfr   	__class__r   r    r  B  s   


zTortoise.__init__c                 c   s0    | j r	|V  d S || j}|V  | }d S N)r   rD   rG   r   )r  modelmr   r   r    temporary_cuda  s   
zTortoise.temporary_cudaFr   c              	      s>  |dv sJ dt    fdd|D }g }|D ]}|t|d  j jd qt j|dd}  j}|	|}W d	   n1 sHw   Y  g }	 j
j}
|D ]}|rctj|d d
dn|d }|dkrt||
}t| jd jd}|	| qUddlm} |dkrg }t||jd |
 D ]6}|d	d	||
 |d |
 f }t||
}t| jd jd}|dkr|	| q|dkr|| q|dkr|	t |d qUt j|	dd}	  j}|	|	}W d	   n1 sw   Y  W d	   n	1 sw   Y  |r||||	fS ||fS )aU  
        Transforms one or more voice_samples into a tuple (autoregressive_conditioning_latent, diffusion_conditioning_latent).
        These are expressive learned latents that encode aspects of the provided clips like voice, intonation, and acoustic
        properties.
        :param voice_samples: List of arbitrary reference clips, which should be *pairs* of torch tensors containing arbitrary kHz waveform data.
        :param latent_averaging_mode: 0/1/2 for following modes:
            0 - latents will be generated as in original tortoise, using ~4.27s from each voice sample, averaging latent across all samples
            1 - latents will be generated using (almost) entire voice samples, averaged across all the ~4.27s chunks
            2 - latents will be generated using (almost) entire voice samples, averaged per voice sample
        )r   r+   rv   z0latent_averaging mode has to be one of (0, 1, 2)c                    s   g | ]} fd d|D qS )c                    s   g | ]}|  jqS r   )rD   rG   ).0vr  r   r    
<listcomp>  s    z@Tortoise.get_conditioning_latents.<locals>.<listcomp>.<listcomp>r   )r  lsr  r   r    r    s    z5Tortoise.get_conditioning_latents.<locals>.<listcomp>r   )rG   mel_norm_filer+   r   Nr`   r_   F)do_normalizationrG   )ceilrv   )r#   rg   appendrL   rG   r  stackr  r  get_conditioningr  r   
torchaudio
functionalresampler!   r
   rD   mathr  ranger   meanr  )r  voice_samplesreturn_melslatent_averaging_modeoriginal_tortoise
auto_condsr  arauto_latentdiffusion_conds
DURS_CONSTsamplecond_melr  temp_diffusion_condschunkcurrent_sampler  diffusion_latentr   r  r    get_conditioning_latents  sh   

 

 


0z!Tortoise.get_conditioning_latentsc                 C   s   | j d u r;td | _ | j tjtj| j	dt
dd td | _| jtjtj| j	dt
dd t  |  tdg| tdgfW  d    S 1 s\w   Y  d S )Nr   zrlg_auto.pthr   r   i   zrlg_diffuser.pthg        )r  r   evalr   r#   r   r   r   r   r  rG   r  rg   tensorr  r   r   r    get_random_conditioning_latents  s$   

"$z(Tortoise.get_random_conditioning_latentsr%   Nc           
      K   s|   |du rdn|}|dur|g}t ||\}}nt |\}}| j||f||d|}|d |d |d |d |d d	}	|	S )
a  Synthesize speech with the given input text.

        Args:
            text (str): Input text.
            config (TortoiseConfig): Config with inference parameters.
            speaker_id (str): One of the available speaker names. If `random`, it generates a random speaker.
            voice_dirs (List[str]): List of paths that host reference audio files for speakers. Defaults to None.
            **kwargs: Inference settings. See `inference()`.

        Returns:
            A dictionary of the output values with `wav` as output waveform, `deterministic_seed` as seed used at inference,
            `text_input` as text token IDs after tokenizer, `voice_samples` as samples used for cloning, `conditioning_latents`
            as latents used at inference.

        Nr%   )r&  rn   wavdeterministic_seedtextr&  rn   )r9  r:  text_inputsr&  rn   )r	   inference_with_config)
r  r;  r   
speaker_id
voice_dirsrH   r&  rn   outputsreturn_dictr   r   r    
synthesize  s&   zTortoise.synthesizec              
   K   s   |j |j|j|j|j|j|jd}dddddddddddd	d
ddddddddddddddddd}d|v rK|||d   |d || | j	|fi |S )zH
        inference with config
        #TODO describe in detail
        )ro   length_penaltyrepetition_penaltytop_pr<   diffusion_temperaturer8   r   r   r,   )num_autoregressive_samplesdiffusion_iterationsr8   r   r   F)rG  rH  r;   rx   zdpm++2mrw   2   `   P   )rG  rH  r*   r     )single_sample
ultra_fastultra_fast_old	very_fastfastfast_oldstandardhigh_qualitypreset)
ro   rC  rD  rE  r<   rF  r8   updatepop	inference)r  r;  r   rH   settingspresetsr   r   r    r=    sR   $

zTortoise.inference_with_configr+   Tr   皙?       @  ra   rv         ?r,   c           7         s  t |d}tjdj}t	|d}|j
d dk s&J d|dur8j|d||d	\}}}}n|durA|\}}n \}}|j}|j}t||||d
}j}|	j ro jd  _|	j sct  g }|	j }jj} d}!jj_|rtd jV}"tjdtj|d= tt|| dD ]+}#|"j||fd||
j|||d|}$||$j
d  }%tj	|$d|%f| d}$||$ qW d   n1 sw   Y  W d   n1 sw   Y  |_g }&jl}'tjdtj|dR t|| dD ]*}(t|(j
d D ]})t|(|) | |(|)< q|'||(j
d d|(dd}*|&|* qtj|&dd}&tj|dd}|tj|&|dj }+W d   n	1 s_w   Y  W d   n	1 sow   Y  ~j3}"|"||d||dtj |j
d g|jd|+tj |+j
d jj! g|jdddd},W d   n	1 sw   Y  ~|rtd g }-t|+j
d D ]}#|+|# d}$|,|# d}.d}/t|$j
d D ]$}0|$d|0f |!kr|/d7 }/nd}/|/dkr|.ddd|0f }. nqj"}1t#|1||.|||d}2W d   n	1 s"w   Y  j$}3|3%|2}4|-|4&  W d   n	1 sEw   Y  qȇfdd  fdd |-D }-t'|-dkrf|-}5n|-d }5W d   n	1 suw   Y  |5ddddd!}6|r|5|||d!}6|6S )"a  
        This function produces an audio clip of the given text being spoken with the given reference voice.

        Args:
            text: (str) Text to be spoken.
            voice_samples: (List[Tuple[torch.Tensor]]) List of an arbitrary number of reference clips, which should be tuple-pairs
                of torch tensors containing arbitrary kHz waveform data.
            conditioning_latents: (Tuple[autoregressive_conditioning_latent, diffusion_conditioning_latent]) A tuple of
                (autoregressive_conditioning_latent, diffusion_conditioning_latent), which can be provided in lieu
                of voice_samples. This is ignored unless `voice_samples=None`. Conditioning latents can be retrieved
                via `get_conditioning_latents()`.
            k: (int) The number of returned clips. The most likely (as determined by Tortoises' CLVP model) clips are returned.
                latent_averaging_mode: (int) 0/1/2 for following modes:
                0 - latents will be generated as in original tortoise, using ~4.27s from each voice sample, averaging latent across all samples
                1 - latents will be generated using (almost) entire voice samples, averaged across all the ~4.27s chunks
                2 - latents will be generated using (almost) entire voice samples, averaged per voice sample
            verbose: (bool) Whether or not to print log messages indicating the progress of creating a clip. Default=true.
            num_autoregressive_samples: (int) Number of samples taken from the autoregressive model, all of which are filtered using CLVP.
                As Tortoise is a probabilistic model, more samples means a higher probability of creating something "great".
            temperature: (float) The softmax temperature of the autoregressive model.
            length_penalty: (float) A length penalty applied to the autoregressive decoder. Higher settings causes the model to produce more terse outputs.
            repetition_penalty: (float) A penalty that prevents the autoregressive decoder from repeating itself during decoding. Can be used to reduce
                the incidence of long silences or "uhhhhhhs", etc.
            top_p: (float) P value used in nucleus sampling. (0,1]. Lower values mean the decoder produces more "likely" (aka boring) outputs.
            max_mel_tokens: (int) Restricts the output length. (0,600] integer. Each unit is 1/20 of a second.
            typical_sampling: (bool) Turns typical sampling on or off. This sampling mode is discussed in this paper: https://arxiv.org/abs/2202.00666
                I was interested in the premise, but the results were not as good as I was hoping. This is off by default, but could use some tuning.
            typical_mass: (float) The typical_mass parameter from the typical_sampling algorithm.
            diffusion_iterations: (int) Number of diffusion steps to perform. [0,4000]. More steps means the network has more chances to iteratively
                refine the output, which should theoretically mean a higher quality output. Generally a value above 250 is not noticeably better, however.
            cond_free: (bool) Whether or not to perform conditioning-free diffusion. Conditioning-free diffusion performs two forward passes for
                each diffusion step: one with the outputs of the autoregressive model and one with no conditioning priors. The output of the two
                is blended according to the cond_free_k value below. Conditioning-free diffusion is the real deal, and dramatically improves realism.
            cond_free_k: (float) Knob that determines how to balance the conditioning free signal with the conditioning-present signal. [0,inf].
                As cond_free_k increases, the output becomes dominated by the conditioning-free signal.
            diffusion_temperature: (float) Controls the variance of the noise fed into the diffusion model. [0,1]. Values at 0
                                      are the "mean" prediction of the diffusion network and will sound bland and smeared.
            hf_generate_kwargs: (**kwargs) The huggingface Transformers generate API is used for the autoregressive transformer.
                                    Extra keyword args fed to this function get forwarded directly to that API. Documentation
                                    here: https://huggingface.co/docs/transformers/internal/generation_utils

        Returns:
            Generated audio clip(s) as a torch tensor. Shape 1,S if k=1 else, (k,1,S) where S is the sample length.
            Sample rate is 24kHz.
        r'   r   )r   r+   r   rL  zVToo much text provided. Break the text up into separate segments and re-try inference.NT)r'  r(  r)  )r:   r;   r<   r8   rv   rM   z#Generating autoregressive samples..r?   )device_typedtypeenabled)disable)	do_samplerE  ro   num_return_sequencesrC  rD  max_generate_lengthr+   )r
  F)return_lossr   )krb   )return_latentclip_inputsz0Transforming autoregressive outputs into audio..r   )ro   rp   c                    s$    j r j| d|dS | S )Nr+   )r   r  redactrC   rB   )rE   r;  r  r   r    potentially_redact&  s   z.Tortoise.inference.<locals>.potentially_redactc                    s   g | ]} |qS r   r   )r  wav_candidate)rk  r;  r   r    r  +  s    z&Tortoise.inference.<locals>.<listcomp>)r9  r:  r;  r&  rn   )(r(   r#   	IntTensorr   encoderB   rD   rG   r   r   r   r5  r8  r=   r   rg   r  stop_mel_tokenrU   r  autocastfloat16r   r$  inference_speechr  r	  r]   repeatcattopkindicesr7  mel_length_compressionr  ru   r   rX  r   rT   )7r  r;  r&  rn   rg  rp   use_deterministic_seedreturn_deterministic_stater(  rG  ro   rC  rD  rE  r   rH  r;   r<   rF  r8   halfr)  hf_generate_kwargsr:  text_tokensauto_conditioningdiffusion_conditioningr   rl   orig_batch_sizesamplesnum_batchesro  
calm_tokenr  brX   padding_neededclip_resultsr	  batchiclvp_resbest_resultsbest_latentswav_candidatesrm   ctokenscoder  rt   r   r9  resrA  r   )rk  r  r;  r    rX  V  s4  
H 




  



	
ozTortoise.inferencec                 C      t dNz$Tortoise Training is not implementedNotImplementedErrorr  r   r   r    forwardC     zTortoise.forwardc                 C   r  r  r  r  r   r   r    	eval_stepF  r  zTortoise.eval_stepTortoiseConfigc                 K   s   t | S r  )r   )r   rH   r   r   r    init_from_configI  s   zTortoise.init_from_configc	              	   K   sT  | j du r|| _ |ptj|d}
|ptj|d}|p"tj|d}|p+tj|d}tj|d| _tj|
rLtj|
tdd}| j	j
|d	d
 tj|r]| jj
t||d
 tj|rn| jj
t||d
 tj|r| j
|jjjtj|tdd |r| j	| jj | j	  | j  | j  | j  dS dS )a  Load a model checkpoints from a directory. This model is with multiple checkpoint files and it
        expects to have all the files to be under the given `checkpoint_dir` with the rigth names.
        If eval is True, set the model to eval mode.

        Args:
            config (TortoiseConfig): The model config.
            checkpoint_dir (str): The directory where the checkpoints are stored.
            ar_checkpoint_path (str, optional): The path to the autoregressive checkpoint. Defaults to None.
            diff_checkpoint_path (str, optional): The path to the diffusion checkpoint. Defaults to None.
            clvp_checkpoint_path (str, optional): The path to the CLVP checkpoint. Defaults to None.
            vocoder_checkpoint_path (str, optional): The path to the vocoder checkpoint. Defaults to None.
            eval (bool, optional): Whether to set the model to eval mode. Defaults to False.
            strict (bool, optional): Whether to load the model strictly. Defaults to True.
        Nzautoregressive.pthzdiffusion_decoder.pthz	clvp2.pthzvocoder.pthzmel_norms.pthr   r   F)strict)r  r   r   r   r  existsr#   r   rG   r  r   r  r	  r   
model_argsr
  optionally_indexpost_init_gpt2_configr  r   r6  )r  r   checkpoint_dirar_checkpoint_pathdiff_checkpoint_pathclvp_checkpoint_pathvocoder_checkpoint_pathr6  r  rH   ar_path	diff_path	clvp_path
checkpointr   r   r    load_checkpointM  s<   

	


zTortoise.load_checkpointc                 C   r  r  r  r  r   r   r    
train_step  r  zTortoise.train_step)Fr   F)r%   N)NNr+   TNFr   r   r[  r+   r\  r[  r]  ra   Trv   r^  r,   TF)r   r  )NNNNFT)r   r   r   r   r   r  r   r  r5  r8  rB  r=  rX  r  r  staticmethodr  r  r  __classcell__r   r   r  r    r   5  s\    J

K
(=
 n
Ar   r  )r)   r*   Tr+   r,   )r>   r?   )T)r+   T)8r   r%   
contextlibr   dataclassesr   r   r#   torch.nn.functionalnnr!  r   r   coqpitr   r   "TTS.tts.layers.tortoise.arch_utilsr   #TTS.tts.layers.tortoise.audio_utilsr   r	   r
   &TTS.tts.layers.tortoise.autoregressiver   "TTS.tts.layers.tortoise.classifierr   TTS.tts.layers.tortoise.clvpr   !TTS.tts.layers.tortoise.diffusionr   r   r   )TTS.tts.layers.tortoise.diffusion_decoderr   /TTS.tts.layers.tortoise.random_latent_generatorr   !TTS.tts.layers.tortoise.tokenizerr   TTS.tts.layers.tortoise.vocoderr   r   )TTS.tts.layers.tortoise.wav2vec_alignmentr   TTS.tts.models.base_ttsr   r!   r(   r=   rL   r]   ru   r   r   r   r   r   r   r   r   r    <module>   sT    



#
k