o
    
j_P                     @   s   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m	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ G d	d
 d
e	jZdS )    N)Path)Union)nn)save_wav)ModelManager)Synthesizer)load_configc                       s&  e Zd ZdZ							dCdededed	ed
edef fddZedd Zedd Z	edd Z
edd Zedd Zedd Zdd ZdefddZdDdedefdd ZdDdedefd!d"ZdDdedefd#d$Z	dEdeded	ed%edef
d&d'Z					dFd(ed)ed*ed+ed,ed-dfd.d/Z						dGd0ed(ed)ed*ed+ed,ed1efd2d3Z					4		5	dHd0ed(ed)ed*ed+ed,ed6ed1efd7d8Zd9ed:efd;d<Z	5dId9ed:ed6efd=d>Z				dJd0ed)ed*ed(ed1ef
d?d@Z			5		dKd0ed)ed*ed6ed(ed1efdAdBZ  ZS )LTTSz2TODO: Add voice conversion and Capacitron support. NTF
model_name
model_pathconfig_pathvocoder_pathvocoder_config_pathprogress_barc                    s   t    t|  |dd| _|rt|nd| _d| _d| _d| _	|r(t
d |durNt|dkrNd|v r=| || nd|v rH| || n| || |r\| j|||||d	 dS dS )
u@
  🐸TTS python interface that allows to load and use the released models.

        Example with a multi-speaker model:
            >>> from TTS.api import TTS
            >>> tts = TTS(TTS.list_models()[0])
            >>> wav = tts.tts("This is a test! This is also a test!!", speaker=tts.speakers[0], language=tts.languages[0])
            >>> tts.tts_to_file(text="Hello world!", speaker=tts.speakers[0], language=tts.languages[0], file_path="output.wav")

        Example with a single-speaker model:
            >>> tts = TTS(model_name="tts_models/de/thorsten/tacotron2-DDC", progress_bar=False, gpu=False)
            >>> tts.tts_to_file(text="Ich bin eine Testnachricht.", file_path="output.wav")

        Example loading a model from a path:
            >>> tts = TTS(model_path="/path/to/checkpoint_100000.pth", config_path="/path/to/config.json", progress_bar=False, gpu=False)
            >>> tts.tts_to_file(text="Ich bin eine Testnachricht.", file_path="output.wav")

        Example voice cloning with YourTTS in English, French and Portuguese:
            >>> tts = TTS(model_name="tts_models/multilingual/multi-dataset/your_tts", progress_bar=False, gpu=True)
            >>> tts.tts_to_file("This is voice cloning.", speaker_wav="my/cloning/audio.wav", language="en", file_path="thisisit.wav")
            >>> tts.tts_to_file("C'est le clonage de la voix.", speaker_wav="my/cloning/audio.wav", language="fr", file_path="thisisit.wav")
            >>> tts.tts_to_file("Isso é clonagem de voz.", speaker_wav="my/cloning/audio.wav", language="pt", file_path="thisisit.wav")

        Example Fairseq TTS models (uses ISO language codes in https://dl.fbaipublicfiles.com/mms/tts/all-tts-languages.html):
            >>> tts = TTS(model_name="tts_models/eng/fairseq/vits", progress_bar=False, gpu=True)
            >>> tts.tts_to_file("This is a test.", file_path="output.wav")

        Args:
            model_name (str, optional): Model name to load. You can list models by ```tts.models```. Defaults to None.
            model_path (str, optional): Path to the model checkpoint. Defaults to None.
            config_path (str, optional): Path to the model config. Defaults to None.
            vocoder_path (str, optional): Path to the vocoder checkpoint. Defaults to None.
            vocoder_config_path (str, optional): Path to the vocoder config. Defaults to None.
            progress_bar (bool, optional): Whether to pring a progress bar while downloading a model. Defaults to True.
            gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
        Fmodels_filer   verboseNr
   z>`gpu` will be deprecated. Please use `tts.to(device)` instead.r   
tts_modelsvoice_conversion_models)r   vocoder_configgpu)super__init__r   get_models_file_pathmanagerr   configsynthesizervoice_converterr   warningswarnlenload_tts_model_by_nameload_vc_model_by_nameload_model_by_nameload_tts_model_by_path)selfr   r   r   r   r   r   r   	__class__ :/home/kuhnn/.local/lib/python3.10/site-packages/TTS/api.pyr      s&   
-


zTTS.__init__c                 C   s
   | j  S N)r   list_tts_modelsr&   r)   r)   r*   modelsU   s   
z
TTS.modelsc                 C   s,   t | jjdr| jjjr| jjjjdkS dS )Nspeaker_manager   F)hasattrr   	tts_modelr/   num_speakersr-   r)   r)   r*   is_multi_speakerY   s   zTTS.is_multi_speakerc                 C   sh   t | jtrd| jv s| jrd| jjv st| jjdkrdS t| jj	dr2| jj	j
r2| jj	j
jdkS dS )Nxttsr0   Tlanguage_managerF)
isinstancer   strr   modelr!   	languagesr1   r   r2   r6   num_languagesr-   r)   r)   r*   is_multi_lingual_   s   

zTTS.is_multi_lingualc                 C      | j sd S | jjjjS r+   )r4   r   r2   r/   speaker_namesr-   r)   r)   r*   speakersm      zTTS.speakersc                 C   r=   r+   )r<   r   r2   r6   language_namesr-   r)   r)   r*   r:   s   r@   zTTS.languagesc                   C   s   t tjd S )Nz.models.json)r   __file__parentr)   r)   r)   r*   r   y   s   zTTS.get_models_file_pathc                 C   s   t t dddS )NFr   )r   r	   r   r-   r)   r)   r*   list_models}   s   zTTS.list_modelsc                 C   s~   | j |\}}}d|v s|d urt|d trd d d d |fS |dd u r-||d d d fS | j |d \}}}||||d fS )Nfairseq	model_urldefault_vocoder)r   download_modelr7   listget)r&   r   r   r   
model_itemr   r   _r)   r)   r*   download_model_by_name   s   zTTS.download_model_by_namer   c                 C   s   |  || dS )u	  Load one of the 🐸TTS models by name.

        Args:
            model_name (str): Model name to load. You can list models by ```tts.models```.
            gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
        N)r"   )r&   r   r   r)   r)   r*   r$      s   zTTS.load_model_by_namec                 C   s.   || _ | |\}}}}}t|||d| _dS )a  Load one of the voice conversion models by name.

        Args:
            model_name (str): Model name to load. You can list models by ```tts.models```.
            gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
        )vc_checkpoint	vc_configuse_cudaN)r   rM   r   r   )r&   r   r   r   r   rL   r)   r)   r*   r#      s   zTTS.load_vc_model_by_namec                 C   sB   d| _ || _| |\}}}}}t||dd||dd||d
| _ dS )u  Load one of 🐸TTS models by name.

        Args:
            model_name (str): Model name to load. You can list models by ```tts.models```.
            gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.

        TODO: Add tests
        N)
tts_checkpointtts_config_pathtts_speakers_filetts_languages_filevocoder_checkpointr   encoder_checkpointencoder_config	model_dirrP   )r   r   rM   r   )r&   r   r   r   r   r   r   rX   r)   r)   r*   r"      s"   	zTTS.load_tts_model_by_namer   c                 C   s    t ||dd||dd|d	| _dS )a  Load a model from a path.

        Args:
            model_path (str): Path to the model checkpoint.
            config_path (str): Path to the model config.
            vocoder_path (str, optional): Path to the vocoder checkpoint. Defaults to None.
            vocoder_config (str, optional): Path to the vocoder config. Defaults to None.
            gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
        N)	rQ   rR   rS   rT   rU   r   rV   rW   rP   )r   r   )r&   r   r   r   r   r   r)   r)   r*   r%      s   zTTS.load_tts_model_by_pathspeakerlanguagespeaker_wavemotionspeedreturnc                 K   s   | j r|du r|du rtd| jr|du rtd| j s)|dur)d|vr)td| js4|dur4td|dur@|durBtddS dS )z/Check if the arguments are valid for the model.Nz4Model is multi-speaker but no `speaker` is provided.z5Model is multi-lingual but no `language` is provided.	voice_dirz5Model is not multi-speaker but `speaker` is provided.z6Model is not multi-lingual but `language` is provided.zSEmotion and speed can only be used with Coqui Studio models. Which is discontinued.)r4   
ValueErrorr<   )r&   rY   rZ   r[   r\   r]   kwargsr)   r)   r*   _check_arguments   s   zTTS._check_argumentstextsplit_sentencesc           
      K   sF   | j d|||||d| | jjd||||dddd|d	|}	|	S )u  Convert text to speech.

        Args:
            text (str):
                Input text to synthesize.
            speaker (str, optional):
                Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
                `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
            language (str): Language of the text. If None, the default language of the speaker is used. Language is only
                supported by `XTTS` model.
            speaker_wav (str, optional):
                Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
                Defaults to None.
            emotion (str, optional):
                Emotion to use for 🐸Coqui Studio models. If None, Studio models use "Neutral". Defaults to None.
            speed (float, optional):
                Speed factor to use for 🐸Coqui Studio models, between 0 and 2.0. If None, Studio models use 1.0.
                Defaults to None.
            split_sentences (bool, optional):
                Split text into sentences, synthesize them separately and concatenate the file audio.
                Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
                applicable to the 🐸TTS models. Defaults to True.
            kwargs (dict, optional):
                Additional arguments for the model.
        )rY   rZ   r[   r\   r]   N)	rc   speaker_namelanguage_namer[   reference_wav	style_wav
style_textreference_speaker_namerd   r)   )rb   r   tts)
r&   rc   rY   rZ   r[   r\   r]   rd   ra   wavr)   r)   r*   rk      s&   $

zTTS.tts      ?
output.wav	file_pathc
                 K   sJ   | j d|||d|
 | jd|||||	d|
}| jj|||d |S )u  Convert text to speech.

        Args:
            text (str):
                Input text to synthesize.
            speaker (str, optional):
                Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
                `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
            language (str, optional):
                Language code for multi-lingual models. You can check whether loaded model is multi-lingual
                `tts.is_multi_lingual` and list available languages by `tts.languages`. Defaults to None.
            speaker_wav (str, optional):
                Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
                Defaults to None.
            emotion (str, optional):
                Emotion to use for 🐸Coqui Studio models. Defaults to "Neutral".
            speed (float, optional):
                Speed factor to use for 🐸Coqui Studio models, between 0.0 and 2.0. Defaults to None.
            pipe_out (BytesIO, optional):
                Flag to stdout the generated TTS wav file for shell pipe.
            file_path (str, optional):
                Output file path. Defaults to "output.wav".
            split_sentences (bool, optional):
                Split text into sentences, synthesize them separately and concatenate the file audio.
                Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
                applicable to the 🐸TTS models. Defaults to True.
            kwargs (dict, optional):
                Additional arguments for the model.
        )rY   rZ   r[   )rc   rY   rZ   r[   rd   )rl   pathpipe_outNr)   )rb   rk   r   r   )r&   rc   rY   rZ   r[   r\   r]   rq   ro   rd   ra   rl   r)   r)   r*   tts_to_file"  s   *zTTS.tts_to_file
source_wav
target_wavc                 C   s   | j j||d}|S )zVoice conversion with FreeVC. Convert source wav to target speaker.

        Args:``
            source_wav (str):
                Path to the source wav file.
            target_wav (str):`
                Path to the target wav file.
        rs   rt   )r   voice_conversion)r&   rs   rt   rl   r)   r)   r*   rv   Y  s   zTTS.voice_conversionc                 C   s(   | j ||d}t||| jjjjd |S )aT  Voice conversion with FreeVC. Convert source wav to target speaker.

        Args:
            source_wav (str):
                Path to the source wav file.
            target_wav (str):
                Path to the target wav file.
            file_path (str, optional):
                Output file path. Defaults to "output.wav".
        ru   rl   rp   sample_rate)rv   r   r   rO   audiooutput_sample_rate)r&   rs   rt   ro   rl   r)   r)   r*   voice_conversion_to_filei  s   zTTS.voice_conversion_to_filec                 C   sn   t jddd}| j||||j|d W d   n1 sw   Y  | jdu r,| d | jj|j|d}|S )u(  Convert text to speech with voice conversion.

        It combines tts with voice conversion to fake voice cloning.

        - Convert text to speech with tts.
        - Convert the output wav to target speaker with voice conversion.

        Args:
            text (str):
                Input text to synthesize.
            language (str, optional):
                Language code for multi-lingual models. You can check whether loaded model is multi-lingual
                `tts.is_multi_lingual` and list available languages by `tts.languages`. Defaults to None.
            speaker_wav (str, optional):
                Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
                Defaults to None.
            speaker (str, optional):
                Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
                `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
            split_sentences (bool, optional):
                Split text into sentences, synthesize them separately and concatenate the file audio.
                Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
                applicable to the 🐸TTS models. Defaults to True.
        z.wavF)suffixdelete)rc   rY   rZ   ro   rd   Nz2voice_conversion_models/multilingual/vctk/freevc24ru   )tempfileNamedTemporaryFilerr   namer   r#   rv   )r&   rc   rZ   r[   rY   rd   fprl   r)   r)   r*   tts_with_vc}  s    

zTTS.tts_with_vcc                 C   s.   | j |||||d}t||| jjjjd dS )u  Convert text to speech with voice conversion and save to file.

        Check `tts_with_vc` for more details.

        Args:
            text (str):
                Input text to synthesize.
            language (str, optional):
                Language code for multi-lingual models. You can check whether loaded model is multi-lingual
                `tts.is_multi_lingual` and list available languages by `tts.languages`. Defaults to None.
            speaker_wav (str, optional):
                Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
                Defaults to None.
            file_path (str, optional):
                Output file path. Defaults to "output.wav".
            speaker (str, optional):
                Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
                `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
            split_sentences (bool, optional):
                Split text into sentences, synthesize them separately and concatenate the file audio.
                Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
                applicable to the 🐸TTS models. Defaults to True.
        )rc   rZ   r[   rY   rd   rw   N)r   r   r   rO   ry   rz   )r&   rc   rZ   r[   ro   rY   rd   rl   r)   r)   r*   tts_with_vc_to_file  s    
zTTS.tts_with_vc_to_file)r
   NNNNTF)F)NNF)NNNNN)NNNNNT)NNNNrm   Nrn   T)rn   )NNNT)NNrn   NT)__name__
__module____qualname____doc__r8   boolr   propertyr.   r4   r<   r?   r:   staticmethodr   rD   rM   r$   r#   r"   r%   floatrb   rk   rr   rv   r{   r   r   __classcell__r)   r)   r'   r*   r	      sB   C





	 


8	

7


-r	   )r~   r   pathlibr   typingr   numpynptorchr    TTS.utils.audio.numpy_transformsr   TTS.utils.manager   TTS.utils.synthesizerr   
TTS.configr   Moduler	   r)   r)   r)   r*   <module>   s    