diff --git a/README.md b/README.md index 676ffb3..9b8755e 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,16 @@ AllTalk is an updated version of the Coqui_tts extension for Text Generation web UI. Features include: - **Custom Start-up Settings:** Adjust your default start-up settings. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) -- **Narrarator:** Use different voices for main character and narration. [Example Narration](https://vocaroo.com/18fYWVxiQpk1) +- **Narrarator:** Use different voices for main character and narration. [Example Narration](https://vocaroo.com/18nrv7FR6wuA) - **Low VRAM mode:** Great for people with small GPU memory or if your VRAM is filled by your LLM. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) - **DeepSpeed:** A 3-4x performance boost generating TTS. [DeepSpeed Windows/Linux Instructions](https://github.com/erew123/alltalk_tts?tab=readme-ov-file#deepspeed-installation-options) [Screenshot](https://github.com/erew123/alltalk_tts/assets/35898566/548619c8-5f1b-47d0-a73d-54d2fee3f3db) - **Local/Custom models:** Use any of the XTTSv2 models (API Local and XTTSv2 Local). - **Optional wav file maintenance:** Configurable deletion of old output wav files. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) +- **Finetuning** Train the model specifically on a voice of your choosing for better reproduction. - **Documentation:** Fully documented with a built in webpage. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) - **Console output** Clear command line output for any warnings or issues. -- **Standalone/3rd Party support via JSON calls** Can be used with 3rd party applications via JSON calls. +- **API Suite and 3rd Party support via JSON calls** Can be used with 3rd party applications via JSON calls. +- **Can be run as a standalone app** Not just inside of text-generation-webui. ## Index @@ -17,7 +19,9 @@ AllTalk is an updated version of the Coqui_tts extension for Text Generation web - πŸŸͺ [Updating & problems with updating](https://github.com/erew123/alltalk_tts?#-updating) - 🟫 [Screenshots](https://github.com/erew123/alltalk_tts#-screenshots) - 🟨 [Help with problems](https://github.com/erew123/alltalk_tts?#-help-with-problems) +- ⚫ [Finetuning a model](https://github.com/erew123/alltalk_tts?#-finetuning-a-model) - πŸ”΅πŸŸ’πŸŸ‘ [DeepSpeed Installation (Windows & Linux)](https://github.com/erew123/alltalk_tts?#-deepspeed-installation-options) +- 🟠 [API Suite and JSON-CURL](https://github.com/erew123/alltalk_tts?#-api-suite-and-json-curl) - πŸ”΄ [Future to-do list & Upcoming updates](https://github.com/erew123/alltalk_tts?#-future-to-do-list) #### Updates @@ -43,9 +47,9 @@ This has been tested on the current Dec 2023 release of Text generation webUI. I 5) Move into the **alltalk_tts** folder:

`cd alltalk_tts` -6) Install the requirements:

-*Nvidia graphics card machines* - `pip install -r requirements_nvidia.txt`

-*Other machines (mac, amd etc)* - `pip install -r requirements_other.txt` +6) Install the requirements that are correct for your machine:

+**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`

+**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt` 7) **(Optional DeepSpeed)** If you have an Nvidia Graphics card on a system running Linux or Windows and wish to use **DeepSpeed** please follow these instructions [here](https://github.com/erew123/alltalk_tts?#-deepspeed-installation-options). **However**, I would highly reccommend before you install DeepSpeed, you start text-generation-webui up, confirm AllTalk starts correctly and everything is working, as DeepSpeed can add another layer of complications troubleshooting any potential start-up issues. If necessary you can `pip uninstall deepspeed`. @@ -81,9 +85,9 @@ This is pretty much a repeat of the installation process. 3) At the command prompt/terminal, type:

`git pull` -4) Install the requirements:

-*Nvidia graphics card machines* - `pip install -r requirements_nvidia.txt`

-*Other machines (mac, amd etc)* - `pip install -r requirements_other.txt` +4) Install the correct requirements for your machine:

+**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`

+**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt` #### πŸŸͺ Updating "git pull" error @@ -123,9 +127,9 @@ This will download a fresh installation. 3) Move into the **alltalk_tts** folder:

`cd alltalk_tts` -4) Install the requirements:

-*Nvidia graphics card machines* - `pip install -r requirements_nvidia.txt`

-*Other machines (mac, amd etc)* - `pip install -r requirements_other.txt` +4) Install the correct requirements for your machine:

+**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`

+**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt` 5) Before starting it up, copy/merge the `models`, `voices` and `outputs` folders over from the `alltalk_tts.old` folder to the newly created `alltalk_tts` folder. This will keep your voices history and also stop it re-downloading the model again. @@ -135,9 +139,10 @@ Assuming its all working fine and you are happy, you can delete the old alltalk_ ## 🟫 Screenshots -|![image](https://github.com/erew123/alltalk_tts/assets/35898566/4ca9b4c7-60ce-4ac6-82e5-fd1989b84644) | ![image](https://github.com/erew123/alltalk_tts/assets/35898566/b0e13dba-c6b1-4ab7-845d-244ac1158330) | +|![image](https://github.com/erew123/alltalk_tts/assets/35898566/4ca9b4c7-60ce-4ac6-82e5-fd1989b84644) | ![image](https://github.com/erew123/alltalk_tts/assets/35898566/548619c8-5f1b-47d0-a73d-54d2fee3f3db) | |:---:|:---:| -|![image](https://github.com/erew123/alltalk_tts/assets/35898566/548619c8-5f1b-47d0-a73d-54d2fee3f3db) | ![image](https://github.com/erew123/alltalk_tts/assets/35898566/e35e987c-543a-486b-b4fb-ee6ebe6f59c6) | +|![image](https://github.com/erew123/alltalk_tts/assets/35898566/b0e13dba-c6b1-4ab7-845d-244ac1158330) | ![image](https://github.com/erew123/alltalk_tts/assets/35898566/e35e987c-543a-486b-b4fb-ee6ebe6f59c6) | +|![image](https://github.com/erew123/alltalk_tts/assets/35898566/68edc968-bdd2-4f98-9d56-b9ca40decf26) | ![image](https://github.com/erew123/alltalk_tts/assets/35898566/eb5e617b-2345-418d-8267-a9d30f705a10) | ## 🟨 Help with problems @@ -160,7 +165,7 @@ Assuming its all working fine and you are happy, you can delete the old alltalk_

-#### 🟨 [AllTalk Startup] Warning TTS Subprocess has NOT started up yet, Will keep trying for 60 seconds maximum. Please wait. It times out after 60 seconds. +#### 🟨 [AllTalk Startup] Warning TTS Subprocess has NOT started up yet, Will keep trying for 120 seconds maximum. Please wait. It times out after 120 seconds.
Click to expand
@@ -171,7 +176,9 @@ Assuming its all working fine and you are happy, you can delete the old alltalk_ **Note:** If you need to create a support ticket, please create a `diagnostics.log` report file to submit with a support request. Details on doing this are above. -Possibilities for this issue are: +Before giving other possibilities, some people with **old machines** are finding their startup times are **very** slow 2-3 minutes. Ive extended the allowed time within the script from 1 minute to 2 minutes. **If you have an older machine** and wish to try extending this further, you can do so by editing `script.py` and changing line 251 `timeout = 120` changing the timeout to a larger value e.g `timeout = 240` (4 minutes). + +Other possibilities for this issue are: 1) You are starting AllTalk in both your `CMD FLAG.txt` and `settings.yaml` file. The `CMD FLAG.txt` you would have manually edited and the `settings.yaml` is the one you change and save in the `session` tab of text-generation-webui and you can `Save UI defaults to settings.yaml`. Please only have one of those two starting up AllTalk. @@ -230,6 +237,59 @@ I would suggest following [Problems Updating](https://github.com/erew123/alltalk As far as I am aware, these are to do with the chrome browser the gradio text-generation-webui in some way. I raised an issue about this on the text-generation-webui [here](https://github.com/oobabooga/text-generation-webui/issues/4788) where you can see that AllTalk is not loaded and the messages persist. Either way, this is more a warning than an actual issue, so shouldnt affect any functionality of either AllTalk or text-generation-webui, they are more just an annoyance.
+## ⚫ Finetuning a model +If you have a voice that the model doesnt quite reproduce correctly, or indeed you just want to improve the reproduced voice, then finetuning is a way to train your "XTTSv2 local" model **(stored in `/alltalk_tts/models/xxxxx/`)** on a specific voice. For this you will need: + +- An Nvidia graphics card +- To install a few portions of the Nvidia CUDA 11.8 Toolkit (this will not impact text-generation-webui's cuda setup. +- 18GB of disk space free (most of this is used temporarily) +- At least 2 minutes of good quality speech from your chosen speaker in mp3, wav or flacc format, in one or more files (have tested as far as 20 minutes worth of audio). + +#### ⚫ How will this work/How complicated is it? +Everything has been done to make this as simple as possible. At its simplest, you can literally just download a large chunk of audio from an interview, and tell the finetuning to strip through it, find spoken parts and build your dataset. You can literally click 4 buttons, then copy a few files and you are done. At it's more complicated end you will clean up the audio a little beforehand, but its still only 4x buttons and copying a few files. + +#### ⚫ The audio you will use +I would suggest that if its in an interview format, you cut out the interviewer speaking in audacity or your chosen audio editing package. You dont have to worry about being perfect with your cuts, the finetuning Step 1 will go and find spoken audio and cut it out for you. Is there is music over the spoken parts, for best quality you would cut out those parts, though its not 100% necessary. As always, try to avoid bad quality audio with noises in it (humming sounds, hiss etc). You can try something like [Audioenhancer](https://audioenhancer.ai/) to try clean up noisier audio. There is no need to down-sample any of the audio, all of that is handled for you. Just give the finetuning some good quality audio to work with. + +#### ⚫ Important requirements CUDA 11.8 +As mentioned you must have a small portion of the Nvidia CUDA Toolkit **11.8** installed. Not higher or lower versions. Specifically **11.8**. You do not have to uninstall any other versions, change any graphics drivers, reinstall torch or anything like that. To keep the download+install as small as possible, you will need to: +- Download the **xxx (network)** install of the Nvidia Cuda Toolkit 11.8 from [here](https://developer.nvidia.com/cuda-11-8-0-download-archive) +- When you run the installation, select **Custom Advanced** as your installation type. Uncheck `CUDA`, `Other Components` and `Driver Components` at the top then expand `CUDA` > `Development` > `Compiler` > and select `nvcc` then expand `Libraries` and select `CUBLAS` +- Back at the top of `CUDA` expand `Runtime` > `Libraries` and select `CUBLAS`. You can now next through the install. +- When that has installed, open a terminal/command prompt and type `nvcc --version`. If it reports back `Cuda compilation tools, release 11.8.` you are good to go. **Specifically, 11.8**. If not continue to the next step. +- For both Windows an Linux, you will need to ensure that `nvcc` and the 11.8 cuda library files are in your environments search path. You can undo the changes below after finetuning if you prefer.

+ **Windows** - Edit the Windows PATH environment variable and add `C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\bin`

+ **Linux** - The path may be different depending on what flavour of Linux you are running, so you may need to seek out specific instructions on the internet. Generic paths **may** be:
+ `export LD_LIBRARY_PATH=/usr/local/cuda-11.8/lib64:${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}` and
+ `export LD_LIBRARY_PATH=/usr/local/cuda-11.8/bin`
+ Add these to your '~/.bashrc' if you want this to be permanent and not something you have to set each time you open a new terminal.

+- When you have made the changes, open a new terminal/command prompt and `nvcc --version`. It should report back `Cuda compilation tools, release 11.8.` at which point, you are good to go. +- If it doesnt report that, check you have correctly set the search environment paths, dont have overlapping other versions of cuda paths etc. + +#### ⚫ Starting Finetuning +1) Close all other applications that are using your GPU/VRAM and copy your audio samples into:

+ `/alltalk_tts/finetune/put-voice-samples-in-here/` +3) In a command prompt/terminal window you need to move into your Text generation webUI folder:

+`cd text-generation-webui` + +4) Start the Text generation webUI Python environment for your OS:

+`cmd_windows.bat`, `./cmd_linux.sh`, `cmd_macos.sh` or `cmd_wsl.bat` + +5) You can double check your search path environment still works correctly with `nvcc --version`. It should report back 11.8:

+ `Cuda compilation tools, release 11.8.` + +7) Move into your extensions folder:

+`cd extensions` + +8) Move into the **alltalk_tts** folder:

+`cd alltalk_tts` + +9) Install the finetune requirements file: `pip install -r requirements_finetune.txt` + +10) Type `python finetune.py` and it should start up. +11) Follow the on-screen instructions when the web interface starts up. +12) When you have finished finetuning, the final tab will tell you what to do with your files and how to move your newly trained model to the correct location on disk. + ## πŸ”΅πŸŸ’πŸŸ‘ DeepSpeed Installation Options #### πŸ”΅ Linux Installation
@@ -381,10 +441,142 @@ def get_shm_size(): **Removal** - If it became necessary to uninstall DeepSpeed, you can do so with `cmd_windows.bat` and then `pip uninstall deepspeed`

+## 🟠 API Suite and JSON-CURL +### 🟠Overview +The Text-to-Speech (TTS) Generation API allows you to generate speech from text input using various configuration options. This API supports both character and narrator voices, providing flexibility for creating dynamic and engaging audio content. + +- URL: `http://127.0.0.1:7851/api/tts-generate`
+- Method: `POST`
+- Content-Type: `application/x-www-form-urlencoded`
+ +### 🟠 Example command lines +Standard TTS speech Example (standard text) generating a time-stamped file
+ +`curl -X POST "http://127.0.0.1:7851/api/tts-generate" -d "text_input=All of this is text spoken by the character. This is text not inside quotes, though that doesnt matter in the slightest" -d "text_filtering=standard" -d "character_voice_gen=female_01.wav" -d "narrator_enabled=false" -d "narrator_voice_gen=male_01.wav" -d "text_not_inside=character" -d "language=en" -d "output_file_name=myoutputfile" -d "output_file_timestamp=true" -d "autoplay=true" -d "autoplay_volume=0.8"`
+ +Narrator Example (standard text) generating a time-stamped file + +`curl -X POST "http://127.0.0.1:7851/api/tts-generate" -d "text_input=*This is text spoken by the narrator* \"This is text spoken by the character\". This is text not inside quotes." -d "text_filtering=standard" -d "character_voice_gen=female_01.wav" -d "narrator_enabled=true" -d "narrator_voice_gen=male_01.wav" -d "text_not_inside=character" -d "language=en" -d "output_file_name=myoutputfile" -d "output_file_timestamp=true" -d "autoplay=true" -d "autoplay_volume=0.8"`
+ +Note that if your text that needs to be generated contains double quotes you will need to escape them with `\"` (Please see the narrator example). + +### 🟠 Request Parameters +🟠 **text_input**: The text you want the TTS engine to produce. Use escaped double quotes for character speech and asterisks for narrator speech if using the narrator function. Example: + +`-d "text_input=*This is text spoken by the narrator* \"This is text spoken by the character\". This is text not inside quotes."` + +🟠 **text_filtering**: Filter for text. Options: + +- **none** No filtering. Whatever is sent will go over to the TTS engine as raw text, which may result in some odd sounds with some special characters.
+- **standard** Human-readable text and a basic level of filtering, just to clean up some special characters.
+- **html** HTML content. Where you are using HTML entity's like "
+ +`-d "text_filtering=none"`
+`-d "text_filtering=standard"`
+`-d "text_filtering=html"`
+ +Example: + +- **Standard Example**: `*This is text spoken by the narrator* "This is text spoken by the character" This is text not inside quotes.`
+- **HTML Example**: `*This is text spoken by the narrator* "This is text spoken by the character" This is text not inside quotes.`
+- **None**: `Will just pass whatever characters/text you send at it.`
+ +🟠 **character_voice_gen**: The WAV file name for the character's voice.
+ +`-d "character_voice_gen=female_01.wav"` + +🟠 **narrator_enabled**: Enable or disable the narrator function. If true, minimum text filtering is set to standard. Anything between double quotes is considered the character's speech, and anything between asterisks is considered the narrator's speech. + +`-d "narrator_enabled=true"`
+`-d "narrator_enabled=false"` + +🟠 **narrator_voice_gen**: The WAV file name for the narrator's voice. + +`-d "narrator_voice_gen=male_01.wav"` + +🟠 **text_not_inside**: Specify the handling of lines not inside double quotes or asterisks, for the narrator feature. Options: + +- **character**: Treat as character speech.
+- **narrator**: Treat as narrator speech.
+ +`-d "text_not_inside=character"`
+`-d "text_not_inside=narrator"` + +🟠 **language**: Choose the language for TTS. Options: + +`ar Arabic`
+`zh-cn Chinese (Simplified)`
+`cs Czech`
+`nl Dutch`
+`en English`
+`fr French`
+`de German`
+`hu Hungarian`
+`it Italian`
+`ja Japanese`
+`ko Korean`
+`pl Polish`
+`pt Portuguese`
+`ru Russian`
+`es Spanish`
+`tr Turkish`
+ +`-d "language=en"`
+ +🟠 **output_file_name**: The name of the output file (excluding the .wav extension). + +`-d "output_file_name=myoutputfile"`
+ +🟠 **output_file_timestamp**: Add a timestamp to the output file name. If true, each file will have a unique timestamp; otherwise, the same file name will be overwritten each time you generate TTS. + +`-d "output_file_timestamp=true"`
+`-d "output_file_timestamp=false"` + +🟠 **autoplay**: Feature not yet available. Enable or disable autoplay. Still needs to be specified in the JSON request. + +`-d "autoplay=true"`
+`-d "autoplay=false"` + +🟠 **autoplay_volume**: Feature not yet available. Set the autoplay volume. Should be between 0.1 and 1.0. Still needs to be specified in the JSON request. + +`-d "autoplay_volume=0.8"` + +### 🟠 TTS Generation Response +The API returns a JSON object with the following properties: + +- **status** Indicates whether the generation was successful (generate-success) or failed (generate-failure).
+- **output_file_path** The on-disk location of the generated WAV file.
+- **output_file_url** The HTTP location for accessing the generated WAV file.
+ +Example JSON TTS Generation Response: + +`{"status": "generate-success", "output_file_path": "C:\text-generation-webui\extensions\alltalk_tts\outputs\myoutputfile_1703149973.wav", "output_file_url": "http://127.0.0.1:7851/audio/myoutputfile_1703149973.wav"}` + +🟠 **Switching Model**

+`curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=API%20Local"`
+`curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=API%20TTS"`
+`curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=XTTSv2%20Local"`
+ +Switch between the 3 models respectively. + +JSON return `{"status": "model-success"}` + +🟠 **Switch DeepSpeed**

+`curl -X POST "http://127.0.0.1:7851/api/deepspeed?new_deepspeed_value=True"` + +Replace True with False to disable DeepSpeed mode. + +JSON return `{"status": "deepspeed-success"}` + +🟠 **Switching Low VRAM**

+`curl -X POST "http://127.0.0.1:7851/api/lowvramsetting?new_low_vram_value=True"` + +Replace True with False to disable Low VRAM mode. + +JSON return `{"status": "lowvram-success"}` + ### πŸ”΄ Future to-do list -- Complete & document the new/full standalone mode API. - Voice output within the command prompt/terminal (TBD). -- Correct an issue on incorrect output folder path when running as a standalone app. -- Correct a few spelling mistakes in the documnentation. +- Correct a few spelling mistakes in the documentation. - Possibly add some additional TTS engines (TBD). - Have a break! diff --git a/finetune.py b/finetune.py new file mode 100644 index 0000000..3ab2be7 --- /dev/null +++ b/finetune.py @@ -0,0 +1,1017 @@ +import argparse +import os +import sys +import tempfile +import signal +import gradio as gr +import torch +import torchaudio +import traceback +from TTS.tts.configs.xtts_config import XttsConfig +from TTS.tts.models.xtts import Xtts +import random +import gc +import time +import shutil +import pandas +import json +from pathlib import Path +from tqdm import tqdm +from faster_whisper import WhisperModel +from TTS.tts.layers.xtts.tokenizer import multilingual_cleaners + + +# STARTUP VARIABLES +this_dir = Path(__file__).parent.resolve() +audio_folder = this_dir / "finetune" / "put-voice-samples-in-here" +out_path = this_dir / "finetune" / "tmp-trn" +progress = 0 +theme = gr.themes.Default() +refresh_symbol = 'πŸ”„' + +# Define the path to the modeldownload config file file +modeldownload_config_file_path = this_dir / "modeldownload.json" + +# Check if the JSON file exists +if modeldownload_config_file_path.exists(): + with open(modeldownload_config_file_path, "r") as config_file: + settings = json.load(config_file) + # Extract settings from the loaded JSON + base_path = Path(settings.get("base_path", "")) + model_path = Path(settings.get("model_path", "")) + files_to_download = settings.get("files_to_download", {}) +else: + # Default settings if the JSON file doesn't exist or is empty + print("[FINETUNE] \033[91mWarning\033[0m modeldownload.json is missing. Please run this script in the /alltalk_tts/ folder") + sys.exit(1) + +##################### +#### STEP 1 BITS #### +##################### + +def create_temp_folder(): + temp_folder = os.path.join(os.path.dirname(__file__), 'temp_files') + os.makedirs(temp_folder, exist_ok=True) + return temp_folder + +def create_temporary_file(folder, suffix=".wav"): + unique_filename = f"custom_tempfile_{int(time.time())}_{random.randint(1, 1000)}{suffix}" + return os.path.join(folder, unique_filename) + +def format_audio_list(target_language, whisper_model, out_path, gradio_progress=progress): + audio_files = [os.path.join(audio_folder, file) for file in os.listdir(audio_folder) if file.endswith('.wav')] + buffer=0.2 + eval_percentage=0.15 + speaker_name="coqui" + audio_total_size = 0 + os.makedirs(out_path, exist_ok=True) + temp_folder = os.path.join(out_path, "temp") # Update with your folder name + os.makedirs(temp_folder, exist_ok=True) + print("[FINETUNE] \033[94mPart of AllTalk\033[0m https://github.com/erew123/alltalk_tts/") + print("[FINETUNE] \033[94mCoqui Public Model License\033[0m") + print("[FINETUNE] \033[94mhttps://coqui.ai/cpml.txt\033[0m") + print("[FINETUNE] \033[94mStarting Step 1\033[0m - Preparing Audio/Generating the dataset") + # Write the target language to lang.txt in the output directory + lang_file_path = os.path.join(out_path, "lang.txt") + + # Check if lang.txt already exists and contains a different language + current_language = None + if os.path.exists(lang_file_path): + with open(lang_file_path, 'r', encoding='utf-8') as existing_lang_file: + current_language = existing_lang_file.read().strip() + + if current_language != target_language: + # Only update lang.txt if target language is different from the current language + with open(lang_file_path, 'w', encoding='utf-8') as lang_file: + lang_file.write(target_language + '\n') + print("[FINETUNE] Updated lang.txt with the target language.") + else: + print("[FINETUNE] The existing language matches the target language") + + # Loading Whisper + device = "cuda" if torch.cuda.is_available() else "cpu" + + print("[FINETUNE] Loading Whisper Model:", whisper_model) + asr_model = WhisperModel(whisper_model, device=device, compute_type="float16") + + metadata = {"audio_file": [], "text": [], "speaker_name": []} + + existing_metadata = {'train': None, 'eval': None} + train_metadata_path = os.path.join(out_path, "metadata_train.csv") + eval_metadata_path = os.path.join(out_path, "metadata_eval.csv") + + if os.path.exists(train_metadata_path): + existing_metadata['train'] = pandas.read_csv(train_metadata_path, sep="|") + print("[FINETUNE] Existing training metadata found and loaded.") + + if os.path.exists(eval_metadata_path): + existing_metadata['eval'] = pandas.read_csv(eval_metadata_path, sep="|") + print("[FINETUNE] Existing evaluation metadata found and loaded.") + + for idx, audio_path in tqdm(enumerate(audio_files)): + if isinstance(audio_path, str): + audio_file_name_without_ext, _ = os.path.splitext(os.path.basename(audio_path)) + # If it's a string, it's already the path to the file + audio_path_name = audio_path + elif hasattr(audio_path, 'read'): + # If it has a 'read' attribute, treat it as a file-like object + # and use a temporary file to save its content + audio_file_name_without_ext, _ = os.path.splitext(os.path.basename(audio_path.name)) + audio_path_name = create_temporary_file(temp_folder) + with open(audio_path, 'rb') as original_file: + file_content = original_file.read() + with open(audio_path_name, 'wb') as temp_file: + temp_file.write(file_content) + + # Create a temporary file path within the new folder + temp_audio_path = create_temporary_file(temp_folder) + + try: + if isinstance(audio_path, str): + audio_path_name = audio_path + elif hasattr(audio_path, 'name'): + audio_path_name = audio_path.name + else: + raise ValueError(f"Unsupported audio_path type: {type(audio_path)}") + except Exception as e: + print("[FINETUNE] Error reading original file: {e}") + # Handle the error or raise it if needed + print("[FINETUNE] Current working file:", audio_path_name) + try: + # Copy the audio content + time.sleep(0.5) # Introduce a small delay + shutil.copy2(audio_path_name, temp_audio_path) + except Exception as e: + print("[FINETUNE] Error copying file: {e}") + # Handle the error or raise it if needed + + # Load the temporary audio file + wav, sr = torchaudio.load(temp_audio_path, format="wav") + wav = torch.as_tensor(wav).clone().detach().t().to(torch.float32), sr + + prefix_check = f"wavs/{audio_file_name_without_ext}_" + + # Check both training and evaluation metadata for an entry that starts with the file name. + skip_processing = False + + for key in ['train', 'eval']: + if existing_metadata[key] is not None: + mask = existing_metadata[key]['audio_file'].str.startswith(prefix_check) + + if mask.any(): + print(f"[FINETUNE] Segments from {audio_file_name_without_ext} have been previously processed; skipping...") + skip_processing = True + break + + # If we found that we've already processed this file before, continue to the next iteration. + if skip_processing: + continue + + wav, sr = torchaudio.load(audio_path) + # stereo to mono if needed + if wav.size(0) != 1: + wav = torch.mean(wav, dim=0, keepdim=True) + + wav = wav.squeeze() + audio_total_size += (wav.size(-1) / sr) + + segments, _ = asr_model.transcribe(audio_path, vad_filter=True, word_timestamps=True, language=target_language) + segments = list(segments) + i = 0 + sentence = "" + sentence_start = None + first_word = True + # added all segments words in a unique list + words_list = [] + for _, segment in enumerate(segments): + words = list(segment.words) + words_list.extend(words) + + # process each word + for word_idx, word in enumerate(words_list): + if first_word: + sentence_start = word.start + # If it is the first sentence, add buffer or get the beginning of the file + if word_idx == 0: + sentence_start = max(sentence_start - buffer, 0) # Add buffer to the sentence start + else: + # get the previous sentence end + previous_word_end = words_list[word_idx - 1].end + # add buffer or get the silence middle between the previous sentence and the current one + sentence_start = max(sentence_start - buffer, (previous_word_end + sentence_start) / 2) + + sentence = word.word + first_word = False + else: + sentence += word.word + + if word.word[-1] in ["!", ".", "?"]: + sentence = sentence[1:] + # Expand number and abbreviations plus normalization + sentence = multilingual_cleaners(sentence, target_language) + audio_file_name, _ = os.path.splitext(os.path.basename(audio_path)) + + audio_file = f"wavs/{audio_file_name}_{str(i).zfill(8)}.wav" + + # Check for the next word's existence + if word_idx + 1 < len(words_list): + next_word_start = words_list[word_idx + 1].start + else: + # If don't have more words it means that it is the last sentence then use the audio len as next word start + next_word_start = (wav.shape[0] - 1) / sr + + # Average the current word end and next word start + word_end = min((word.end + next_word_start) / 2, word.end + buffer) + + absolute_path = os.path.join(out_path, audio_file) + os.makedirs(os.path.dirname(absolute_path), exist_ok=True) + i += 1 + first_word = True + + audio = wav[int(sr * sentence_start):int(sr * word_end)].unsqueeze(0) + # if the audio is too short, ignore it (i.e., < 0.33 seconds) + if audio.size(-1) >= sr / 3: + torchaudio.save( + absolute_path, + audio, + sr + ) + else: + continue + + metadata["audio_file"].append(audio_file) + metadata["text"].append(sentence) + metadata["speaker_name"].append(speaker_name) + + os.remove(temp_audio_path) + + if os.path.exists(train_metadata_path) and os.path.exists(eval_metadata_path): + existing_train_df = existing_metadata['train'] + existing_eval_df = existing_metadata['eval'] + audio_total_size = 121 + else: + existing_train_df = pandas.DataFrame(columns=["audio_file", "text", "speaker_name"]) + existing_eval_df = pandas.DataFrame(columns=["audio_file", "text", "speaker_name"]) + + new_data_df = pandas.DataFrame(metadata) + + combined_train_df = pandas.concat([existing_train_df, new_data_df], ignore_index=True).drop_duplicates().reset_index(drop=True) + + combined_train_df_shuffled = combined_train_df.sample(frac=1) + num_val_samples = int(len(combined_train_df_shuffled) * eval_percentage) + + final_eval_set = combined_train_df_shuffled[:num_val_samples] + final_training_set = combined_train_df_shuffled[num_val_samples:] + + final_training_set.sort_values('audio_file').to_csv(train_metadata_path, sep='|', index=False) + final_eval_set.sort_values('audio_file').to_csv(eval_metadata_path, sep='|', index=False) + + # deallocate VRAM and RAM + del asr_model, final_eval_set, final_training_set, new_data_df, existing_metadata + gc.collect() + print("[FINETUNE] Train CSV:", train_metadata_path) + print("[FINETUNE] Eval CSV:", eval_metadata_path) + print("[FINETUNE] Audio Total:", audio_total_size) + return train_metadata_path, eval_metadata_path, audio_total_size + +###################### +#### STEP 2 BITS ##### +###################### + +from trainer import Trainer, TrainerArgs + +from TTS.config.shared_configs import BaseDatasetConfig +from TTS.tts.datasets import load_tts_samples +from TTS.tts.layers.xtts.trainer.gpt_trainer import GPTArgs, GPTTrainer, GPTTrainerConfig, XttsAudioConfig +from TTS.utils.manage import ModelManager + + +def train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path, max_audio_length=255995): + # Logging parameters + RUN_NAME = "XTTS_FT" + PROJECT_NAME = "XTTS_trainer" + DASHBOARD_LOGGER = "tensorboard" + LOGGER_URI = None + + # Set here the path that the checkpoints will be saved. Default: ./training/ + OUT_PATH = os.path.join(output_path, "training") + print("[FINETUNE] \033[94mStarting Step 2\033[0m - Fine-tuning the XTTS Encoder") + # Create the directory + os.makedirs(OUT_PATH, exist_ok=True) + + # Training Parameters + OPTIMIZER_WD_ONLY_ON_WEIGHTS = True # for multi-gpu training please make it False + START_WITH_EVAL = False # if True it will star with evaluation + BATCH_SIZE = batch_size # set here the batch size + GRAD_ACUMM_STEPS = grad_acumm # set here the grad accumulation steps + + # Define here the dataset that you want to use for the fine-tuning on. + config_dataset = BaseDatasetConfig( + formatter="coqui", + dataset_name="ft_dataset", + path=os.path.dirname(train_csv), + meta_file_train=train_csv, + meta_file_val=eval_csv, + language=language, + ) + + # Add here the configs of the datasets + DATASETS_CONFIG_LIST = [config_dataset] + + # XTTS model checkpoints for fine-tuning. + TOKENIZER_FILE = str(this_dir / base_path / model_path / "vocab.json") # vocab.json file + XTTS_CHECKPOINT = str(this_dir / base_path / model_path / "model.pth") # model.pth file + XTTS_CONFIG_FILE = str(this_dir / base_path / model_path / "config.json") # config.json file + DVAE_CHECKPOINT = str(this_dir / base_path / model_path / "dvae.pth") + MEL_NORM_FILE = str(this_dir / base_path / model_path / "mel_stats.pth") + + # init args and config + model_args = GPTArgs( + max_conditioning_length=132300, # 6 secs + min_conditioning_length=66150, # 3 secs + debug_loading_failures=False, + max_wav_length=max_audio_length, # ~11.6 seconds + max_text_length=200, + mel_norm_file=MEL_NORM_FILE, + dvae_checkpoint=DVAE_CHECKPOINT, + xtts_checkpoint=XTTS_CHECKPOINT, # checkpoint path of the model that you want to fine-tune + tokenizer_file=TOKENIZER_FILE, + gpt_num_audio_tokens=1026, + gpt_start_audio_token=1024, + gpt_stop_audio_token=1025, + gpt_use_masking_gt_prompt_approach=True, + gpt_use_perceiver_resampler=True, + ) + # define audio config + audio_config = XttsAudioConfig(sample_rate=22050, dvae_sample_rate=22050, output_sample_rate=24000) + + # training parameters config + config = GPTTrainerConfig( + epochs=num_epochs, + output_path=OUT_PATH, + model_args=model_args, + run_name=RUN_NAME, + project_name=PROJECT_NAME, + run_description="GPT XTTS training", + dashboard_logger=DASHBOARD_LOGGER, + logger_uri=LOGGER_URI, + audio=audio_config, + batch_size=BATCH_SIZE, + batch_group_size=48, + eval_batch_size=BATCH_SIZE, + num_loader_workers=8, + eval_split_max_size=256, + print_step=50, + plot_step=100, + log_model_step=100, + save_step=1000, + save_n_checkpoints=1, + save_checkpoints=True, + # target_loss="loss", + print_eval=False, + # Optimizer values like tortoise, pytorch implementation with modifications to not apply WD to non-weight parameters. + optimizer="AdamW", + optimizer_wd_only_on_weights=OPTIMIZER_WD_ONLY_ON_WEIGHTS, + optimizer_params={"betas": [0.9, 0.96], "eps": 1e-8, "weight_decay": 1e-2}, + lr=5e-06, # learning rate + lr_scheduler="MultiStepLR", + # it was adjusted accordly for the new step scheme + lr_scheduler_params={"milestones": [50000 * 18, 150000 * 18, 300000 * 18], "gamma": 0.5, "last_epoch": -1}, + test_sentences=[], + ) + + # init the model from config + model = GPTTrainer.init_from_config(config) + # load training samples + train_samples, eval_samples = load_tts_samples( + DATASETS_CONFIG_LIST, + eval_split=True, + eval_split_max_size=config.eval_split_max_size, + eval_split_size=config.eval_split_size, + ) + + # init the trainer + trainer = Trainer( + TrainerArgs( + restore_path=None, # xtts checkpoint is restored via xtts_checkpoint key so no need of restore it using Trainer restore_path parameter + skip_train_epoch=False, + start_with_eval=START_WITH_EVAL, + grad_accum_steps=GRAD_ACUMM_STEPS, + ), + config, + output_path=OUT_PATH, + model=model, + train_samples=train_samples, + eval_samples=eval_samples, + ) + trainer.fit() + + # get the longest text audio file to use as speaker reference + samples_len = [len(item["text"].split(" ")) for item in train_samples] + longest_text_idx = samples_len.index(max(samples_len)) + speaker_ref = train_samples[longest_text_idx]["audio_file"] + + trainer_out_path = trainer.output_path + + # deallocate VRAM and RAM + del model, trainer, train_samples, eval_samples + gc.collect() + + return XTTS_CONFIG_FILE, XTTS_CHECKPOINT, TOKENIZER_FILE, trainer_out_path, speaker_ref + +########################## +#### STEP 3 AND OTHER #### +########################## + +def clear_gpu_cache(): + # clear the GPU cache + if torch.cuda.is_available(): + torch.cuda.empty_cache() + +XTTS_MODEL = None +def load_model(xtts_checkpoint, xtts_config, xtts_vocab): + global XTTS_MODEL + clear_gpu_cache() + if not xtts_checkpoint or not xtts_config or not xtts_vocab: + return "You need to run the previous steps or manually set the `XTTS checkpoint path`, `XTTS config path`, and `XTTS vocab path` fields !!" + config = XttsConfig() + config.load_json(xtts_config) + XTTS_MODEL = Xtts.init_from_config(config) + print("[FINETUNE] \033[94mStarting Step 3\033[0m Loading XTTS model!") + XTTS_MODEL.load_checkpoint(config, checkpoint_path=xtts_checkpoint, vocab_path=xtts_vocab, use_deepspeed=False) + if torch.cuda.is_available(): + XTTS_MODEL.cuda() + + print("[FINETUNE] Model Loaded!") + return "Model Loaded!" + +def run_tts(lang, tts_text, speaker_audio_file): + if XTTS_MODEL is None or not speaker_audio_file: + return "You need to run the previous step to load the model !!", None, None + speaker_audio_file = str(speaker_audio_file) + gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(audio_path=speaker_audio_file, gpt_cond_len=XTTS_MODEL.config.gpt_cond_len, max_ref_length=XTTS_MODEL.config.max_ref_len, sound_norm_refs=XTTS_MODEL.config.sound_norm_refs) + out = XTTS_MODEL.inference( + text=tts_text, + language=lang, + gpt_cond_latent=gpt_cond_latent, + speaker_embedding=speaker_embedding, + temperature=XTTS_MODEL.config.temperature, # Add custom parameters here + length_penalty=XTTS_MODEL.config.length_penalty, + repetition_penalty=XTTS_MODEL.config.repetition_penalty, + top_k=XTTS_MODEL.config.top_k, + top_p=XTTS_MODEL.config.top_p, + ) + + with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp: + out["wav"] = torch.tensor(out["wav"]).unsqueeze(0) + out_path = fp.name + torchaudio.save(out_path, out["wav"], 24000) + + return "Speech generated !", out_path, speaker_audio_file + + +def get_available_voices(minimum_size_kb=1300): + voice_files = [ + voice for voice in Path(f"{this_dir}/finetune/tmp-trn/wavs").glob("*.wav") + if voice.stat().st_size > minimum_size_kb * 1300 # Convert KB to bytes + ] + return sorted([str(file) for file in voice_files]) # Return full path as string + +def find_models(directory, extension): + """Find files with a specific extension in the given directory.""" + return [file for file in Path(directory).rglob(f"*.{extension}")] + +def find_jsons(directory, filename): + """Find files with a specific filename in the given directory.""" + return list(Path(directory).rglob(filename)) + +# Your main directory +main_directory = Path(this_dir) / "finetune" / "tmp-trn" +# XTTS checkpoint files (*.pth) +xtts_checkpoint_files = find_models(main_directory, "pth") +# XTTS config files (config.json) +xtts_config_files = find_jsons(main_directory, "config.json") +# XTTS vocab files (vocab.json) +xtts_vocab_files = find_jsons(main_directory, "vocab.json") + + +# define a logger to redirect +class Logger: + def __init__(self, filename="finetune.log"): + self.log_file = filename + self.terminal = sys.stdout + self.log = open(self.log_file, "w") + + def write(self, message): + self.terminal.write(message) + self.log.write(message) + + def flush(self): + self.terminal.flush() + self.log.flush() + + def isatty(self): + return False + +# redirect stdout and stderr to a file +sys.stdout = Logger() +sys.stderr = sys.stdout + + +# logging.basicConfig(stream=sys.stdout, level=logging.INFO) +import logging +logging.basicConfig( + level=logging.INFO, + format="[FINETUNE] %(message)s", + handlers=[ + logging.StreamHandler(sys.stdout) + ] +) + + +def read_logs(): + sys.stdout.flush() + with open(sys.stdout.log_file, "r") as f: + return f.read() + + +def cleanup_before_exit(signum, frame): + print("[FINETUNE] Received interrupt signal. Cleaning up and exiting...") + # Perform cleanup operations here if necessary + sys.exit(0) + + +def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_class, interactive=True): + """ + Copied from https://github.com/AUTOMATIC1111/stable-diffusion-webui + """ + def refresh(): + refresh_method() + args = refreshed_args() if callable(refreshed_args) else refreshed_args + + for k, v in args.items(): + setattr(refresh_component, k, v) + + return gr.update(**(args or {})) + + refresh_button = gr.Button(refresh_symbol, elem_classes=elem_class, interactive=interactive, scale=0) + refresh_button.click( + fn=refresh, + inputs=[], + outputs=[refresh_component] + ) + + return refresh_button + + +if __name__ == "__main__": + # Register the signal handler + signal.signal(signal.SIGINT, cleanup_before_exit) + + +################ +#### GRADIO #### +################ + + parser = argparse.ArgumentParser( + description="""XTTS fine-tuning demo\n\n""" + """ + Example runs: + python3 TTS/demos/xtts_ft_demo/xtts_demo.py --port + """, + formatter_class=argparse.RawTextHelpFormatter, + ) + parser.add_argument( + "--num_epochs", + type=int, + help="Number of epochs to train. Default: 10", + default=10, + ) + parser.add_argument( + "--batch_size", + type=int, + help="Batch size. Default: 4", + default=4, + ) + parser.add_argument( + "--grad_acumm", + type=int, + help="Grad accumulation steps. Default: 1", + default=1, + ) + parser.add_argument( + "--max_audio_length", + type=int, + help="Max permitted audio size in seconds. Default: 11", + default=11, + ) + + args = parser.parse_args() + +##################### +#### GRADIO INFO #### +##################### + + with gr.Blocks(theme=theme) as demo: + with gr.Tab("Information/Guide"): + + gr.Markdown( + f""" + ## Finetuning Information
+ ### πŸŸ₯ Important Note + ####      πŸŸ₯ finetune.py needs to be run from the /alltalk_tts/ folder. Don't move the location of this script. + ####      πŸŸ₯ Have you run AllTalk at least once? It needs to have downloaded the voice model, before we can finetune it. + ### 🟦 What you need to run finetuning + ####      🟦 An Nvidia GPU. Tested on Windows with extended shared VRAM and training used about 16GB's total (which worked on a 12GB card). + ####      🟦 I have not been able to test this on a GPU with less than 12GB of VRAM, so cannot say if it will work or how that would affect performance. + ####      🟦 Version 11.8 of Nvidia cuBLAS and cuDNN (guide below). Only 11.8 of cuBLAS and cuDNN work for this process currently. + ####      🟦 Minimum 18GB free disk space (most of it is used temporarily). + ####      🟦 Some decent quality audio, multiple files if you like. Minimum of 2 minutes and Ive tested up to 20 minutes of audio. + ####      🟦 There is no major need to chop down your audio files into small slices as Step 1 will do that for you automatically and prepare the training set. Ive been testing with 5 minute long clips. + ####      🟦 This process will need access to all your GPU and VRAM, so close any other software that's using your GPU currently. + ### 🟨 Setting up cuBLAS and cuDNN Version 11.8 + ####      🟨 If you have the Nvidia CUDA Toolkit Version 11.8 installed and can type nvcc --version at the command prompt/terminal and it reports Cuda compilation tools, release 11.8 you should be good to go. + ####      🟨 If you dont have the toolkit installed, the idea is just to install the smallest bit possible and this will not affect or impact other things on your system. + ####      🟨 You will need to download the Nvidia Cuda Toolkit 11.8 network install from [here](https://developer.nvidia.com/cuda-11-8-0-download-archive) + ####          1) Run the installer and select Custom Advanced Uncheck everything at the top then expand CUDA, Development > Compiler > and select nvcc then expand Libraries and select CUBLAS. + ####          2) Back at the top of CUDA, expand Runtime > Libraries and select CUBLAS. Click Next, accept the default path (taking a note of its location) and let the install run. + ####          3) You should be able to drop to your terminal or command prompt and type nvcc --version and have it report Cuda compilation tools, release 11.8. If it does you are good to go. If it doesn't > Step 4. + ####          4) Linux users, you can temporarily add these paths on your current terminal window with (you may need to confirm these are correct for your flavour of Linux): + ####              export LD_LIBRARY_PATH=/usr/local/cuda-11.8/lib64:${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} (Add it to your ~/.bashrc if you want this to be permanent) + ####              export LD_LIBRARY_PATH=/usr/local/cuda-11.8/bin + ####          Windows users need the add the following to the PATH environment variable. Start menu and search for "Environment Variables" or "Edit the system environment variables.". + ####          Find and select the "Path" variable, then click on the "Edit...". Click on the "New" button and add: + ####              C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\bin. + ####          5) Once you have these set correctly, you should be able to open a new command prompt/terminal and nvcc --version at the command prompt/terminal, resulting in Cuda compilation tools, release 11.8. + ####          6) If the nvcc command doesn't work OR it reports a version different from 11.8, finetuning wont work, so you will to double check your environment variables and get them working correctly. + """ + ) + +####################### +#### GRADIO STEP 1 #### +####################### + with gr.Tab("Step 1 - Preparing Audio/Generating the dataset"): + + gr.Markdown( + f""" + ## STEP 1 - Preparing Audio/Generating the dataset
+ ### 🟦 What you need to do + ####      🟦 Please read Coqui's guide on what makes a good dataset [here](https://docs.coqui.ai/en/latest/what_makes_a_good_dataset.html#what-makes-a-good-dataset) + ####      🟦 Place your audio files in {str(audio_folder)} + ####      🟦 Your audio samples can be in the format mp3, wav, or flac. + ####      🟦 You will need a minimum of 2 minutes of audio in either one or multiple audio files. + ####      🟦 When you have completed Steps 1, 2, and 3, you are welcome to delete your samples from "put-voice-samples-in-here".
+ ### 🟨 What this step is doing + ####      🟨 With step one, we are going to be stripping your audio file(s) into smaller files, using Whisper to find spoken words/sentences, compile that into excel sheets of training data, ready for finetuning the model on Step 2. + ####      🟨 Whilst you can choose multiple Whisper models, its best only to use the 1 model as each one is about 3GB in size and will download to your local huggingface cache on first-time use. If and when you have completed training, you wish to delete this 3GB model from your system, you are welcome to do so. + ### 🟩 How long will this take? + ####      🟩 First time, it needs to download the Whisper model which is 3GB. After that a few minutes on an average 3-4 year old system. + """ + ) + + out_path = gr.Textbox( + label="Output path (where data and checkpoints will be saved):", + value=out_path, + visible=False, + ) + + whisper_model = gr.Dropdown( + label="Whisper Model", + value="large-v3", + choices=[ + "large-v3", + "large-v2", + "large", + "medium", + "small" + ], + ) + + lang = gr.Dropdown( + label="Dataset Language", + value="en", + choices=[ + "en", + "es", + "fr", + "de", + "it", + "pt", + "pl", + "tr", + "ru", + "nl", + "cs", + "ar", + "zh", + "hu", + "ko", + "ja" + ], + ) + progress_data = gr.Label( + label="Progress:" + ) + logs = gr.Textbox( + label="Logs:", + interactive=False, + ) + demo.load(read_logs, None, logs, every=1) + + prompt_compute_btn = gr.Button(value="Step 1 - Create dataset") + + def preprocess_dataset(language, whisper_model, out_path, progress=gr.Progress(track_tqdm=True)): + clear_gpu_cache() + test_for_audio_files = [file for file in os.listdir(audio_folder) if any(file.lower().endswith(ext) for ext in ['.wav', '.mp3', '.flac'])] + if not test_for_audio_files: + return "I cannot find any mp3, wav or flac files in the folder called 'put-voice-samples-in-here'", "", "" + else: + try: + train_meta, eval_meta, audio_total_size = format_audio_list(target_language=language, whisper_model=whisper_model ,out_path=out_path, gradio_progress=progress) + except: + traceback.print_exc() + error = traceback.format_exc() + return f"The data processing was interrupted due an error !! Please check the console to verify the full error message! \n Error summary: {error}", "", "" + + clear_gpu_cache() + + # if audio total len is less than 2 minutes raise an error + if audio_total_size < 120: + message = "The total duration of the audio file or files you provided, was less than 2 minutes in length. Please add more audio samples." + print("[FINETUNE] ", message) + return message, "", "" + + print("[FINETUNE] Dataset Generated. Move to Step 2") + return "Dataset Generated. Move to Step 2", train_meta, eval_meta +####################### +#### GRADIO STEP 2 #### +####################### + with gr.Tab("Step 2 - Fine-tuning the XTTS Encoder"): + + gr.Markdown( + f""" + ## STEP 2 - Fine-tuning the XTTS Encoder
+ ### 🟦 What you need to do + ####      🟦 The Train CSV and Eval CSV should already be populated. If not, just go back to Step 1 and click the button again. + ####      🟦 If for any reason it crashed, close the app and re-start the finetuning and kick it off again, clicking through setp 1 (it doesnt need to regenerate the data) + ####      🟦 The settings below are factory and should be ok.
+ ### 🟨 What this step is doing + ####      🟨 Very simply put, it's taking all our wav files generated in Step 1, along with our recorded speech in out excel documents and its training the model on that voice. + ### 🟩 How long will this take? + ####      🟩 On a RTX 4070 with factory settings (as below) and 20 minutes of audio, this took 20 minutes. Again, it will vary by system and how much audio you are throwing at it. You have time to go make a coffee. + ####      🟩 Look at your command prompt/terminal window if you want to see what it is doing. + """ + ) + + train_csv = gr.Textbox( + label="Train CSV:", + ) + eval_csv = gr.Textbox( + label="Eval CSV:", + ) + num_epochs = gr.Slider( + label="Number of epochs:", + minimum=1, + maximum=100, + step=1, + value=args.num_epochs, + ) + batch_size = gr.Slider( + label="Batch size:", + minimum=2, + maximum=512, + step=1, + value=args.batch_size, + ) + grad_acumm = gr.Slider( + label="Grad accumulation steps:", + minimum=2, + maximum=128, + step=1, + value=args.grad_acumm, + ) + max_audio_length = gr.Slider( + label="Max permitted audio size in seconds:", + minimum=2, + maximum=20, + step=1, + value=args.max_audio_length, + ) + progress_train = gr.Label( + label="Progress:" + ) + logs_tts_train = gr.Textbox( + label="Logs:", + interactive=False, + ) + demo.load(read_logs, None, logs_tts_train, every=1) + train_btn = gr.Button(value="Step 2 - Run the training") + + def train_model(language, train_csv, eval_csv, num_epochs, batch_size, grad_acumm, output_path, max_audio_length): + clear_gpu_cache() + if not train_csv or not eval_csv: + return "You need to run the data processing step or manually set `Train CSV` and `Eval CSV` fields !", "", "", "", "" + try: + # convert seconds to waveform frames + max_audio_length = int(max_audio_length * 22050) + config_path, original_xtts_checkpoint, vocab_file, exp_path, speaker_wav = train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path=str(output_path), max_audio_length=max_audio_length) + except: + traceback.print_exc() + error = traceback.format_exc() + return f"The training was interrupted due an error !! Please check the console to check the full error message! \n Error summary: {error}", "", "", "", "" + + # copy original files to avoid parameters changes issues + os.system(f"cp {config_path} {exp_path}") + os.system(f"cp {vocab_file} {exp_path}") + + ft_xtts_checkpoint = os.path.join(exp_path, "best_model.pth") + print("[FINETUNE] Model training done. Move to Step 3") + clear_gpu_cache() + return "Model training done. Move to Step 3", config_path, vocab_file, ft_xtts_checkpoint, speaker_wav + +####################### +#### GRADIO STEP 3 #### +####################### + + with gr.Tab("Step 3 - Inference/Testing"): + gr.Markdown( + f""" + ## STEP 3 - Inference/Testing
+ ### πŸŸ₯ Important Note + ####      πŸŸ₯ This step will error if you are using TTS version 0.22.0. Please re-run pip install -r requirements_finetune.txt if it errors loading the model. + ### 🟦 What you need to do + ####      🟦 The model is now trained and you are at the testing stage. Hopefully all the dropdowns should be pre-populated now. + ####      🟦 You need to Load Fine-tuned XTTS model and then select your Speaker Reference Audio. You can choose various Speaker Reference Audios to see which works best. + ####      🟦 All the Speaker Reference Audios in the dropdown are ones that are 8 seconds long or more. You can use one of these later for your voice sample in All Talk, so remember the one you like. + ####      🟦 Some Speaker Reference Audios are a bit long and may cause issues generating the TTS, so try different ones. + ####      🟦 Once you are happy, move to the next tab for instruction on cleaning out the training data and how to copy your newly trained model over your current model. + ### 🟨 What this step is doing + ####      🟨 Its loading the finetuned model into memory, loading a voice sample and generating TTS, so that you can test out how well fine tuning worked. + """ + ) + + with gr.Row(): + with gr.Column() as col1: + xtts_checkpoint = gr.Dropdown( + [str(file) for file in xtts_checkpoint_files], + label="XTTS checkpoint path:", + value="", + allow_custom_value=True, + ) + + xtts_config = gr.Dropdown( + [str(file) for file in xtts_config_files], + label="XTTS config path:", + value="", + allow_custom_value=True, + ) + + xtts_vocab = gr.Dropdown( + [str(file) for file in xtts_vocab_files], + label="XTTS vocab path:", + value="", + allow_custom_value=True, + ) + progress_load = gr.Label( + label="Progress:" + ) + load_btn = gr.Button(value="Step 3 - Load Fine-tuned XTTS model") + + with gr.Column() as col2: + with gr.Row(): + # Gather the voice files + available_speaker_audios = get_available_voices() + + # Create Dropdown for speaker reference audio + speaker_reference_audio = gr.Dropdown( + available_speaker_audios, + label="Speaker reference audio:", + value="", # Set the default value if needed + allow_custom_value=True, # Allow custom values + scale=1, + ) + # Create refresh button + refresh_button = create_refresh_button( + speaker_reference_audio, + lambda: None, # Specify your refresh logic if needed + lambda: {"choices": get_available_voices(), "value": ""}, # Update choices and value + "refresh-button", + ) + + tts_language = gr.Dropdown( + label="Language", + value="en", + choices=[ + "en", + "es", + "fr", + "de", + "it", + "pt", + "pl", + "tr", + "ru", + "nl", + "cs", + "ar", + "zh", + "hu", + "ko", + "ja", + ] + ) + tts_text = gr.Textbox( + label="Input Text:", + value="I've just fine tuned a text to speech language model and this is how it sounds. If it doesn't sound right, I will try a different Speaker Reference Audio file.", + lines=6, + ) + tts_btn = gr.Button(value="Step 4 - Inference (Generate TTS)") + + with gr.Column() as col3: + progress_gen = gr.Label( + label="Progress:" + ) + tts_output_audio = gr.Audio(label="TTS Generated Audio.") + reference_audio = gr.Audio(label="Speaker Reference Audio Used.") + + with gr.Tab("What to do next"): + gr.Markdown( + f""" + ## What to do next
+ ### 🟦 What you need to do + ####      🟦 The wav(s) you liked from Speaker Reference Audios are in /finetune/tmp-trn/wavs/ so copy the one(s) you selected to your /alltalk_tts/voices/ samples folder. + ####      🟦 You can delete your original samples from inside of the /finetune/put-voice-samples-in-here/ folder. + ####      🟦 In the folder /finetune/tmp-trn/training/XTTS_FT(date here)/ you will find your best_model.pth, config.json and voice.json (also the last epoch training best_model_xxx.pth) + ####      🟦 You can delete the last epoch training model file best_model_xxx.pth (the one with the numbers). + ####      🟦 You will need to rename best_model.pth to model.pth. + ####      🟦 You will close the Finetuning application and copy your 3 files listed above over the top of the existing model files inside your /alltalk_tts/models/xttsv2_2.0.2/ folder. + ####      🟦 Start up Alltalk and you should be off and running. Preferably use the XTTS Local method for best results. + ### 🟨 Clearing up disk space + ####      🟨 When you are happy with everything, you can delete the /alltalk_tts/finetune/tmp-trn/ folder. This will delete all training data that was generated. + ####      🟨 If you are not going to train anything again, you can delete the whisper model from inside of your huggingface cache (3GB approx) + ####          Linux ~/.cache/huggingface/hub/(folder-here) + ####          Windows C:\users(your-username)\.cache\huggingface\hub\(folder-here). + ####      🟨 You can also uninstall the Nvidia CUDA 11.8 Toolkit if you wish and remove your environment variable entries. + """ + ) + + + prompt_compute_btn.click( + fn=preprocess_dataset, + inputs=[ + lang, + whisper_model, + out_path, + ], + outputs=[ + progress_data, + train_csv, + eval_csv, + ], + ) + + + train_btn.click( + fn=train_model, + inputs=[ + lang, + train_csv, + eval_csv, + num_epochs, + batch_size, + grad_acumm, + out_path, + max_audio_length, + ], + outputs=[progress_train, xtts_config, xtts_vocab, xtts_checkpoint, speaker_reference_audio], + ) + + load_btn.click( + fn=load_model, + inputs=[ + xtts_checkpoint, + xtts_config, + xtts_vocab + ], + outputs=[progress_load], + ) + + tts_btn.click( + fn=run_tts, + inputs=[ + tts_language, + tts_text, + speaker_reference_audio, + ], + outputs=[progress_gen, tts_output_audio, reference_audio], + ) + + demo.queue().launch( + show_api=False, + inbrowser=True, + share=False, + debug=False, + server_port=7052, + server_name="127.0.0.1", + ) + diff --git a/finetune/put-voice-samples-in-here/put your voice samples in here.txt b/finetune/put-voice-samples-in-here/put your voice samples in here.txt new file mode 100644 index 0000000..e69de29 diff --git a/modeldownload.json b/modeldownload.json index 33ed1e0..76afdcd 100644 --- a/modeldownload.json +++ b/modeldownload.json @@ -6,6 +6,8 @@ "README.md": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/README.md?download=true", "config.json": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/config.json?download=true", "model.pth": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/model.pth?download=true", + "dvae.pth": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/dvae.pth?download=true", + "mel_stats.pth": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/mel_stats.pth?download=true", "vocab.json": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/vocab.json?download=true" } } diff --git a/requirements_finetune.txt b/requirements_finetune.txt new file mode 100644 index 0000000..7cd0a2d --- /dev/null +++ b/requirements_finetune.txt @@ -0,0 +1,7 @@ +gradio>=3.50.2 +torch>=2.1.0+cu118 +torchaudio>=2.1.0+cu118 +TTS==0.21.3 +faster-whisper>=0.10.0 +tqdm>=4.66.0 +pandas>=1.5.0 \ No newline at end of file diff --git a/requirements_nvidia.txt b/requirements_nvidia.txt index 08244e4..64bdcfe 100644 --- a/requirements_nvidia.txt +++ b/requirements_nvidia.txt @@ -1,7 +1,7 @@ numpy>=1.22.0 soundfile>=0.12.1 uvicorn>=0.24.0.post1 -TTS>=0.22.0 +TTS>=0.21.3 torch>=2.1.0+cu118 torchaudio>=2.1.0+cu118 fastapi>=0.104.1 diff --git a/requirements_other.txt b/requirements_other.txt index 2754be7..667d885 100644 --- a/requirements_other.txt +++ b/requirements_other.txt @@ -1,7 +1,7 @@ numpy>=1.22.0 soundfile>=0.12.1 uvicorn>=0.24.0.post1 -TTS>=0.22.0 +TTS>=0.21.3 torch>=2.1.0 torchaudio>=2.1.0 fastapi>=0.104.1 diff --git a/script.py b/script.py index c185a33..e325457 100644 --- a/script.py +++ b/script.py @@ -39,8 +39,8 @@ try: except ModuleNotFoundError: logger.error( f"[{params['branding']}]\033[91mWarning\033[0m Could not find the TTS module. Make sure to install the requirements for the {params['branding']} extension." - f"[{params['branding']}]\033[91mWarning\033[0m Linux / Mac:\npip install -r extensions/alltalk_tts/requirements.txt\n" - f"[{params['branding']}]\033[91mWarning\033[0m Windows:\npip install -r extensions\\alltalk_tts\\requirements.txt\n" + f"[{params['branding']}]\033[91mWarning\033[0m Linux / Mac:\npip install -r /alltalk_tts/requirements.txt\n" + f"[{params['branding']}]\033[91mWarning\033[0m Windows:\npip install -r \\alltalk_tts\\requirements.txt\n" f"[{params['branding']}]\033[91mWarning\033[0m If you used the one-click installer, paste the command above in the terminal window launched after running the cmd_ script. On Windows, that's cmd_windows.bat." ) raise @@ -62,7 +62,9 @@ try: from modules.utils import gradio # This is set to check if the script is being run within text generation webui or as a standalone script. False is running as part of text gen web ui or a gradio interface running_in_standalone = False + output_folder_wav = params["output_folder_wav"] except ModuleNotFoundError: + output_folder_wav = params["output_folder_wav_standalone"] print(f"[{params['branding']}Startup] Running script.py in standalone mode") # This is set to check if the script is being run within text generation webui or as a standalone script. true means standalone running_in_standalone = True @@ -108,7 +110,6 @@ def delete_old_files(folder_path, days_to_keep): # Extract settings using params dictionary delete_output_wavs_setting = params["delete_output_wavs"] -output_folder_wav = params["output_folder_wav"] output_folder_wav = os.path.normpath(output_folder_wav) # Check and perform file deletion @@ -551,15 +552,10 @@ def output_modifier(string, state): else: cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', '')) voice_to_use = params["narrator_voice"] - # Check if character name exists and if not, just call it TTSOUT_ - if "character_menu" in state: - output_file = Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{int(time.time())}_{i}.wav') - else: - output_file = Path(f'{params["output_folder_wav"]}/TTSOUT_{int(time.time())}_{i}.wav') # Generate that TTS and output to a file - output_file_str = output_file.as_posix() + output_filename = get_output_filename(state) generate_response = send_generate_request( - cleaned_part, voice_to_use, language_code, output_file_str + cleaned_part, voice_to_use, language_code, output_filename ) audio_path = generate_response.get("data", {}).get("audio_path") audio_files_paragraph.append(audio_path) @@ -580,14 +576,9 @@ def output_modifier(string, state): ) cleaned_part = html.unescape(processed_string) # Process the part and give it a non-character name if being used vai API or standalone. - if "character_menu" in state: - output_file = Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{int(time.time())}.wav') - else: - output_file = Path(f'{params["output_folder_wav"]}/TTSOUT_{int(time.time())}.wav') - output_file_str = output_file.as_posix() - output_file = get_output_filename(state) + output_filename = get_output_filename(state) generate_response = send_generate_request( - cleaned_part, params["voice"], language_code, output_file_str + cleaned_part, params["voice"], language_code, output_filename ) audio_path = generate_response.get("data", {}).get("audio_path") final_output_file = audio_path @@ -627,9 +618,11 @@ def output_modifier(string, state): def get_output_filename(state): - return Path( - f'{params["output_folder_wav"]}/{state["character_menu"]}_{str(uuid.uuid4())[:8]}.wav' - ).as_posix() + # Check if character name exists and if not, just call it TTSOUT_ + if "character_menu" in state: + return Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{int(time.time())}.wav').as_posix() + else: + return Path(f'{params["output_folder_wav"]}/TTSOUT_{int(time.time())}.wav').as_posix() ############################################### diff --git a/tts_server.py b/tts_server.py index ebaefd0..938bbc6 100644 --- a/tts_server.py +++ b/tts_server.py @@ -22,6 +22,7 @@ from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles from jinja2 import Template from contextlib import asynccontextmanager +from pydantic import field_validator ########################### #### STARTUP VARIABLES #### @@ -161,7 +162,9 @@ async def setup(): # Set "tts_model_loaded" to true params["tts_model_loaded"] = True # Set the output path for wav files - Path(f'{params["output_folder_wav"]}').mkdir(parents=True, exist_ok=True) + output_directory = this_dir / params["output_folder_wav_standalone"] + output_directory.mkdir(parents=True, exist_ok=True) + #Path(f'this_folder/outputs/').mkdir(parents=True, exist_ok=True) # MODEL LOADER For "API TTS" @@ -617,6 +620,218 @@ async def get_audio(filename: str): audio_path = this_dir / "outputs" / filename return FileResponse(audio_path) +######################## +#### GENERATION API #### +######################## +import html +import re +import numpy as np +import soundfile as sf +from typing import Union, Dict +from pydantic import BaseModel, ValidationError, Field + +class Request(BaseModel): + # Define the structure of the 'Request' class if needed + pass + +class JSONInput(BaseModel): + text_input: str = Field(..., max_length=1000, description="text_input needs to be 1000 characters or less.") + text_filtering: str = Field(..., pattern="^(none|standard|html)$", description="text_filtering needs to be 'none', 'standard' or 'html'.") + character_voice_gen: str = Field(..., pattern="^.*\.wav$", description="character_voice_gen needs to be the name of a wav file e.g. mysample.wav.") + narrator_enabled: bool = Field(..., description="narrator_enabled needs to be true or false.") + narrator_voice_gen: str = Field(..., pattern="^.*\.wav$", description="narrator_voice_gen needs to be the name of a wav file e.g. mysample.wav.") + text_not_inside: str = Field(..., pattern="^(character|narrator)$", description="text_not_inside needs to be 'character' or 'narrator'.") + language: str = Field(..., pattern="^(ar|zh-cn|cs|nl|en|fr|de|hu|it|ja|ko|pl|pt|ru|es|tr)$", description="language needs to be one of the following ar|zh-cn|cs|nl|en|fr|de|hu|it|ja|ko|pl|pt|ru|es|tr.") + output_file_name: str = Field(..., pattern="^[a-zA-Z0-9_]+$", description="output_file_name needs to be the name without any special characters or file extension e.g. 'filename'") + output_file_timestamp: bool = Field(..., description="output_file_timestamp needs to be true or false.") + autoplay: bool = Field(..., description="autoplay needs to be a true or false value.") + autoplay_volume: float = Field(..., ge=0.1, le=1.0, description="autoplay_volume needs to be from 0.1 to 1.0") + + @field_validator("autoplay_volume") + @classmethod + def validate_autoplay_volume(cls, value): + if not (0.1 <= value <= 1.0): + raise ValidationError("Autoplay volume must be between 0.1 and 1.0") + return value + + +class TTSGenerator: + @staticmethod + def validate_json_input(json_data: Union[Dict, str]) -> Union[None, str]: + try: + if isinstance(json_data, str): + json_data = json.loads(json_data) + JSONInput(**json_data) + return None # JSON is valid + except ValidationError as e: + return str(e) + +def standard_filtering(text_input): + text_output = (text_input + .replace("***", "") + .replace("**", "") + .replace("*", "") + .replace("\n\n", "\n") + .replace("'", "'") + ) + return text_output + +def narrator_filtering(narrator_text_input): + processed_string = re.sub(r'\.\*\n\*', '. ', narrator_text_input) + processed_string = ( + processed_string + .replace("\n", " ") + .replace('"', '"<') + .replace('"', '"<') + ) + processed_string = processed_string.replace('"<. *', '"< *"') + processed_string = processed_string.replace('< *"', '< *') + processed_string = processed_string.replace('. *', '< *') + text_output = html.unescape(processed_string) + return text_output + +def combine(output_file_timestamp, output_file_name, audio_files): + audio = np.array([]) + sample_rate = None + try: + for audio_file in audio_files: + audio_data, current_sample_rate = sf.read(audio_file) + if audio.size == 0: + audio = audio_data + sample_rate = current_sample_rate + elif sample_rate == current_sample_rate: + audio = np.concatenate((audio, audio_data)) + else: + raise ValueError("Sample rates of input files are not consistent.") + except Exception as e: + # Handle exceptions (e.g., file not found, invalid audio format) + return None, None + if output_file_timestamp: + timestamp = int(time.time()) + output_file_path = os.path.join(this_dir / "outputs" / f'{output_file_name}_{timestamp}_combined.wav') + output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}_{timestamp}_combined.wav' + else: + output_file_path = os.path.join(this_dir / "outputs" / f'{output_file_name}_combined.wav') + output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav' + try: + sf.write(output_file_path, audio, samplerate=sample_rate) + # Clean up unnecessary files + for audio_file in audio_files: + os.remove(audio_file) + except Exception as e: + # Handle exceptions (e.g., failed to write output file) + return None, None + return output_file_path, output_file_url + +# Generation API (separate from text-generation-webui) +@app.post("/api/tts-generate", response_class=JSONResponse) +async def tts_generate( + text_input: str = Form(...), + text_filtering: str = Form(...), + character_voice_gen: str = Form(...), + narrator_enabled: bool = Form(...), + narrator_voice_gen: str = Form(...), + text_not_inside: str = Form(...), + language: str = Form(...), + output_file_name: str = Form(...), + output_file_timestamp: bool = Form(...), + autoplay: bool = Form(...), + autoplay_volume: float = Form(...), +): + try: + #print(f"text_filtering: {text_filtering}") + #print(f"narrator_enabled: {narrator_enabled}") + #print(f"text_not_inside: {text_not_inside}") + #print(f"output_file_timestamp: {output_file_timestamp}") + json_input_data = { + "text_input": text_input, + "text_filtering": text_filtering, + "character_voice_gen": character_voice_gen, + "narrator_enabled": narrator_enabled, + "narrator_voice_gen": narrator_voice_gen, + "text_not_inside": text_not_inside, + "language": language, + "output_file_name": output_file_name, + "output_file_timestamp": output_file_timestamp, + "autoplay": autoplay, + "autoplay_volume": autoplay_volume, + } + JSONresult = TTSGenerator.validate_json_input(json_input_data) + if JSONresult is None: + pass + else: + return JSONResponse(content={"error": JSONresult}, status_code=400) + if narrator_enabled: + print("ORIGINAL UNTOUCHED STRING IS:", text_input,"\n") + if text_filtering in ["standard", "none"]: + cleaned_string = ( + text_input + .replace('"', '"<') + .replace('*', '<*') + ) + print("STANDARD FILTERING IS NOW:", cleaned_string,"\n") + #parts = re.split(r'\.(?Using Voice Samples
  • Text Not inside
  • Low VRAM
  • +
  • Finetuning (Training the model)
  • DeepSpeed