o
    :is                  %   @   s  d Z ddlZddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlZddlZ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mZ dd	lmZ dd
lmZmZ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(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0 dZ1dddZ2dd Z3dAde
e4 fddZ5							dBde4de4d e4d!e4d"ej6j7d#ej6j7d$ed%e&d&ej8d'e9d(e:d)e:d*e:d+e:d,e:d-e9f d.d/Z;								0	1dCde4de4d e4d!e4d"ej6j7d#ej6j7d$ed%e&d&ej8d'e9d(e:d)e:d*e:d+e:d,e:d-e9d2e:d3e<f$d4d5Z=								1	0	1dDd6e4d7e4d"ej6j7d#ej6j7d$ed%e&d&ej8d'e9d(e:d)e:d*e:d+e:d,e:d-e9d8e<d2e:d3e<f"d9d:Z>e? d;d< Z@eAd=kr[d>ZBejCeBejDd?d@ e@  dS dS )Ea  
This script generates speech with our pre-trained ZipVoice or
    ZipVoice-Distill models. If no local model is specified,
    Required files will be automatically downloaded from HuggingFace.

Usage:

Note: If you having trouble connecting to HuggingFace,
    try switching endpoint to mirror site:
export HF_ENDPOINT=https://hf-mirror.com

(1) Inference of a single sentence:

python3 -m zipvoice.bin.infer_zipvoice     --model-name zipvoice     --prompt-wav prompt.wav     --prompt-text "I am a prompt."     --text "I am a sentence."     --res-wav-path result.wav

(2) Inference of a list of sentences:

python3 -m zipvoice.bin.infer_zipvoice     --model-name zipvoice     --test-list test.tsv     --res-dir results

`--model-name` can be `zipvoice` or `zipvoice_distill`,
    which are the models before and after distillation, respectively.

Each line of `test.tsv` is in the format of
    `{wav_name}	{prompt_transcription}	{prompt_wav}	{text}`.


(3) Inference with TensorRT:

python3 -m zipvoice.bin.infer_zipvoice     --model-name zipvoice_distill     --prompt-wav prompt.wav     --prompt-text "I am a prompt."     --text "I am a sentence."     --res-wav-path result.wav     --trt-engine-path models/zipvoice_distill_onnx_trt/fm_decoder.fp16.plan
    N)Path)Optional)hf_hub_download)fix_random_seed)Vocos)ZipVoice)ZipVoiceDistill)EmiliaTokenizerEspeakTokenizerLibriTTSTokenizerSimpleTokenizer)load_checkpoint)AttributeDictstr2bool)
VocosFbank)add_punctuationbatchify_tokenschunk_tokens_punctuationcross_fade_concatload_prompt_wavremove_silencerms_norm)load_trtzk2-fsa/ZipVoicezipvoicezipvoice_distillr   r   c                  C   s  t jt jd} | jdtdddgdd | jdtd dd	 | jd
tddd	 | jdtd dd	 | jdtdg ddd | jdtddd	 | jdtd dd	 | jdtd dd	 | jdtd dd	 | jdtd dd	 | jdtdd d	 | jd!td"d#d	 | jd$td d%d	 | jd&td d'd	 | jd(td)d*d	 | jd+td,d-d	 | jd.td/d0d	 | jd1td)d2d	 | jd3td4d5d	 | jd6td7d8d	 | jd9td:d;d	 | jd<td=d>d	 | jd?td:d@d	 | jdAtd dBd	 | S )CN)formatter_classz--model-namer   r   zThe model used for inference)typedefaultchoiceshelpz--model-dirzThe model directory that contains model checkpoint, configuration file model.json, and tokens file tokens.txt. Will download pre-trained checkpoint from huggingface if not specified.)r   r   r    z--checkpoint-namezmodel.ptzThe name of model checkpoint.z--vocoder-pathz\The vocoder checkpoint. Will download pre-trained vocoder from huggingface if not specified.z--tokenizeremilia)r!   librittsespeaksimplezTokenizer type.z--langzen-usz~Language identifier, used when tokenizer type is espeak. seehttps://github.com/rhasspy/espeak-ng/blob/master/docs/languages.mdz--test-listzThe list of prompt speech, prompt_transcription, and text to synthesizein the format of '{wav_name}	{prompt_transcription}	{prompt_wav}	{text}'.z--prompt-wavzThe prompt wav to mimicz--prompt-textz#The transcription of the prompt wavz--textzThe text to synthesizez	--res-dirresultsz^
        Path name of the generated wavs dir,
        used when test-list is not None
        z--res-wav-pathz
result.wavzZ
        Path name of the generated wav path,
        used when test-list is None
        z--guidance-scalez7The scale of classifier-free guidance during inference.z
--num-stepzThe number of sampling steps.z--feat-scale皙?z!The scale factor of fbank featurez--speed      ?z;Control speech speed, 1.0 means normal, >1.0 means speed upz	--t-shift      ?z(Shift t to smaller ones if t_shift < 1.0z--target-rmszHTarget speech normalization rms value, set to 0 to disable normalizationz--seedi  zRandom seedz--num-thread   z,Number of threads to use for PyTorch on CPU.z--raw-evaluationFztWhether to use the 'raw' evaluation mode where provided prompts and text are fed to the model without pre-processingz--max-durationd   zMaximum duration (seconds) in a single batch, including durations of the prompt and generated wavs. You can reduce it if it causes CUDA OOM.z--remove-long-silzqWhether to remove long silences in the middle of the generated speech (edge silences will be removed by default).z--trt-engine-pathz%The path to the TensorRT engine file.)argparseArgumentParserArgumentDefaultsHelpFormatteradd_argumentstrfloatintr   )parser r3   2/home/ubuntu/LuxTTS/zipvoice/bin/infer_zipvoice.py
get_parserl   s,  		

	r5   vocos_local_pathc                 C   sF   | rt |  d}tj|  dddd}|| |S t d}|S )Nz/config.yamlz/pytorch_model.binTcpu)weights_onlymap_locationzcharactr/vocos-mel-24khz)r   from_hparamstorchloadload_state_dictfrom_pretrained)r6   vocoder
state_dictr3   r3   r4   get_vocoder-  s   

rA      r'   r(   r&   ]  	save_pathprompt_text
prompt_wavtextmodelr?   	tokenizerfeature_extractordevicenum_stepguidance_scalespeedt_shift
target_rms
feat_scalesampling_ratec           $      C   sb  t ||d}t||\}}|j||d|}|d| }tj|dg|d}||g}||g}t	j
 }|j||||||d|	|
d	\}}}}|ddd| }t	j
 }||ddd}t	j
 |  }||  }t	j
 |  }|jd | }|| } || }!|| }"||||| |!|"d	}#||k r|| | }tj| | |d
 |#S )a"  
    Generate waveform of a text based on a given prompt waveform and its transcription,
        this function directly feed the prompt_text, prompt_wav and text to the model.
        It is not efficient and can have poor results for some inappropriate inputs.
        (e.g., prompt wav contains long silence, text to be generated is too long)
        This function can be used to evaluate the "raw" performance of the model.

    Args:
        save_path (str): Path to save the generated wav.
        prompt_text (str): Transcription of the prompt wav.
        prompt_wav (str): Path to the prompt wav file.
        text (str): Text to be synthesized into a waveform.
        model (torch.nn.Module): The model used for generation.
        vocoder (torch.nn.Module): The vocoder used to convert features to waveforms.
        tokenizer (EmiliaTokenizer): The tokenizer used to convert text to tokens.
        feature_extractor (VocosFbank): The feature extractor used to
            extract acoustic features.
        device (torch.device): The device on which computations are performed.
        num_step (int, optional): Number of steps for decoding. Defaults to 16.
        guidance_scale (float, optional): Scale for classifier-free guidance.
            Defaults to 1.0.
        speed (float, optional): Speed control. Defaults to 1.0.
        t_shift (float, optional): Time shift. Defaults to 0.5.
        target_rms (float, optional): Target RMS for waveform normalization.
            Defaults to 0.1.
        feat_scale (float, optional): Scale for features.
            Defaults to 0.1.
        sampling_rate (int, optional): Sampling rate for the waveform.
            Defaults to 24000.
    Returns:
        metrics (dict): Dictionary containing time and real-time
            factor metrics for processing.
    rR   r   r)   rK   predict	tokensprompt_tokensprompt_featuresprompt_features_lensrN   rO   durationrL   rM      tt_no_vocoder	t_vocoderwav_secondsrtfrtf_no_vocoderrtf_vocodersample_rate)r   r   extractto	unsqueezer;   tensorsizetexts_to_token_idsdtdatetimenowsamplepermutedecodesqueezeclamptotal_secondsshape
torchaudiosaver7   )$rD   rE   rF   rG   rH   r?   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   
prompt_rmsrY   rZ   rW   rX   start_tpred_featurespred_features_lenspred_prompt_featurespred_prompt_features_lensstart_vocoder_twavr_   r`   ra   rb   rc   rd   re   metricsr3   r3   r4    generate_sentence_raw_evaluation;  sd   5

r   r*   Fmax_durationremove_long_silc           8         s$  t ||d}t||ddd}t||\}}|jd | }|dkr*td| d n|d	kr7td
| d |j||d|}|d| }t	|}t	|}|
|gd }|
|gd }|jd | t||  }td| | }t||d}||}||g}t||||\}}g }tj }|D ]A} |t|  }!|t| dd}"tjt| f|d|d}#|j| |!|"|#||d|	|
d	\}$}%}&}'|$ddd| }$||$|%f qg }(tj })|D ]>\}$}%g }*t|$dD ]+}+||$|+ dddd|%|+ f ddd},||k r|,| | },|*|, q|(|* qtj |  }-dd t ||(D }.t!|.dd d  fddtt D }/t"|/d|d}0t|0|| dd}0|)|  }1tj |)  }2|0jd | }3|-|3 }4|1|3 }5|2|3 }6|-|1|2|3|4|5|6d}7t#j$| |0% |d |7S )aQ  
    Generate waveform of a text based on a given prompt waveform and its transcription,
        this function will do the following to improve the generation quality:
        1. chunk the text according to punctuations.
        2. process chunked texts in batches.
        3. remove long silences in the prompt audio.
        4. add punctuation to the end of prompt text and text if there is not.

    Args:
        save_path (str): Path to save the generated wav.
        prompt_text (str): Transcription of the prompt wav.
        prompt_wav (str): Path to the prompt wav file.
        text (str): Text to be synthesized into a waveform.
        model (torch.nn.Module): The model used for generation.
        vocoder (torch.nn.Module): The vocoder used to convert features to waveforms.
        tokenizer (EmiliaTokenizer): The tokenizer used to convert text to tokens.
        feature_extractor (VocosFbank): The feature extractor used to
            extract acoustic features.
        device (torch.device): The device on which computations are performed.
        num_step (int, optional): Number of steps for decoding. Defaults to 16.
        guidance_scale (float, optional): Scale for classifier-free guidance.
            Defaults to 1.0.
        speed (float, optional): Speed control. Defaults to 1.0.
        t_shift (float, optional): Time shift. Defaults to 0.5.
        target_rms (float, optional): Target RMS for waveform normalization.
            Defaults to 0.1.
        feat_scale (float, optional): Scale for features.
            Defaults to 0.1.
        sampling_rate (int, optional): Sampling rate for the waveform.
            Defaults to 24000.
        max_duration (float, optional): The maximum duration to process in each
            batch. Used to control memory consumption when generating long audios.
        remove_long_sil (bool, optional): Whether to remove long silences in the
            middle of the generated speech (edge silences will be removed by default).
    Returns:
        metrics (dict): Dictionary containing time and real-time
            factor metrics for processing.
    rS   F   )	only_edge	trail_silr]      zGiven prompt wav is too long (z>s). Please provide a shorter one (1-3 seconds is recommended).
   zGiven prompt wav is long (zMs). It will lead to slower inference speed and possibly worse speech quality.r      )
max_tokensr)   rT   rU   rV   r\   Nc                 S   s   g | ]\}}||fqS r3   r3   ).0indexr   r3   r3   r4   
<listcomp>`  s    z%generate_sentence.<locals>.<listcomp>c                 S   s   | d S )Nr   r3   )xr3   r3   r4   <lambda>c  s    z#generate_sentence.<locals>.<lambda>)keyc                    s   g | ]} | d  qS )r)   r3   )r   isequential_indexed_chunked_wavsr3   r4   r   d  s    
r&   )fade_durationrg   r^   rf   )&r   r   r   rw   loggingwarningrh   ri   rj   r   texts_to_tokenslenr1   r   tokens_to_token_idsr   rn   ro   rp   repeatr;   fullrl   rq   rr   appendrangers   rt   ru   extendrv   zipsortedr   rx   ry   r7   )8rD   rE   rF   rG   rH   r?   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   r   r   rz   prompt_durationrY   
tokens_strprompt_tokens_strtoken_durationr   chunked_tokens_strchunked_tokensrX   tokens_batcheschunked_indexchunked_featuresr{   batch_tokensbatch_prompt_tokensbatch_prompt_featuresbatch_prompt_features_lensr|   r}   r~   r   chunked_wavsr   	batch_wavr   r   r_   indexed_chunked_wavssequential_chunked_wavs	final_wavr`   ra   rb   rc   rd   re   r   r3   r   r4   generate_sentence  s   <






"




r   res_dir	test_listraw_evaluationc                  C   s  g }g }g }g }t |d}| }W d    n1 sw   Y  t|D ]\}}| d\}}}}|  d| d}i d|d|d|d|d	|d
|d|d|d|d|d|d|	d|
d|d|d|}|rxtd"i |}ntd"i |||d}td| d|  td| d|d d |	|d  |	|d  |	|d  |	|d  q%tdt
|t
| d td t
|t
| d td!t
|t
| d d S )#Nr	/z.wavrD   rE   rF   rG   rH   r?   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   )r   r   z[Sentence: z] Saved to: z] RTF: rc   z.4fr_   r`   ra   rb   zAverage RTF: zAverage RTF w/o vocoder: zAverage RTF vocoder: r3   )open	readlines	enumeratestripsplitr   r   r   infor   npsum) r   r   rH   r?   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   r   r   r   total_ttotal_t_no_vocodertotal_t_vocodertotal_wav_secondsfrlinesr   linewav_namerE   rF   rG   rD   common_paramsr   r3   r3   r4   generate_list  s   
	

"r   c                  C   sd  t  } |  }t|j t|j t }|t| t	|j
 ddddddd}||ji }| D ]\}}t||d u rTt||| td| d|  q8|jd u|joa|joa|jd uA siJ d	|jd urt|j|_|j st|j d
|jddfD ]}|j|  st|j|  d
q|j|j }|jd }	|jd }
td|j d|j d|j  n.td|j d ttt|j  dd}ttt|j  dd}	ttt|j  dd}
|jdkrt |
d}n'|jdkrt!|
d}n|jdkrt"|
|j#d}n|jdksJ t$|
d}|j%|j&d}t'|	d}t()|}	W d    n	1 s:w   Y  |jdkrQt*dHi |	d |}n|jd ksYJ t+dHi |	d |}t,|-d!rtt.j/|| nt,|-d"rt0||d#d$ nt1d%| tj23 rt4d&d'|_4ntj5j63 rt4d(|_4nt4d)|_4td*|j4  |7|j4}|8  |j9rt:||j9 t;|j<}|7|j4}|8  |	d+ d, d-krt= }nt1d.|	d+ d,  |	d+ d/ |_>td0 |jrQ|j?}t@jA|d#d1 tBdHi d2|j?d3|jd|d4|d5|d6|d7|j4d8|jCd9|jDd:|jEd;|jFd<|jGd=|jHd/|j>d>|jId?|jJd@|jK nZ|jIrYJ dAtLdHi dB|jMdC|jdD|jdE|jd|d4|d5|d6|d7|j4d8|jCd9|jDd:|jEd;|jFd<|jGd=|jHd/|j>d?|jJd@|jK tdF|jM  tdG d S )INrB   r'   )rL   rM      g      @r   zSetting z to default value: zuFor inference, please provide prompts and text with either '--test-list' or '--prompt-wav, --prompt-text and --text'.z does not existz
model.jsonz
tokens.txtzUsing z in local model dir z, checkpoint zUsing pretrained z model from the Huggingfacez	/model.pt)filenamez/model.jsonz/tokens.txtr!   )
token_filer"   r#   )r   langr$   )
vocab_sizepad_idr   r   rH   r   z.safetensorsz.ptT)r   rH   strictz%Unsupported model checkpoint format: cudar   mpsr7   zDevice: featurer   vocoszUnsupported feature type: rR   zStart generating...)exist_okr   r   r?   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   r   r   r   z-Raw evaluation is only valid with --test-listrD   rE   rF   rG   z
Saved to: Doner3   )Nr5   
parse_argsr;   set_num_threads
num_threadset_num_interop_threadsr   updatevarsr   seedget
model_nameitemsgetattrsetattrr   r   r   rF   rE   rG   	model_dirr   is_dirFileNotFoundErrorcheckpoint_nameis_filer   HUGGINGFACE_REPO	MODEL_DIRrI   r	   r   r
   r   r   r   r   r   jsonr<   r   r   r/   endswithsafetensors
load_modelr   NotImplementedErrorr   is_availablerK   backendsr   ri   evaltrt_engine_pathr   rA   vocoder_pathr   rR   r   osmakedirsr   rL   rM   rN   rO   rP   rQ   r   r   r   r   res_wav_path)r2   argsparamsmodel_defaultsmodel_specific_defaultsparamvaluer   
model_ckptmodel_configr   rI   tokenizer_configfrH   r?   rJ   r   r3   r3   r4   main  sj  








	
	
r  __main__z?%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)sT)formatlevelforce)N)rB   r'   r'   r(   r&   r&   rC   )	rB   r'   r'   r(   r&   r&   rC   r*   F)
rB   r'   r'   r(   r&   r&   rC   Fr*   F)E__doc__r+   ro   rn   r   r   r   pathlibr   typingr   numpyr   safetensors.torchr   r;   rx   huggingface_hubr   lhotse.utilsr   r   r   zipvoice.models.zipvoicer    zipvoice.models.zipvoice_distillr   zipvoice.tokenizer.tokenizerr	   r
   r   r   zipvoice.utils.checkpointr   zipvoice.utils.commonr   r   zipvoice.utils.featurer   zipvoice.utils.inferr   r   r   r   r   r   r   zipvoice.utils.tensorrtr   r   r   r5   r/   rA   nnModulerK   r1   r0   r   boolr   r   inference_moder  __name__	formatterbasicConfigINFOr3   r3   r3   r4   <module>   sV  -$	 B	

 	

 X	

L
 
/
