Compare commits

..
34 Commits
Author SHA1 Message Date
erew123 ba1328311c Update README.md 2024-01-01 20:47:32 +00:00
erew123 9e6b9396bc Corrected Spelling mistakes 2024-01-01 20:30:18 +00:00
erew123 2e40db5fe5 Merge pull request #39 from erew123/dev
Dev
2024-01-01 20:05:09 +00:00
erew123 720bf8697f Merge branch 'main' into dev 2024-01-01 20:05:00 +00:00
erew123 1893d1a130 remove unused style.css file 2024-01-01 19:55:38 +00:00
erew123 8472baf031 Delete style.css 2024-01-01 19:51:23 +00:00
erew123 6cab618706 Update README.md 2024-01-01 18:45:41 +00:00
erew123 ebf3b362f7 Add files via upload 2024-01-01 18:20:44 +00:00
erew123 2dd303f53c Add files via upload 2024-01-01 18:10:14 +00:00
erew123 df69fb0b07 Merge pull request #36 from rbruels/feature/add-streaming-tts
Feature: Add streaming TTS, using the new inference_stream() function from CoquiTTS
2024-01-01 16:58:33 +00:00
erew123 a0d9771fa6 Add files via upload 2024-01-01 16:20:58 +00:00
erew123 a71c46bb98 Merge pull request #35 from rbruels/enhancement/templatize-tts-server-html
Enhancement: Templatize tts-server html for ease of editing
2024-01-01 12:41:08 +00:00
erew123 995f317b4f Merge pull request #37 from erew123/main
sync main to dev
2024-01-01 12:36:36 +00:00
Ryan 6ef2de2923 Support streaming of model inference to lower time to first token for long passages. Uses the new CoquiTTS inference_stream() function 2024-01-01 00:27:11 -08:00
Ryan 37c4e86566 Merge branch 'main' into enhancement/templatize-tts-server-html 2023-12-31 15:09:11 -08:00
Ryan 11071b279b Templatize the tts-server HTML for ease of editing 2023-12-31 15:06:39 -08:00
erew123 5ab7463f35 More narrator shenanigans 2023-12-31 21:35:23 +00:00
erew123 74c9238e3a Update README.md 2023-12-30 22:15:30 +00:00
erew123 e874e46304 Update README.md 2023-12-30 15:26:02 +00:00
erew123 b32df6ac15 Additional note in finetune re multiple GPU support 2023-12-30 14:45:42 +00:00
erew123 b76dd3561f Merge pull request #34 from erew123/dev
Dev
2023-12-30 14:23:22 +00:00
erew123 60bfbdcabd Update README.md 2023-12-30 14:12:41 +00:00
erew123 c128d0851b Updated Finetune 2023-12-30 14:00:36 +00:00
erew123 2f3b7762e4 Update README.md 2023-12-30 13:31:41 +00:00
erew123 0e594f5098 Update .gitignore 2023-12-30 13:30:16 +00:00
erew123 14151d4dda Update README.md 2023-12-30 11:27:20 +00:00
erew123 94ab21fb15 Update README.md 2023-12-30 11:26:29 +00:00
erew123 1acac3d6c6 Update README.md 2023-12-30 11:23:59 +00:00
erew123 95ec2dc9d2 Merge pull request #32 from erew123/main
merge main to dev
2023-12-30 11:11:11 +00:00
erew123 6b93eb6c1e Update README.md 2023-12-29 23:38:38 +00:00
erew123 838578a042 Update README.md 2023-12-29 23:28:47 +00:00
erew123 2f689f0438 Model loader for Finetuned models
Adds a detection routine and additional loader for a finetuned model. 
Model has to be in /models/trainedmodel/
2023-12-29 23:15:15 +00:00
erew123 022025ded6 Update README.md 2023-12-29 20:57:28 +00:00
erew123 320a7a6aba Update README.md 2023-12-29 20:51:45 +00:00
10 changed files with 2765 additions and 1220 deletions

No files matched your search

+1
View File
@@ -1,6 +1,7 @@
voices/*.* voices/*.*
models/*.* models/*.*
outputs/*.* outputs/*.*
finetune/*.*
config.json config.json
confignew.json confignew.json
models.json models.json
+9
View File
@@ -0,0 +1,9 @@
{
"files.associations": {
"*.html": "jinja-html"
},
"emmet.includeLanguages": {
"jinja-html": "html",
"jinja2": "html"
},
}
+51 -14
View File
@@ -25,12 +25,9 @@ AllTalk is an updated version of the Coqui_tts extension for Text Generation web
- 🟠 [API Suite and JSON-CURL](https://github.com/erew123/alltalk_tts?#-api-suite-and-json-curl) - 🟠 [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) - 🔴 [Future to-do list & Upcoming updates](https://github.com/erew123/alltalk_tts?#-future-to-do-list)
#### Updates ## 🔄 Updates
**Dec 28th**- Finetuning has been updated to compact models and make the final steps easier (buttons basically). Narrator has been updated. If you wish to compact existing finetuned models, pre the update please see [here](https://github.com/erew123/alltalk_tts/issues/28) Please check the below link to find a list of all recent updates and changes.
####     🔄 **Updates list & bug fixes list** can be found [here](https://github.com/erew123/alltalk_tts/issues/25)
**Dec 25th** - Applied a small update to avoid a possible race condition on file naming with small sentences when generating narrator/character speech. Please update if you are experiencing missing small bits of missing audio on narrator/character.
####     🔄 **Minor updates/bug fixes list** can be found [here](https://github.com/erew123/alltalk_tts/issues/25)
## 🟩 Installation on Text generation web UI ## 🟩 Installation on Text generation web UI
This has been tested on the current Dec 2023 release of Text generation webUI. If you have not updated it for a while, you may wish to update Text generation webUI, [instructions here](https://github.com/oobabooga/text-generation-webui?tab=readme-ov-file#how-to-install) This has been tested on the current Dec 2023 release of Text generation webUI. If you have not updated it for a while, you may wish to update Text generation webUI, [instructions here](https://github.com/oobabooga/text-generation-webui?tab=readme-ov-file#how-to-install)
@@ -72,17 +69,20 @@ Once the extension is loaded, please find all documentation and settings on the
**Where to find voices** https://aiartes.com/voiceai or https://commons.wikimedia.org/ or interviews on youtube etc. Instructions on how to cut down and prepare a voice sample are within the built in documentation. **Where to find voices** https://aiartes.com/voiceai or https://commons.wikimedia.org/ or interviews on youtube etc. Instructions on how to cut down and prepare a voice sample are within the built in documentation.
#### 🟩 The one thing I cant easily work around #### 🟩 The one thing I cant easily work around
Narrator function specific - With a RP chat with your AI, **on your character card** `parameters menu` > `character tab` > `greeting` make sure that anything in there that is the **narrator is in asterisks** and anything **spoken is in double quotes**, then hit the `save` (💾) button. Greeting paragraphs/sentences are handled differently from how the AI sends text and so its difficut to account for them both. Messages intended for the Narrator should be enclosed in asterisks `*` and those for the character inside quotation marks `"`. However, AI systems often deviate from these rules, resulting in text that is neither in quotes nor asterisks. Sometimes, text may appear with only a single asterisk, and AI models may vary their formatting mid-conversation. For example, they might use asterisks initially and then switch to unmarked text. A properly formatted line should look like this:
I could force a delimeter in at this stage, but I know it would/may affect things further down the line in the chat and I need a good think about that before just making a change. This issue **only** affects the greeting card/start of conversation and the "example" card that comes with text-generation-webui suffers this issue (if you want to try it for yourself). So you would put double quotes around like this (from the example card): `"`Hey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers.`"` `*`She walked across the room and picked up her cup of coffee`*`
`"`*Hey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers. I'm sure you have a wealth of knowledge that I can learn from.*`"` Most narrator/character systems switch voices upon encountering an asterisk or quotation marks, which is somewhat effective. AllTalk has undergone several revisions in its sentence splitting and identification methods. While some irregularities and AI deviations in message formatting are inevitable, any line beginning or ending with an asterisk should now be recognized as Narrator dialogue. Lines enclosed in double quotes are identified as Character dialogue. For any other text, you can choose how AllTalk handles it: whether it should be interpreted as Character or Narrator dialogue (most AI systems tend to lean more towards one format when generating text not enclosed in quotes or asterisks).
With improvements to the splitter/processor, I'm confident it's functioning well. You can monitor what AllTalk identifies as Narrator lines on the command line and adjust its behavior if needed (Text Not Inside - Function).
## 🟪 Updating ## 🟪 Updating
This is pretty much a repeat of the installation process. This is pretty much a repeat of the installation process.
1) In a command prompt/terminal window you need to move into your Text generation webUI folder:<br><br> 1) In a command prompt/terminal window you need to move into your Text generation webUI folder:<br><br>
`cd text-generation-webui` `cd text-generation-webui` and start the Python environment for your OS with whichever **one** of the below is correct for your OS:<br><br>
`cmd_windows.bat`, `./cmd_linux.sh`, `cmd_macos.sh` or `cmd_wsl.bat`<br>
2) Move into your extensions and alltalk_tts folder:<br><br> 2) Move into your extensions and alltalk_tts folder:<br><br>
`cd extensions` then `cd alltalk_tts` `cd extensions` then `cd alltalk_tts`
@@ -104,6 +104,7 @@ I did leave a mistake in the `/extensions/alltalk_tts/.gitignore` file at one po
voices/*.* voices/*.*
models/*.* models/*.*
outputs/*.* outputs/*.*
finetune/*.*
config.json config.json
confignew.json confignew.json
models.json models.json
@@ -256,10 +257,29 @@ 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. 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.
</details> </details>
#### 🟨 I have multiple GPU's and I have problems running Finetuning
<details>
<summary>Click to expand</summary><br>
Finetuning pulls in various other scripts and some of those scripts can have issues with multiple Nvidia GPU's being present. Until the people that created those other scripts fix up their code, there is a workaround to temporarily tell your system to only use the 1x of your Nvidia GPU's. To do this:
- **Windows** - You will start the script with `set CUDA_VISIBLE_DEVICES=0 && python finetune.py`<br>
After you have completed training, you can reset back with `set CUDA_VISIBLE_DEVICES=`<br>
- **Linux** - You will start the script with `CUDA_VISIBLE_DEVICES=0 python finetune.py`<br>
After you have completed training, you can reset back with `unset CUDA_VISIBLE_DEVICES`<br>
Rebooting your system will also unset this. The setting is only applied temporarily.
Depending on which of your Nvidia GPU's is the more powerful one, you can change the `0` to `1` or whichever of your GPU's is the most powerful.
</details>
## ⚫ Finetuning a model ## ⚫ 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: 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 - An Nvidia graphics card. (Please see this [note](https://github.com/erew123/alltalk_tts#-i-have-multiple-gpus-and-i-have-problems-running-finetuning) if you have multiple Nvidia GPU's).
- To install a few portions of the Nvidia CUDA 11.8 Toolkit (this will not impact text-generation-webui's cuda setup. - 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) - 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). - 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).
@@ -317,6 +337,18 @@ As mentioned you must have a small portion of the Nvidia CUDA Toolkit **11.8** i
11) Follow the on-screen instructions when the web interface starts 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. 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.
#### ⚫ Using a Finetuned model in Text-generation-webui
At the end of the finetune process, you will have an option to `Compact and move model to /trainedmodel/` this will compact the raw training file and move it to `/model/trainedmodel/`. When AllTalk starts up within Text-generation-webui, if it finds a model in this location a new loader will appear in the interface for `XTTSv2 FT` and you can use this to load your finetuned model. <br><br>**Be careful** not to train a new model from the base model, then overwrite your current `/model/trainedmodel/` **if** you want a seperately trained model. This is why there is an `OPTION B` to move your just trained model to `/models/lastfinetuned/`.
#### ⚫ Training one model with multiple voices
At the end of the finetune process, you will have an option to `Compact and move model to /trainedmodel/` this will compact the raw training file and move it to `/model/trainedmodel/`. This model will become available when you start up finetuning. You will have a choice to train the Base Model or the `Existing finetuned model` (which is the one in `/model/trainedmodel/`). So you can use this to keep further training this model with additional voices, then copying it back to `/model/trainedmodel/` at the end of training.
#### ⚫ Do I need to keep the raw training data/model?
If you've compacted and moved your model, its highly unlikely you would want to keep that data, however the choice is there to keep it if you wish. It will be between 5-10GB in size, so most people will want to delete it.
## 🔵🟢🟡 DeepSpeed Installation Options ## 🔵🟢🟡 DeepSpeed Installation Options
**NOTE**: You **DO NOT** need to set Text-generation-webUI's **--deepspeed** setting for AllTalk to be able to use DeepSpeed. These are two completely separate things and incorrectly setting that on Text-generation-webUI may cause other complications. **NOTE**: You **DO NOT** need to set Text-generation-webUI's **--deepspeed** setting for AllTalk to be able to use DeepSpeed. These are two completely separate things and incorrectly setting that on Text-generation-webUI may cause other complications.
@@ -473,7 +505,7 @@ def get_shm_size():
## 🟦 Running AllTalk as a standalone app ## 🟦 Running AllTalk as a standalone app
AllTalk will run as a standalone app, as long as you install its requirements files into whatever Python environment you are using. You can follow the steps to install the AllTalk's requirements into whatever Python environment you wish. Because I dont know what Python environment you are wanting to use, I can only give you a loose set of installation instructions. AllTalk will run as a standalone app, as long as you install its requirements files into whatever Python environment you are using. You can follow the steps to install the AllTalk's requirements into whatever Python environment you wish. Because I dont know what Python environment you are wanting to use, I can only give you a loose set of installation instructions.
Please note, at time of writing, the TTS engine requires Python **3.9.x** to **3.11.x** [TTS Engine details here](https://pypi.org/project/TTS/) Please note, at time of writing, the TTS engine requires Python **3.9.x** to **3.11.x** [TTS Engine details here](https://pypi.org/project/TTS/). AllTalk and its requirements are tested on Python 3.11.x.
#### 🟦 (Option 1) I already have AllTalk installed as an extension of Text-generation-webui #### 🟦 (Option 1) I already have AllTalk installed as an extension of Text-generation-webui
If you already have AllTalk as a extension of Text-generation-webui, and wish to run it as standalone, load Text-generation-webui's Python environment `cmd_windows.bat`, `./cmd_linux.sh`, `cmd_macos.sh` or `cmd_wsl.bat`, move into the AllTalk folder `cd extensions` > `cd alltalk_tts` and start AllTalk with `python script.py`. There is nothing beyond this you would need to do. If you already have AllTalk as a extension of Text-generation-webui, and wish to run it as standalone, load Text-generation-webui's Python environment `cmd_windows.bat`, `./cmd_linux.sh`, `cmd_macos.sh` or `cmd_wsl.bat`, move into the AllTalk folder `cd extensions` > `cd alltalk_tts` and start AllTalk with `python script.py`. There is nothing beyond this you would need to do.
@@ -537,6 +569,10 @@ Generate a preview of a specified voice with hardcoded settings.
Switch between the 3 models respectively. Switch between the 3 models respectively.
`curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=XTTSv2%20FT"`<br>
If you have a finetuned model in `/models/trainedmodel/` (will error otherwise)
JSON return `{"status": "model-success"}` JSON return `{"status": "model-success"}`
#### 🟠 Switch DeepSpeed Endpoint<br> #### 🟠 Switch DeepSpeed Endpoint<br>
@@ -658,11 +694,12 @@ The API returns a JSON object with the following properties:
- **status** Indicates whether the generation was successful (generate-success) or failed (generate-failure).<br> - **status** Indicates whether the generation was successful (generate-success) or failed (generate-failure).<br>
- **output_file_path** The on-disk location of the generated WAV file.<br> - **output_file_path** The on-disk location of the generated WAV file.<br>
- **output_file_url** The HTTP location for accessing the generated WAV file.<br> - **output_file_url** The HTTP location for accessing the generated WAV file for browser playback.<br>
- **output_cache_url** The HTTP location for accessing the generated WAV file as a pushed download.<br>
Example JSON TTS Generation Response: 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"}` `{"status":"generate-success","output_file_path":"C:\\text-generation-webui\\extensions\\alltalk_tts\\outputs\\myoutputfile_1704141936.wav","output_file_url":"http://127.0.0.1:7851/audio/myoutputfile_1704141936.wav","output_cache_url":"http://127.0.0.1:7851/audiocache/myoutputfile_1704141936.wav"}`
### 🔴 Future to-do list ### 🔴 Future to-do list
- Voice output within the command prompt/terminal (TBD). - Voice output within the command prompt/terminal (TBD).
+329 -125
View File
@@ -48,6 +48,20 @@ else:
print("[FINETUNE] \033[91mWarning\033[0m modeldownload.json is missing. Please run this script in the /alltalk_tts/ folder") print("[FINETUNE] \033[91mWarning\033[0m modeldownload.json is missing. Please run this script in the /alltalk_tts/ folder")
sys.exit(1) sys.exit(1)
##################################################
#### Check to see if a finetuned model exists ####
##################################################
# Set the path to the directory
trained_model_directory = this_dir / "models" / "trainedmodel"
# Check if the directory "trainedmodel" exists
finetuned_model = trained_model_directory.exists()
# If the directory exists, check for the existence of the required files
# If true, this will add a extra option in the Gradio interface for loading Xttsv2 FT
if finetuned_model:
required_files = ["model.pth", "config.json", "vocab.json", "mel_stats.pth", "dvae.pth"]
finetuned_model = all((trained_model_directory / file).exists() for file in required_files)
basemodel_or_finetunedmodel = True
##################### #####################
#### STEP 1 BITS #### #### STEP 1 BITS ####
##################### #####################
@@ -272,6 +286,8 @@ def format_audio_list(target_language, whisper_model, out_path, gradio_progress=
# deallocate VRAM and RAM # deallocate VRAM and RAM
del asr_model, final_eval_set, final_training_set, new_data_df, existing_metadata del asr_model, final_eval_set, final_training_set, new_data_df, existing_metadata
gc.collect() gc.collect()
existing_train_df = None
existing_eval_df = None
print("[FINETUNE] Train CSV:", train_metadata_path) print("[FINETUNE] Train CSV:", train_metadata_path)
print("[FINETUNE] Eval CSV:", eval_metadata_path) print("[FINETUNE] Eval CSV:", eval_metadata_path)
print("[FINETUNE] Audio Total:", audio_total_size) print("[FINETUNE] Audio Total:", audio_total_size)
@@ -289,6 +305,13 @@ from TTS.tts.layers.xtts.trainer.gpt_trainer import GPTArgs, GPTTrainer, GPTTrai
from TTS.utils.manage import ModelManager from TTS.utils.manage import ModelManager
def basemodel_or_finetunedmodel_choice(value):
global basemodel_or_finetunedmodel
if value == "Base Model":
basemodel_or_finetunedmodel = True
elif value == "Existing finetuned model":
basemodel_or_finetunedmodel = False
def train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path, max_audio_length=255995): def train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path, max_audio_length=255995):
# Logging parameters # Logging parameters
RUN_NAME = "XTTS_FT" RUN_NAME = "XTTS_FT"
@@ -321,12 +344,22 @@ def train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv,
# Add here the configs of the datasets # Add here the configs of the datasets
DATASETS_CONFIG_LIST = [config_dataset] DATASETS_CONFIG_LIST = [config_dataset]
# XTTS model checkpoints for fine-tuning. if basemodel_or_finetunedmodel:
TOKENIZER_FILE = str(this_dir / base_path / model_path / "vocab.json") # vocab.json file # BASE XTTS model checkpoints for fine-tuning.
XTTS_CHECKPOINT = str(this_dir / base_path / model_path / "model.pth") # model.pth file print("[FINETUNE] Starting finetuning on Base Model")
XTTS_CONFIG_FILE = str(this_dir / base_path / model_path / "config.json") # config.json file TOKENIZER_FILE = str(this_dir / base_path / model_path / "vocab.json")
DVAE_CHECKPOINT = str(this_dir / base_path / model_path / "dvae.pth") XTTS_CHECKPOINT = str(this_dir / base_path / model_path / "model.pth")
MEL_NORM_FILE = str(this_dir / base_path / model_path / "mel_stats.pth") XTTS_CONFIG_FILE = str(this_dir / base_path / model_path / "config.json")
DVAE_CHECKPOINT = str(this_dir / base_path / model_path / "dvae.pth")
MEL_NORM_FILE = str(this_dir / base_path / model_path / "mel_stats.pth")
else:
# FINETUNED XTTS model checkpoints for fine-tuning.
print("[FINETUNE] Starting finetuning on Existing Finetuned Model")
TOKENIZER_FILE = str(this_dir / base_path / "trainedmodel" / "vocab.json")
XTTS_CHECKPOINT = str(this_dir / base_path / "trainedmodel" / "model.pth")
XTTS_CONFIG_FILE = str(this_dir / base_path / "trainedmodel" / "config.json")
DVAE_CHECKPOINT = str(this_dir / base_path / "trainedmodel" / "dvae.pth")
MEL_NORM_FILE = str(this_dir / base_path / "trainedmodel" / "mel_stats.pth")
# init args and config # init args and config
model_args = GPTArgs( model_args = GPTArgs(
@@ -417,9 +450,14 @@ def train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv,
trainer_out_path = trainer.output_path trainer_out_path = trainer.output_path
# deallocate VRAM and RAM # deallocate VRAM and RAM
del model, trainer, train_samples, eval_samples del model, trainer, train_samples, eval_samples, config, model_args, config_dataset
gc.collect() gc.collect()
train_samples = None
eval_samples = None
config_dataset = None
trainer = None
model = None
model_args = None
return XTTS_CONFIG_FILE, XTTS_CHECKPOINT, TOKENIZER_FILE, trainer_out_path, speaker_ref return XTTS_CONFIG_FILE, XTTS_CHECKPOINT, TOKENIZER_FILE, trainer_out_path, speaker_ref
########################## ##########################
@@ -514,7 +552,7 @@ def compact_model():
# Check if the best model file exists # Check if the best model file exists
if best_model_path_str is None: if best_model_path_str is None:
print("No trained model was found.") print("[FINETUNE] No trained model was found.")
return "No trained model was found." return "No trained model was found."
# Convert model_path_str to Path # Convert model_path_str to Path
@@ -524,7 +562,7 @@ def compact_model():
try: try:
checkpoint = torch.load(best_model_path, map_location=torch.device("cpu")) checkpoint = torch.load(best_model_path, map_location=torch.device("cpu"))
except Exception as e: except Exception as e:
print("Error loading checkpoint:", e) print("[FINETUNE] Error loading checkpoint:", e)
raise raise
del checkpoint["optimizer"] del checkpoint["optimizer"]
@@ -565,20 +603,128 @@ def compact_model():
return "Model copied to '/models/trainedmodel/'" return "Model copied to '/models/trainedmodel/'"
def compact_lastfinetuned_model():
this_dir = Path(__file__).parent.resolve()
best_model_path_str = find_latest_best_model(this_dir / "finetune" / "tmp-trn" / "training")
# Check if the best model file exists
if best_model_path_str is None:
print("[FINETUNE] No trained model was found.")
return "No trained model was found."
# Convert model_path_str to Path
best_model_path = Path(best_model_path_str)
# Attempt to load the model
try:
checkpoint = torch.load(best_model_path, map_location=torch.device("cpu"))
except Exception as e:
print("[FINETUNE] Error loading checkpoint:", e)
raise
del checkpoint["optimizer"]
for key in list(checkpoint["model"].keys()):
if "dvae" in key:
del checkpoint["model"][key]
# Define the target directory
target_dir = this_dir / "models" / "lastfinetuned"
# Create the target directory if it doesn't exist
target_dir.mkdir(parents=True, exist_ok=True)
# Save the modified checkpoint in the target directory
torch.save(checkpoint, target_dir / "model.pth")
# Specify the files you want to copy
files_to_copy = ["vocab.json", "config.json", "dvae.pth", "mel_stats.pth"]
for file_name in files_to_copy:
src_path = this_dir / base_path / base_model_path / file_name
dest_path = target_dir / file_name
shutil.copy(str(src_path), str(dest_path))
source_wavs_dir = this_dir / "finetune" / "tmp-trn" / "wavs"
target_wavs_dir = target_dir / "wavs"
target_wavs_dir.mkdir(parents=True, exist_ok=True)
# Iterate through files in the source directory
for file_path in source_wavs_dir.iterdir():
# Check if it's a file and larger than 1000 KB
if file_path.is_file() and file_path.stat().st_size > 1000 * 1024:
# Copy the file to the target directory
shutil.copy(str(file_path), str(target_wavs_dir / file_path.name))
print("[FINETUNE] Model copied to '/models/lastfinetuned/'")
return "Model copied to '/models/lastfinetuned/'"
def compact_legacy_model():
this_dir = Path(__file__).parent.resolve()
best_model_path_str = os.path.join(this_dir, "finetune", "best_model.pth")
# Check if the best model file exists
if not os.path.exists(best_model_path_str):
print("[FINETUNE] No model called best_model.pth was found in /finetune/")
return "No model called best_model.pth was found in /finetune/"
# Convert model_path_str to Path
best_model_path = Path(best_model_path_str)
# Attempt to load the model
try:
checkpoint = torch.load(best_model_path, map_location=torch.device("cpu"))
except Exception as e:
print("[FINETUNE] Error loading checkpoint:", e)
raise
del checkpoint["optimizer"]
for key in list(checkpoint["model"].keys()):
if "dvae" in key:
del checkpoint["model"][key]
# Define the target directory
target_dir = this_dir / "finetune"
# Create the target directory if it doesn't exist
target_dir.mkdir(parents=True, exist_ok=True)
# Save the modified checkpoint in the target directory
torch.save(checkpoint, target_dir / "model.pth")
print("[FINETUNE] model.pth created in '/finetune/'")
return "model.pth created in '/finetune/'"
def delete_training_data(): def delete_training_data():
# Define the folder to be deleted # Define the folder to be deleted
folder_to_delete = Path(this_dir / "finetune" / "tmp-trn") folder_to_delete = Path(this_dir / "finetune" / "tmp-trn")
# Check if the folder exists before deleting # Check if the folder exists before deleting
if folder_to_delete.exists(): if folder_to_delete.exists():
# Delete the folder and its contents # Iterate over all files and subdirectories
shutil.rmtree(folder_to_delete) for item in folder_to_delete.iterdir():
print(f"[FINETUNE] Folder {folder_to_delete} and its contents deleted successfully.") # Exclude trainer_0_log.txt from deletion
return "Folder '/finetune/tmp-trn/' and its contents deleted successfully." if item.name != "trainer_0_log.txt":
try:
if item.is_file():
item.unlink()
elif item.is_dir():
shutil.rmtree(item)
except PermissionError:
print(f"[FINETUNE] PermissionError: Could not delete {item}. Skipping.")
print(f"[FINETUNE] Folder {folder_to_delete} contents (excluding trainer_0_log.txt) deleted successfully.")
return "Folder '/finetune/tmp-trn/' contents (excluding trainer_0_log.txt) deleted successfully."
else: else:
print(f"[FINETUNE] Folder {folder_to_delete} does not exist.") print(f"[FINETUNE] Folder {folder_to_delete} does not exist.")
return "Folder '/finetune/tmp-trn/' does not exist." return "Folder '/finetune/tmp-trn/' does not exist."
def delete_voice_sample_contents(): def delete_voice_sample_contents():
# Define the folder to be cleared # Define the folder to be cleared
folder_to_clear = Path(this_dir / "finetune" / "put-voice-samples-in-here") folder_to_clear = Path(this_dir / "finetune" / "put-voice-samples-in-here")
@@ -729,20 +875,21 @@ if __name__ == "__main__":
f""" f"""
## <u>Finetuning Information</u><br> ## <u>Finetuning Information</u><br>
### 🟥 <u>Important Note</u> ### 🟥 <u>Important Note</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟥 <span style="color: #3366ff;">finetune.py</span> needs to be run from the <span style="color: #3366ff;">/alltalk_tts/</span> folder. Don't move the location of this script. #### &nbsp;&nbsp;&nbsp;&nbsp; - <span style="color: #3366ff;">finetune.py</span> needs to be run from the <span style="color: #3366ff;">/alltalk_tts/</span> folder. Don't move the location of this script.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟥 Have you run AllTalk at least once? It needs to have downloaded+updated the voice model, before we can finetune it. #### &nbsp;&nbsp;&nbsp;&nbsp; - Have you run AllTalk at least once? It needs to have downloaded+updated the voice model, before we can finetune it.
### 🟦 <u>What you need to run finetuning</u> ### 🟦 <u>What you need to run finetuning</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 An Nvidia GPU. Tested on Windows with extended shared VRAM and training used about 16GB's total (which worked on a 12GB card). #### &nbsp;&nbsp;&nbsp;&nbsp; - An Nvidia GPU. Tested on Windows with extended shared VRAM and training used about 16GB's total (which worked on a 12GB card).
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - If you have multiple Nvidia GPU's in your system, please see this [important note](https://github.com/erew123/alltalk_tts#-i-have-multiple-gpus-and-i-have-problems-running-finetuning).
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 <span style="color: red;">Version 11.8</span> of Nvidia cuBLAS and cuDNN (guide below). Only 11.8 of cuBLAS and cuDNN work for this process currently. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 Minimum <span style="color: red;">18GB</span> free disk space (most of it is used temporarily). #### &nbsp;&nbsp;&nbsp;&nbsp; - <span style="color: red;">Version 11.8</span> of Nvidia cuBLAS and cuDNN (guide below). Only 11.8 of cuBLAS and cuDNN work for this process currently.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 Some decent quality audio, multiple files if you like. Minimum of 2 minutes and Ive tested up to 20 minutes of audio. #### &nbsp;&nbsp;&nbsp;&nbsp; - Minimum <span style="color: red;">18GB</span> free disk space (most of it is used temporarily).
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - Some decent quality audio, multiple files if you like. Minimum of 2 minutes and Ive tested up to 20 minutes of audio.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 This process will need access to all your GPU and VRAM, so close any other software that's using your GPU currently. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
#### &nbsp;&nbsp;&nbsp;&nbsp; - This process will need access to all your GPU and VRAM, so close any other software that's using your GPU currently.
### 🟨 <u>Setting up cuBLAS and cuDNN <span style="color: red;">Version 11.8</span></u> ### 🟨 <u>Setting up cuBLAS and cuDNN <span style="color: red;">Version 11.8</span></u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 If you have the <span style="color: #3366ff;;">Nvidia CUDA Toolkit Version 11.8</span> installed and can type <span style="color: #3366ff;;">nvcc --version</span> at the command prompt/terminal and it reports <span style="color: #00a000;">Cuda compilation tools, release 11.8</span> you should be good to go. #### &nbsp;&nbsp;&nbsp;&nbsp; - If you have the <span style="color: #3366ff;;">Nvidia CUDA Toolkit Version 11.8</span> installed and can type <span style="color: #3366ff;;">nvcc --version</span> at the command prompt/terminal and it reports <span style="color: #00a000;">Cuda compilation tools, release 11.8</span> you should be good to go.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 You will need to download the Nvidia Cuda Toolkit 11.8<span style="color: #3366ff;"> network</span> install from [here](https://developer.nvidia.com/cuda-11-8-0-download-archive) #### &nbsp;&nbsp;&nbsp;&nbsp; - You will need to download the Nvidia Cuda Toolkit 11.8<span style="color: #3366ff;"> network</span> install from [here](https://developer.nvidia.com/cuda-11-8-0-download-archive)
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1) Run the installer and select <span style="color: #3366ff;">Custom Advanced</span> Uncheck <span style="color: #3366ff;">everything</span> at the top then expand <span style="color: #3366ff;">CUDA</span>, <span style="color: #3366ff;">Development</span> > <span style="color: #3366ff;">Compiler</span> > and select <span style="color: #3366ff;;">nvcc</span> then expand <span style="color: #3366ff;;">Libraries</span> and select <span style="color: #3366ff;;">CUBLAS</span>. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1) Run the installer and select <span style="color: #3366ff;">Custom Advanced</span> Uncheck <span style="color: #3366ff;">everything</span> at the top then expand <span style="color: #3366ff;">CUDA</span>, <span style="color: #3366ff;">Development</span> > <span style="color: #3366ff;">Compiler</span> > and select <span style="color: #3366ff;;">nvcc</span> then expand <span style="color: #3366ff;;">Libraries</span> and select <span style="color: #3366ff;;">CUBLAS</span>.
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2) Back at the top of <span style="color: #3366ff;">CUDA</span>, expand <span style="color: #3366ff;">Runtime</span> > <span style="color: #3366ff;">Libraries</span> and select <span style="color: #3366ff;">CUBLAS</span>. Click <span style="color: #3366ff;;">Next</span>, accept the default path (taking a note of its location) and let the install run. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2) Back at the top of <span style="color: #3366ff;">CUDA</span>, expand <span style="color: #3366ff;">Runtime</span> > <span style="color: #3366ff;">Libraries</span> and select <span style="color: #3366ff;">CUBLAS</span>. Click <span style="color: #3366ff;;">Next</span>, accept the default path (taking a note of its location) and let the install run.
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3) You should be able to drop to your terminal or command prompt and type <span style="color: #3366ff;">nvcc --version</span> and have it report <span style="color: #00a000;">Cuda compilation tools, release 11.8</span>. If it does you are good to go. If it doesn't > Step 4. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3) You should be able to drop to your terminal or command prompt and type <span style="color: #3366ff;">nvcc --version</span> and have it report <span style="color: #00a000;">Cuda compilation tools, release 11.8</span>. If it does you are good to go. If it doesn't > Step 4.
@@ -766,16 +913,16 @@ if __name__ == "__main__":
f""" f"""
## <u>STEP 1 - Preparing Audio/Generating the dataset</u><br> ## <u>STEP 1 - Preparing Audio/Generating the dataset</u><br>
### 🟦 <u>What you need to do</u> ### 🟦 <u>What you need to do</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 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) #### &nbsp;&nbsp;&nbsp;&nbsp; - 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)
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 Place your audio files in <span style="color: #3366ff;">{str(audio_folder)}</span> #### &nbsp;&nbsp;&nbsp;&nbsp; - Place your audio files in <span style="color: #3366ff;">{str(audio_folder)}</span>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 Your audio samples can be in the format <span style="color: #3366ff;">mp3, wav,</span> or <span style="color: #3366ff;">flac.</span> #### &nbsp;&nbsp;&nbsp;&nbsp; - Your audio samples can be in the format <span style="color: #3366ff;">mp3, wav,</span> or <span style="color: #3366ff;">flac.</span>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 You will need a minimum of <span style="color: #3366ff;">2 minutes</span> of audio in either one or multiple audio files. #### &nbsp;&nbsp;&nbsp;&nbsp; - You will need a minimum of <span style="color: #3366ff;">2 minutes</span> of audio in either one or multiple audio files. Very small sample files cause errors, so I would suggest 30 seconds and longer samples.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 When you have completed Steps 1, 2, and 3, you are welcome to delete your samples from "put-voice-samples-in-here".<br> #### &nbsp;&nbsp;&nbsp;&nbsp; - When you have completed Steps 1, 2, and 3, you are welcome to delete your samples from "put-voice-samples-in-here".<br>
### 🟨 <u>What this step is doing</u> ### 🟨 <u>What this step is doing</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
### 🟩 <u>How long will this take?</u> ### 🟩 <u>How long will this take?</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟩 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
""" """
) )
@@ -784,41 +931,41 @@ if __name__ == "__main__":
value=out_path, value=out_path,
visible=False, visible=False,
) )
with gr.Row():
whisper_model = gr.Dropdown(
label="Whisper Model",
value="large-v3",
choices=[
"large-v3",
"large-v2",
"large",
"medium",
"small"
],
)
whisper_model = gr.Dropdown( lang = gr.Dropdown(
label="Whisper Model", label="Dataset Language",
value="large-v3", value="en",
choices=[ choices=[
"large-v3", "en",
"large-v2", "es",
"large", "fr",
"medium", "de",
"small" "it",
], "pt",
) "pl",
"tr",
lang = gr.Dropdown( "ru",
label="Dataset Language", "nl",
value="en", "cs",
choices=[ "ar",
"en", "zh",
"es", "hu",
"fr", "ko",
"de", "ja"
"it", ],
"pt", )
"pl",
"tr",
"ru",
"nl",
"cs",
"ar",
"zh",
"hu",
"ko",
"ja"
],
)
progress_data = gr.Label( progress_data = gr.Label(
label="Progress:" label="Progress:"
) )
@@ -863,51 +1010,67 @@ if __name__ == "__main__":
f""" f"""
## <u>STEP 2 - Fine-tuning the XTTS Encoder</u><br> ## <u>STEP 2 - Fine-tuning the XTTS Encoder</u><br>
### 🟦 <u>What you need to do</u> ### 🟦 <u>What you need to do</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 The <span style="color: #3366ff;">Train CSV</span> and <span style="color: #3366ff;">Eval CSV</span> should already be populated. If not, just go back to Step 1 and click the button again. #### &nbsp;&nbsp;&nbsp;&nbsp; - The <span style="color: #3366ff;">Train CSV</span> and <span style="color: #3366ff;">Eval CSV</span> should already be populated. If not, just go back to Step 1 and click the button again.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 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) #### &nbsp;&nbsp;&nbsp;&nbsp; - 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)
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 The settings below are factory and should be ok.<br> #### &nbsp;&nbsp;&nbsp;&nbsp; - The settings below are factory and should be ok.<br>
### 🟨 <u>What this step is doing</u> ### 🟨 <u>What this step is doing</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
### 🟩 <u>How long will this take?</u> ### 🟩 <u>How long will this take?</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟩 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟩 Look at your command prompt/terminal window if you want to see what it is doing. #### &nbsp;&nbsp;&nbsp;&nbsp; - Look at your command prompt/terminal window if you want to see what it is doing.
""" """
) )
with gr.Row():
train_csv = gr.Textbox(
label="Train CSV:",
)
eval_csv = gr.Textbox(
label="Eval CSV:",
)
with gr.Row():
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,
)
with gr.Row():
model_to_train_choices = ["Base Model"]
if finetuned_model:
model_to_train_choices.append("Existing finetuned model")
model_to_train = gr.Radio(
choices=model_to_train_choices,
label="Which model do you want to train?",
value="Base Model"
)
gr.Markdown(
f"""
##### If you have an existing finetuned model in <span style="color: #3366ff;">/models/trainedmodel/</span> you will have an option to select <span style="color: #3366ff;">Existing finetuned model</span>, allowing you to further train it. Otherwise, you will only have Base Model as an option.
"""
)
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( progress_train = gr.Label(
label="Progress:" label="Progress:"
) )
@@ -949,16 +1112,16 @@ if __name__ == "__main__":
f""" f"""
## <u>STEP 3 - Inference/Testing</u><br> ## <u>STEP 3 - Inference/Testing</u><br>
### 🟥 <u>Important Note</u> ### 🟥 <u>Important Note</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟥 This step will error if you are using TTS version 0.22.0. Please re-run <span style="color: #3366ff;">pip install -r requirements_finetune.txt</span> if it errors loading the model. #### &nbsp;&nbsp;&nbsp;&nbsp; - This step will error if you are using TTS version 0.22.0. Please re-run <span style="color: #3366ff;">pip install -r requirements_finetune.txt</span> if it errors loading the model.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟥 If you dont see multiple speaker reference files and you used more than 3 minutes of speech, try refreshing the page as it may not have loaded them correctly. #### &nbsp;&nbsp;&nbsp;&nbsp; - If you dont see multiple speaker reference files and you used more than 3 minutes of speech, try refreshing the page as it may not have loaded them correctly.
### 🟦 <u>What you need to do</u> ### 🟦 <u>What you need to do</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 The model is now trained and you are at the testing stage. Hopefully all the dropdowns should be pre-populated now. #### &nbsp;&nbsp;&nbsp;&nbsp; - The model is now trained and you are at the testing stage. Hopefully all the dropdowns should be pre-populated now.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 You need to <span style="color: #3366ff;">Load Fine-tuned XTTS model</span> and then select your <span style="color: #3366ff;">Speaker Reference Audio</span>. You can choose various <span style="color: #3366ff;">Speaker Reference Audios</span> to see which works best. #### &nbsp;&nbsp;&nbsp;&nbsp; - You need to <span style="color: #3366ff;">Load Fine-tuned XTTS model</span> and then select your <span style="color: #3366ff;">Speaker Reference Audio</span>. You can choose various <span style="color: #3366ff;">Speaker Reference Audios</span> to see which works best.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 All the <span style="color: #3366ff;">Speaker Reference Audios</span> in the dropdown are ones that are <span style="color: #3366ff;">8 seconds</span> long or more. You can use one of these later for your voice sample in All Talk, so remember the one you like. #### &nbsp;&nbsp;&nbsp;&nbsp; - All the <span style="color: #3366ff;">Speaker Reference Audios</span> in the dropdown are ones that are <span style="color: #3366ff;">8 seconds</span> long or more. You can use one of these later for your voice sample in All Talk, so remember the one you like.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 Some <span style="color: #3366ff;">Speaker Reference Audios</span> are a bit long and may cause issues generating the TTS, so try different ones. #### &nbsp;&nbsp;&nbsp;&nbsp; - Some <span style="color: #3366ff;">Speaker Reference Audios</span> are a bit long and may cause issues generating the TTS, so try different ones.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
### 🟨 <u>What this step is doing</u> ### 🟨 <u>What this step is doing</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 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. #### &nbsp;&nbsp;&nbsp;&nbsp; - 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.
""" """
) )
@@ -1051,25 +1214,57 @@ if __name__ == "__main__":
f""" f"""
## <u>What to do next</u><br> ## <u>What to do next</u><br>
### 🟦 <u>What you need to do</u> ### 🟦 <u>What you need to do</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 There are 3x buttons below: #### &nbsp;&nbsp;&nbsp;&nbsp; - You have a few options below:
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Compact &amp; move model. This will compress the trained model and move it, along with any large enough wav files created to <span style="color: #3366ff;">/models/trainedmodel/</span>. You can use the wav files as sample voices.. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Compact &amp; move model. This will compress the raw finetuned model and move it, along with any large enough wav files created to one of two locations (please read text next to the button).<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; You can use the wav files in that location as sample voices with your model. Models moved to <span style="color: #3366ff;">/models/trainedmodel/</span> will be loadable within Text-gen-webui on the <span style="color: #3366ff;">XTTSv2 FT</span> loader.
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Delete Generated Training data. This will delete the finetuned model and any other training data generated during this process. You will more than likely want to do this after you have Compacted &amp; moved the model. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Delete Generated Training data. This will delete the finetuned model and any other training data generated during this process. You will more than likely want to do this after you have Compacted &amp; moved the model.
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Delete original voice samples. This will delete the voice samples you placed in put-voice-samples-in-here (if you no longer have a use for them). #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Delete original voice samples. This will delete the voice samples you placed in put-voice-samples-in-here (if you no longer have a use for them).
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 I will at some point add an option within AllTalk to load a finetuned model as a seperate model. However, for now, you will have to copy it over the model in the <span style="color: #3366ff;">/models/xttsv2_2.0.2/</span> model, if you wish to use it. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 🔹 Compress a legacy finetuned model. For any models that were generated pre the current version of finetuning, you can still compact them down.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟦 If you wish to further train this model, you will also need to copy it over the model in the <span style="color: #3366ff;">/models/xttsv2_2.0.2/</span> model folder.. #### &nbsp;&nbsp;&nbsp;&nbsp; - Instructions on using the finetuned model in Text-generation-webui and also further tuning this model you just created are on <span style="color: #3366ff;">OPTION A - Compact and move model to '/trainedmodel/'</span>.
### 🟨 <u>Clearing up disk space</u> ### 🟨 <u>Clearing up disk space</u>
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 If you are not going to train anything again, you can delete the whisper model from inside of your huggingface cache (3GB approx) #### &nbsp;&nbsp;&nbsp;&nbsp; - If you are not going to train anything again, you can delete the whisper model from inside of your huggingface cache (3GB approx)
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Linux <span style="color: #3366ff;">~/.cache/huggingface/hub/(folder-here)</span> #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Linux <span style="color: #3366ff;">~/.cache/huggingface/hub/(folder-here)</span>
#### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Windows <span style="color: #3366ff;">C:&bsol;users&lpar;your-username&rpar;&bsol;.cache&bsol;huggingface&bsol;hub&bsol;(folder-here)</span>. #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Windows <span style="color: #3366ff;">C:&bsol;users&lpar;your-username&rpar;&bsol;.cache&bsol;huggingface&bsol;hub&bsol;(folder-here)</span>.
#### &nbsp;&nbsp;&nbsp;&nbsp; 🟨 You can also uninstall the Nvidia CUDA 11.8 Toolkit if you wish and remove your environment variable entries. #### &nbsp;&nbsp;&nbsp;&nbsp; - You can also uninstall the Nvidia CUDA 11.8 Toolkit if you wish and remove your environment variable entries.
""" """
) )
final_progress_data = gr.Label( final_progress_data = gr.Label(
label="Progress:" label="Progress:"
) )
compact_btn = gr.Button(value="Compact and move model to '/models/trainedmodel/' (THIS WILL OVER-WRITE ANY MODEL IN THAT LOCATION)") with gr.Row():
delete_training_btn = gr.Button(value="Delete generated training data") compact_btn = gr.Button(value="OPTION A - Compact and move model to '/trainedmodel/'")
delete_voicesamples_btn = gr.Button(value="Delete original voice samples") gr.Markdown(
f"""
##### This will compact the model and move it, along with the reference wav's to <span style="color: #3366ff;">/models/trainedmodel/</span> and will <span style="color: red;">OVERWRITE</span> any model in that location. This model will become available to load in Text-gen-webui with the <span style="color: #3366ff;">XTTSv2 FT</span> loader. It will also be detected by Finetune as a model that can be further trained (Reload finetune.py).
"""
)
with gr.Row():
compact_lastfinetuned_btn = gr.Button(value="OPTION B - Compact and move model to '/lastfinetuned/'")
gr.Markdown(
f"""
##### This will compact the model and move it, along with the reference wav's to <span style="color: #3366ff;">/models/lastfinetuned/</span> and will <span style="color: red;">OVERWRITE</span> any model in that location. This will just leave you a finetuned model that you can do with as you please. It will <span style="color: red;">NOT</span> be available in Text-gen-webui unless you copy it over one of the other model loader locations.
"""
)
with gr.Row():
delete_training_btn = gr.Button(value="Delete generated training data")
gr.Markdown(
f"""
##### This will <span style="color: red;">DELETE</span> your training data and the raw finetuned model from <span style="color: #3366ff;">/finetune/tmp-trn/</span>.
"""
)
with gr.Row():
delete_voicesamples_btn = gr.Button(value="Delete original voice samples")
gr.Markdown(
f"""
##### This will <span style="color: red;">DELETE</span> your original voice samples from <span style="color: #3366ff;">/finetune/put-voice-samples-in-here/</span>.
"""
)
with gr.Row():
compact_legacy_btn = gr.Button(value="Compact a legacy finetuned model")
gr.Markdown(
f"""
##### This will compact your old finetuned models from 5GB to 1.9GB. Place your 5GB <span style="color: #3366ff;">base_model.pth</span> file in <span style="color: #3366ff;">/finetune/</span> (rename your file to <span style="color: #3366ff;">base_model.pth</span> if necessary). This will generate you a <span style="color: #3366ff;">model.pth</span> file.
"""
)
prompt_compute_btn.click( prompt_compute_btn.click(
fn=preprocess_dataset, fn=preprocess_dataset,
@@ -1125,6 +1320,10 @@ if __name__ == "__main__":
fn=compact_model, fn=compact_model,
outputs=[final_progress_data], outputs=[final_progress_data],
) )
compact_lastfinetuned_btn.click(
fn=compact_lastfinetuned_model,
outputs=[final_progress_data],
)
delete_training_btn.click( delete_training_btn.click(
fn=delete_training_data, fn=delete_training_data,
outputs=[final_progress_data], outputs=[final_progress_data],
@@ -1133,6 +1332,11 @@ if __name__ == "__main__":
fn=delete_voice_sample_contents, fn=delete_voice_sample_contents,
outputs=[final_progress_data], outputs=[final_progress_data],
) )
compact_legacy_btn.click(
fn=compact_legacy_model,
outputs=[final_progress_data],
)
model_to_train.change(basemodel_or_finetunedmodel_choice, model_to_train, None)
demo.queue().launch( demo.queue().launch(
show_api=False, show_api=False,
+111 -69
View File
@@ -77,6 +77,8 @@ with open(this_dir / "languages.json", encoding="utf8") as f:
languages = json.load(f) languages = json.load(f)
# Create a global lock # Create a global lock
process_lock = threading.Lock() process_lock = threading.Lock()
# Base setting for a possible FineTuned model existing and the loader being available
tts_method_xtts_ft = False
# Gather the voice files # Gather the voice files
def get_available_voices(): def get_available_voices():
@@ -139,10 +141,23 @@ def check_required_files():
subprocess.run(["python", str(download_script_path)]) subprocess.run(["python", str(download_script_path)])
print(f"[{params['branding']}Startup] All required files are present.") print(f"[{params['branding']}Startup] All required files are present.")
# STARTUP Call Check routine # STARTUP Call Check routine
check_required_files() check_required_files()
##################################################
#### Check to see if a finetuned model exists ####
##################################################
# Set the path to the directory
trained_model_directory = this_dir / "models" / "trainedmodel"
# Check if the directory "trainedmodel" exists
finetuned_model = trained_model_directory.exists()
# If the directory exists, check for the existence of the required files
# If true, this will add a extra option in the Gradio interface for loading Xttsv2 FT
if finetuned_model:
required_files = ["model.pth", "config.json", "vocab.json"]
finetuned_model = all((trained_model_directory / file).exists() for file in required_files)
if finetuned_model:
print(f"[{params['branding']}Startup] Finetuned model \033[93mDetected\033[0m")
#################################################### ####################################################
#### SET GRADIO BUTTONS BASED ON confignew.json #### #### SET GRADIO BUTTONS BASED ON confignew.json ####
@@ -272,11 +287,13 @@ else:
# Cleanly kill off this script, but allow text-generation-webui to keep running, albeit without this alltalk_tts # Cleanly kill off this script, but allow text-generation-webui to keep running, albeit without this alltalk_tts
sys.exit(1) sys.exit(1)
##################################### #####################################
#### MODEL LOADING AND UNLOADING #### #### MODEL LOADING AND UNLOADING ####
##################################### #####################################
# MODEL - Swap model based on Gradio selection API TTS, API Local, XTTSv2 Local # MODEL - Swap model based on Gradio selection API TTS, API Local, XTTSv2 Local
def send_reload_request(tts_method): def send_reload_request(tts_method):
global tts_method_xtts_ft
try: try:
params["tts_model_loaded"] = False params["tts_model_loaded"] = False
url = f"{base_url}/api/reload" url = f"{base_url}/api/reload"
@@ -295,17 +312,26 @@ def send_reload_request(tts_method):
params["tts_method_api_tts"] = True params["tts_method_api_tts"] = True
params["deepspeed_activate"] = False params["deepspeed_activate"] = False
audio_path = this_dir / "templates" / "apitts.wav" audio_path = this_dir / "templates" / "apitts.wav"
tts_method_xtts_ft = False
elif tts_method == "API Local": elif tts_method == "API Local":
params["tts_method_api_tts"] = False params["tts_method_api_tts"] = False
params["tts_method_xtts_local"] = False params["tts_method_xtts_local"] = False
params["tts_method_api_local"] = True params["tts_method_api_local"] = True
params["deepspeed_activate"] = False params["deepspeed_activate"] = False
audio_path = this_dir / "templates" / "apilocal.wav" audio_path = this_dir / "templates" / "apilocal.wav"
tts_method_xtts_ft = False
elif tts_method == "XTTSv2 Local": elif tts_method == "XTTSv2 Local":
params["tts_method_api_tts"] = False params["tts_method_api_tts"] = False
params["tts_method_api_local"] = False params["tts_method_api_local"] = False
params["tts_method_xtts_local"] = True params["tts_method_xtts_local"] = True
audio_path = this_dir / "templates" / "xttslocal.wav" audio_path = this_dir / "templates" / "xttslocal.wav"
tts_method_xtts_ft = False
elif tts_method == "XTTSv2 FT":
params["tts_method_api_tts"] = False
params["tts_method_api_local"] = False
params["tts_method_xtts_local"] = False
audio_path = this_dir / "templates" / "xttsfinetuned.wav"
tts_method_xtts_ft = True
return f'<audio src="file/{audio_path}" controls autoplay></audio>' return f'<audio src="file/{audio_path}" controls autoplay></audio>'
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
# Handle the HTTP request error # Handle the HTTP request error
@@ -483,8 +509,53 @@ def voice_preview(string):
return f"[{params['branding']}Server] Audio generation failed. Status: {generate_response.get('status')}" return f"[{params['branding']}Server] Audio generation failed. Status: {generate_response.get('status')}"
def replace_asterisk(match): def process_text(text):
return match.group(0) + '&quot;<*' # Normalize HTML encoded quotes
text = html.unescape(text)
# Replace ellipsis with a single dot
text = re.sub(r'\.{3,}', '.', text)
# Pattern to identify combined narrator and character speech
combined_pattern = r'(\*[^*"]+\*|"[^"*]+")'
# List to hold parts of speech along with their type
ordered_parts = []
# Track the start of the next segment
start = 0
# Find all matches
for match in re.finditer(combined_pattern, text):
# Add the text before the match, if any, as ambiguous
if start < match.start():
ambiguous_text = text[start:match.start()].strip()
if ambiguous_text:
ordered_parts.append(('ambiguous', ambiguous_text))
# Add the matched part as either narrator or character
matched_text = match.group(0)
if matched_text.startswith('*') and matched_text.endswith('*'):
ordered_parts.append(('narrator', matched_text.strip('*').strip()))
elif matched_text.startswith('"') and matched_text.endswith('"'):
ordered_parts.append(('character', matched_text.strip('"').strip()))
else:
# In case of mixed or improperly formatted parts
if '*' in matched_text:
ordered_parts.append(('narrator', matched_text.strip('*').strip('"')))
else:
ordered_parts.append(('character', matched_text.strip('"').strip('*')))
# Update the start of the next segment
start = match.end()
# Add any remaining text after the last match as ambiguous
if start < len(text):
ambiguous_text = text[start:].strip()
if ambiguous_text:
ordered_parts.append(('ambiguous', ambiguous_text))
return ordered_parts
################################# #################################
#### TTS STANDARD GENERATION #### #### TTS STANDARD GENERATION ####
@@ -494,7 +565,7 @@ def output_modifier(string, state):
if not params["activate"]: if not params["activate"]:
return string return string
original_string = string original_string = string
#print("ORGINAL STRING: ", original_string) #print("ORIGINAL STRING IS:", original_string)
cleaned_string = before_audio_generation(string, params) cleaned_string = before_audio_generation(string, params)
if cleaned_string is None: if cleaned_string is None:
return return
@@ -505,83 +576,55 @@ def output_modifier(string, state):
if process_lock.acquire(blocking=False): if process_lock.acquire(blocking=False):
try: try:
if params["narrator_enabled"]: if params["narrator_enabled"]:
#print(original_string) processed_parts = process_text(original_string)
# Do Some basic stripping and remove any double CR's
processed_string = (
original_string
.replace("***", "*")
.replace("**", "*")
.replace("\n\n", "\n")
.replace("\n", "")
)
processed_string = re.sub(r'\.\*\n\*', '. ', processed_string)
processed_string = (processed_string .replace('&quot;\n\n*', '&quot;<*'))
processed_string = (processed_string .replace('&quot;\n', '< '))
processed_string = (processed_string .replace("&#x27;", "'"))
processed_string = (processed_string .replace("\n", " "))
processed_string = (processed_string .replace('&quot;', '&quot;<'))
processed_string = (processed_string .replace('"', '&quot;<'))
#pattern = re.compile(r'(?<=[a-zA-Z!])&quot;<(?=[a-zA-Z])')
pattern = re.compile(r'(?<=[a-zA-Z!?\.])&quot;<(?=[a-zA-Z])')
processed_string = pattern.sub('&quot; ', processed_string)
pattern = re.compile(r'(?<=[a-zA-Z])\*(?=[a-zA-Z])')
processed_string = pattern.sub('*&quot;', processed_string)
processed_string = processed_string.replace('&quot;<. *', '&quot;< *"')
processed_string = processed_string.replace('< *"', '< *')
processed_string = processed_string.replace('. *', '< *')
processed_string = processed_string.replace('! *', '&quot;< *')
processed_string = processed_string.replace('? *', '< *')
processed_string = processed_string.replace('* ', '* &quot;<')
processed_string = processed_string.replace('*. ', '* &quot;<')
processed_string = re.sub(r'\*(?=[a-zA-Z])', replace_asterisk, processed_string)
# Set up a tracking of the individual wav files.
audio_files_all_paragraphs = [] audio_files_all_paragraphs = []
# Split the line using &quot; and ".* " (so end of sentences, leaving special characters added to the start of all OTHER sentences, bar possibly the first one if its starting with a * for part_type, part in processed_parts:
parts = re.split(r'&quot;|\.\*', processed_string)
audio_files_paragraph = []
for i, part in enumerate(parts):
# Skip parts that are too short # Skip parts that are too short
if len(part.strip()) <= 3: if len(part.strip()) <= 3:
continue continue
# Figure out which type of line it is, then replace characters as necessary to avoid TTS trying to pronunce them, htmlunescape after.
# Character will always be a < with a letter immediately after it # Determine the voice to use based on the part type
if '<' in part and '< *' not in part and '<*' not in part and '< *' not in part and '< ' not in part and '< ' not in part: if part_type == 'narrator':
cleaned_part = html.unescape(part.replace('<', ''))
voice_to_use = params["voice"]
#Narrator will always be an * or < with an * a position or two after it.
elif '<*' in part or '< *' in part or '< *' in part or '*' in part:
cleaned_part = html.unescape(part.replace('<*', '').replace('< *', '').replace('< *', '').replace('*', ''))
voice_to_use = params["narrator_voice"] voice_to_use = params["narrator_voice"]
#If the other two dont capture it, aka, the AI gave no * or &quot; on the line, use non_quoted_text_is aka user interface, user can choose Char or Narrator print(f"[{params['branding']}TTSGen] \033[92mNarrator\033[0m") # Green
elif non_quoted_text_is: elif part_type == 'character':
cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', ''))
voice_to_use = params["voice"] voice_to_use = params["voice"]
print(f"[{params['branding']}TTSGen] \033[36mCharacter\033[0m") # Yellow
else: else:
cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', '')) # Handle ambiguous parts based on user preference
voice_to_use = params["narrator_voice"] voice_to_use = params["voice"] if non_quoted_text_is else params["narrator_voice"]
# Generate that TTS and output to a file voice_description = "\033[36mCharacter (Text-not-inside)\033[0m" if non_quoted_text_is else "\033[92mNarrator (Text-not-inside)\033[0m"
print(f"[{params['branding']}TTSGen] {voice_description}")
# Replace multiple exclamation marks, question marks, or other punctuation with a single instance
cleaned_part = re.sub(r'([!?.])\1+', r'\1', part)
# Further clean to remove any other unwanted characters
cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_part)
# Remove all newline characters (single or multiple)
cleaned_part = re.sub(r'\n+', ' ', cleaned_part)
# Generate TTS and output to a file
output_filename = get_output_filename(state) output_filename = get_output_filename(state)
generate_response = send_generate_request( generate_response = send_generate_request(
cleaned_part, voice_to_use, language_code, output_filename cleaned_part, voice_to_use, language_code, output_filename
) )
audio_path = generate_response.get("data", {}).get("audio_path") audio_path = generate_response.get("data", {}).get("audio_path")
audio_files_paragraph.append(audio_path) audio_files_all_paragraphs.append(audio_path)
# Accumulate audio files within the paragraph
audio_files_all_paragraphs.extend(audio_files_paragraph)
# Combine audio files across paragraphs # Combine audio files across paragraphs
final_output_file = combine( final_output_file = combine(
audio_files_all_paragraphs, params["output_folder_wav"], state audio_files_all_paragraphs, params["output_folder_wav"], state
) )
else: else:
processed_string = ( # Decode HTML entities first
original_string cleaned_part = html.unescape(original_string)
.replace("***", "") # Replace multiple instances of certain punctuation marks with a single instance
.replace("**", "") cleaned_part = re.sub(r'([!?.])\1+', r'\1', cleaned_part)
.replace("*", "") # Further clean to remove any other unwanted characters
.replace("\n\n", "\n") cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_part)
.replace("&#x27;", "'") # Remove all newline characters (single or multiple)
) cleaned_part = re.sub(r'\n+', ' ', cleaned_part)
cleaned_part = html.unescape(processed_string)
# Process the part and give it a non-character name if being used vai API or standalone. # Process the part and give it a non-character name if being used vai API or standalone.
if "character_menu" in state: if "character_menu" in state:
output_file = Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{int(time.time())}.wav') output_file = Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{int(time.time())}.wav')
@@ -689,10 +732,6 @@ def input_modifier(string, state):
shared.processing_message = "*Is recording a voice message...*" shared.processing_message = "*Is recording a voice message...*"
return string return string
def custom_css():
path_to_css = Path(f"{this_dir}/style.css")
return open(path_to_css, "r").read()
def ui(): def ui():
with gr.Accordion(params["branding"] + " TTS (XTTSv2)"): with gr.Accordion(params["branding"] + " TTS (XTTSv2)"):
@@ -786,8 +825,11 @@ def ui():
deepspeed_checkbox_play = gr.HTML(visible=False) deepspeed_checkbox_play = gr.HTML(visible=False)
with gr.Row(): with gr.Row():
model_loader_choices=["API TTS", "API Local", "XTTSv2 Local"]
if finetuned_model:
model_loader_choices.append("XTTSv2 FT")
tts_radio_buttons = gr.Radio( tts_radio_buttons = gr.Radio(
choices=["API TTS", "API Local", "XTTSv2 Local"], choices=model_loader_choices,
label="Select TTS Generation Method (Read NOTE)", label="Select TTS Generation Method (Read NOTE)",
value=gr_modelchoice, # Set the default value value=gr_modelchoice, # Set the default value
) )
-8
View File
@@ -1,8 +0,0 @@
.SDAP .hires_opts input[type="number"] {
width: 6em !important;
}
/* silero_tts preview */
.form:has(> #silero_preview_text) {
min-width: 75%
}
+584
View File
@@ -0,0 +1,584 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AllTalk TTS Generator</title>
<style>
body,
textarea,
select,
input[type="range"],
input[type="number"],
button {
font-family: Arial, sans-serif;
}
body {
margin: 20px;
background-color: #f7f7f7;
color: #333;
}
h1 {
color: #333;
text-align: center;
}
.form-container {
max-width: 80%;
margin: 50px auto;
padding: 20px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, .2);
}
.settings-section {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
/* Align items to the start */
align-items: center;
/* Align items vertically */
gap: 20px;
/* This creates a consistent gap between all child elements */
}
.setting {
margin-bottom: 10px;
/* Space from bottom if wrapped */
display: flex;
flex-direction: column;
/* Removed flex property to stop forcing them to grow */
}
label {
font-size: 0.9em;
color: #333;
margin-bottom: 5px;
}
textarea {
resize: vertical;
width: 100%;
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
/* Ensure select and input elements do not exceed the width of their parent */
select,
input[type="range"],
input[type="number"] {
width: 100%;
/* They will fill the width of their .setting container */
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
@media (min-width: 768px) {
select,
input[type="range"],
input[type="number"] {
width: auto;
/* Only auto width for larger screens */
}
}
button {
background-color: #4caf50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
display: inline-block;
margin: 5px 0;
}
button:hover {
background-color: #45a049;
}
.dark-mode {
background-color: #121212;
color: #ffffff;
/* Text color for dark mode background */
}
.dark-mode .form-container {
background-color: #1e1e1e;
}
/* Modify the text color for elements within dark mode */
.dark-mode label,
.dark-mode textarea,
.dark-mode select,
.dark-mode input[type="range"],
.dark-mode input[type="number"],
.dark-mode button,
.dark-mode .error {
color: #ffffff;
/* Text color for dark mode elements */
}
/* Modify text color for input elements, textarea, and dropdowns in dark mode */
.dark-mode input,
.dark-mode textarea,
.dark-mode select {
color: #000000;
/* Text color for input elements, textarea, and dropdowns in dark mode */
}
/* Set background color for textarea in dark mode */
.dark-mode textarea {
background-color: #C0C0C0;
/* Light grey background color for textarea in dark mode */
}
/* Set background color for option elements within select in dark mode */
.dark-mode select {
background-color: #C0C0C0;
/* Light grey background color for options in dark mode */
}
/* Additional styles if needed for fixed-width dropdowns */
.fixed-size-dropdown {
width: 130px;
/* Adjust the width as needed */
}
.progress-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.spinner {
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.error {
color: #ff0000;
}
/* Add space between sliders */
.slider-setting {
margin-right: 20px;
}
/* Adjust the thumb appearance for a more standard line slider look */
input[type="range"]::-webkit-slider-thumb,
input[type="range"]::-moz-range-thumb,
input[type="range"]::-ms-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
/* Smaller width for a more standard thumb size */
height: 16px;
/* Smaller height for a more standard thumb size */
border-radius: 50%;
/* Keep it rounded, or set to 0 for square */
background: #3071a9;
cursor: pointer;
margin-top: -7px;
/* Adjust if needed to align thumb with the track */
}
</style>
</head>
<h1>AllTalk TTS Generator</h1>
<div class="form-container">
<div class="input-section">
<label for="text_input">Text Input:</label>
<textarea id="text_input" rows="8"></textarea> <!-- Removed cols attribute -->
</div>
<div class="settings-section">
<div class="setting voice-setting">
<label for="character_voice_gen">Character Voice:</label>
<select id="character_voice_gen"></select>
</div>
<div class="setting language-setting">
<label for="language">Language:</label>
<select id="language" name="language" class="fixed-size-dropdown">
<option value="ar">Arabic</option>
<option value="zh-cn">Chinese (Simplified)</option>
<option value="cs">Czech</option>
<option value="nl">Dutch</option>
<option value="en" selected>English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="hu">Hungarian</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="ko">Korean</option>
<option value="pl">Polish</option>
<option value="pt">Portuguese</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="tr">Turkish</option>
</select>
</div>
<div class="setting play-mode-setting">
<label for="playMode">Playback:</label>
<select id="playMode" name="playMode" class="fixed-size-dropdown">
<option value="local" selected>In Browser</option>
<option value="remote">On Server</option>
</select>
</div>
<div class="setting theme-mode-setting">
<label for="themeMode">Theme:</label>
<select id="themeMode" name="themeMode" class="fixed-size-dropdown">
<option value="light" selected>Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div class="setting chunk-size-setting">
<label for="chunkSize">Sentence Chunk Size:</label>
<input type="range" id="chunkSize" name="chunkSize" class="slider-setting" min="1" max="10" value="4"
oninput="updateChunkSizeValue(this.value)">
<span id="chunkSizeValue">3</span> <!-- Display the value of the slider -->
</div>
<div class="setting volume-setting">
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" class="slider-setting" min="0.1" max="1.0" step="0.1"
value="0.8" oninput="updateVolumeValue(this.value)">
<span id="volumeValue">0.8</span>
</div>
</div>
<div class="action-buttons">
<button onclick="generateTTS()">Generate TTS</button>
<button onclick="stopPlayback()">Stop Playback</button>
<button onclick="previewVoice()">Preview Voice</button>
</div>
<div id="progressIndicator" class="progress-overlay" style="display: none;">
<div class="spinner"></div>
</div>
</div>
<script>
async function fetchVoices() {
try {
const response = await fetch("http://127.0.0.1:7851/api/voices");
const result = await response.json();
const characterVoiceSelect = document.getElementById("character_voice_gen");
result.voices.forEach(voice => {
const option = document.createElement("option");
option.value = voice;
option.text = voice;
characterVoiceSelect.add(option);
});
} catch (error) {
console.error(error);
}
}
function updateVolumeValue(value) {
document.getElementById("volumeValue").innerText = value;
// Set the volume for browser playback
audioElement.volume = parseFloat(value);
}
let stopTTSGeneration = false;
let audioQueue = [];
let currentlyPlaying = false;
const audioElement = new Audio();
async function generateTTS() {
try {
// Reset the flag at the start
stopTTSGeneration = false;
const textInput = document.getElementById("text_input").value;
const language = document.getElementById("language").value;
const characterVoice = document.getElementById("character_voice_gen").value;
const volume = parseFloat(document.getElementById("volume").value);
const chunkSize = parseInt(document.getElementById("chunkSize").value);
// Retrieve the value of the selected option for playMode from the dropdown
const playModeValue = document.getElementById("playMode").value;
// Clean up the textInput
let cleanedText = textInput.replace(/ \- | \– /g, ' '); // Replaces " - " and " – " with " "
cleanedText = cleanedText.replace(/\.\s'/g, ".'"); // Correctly remove space between a period and a single quote
cleanedText = cleanedText.replace(/'/g, ""); // Remove all single quotes
// Split text into chunks based on the specified number of sentences
const sentences = cleanedText.match(/("[^"]+"|[^.!?]+[.!?]+)/g);
const chunks = [];
for (let i = 0; i < sentences.length; i += chunkSize) {
let chunk = sentences.slice(i, i + chunkSize).map(s => s.trim()).join(' ');
chunks.push(chunk);
}
// Use playModeValue for the conditional check
if (playModeValue === "remote") {
for (const chunk of chunks) {
if (stopTTSGeneration) break; // Stop if flag is set
await generateAndPlayRemote(chunk, language, characterVoice, volume);
}
} else if (playModeValue === "local") {
generateAndPlayLocal(chunks, 0);
}
} catch (error) {
console.error("Error in generateTTS:", error);
}
}
async function generateAndPlayLocal(chunks, index) {
if (index >= chunks.length || stopTTSGeneration) {
return; // Stop if no more chunks or flag is set
}
if (index >= chunks.length) {
// No more chunks to process
return;
}
try {
const chunk = chunks[index];
const data = new URLSearchParams({
text_input: chunk.trim(),
text_filtering: "standard",
character_voice_gen: document.getElementById("character_voice_gen").value,
narrator_enabled: "false",
narrator_voice_gen: document.getElementById("character_voice_gen").value,
text_not_inside: "character",
language: document.getElementById("language").value,
output_file_name: "myoutputfile",
output_file_timestamp: "true",
autoplay: "false",
autoplay_volume: document.getElementById("volume").value
});
const response = await fetch("http://127.0.0.1:7851/api/tts-generate", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: data,
});
const result = await response.json();
if (result.output_file_url) {
audioQueue.push(result.output_file_url);
if (!currentlyPlaying) {
playNextLocalChunk();
}
}
// Recursively call the function with the next index
generateAndPlayLocal(chunks, index + 1);
} catch (error) {
console.error("Error in generateAndPlayLocal with chunk index", index, ":", error);
}
}
async function generateAndPlayRemote(chunk, language, characterVoice, volume) {
try {
if (stopTTSGeneration) {
console.log("TTS generation stopped.");
return; // Early return if stop flag is set
}
const data = new URLSearchParams({
text_input: chunk.trim(),
text_filtering: "standard",
character_voice_gen: characterVoice,
narrator_enabled: "false",
narrator_voice_gen: characterVoice,
text_not_inside: "character",
language: language,
output_file_name: "myoutputfile",
output_file_timestamp: "true",
autoplay: "true",
autoplay_volume: volume.toString(),
});
const response = await fetch("http://127.0.0.1:7851/api/tts-generate", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: data,
});
const result = await response.json();
if (!response.ok) {
throw new Error(`API error: ${result.detail || 'Unknown error'}`);
}
console.log("TTS generation complete for chunk:", chunk);
} catch (error) {
console.error("Error in generateAndPlayRemote:", error);
}
}
async function previewVoice() {
const characterVoice = document.getElementById("character_voice_gen").value;
try {
const formData = new FormData();
formData.append("voice", characterVoice);
const response = await fetch("http://127.0.0.1:7851/api/previewvoice/", {
method: "POST",
body: formData,
});
const result = await response.json();
if (result.status === "generate-success") {
// Play the preview audio
const audioPreview = new Audio(result.output_file_url);
audioPreview.play();
} else {
throw new Error('Preview generation failed');
}
} catch (error) {
console.error('Error in previewVoice:', error);
}
}
function playNextLocalChunk() {
if (audioQueue.length > 0) {
currentlyPlaying = true;
const audioUrl = audioQueue.shift();
audioElement.src = audioUrl;
audioElement.play();
audioElement.onended = () => {
currentlyPlaying = false;
playNextLocalChunk();
};
}
}
function toggleThemeMode() {
// Retrieve the value of the selected option for themeMode from the dropdown
const themeModeValue = document.getElementById('themeMode').value;
if (themeModeValue === "dark") {
document.body.classList.add('dark-mode');
localStorage.setItem('darkMode', 'enabled'); // Assuming saveDarkModePreference sets this
} else {
document.body.classList.remove('dark-mode');
localStorage.setItem('darkMode', 'disabled'); // Assuming saveDarkModePreference sets this
}
}
function updateChunkSizeValue(value) {
document.getElementById("chunkSizeValue").innerText = value;
}
// Optionally, save the dark mode preference in localStorage
function saveDarkModePreference(isDarkMode) {
localStorage.setItem('darkMode', isDarkMode ? 'enabled' : 'disabled');
}
function stopPlayback() {
// Stop current audio playback
audioElement.pause();
audioElement.currentTime = 0;
// Clear the audio queue, reset playback flag, and stop further TTS generation
audioQueue = [];
currentlyPlaying = false;
stopTTSGeneration = true; // Set flag to stop TTS generation
}
function showProgress() {
document.getElementById('progressIndicator').style.display = 'flex';
}
function hideProgress() {
document.getElementById('progressIndicator').style.display = 'none';
}
function displayOutput(result) {
const outputContainer = document.getElementById("output");
outputContainer.innerHTML = `<p>Status: ${result.status}</p>`;
if (result.output_file_path) {
outputContainer.innerHTML += `<p>File Path: ${result.output_file_path}</p>`;
}
if (result.output_file_url) {
outputContainer.innerHTML += `<p>File URL: ${result.output_file_url}</p>`;
}
if (result.error) {
outputContainer.innerHTML += `<p class="error">Error: ${result.error}</p>`;
}
}
window.onload = function() {
fetchVoices();
const isDarkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
const themeModeSelect = document.getElementById('themeMode');
if (isDarkModeEnabled) {
document.body.classList.add('dark-mode');
themeModeSelect.value = 'dark';
} else {
themeModeSelect.value = 'light';
}
// Add change event listener to the themeMode dropdown
themeModeSelect.addEventListener('change', toggleThemeMode);
// Initialize other elements if necessary
};
</script>
</body>
</html>
+1430
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+250 -1004
View File
File diff suppressed because it is too large. Load diff