Compare commits

..
179 Commits
Author SHA1 Message Date
erew123 9bb0d1fa58 Update README.md 2024-03-04 09:34:55 +00:00
erew123 015b9033ec Additional updates re chinese
CJK Symbols and Punctuation range u3000 > u303F
2024-02-21 20:58:57 +00:00
erew123 7f261bb5e9 Attempt to allow Chinese character set through 2024-02-21 12:24:11 +00:00
erew123 00b93cfe1b explicit allowance for ć, ś, ń, ł etc 2024-02-07 12:44:42 +00:00
erew123 c0d01ee931 Update tts_server.py 2024-02-05 14:05:49 +00:00
erew123 d0ceb2bb65 Update atsetup.sh 2024-01-30 11:37:23 +00:00
erew123 3231e61d56 Bumped transformers requirements >=4.37.1
Now transformers is fixed, bumped requirements up to skip 4.37.0
2024-01-30 11:36:37 +00:00
erew123 32f3b721c2 Update README.md 2024-01-24 17:06:26 +00:00
erew123 8c588939d2 Merge pull request #86 from erew123/dev
merge main > dev
2024-01-23 14:24:57 +00:00
erew123 ff1077f282 Update docker-compose-cuda.yml 2024-01-23 13:25:37 +00:00
erew123 36d0e92ed9 Update docker-compose.yml 2024-01-23 13:25:09 +00:00
erew123 8dfb84d7e2 Merge pull request #83 from Josh-XT/main
Standalone Docker Container
2024-01-23 13:05:38 +00:00
erew123 4caecdc5eb Merge pull request #85 from erew123/main
main to dev merge
2024-01-23 13:01:56 +00:00
Josh XT 40f2fbf54e Merge branch 'erew123:main' into main 2024-01-23 06:57:54 -05:00
erew123 ab37dd8849 Update README.md 2024-01-23 11:45:29 +00:00
erew123 03b02e0e4c Update README.md 2024-01-23 11:18:42 +00:00
Josh XT 351f46c7b5 Merge branch 'erew123:main' into main 2024-01-22 21:20:17 -05:00
Josh XT 71ba584e7c Add voices 2024-01-22 21:15:29 -05:00
Josh XT b3f53e93cc fix typo 2024-01-22 20:46:53 -05:00
Josh XT 0ed3cb75b5 Add modeldownload 2024-01-22 20:44:18 -05:00
Josh XT c29de18ad4 add chmod 2024-01-22 19:41:18 -05:00
Josh XT ec1d0e8c5d Check if running in docker 2024-01-22 19:26:23 -05:00
Josh XT 12bf008b3f Run back end without subprocess 2024-01-22 19:15:54 -05:00
erew123 ecdc10ece5 Update atsetup.bat 2024-01-22 23:27:55 +00:00
Josh XT 360f70cb0a Disable deepspeed 2024-01-22 18:10:20 -05:00
Josh XT 51c91c3d70 Fix config 2024-01-22 17:35:21 -05:00
Josh XT 81a9f4c847 Persist config 2024-01-22 17:33:02 -05:00
Josh XT cdce7511dc Use deepspeed 2024-01-22 17:31:41 -05:00
erew123 6d4b6d336b Update README.md 2024-01-22 22:30:47 +00:00
erew123 6c4a9b19c7 Update README.md 2024-01-22 22:21:21 +00:00
erew123 82ecf3eecc Update README.md 2024-01-22 22:18:16 +00:00
Josh XT d750959f52 Add docker-compose 2024-01-22 17:04:28 -05:00
Josh XT bd74de53da Add portaudio19-dev 2024-01-22 16:53:08 -05:00
Josh XT fcec9d8f5b Fix python alias 2024-01-22 16:32:30 -05:00
Josh XT 85e5e6ab86 Merge branch 'erew123:main' into main 2024-01-22 16:06:30 -05:00
Josh XT d15931bdda 3 2024-01-22 15:54:46 -05:00
erew123 abc9cf1fb7 Update README.md 2024-01-22 20:45:11 +00:00
erew123 2b60f5b0da Update requirements_other.txt 2024-01-22 20:01:16 +00:00
erew123 e524063ec2 Update requirements_nvidia.txt 2024-01-22 20:01:04 +00:00
erew123 d93906a75f Update atsetup.sh 2024-01-22 20:00:47 +00:00
erew123 ad57deed20 Update atsetup.bat 2024-01-22 20:00:21 +00:00
erew123 d0866e3c6c Update README.md 2024-01-22 19:16:54 +00:00
erew123 af907a299d Update requirements_other.txt 2024-01-22 18:56:50 +00:00
erew123 7928af1bb7 Update requirements_nvidia.txt 2024-01-22 18:56:39 +00:00
erew123 4d837a0219 Update atsetup.sh
force     pip install transformers==4.36.2
2024-01-22 18:56:11 +00:00
erew123 e50817a234 Update atsetup.bat
force install of transformers pip install transformers==4.36.2
2024-01-22 18:55:45 +00:00
Josh XT c3bb58d2af Update dockerhub 2024-01-22 12:15:10 -05:00
Josh XT c17959f142 Add dockerhub publish 2024-01-22 12:12:22 -05:00
Josh XT def2d51c5f Use ubuntu 2024-01-22 11:54:29 -05:00
Josh XT 6166d4f751 No arm support 2024-01-22 11:52:41 -05:00
Josh XT cd164ae258 Updates 2024-01-22 11:49:10 -05:00
Josh XT f089e3e85b Add multi build 2024-01-22 11:45:55 -05:00
Josh XT d008c7ab0a Move install 2024-01-22 11:27:35 -05:00
Josh XT a199adfbd6 Add deps 2024-01-22 11:24:54 -05:00
Josh XT 61998b4d39 Set to nvidia 2024-01-22 11:21:15 -05:00
Josh XT 55799b2de8 Add workflow 2024-01-22 10:54:14 -05:00
Josh XT ece55ffe06 Create Dockerfile 2024-01-22 10:46:10 -05:00
erew123 dbc2582fa6 Update README.md 2024-01-21 13:05:35 +00:00
erew123 535c9b652a Update README.md 2024-01-21 12:53:04 +00:00
erew123 6c28d58b4a Update README.md 2024-01-21 12:23:53 +00:00
erew123 c9a222932c Update README.md 2024-01-21 12:22:14 +00:00
erew123 7010369966 Added startup_wait_time to top of script
Making it simple for people to adjust the allowed start-up time
2024-01-21 12:20:29 +00:00
erew123 525a337835 Update README.md 2024-01-20 13:47:58 +00:00
erew123 2bd1ef843e Dynamic IP support 2024-01-20 00:18:06 +00:00
erew123 a9d95fc563 Update script.py 2024-01-18 14:15:34 +00:00
erew123 1a37ae4ba5 Merge pull request #76 from S95Sedan/main
Temperature and Repetition_penalty
2024-01-18 14:14:04 +00:00
erew123 8c6fc4853d Updated ST files 2024-01-17 22:01:51 +00:00
erew123 f34ebbd675 Update README.md 2024-01-16 01:00:48 +00:00
S95Sedan 64cffcdf80 Updated tts_server.py
With changes in: https://github.com/S95Sedan/alltalk_tts/commit/cefd1e045baf15c68fbdcac15fb1978850f8987f#commitcomment-137124105
2024-01-16 01:47:29 +01:00
erew123 2731a559f4 Update README.md 2024-01-16 00:12:54 +00:00
erew123 a91a83268f eval % option 2024-01-15 23:55:54 +00:00
S95Sedan 5d406fbbfb Load variables fix
Load temp/repetition variables in tts_server incase of API only usage.
2024-01-16 00:37:10 +01:00
S95Sedan cefd1e045b Temperature and Repetition_penalty modification
Modified script.py to enable temperature and repetition_penalty to be parsed and tts_server.py to recieve those variables.
2024-01-15 21:51:00 +01:00
erew123 bec4e905d3 Push JS mimetype on /static
Push JS files with mimetype of application/javascript
2024-01-15 16:38:37 +00:00
erew123 f5e99a5e72 Update README.md 2024-01-15 13:38:28 +00:00
erew123 631ea6dd8a Update README.md 2024-01-15 13:38:00 +00:00
erew123 08a04ba506 Added warning about starting from disk location 2024-01-15 11:36:29 +00:00
erew123 c78927b80a Create FND 2024-01-14 12:51:41 +00:00
erew123 04e08c58b8 Delete .github/ISSUE_TEMPLATE/FUNDING.yml 2024-01-14 12:50:57 +00:00
erew123 893747c9a9 Add files via upload 2024-01-14 12:48:49 +00:00
erew123 d52dcf86d5 Update README.md 2024-01-13 23:43:15 +00:00
erew123 ad0eab1224 Update atsetup.sh
added cutlet and unidic-lite
2024-01-13 22:45:01 +00:00
erew123 62d1cc05d3 Added cutlet and unidic-lite for Japanese 2024-01-13 22:43:41 +00:00
erew123 b8292da92f Update README.md 2024-01-13 21:47:49 +00:00
erew123 180adb45dd Merge pull request #68 from erew123/dev
Update to Main
2024-01-13 21:28:59 +00:00
erew123 5c0f08d49e Update README.md 2024-01-13 21:23:47 +00:00
erew123 571872dbe2 Update README.md 2024-01-13 21:16:01 +00:00
erew123 467bfbea55 Applied UUID to API generated TTS
To avoid over-writing if 2x generations happen quickly enough.
2024-01-13 21:07:18 +00:00
erew123 5a3cbb6366 Update README.md 2024-01-13 20:22:10 +00:00
erew123 2351e418fd Changed demo endpoint 2024-01-13 20:13:38 +00:00
erew123 b987ff38a7 Update README.md 2024-01-13 20:07:22 +00:00
erew123 43899028e3 Update README.md 2024-01-13 19:59:10 +00:00
erew123 2c1ca8b2a3 Update README.md 2024-01-13 19:56:31 +00:00
erew123 139162c4e6 Update README.md 2024-01-13 19:55:24 +00:00
erew123 7da78ec045 Add files via upload 2024-01-13 19:39:58 +00:00
erew123 11c70c7432 Tidied console messages 2024-01-13 19:03:26 +00:00
erew123 c2822edb1b Add files via upload 2024-01-13 18:53:12 +00:00
erew123 cba7ed7b88 Update README.md 2024-01-13 18:38:21 +00:00
erew123 471a26f2a4 Update README.md 2024-01-13 18:23:48 +00:00
erew123 34d1b81ae4 Update README.md 2024-01-13 18:20:35 +00:00
erew123 f1b4d4b8b6 Update README.md 2024-01-13 16:41:30 +00:00
erew123 c05237143b Update README.md 2024-01-13 15:28:45 +00:00
erew123 c5846b832a Update README.md 2024-01-13 14:59:38 +00:00
erew123 7a38730c56 Update README.md 2024-01-13 14:48:06 +00:00
erew123 0b1e6f8711 Update README.md 2024-01-13 14:47:05 +00:00
erew123 8c38e925dd Update README.md 2024-01-13 14:46:04 +00:00
erew123 df70481934 Update README.md 2024-01-13 14:43:19 +00:00
erew123 e43c58a56e Delete atstart.sh 2024-01-13 13:09:20 +00:00
erew123 8dc9304a4c Update tts_server.py - _combined path
corrected _combined on narrated without timestamp
2024-01-13 11:37:23 +00:00
erew123 102424669b Update tts_server.py - URL file path no timestamp 2024-01-13 11:31:22 +00:00
erew123 5210d075c1 added an additional note to finetune. 2024-01-13 00:31:14 +00:00
erew123 30db974439 Update README.md 2024-01-12 16:17:55 +00:00
erew123 c2a558110b Update README.md 2024-01-12 16:13:11 +00:00
erew123 83ac18b83f Update README.md 2024-01-12 16:12:54 +00:00
erew123 6e36415746 Update README.md 2024-01-12 16:09:41 +00:00
erew123 fe7ffb535c Delete atstart.sh 2024-01-12 15:31:45 +00:00
erew123 80b7fccb50 alltalk.sh adds env file. 2024-01-12 15:30:26 +00:00
erew123 2790ee9860 added environment routine to atsetup.bat 2024-01-12 14:42:31 +00:00
erew123 74ce2584cc Update README.md 2024-01-12 14:27:53 +00:00
erew123 8dd11541b4 Update README.md 2024-01-12 14:05:44 +00:00
erew123 d1317b49f0 Merge pull request #64 from q5sys/patch-1
Update README.md
2024-01-12 13:51:24 +00:00
erew123 a50d5a5028 Merge branch 'dev' into patch-1 2024-01-12 13:51:17 +00:00
erew123 33264554cd Update README.md 2024-01-12 13:46:02 +00:00
erew123 4a116e359a updated atsetup.bat 2024-01-12 12:21:07 +00:00
erew123 36bfb17eda Updated atsetup.sh 2024-01-12 11:30:12 +00:00
erew123 697fb098c3 Rename atstart.sh to atsetup.sh 2024-01-12 09:56:05 +00:00
q5sys (JT) 51a8e93df7 Update README.md
Add specific section for deepspeed installation on linux for standalone app. 
Related to https://github.com/erew123/alltalk_tts/issues/62
2024-01-11 21:21:30 -05:00
erew123 257fa59e70 Linux atstart script 2024-01-11 23:26:59 +00:00
erew123 7dbad85fc3 Linux atstart script 2024-01-11 23:26:14 +00:00
erew123 510894c793 Delete start_standalone.bat 2024-01-11 22:21:06 +00:00
erew123 a85058a3ac updated diagnostics 2024-01-11 20:47:13 +00:00
erew123 e54c7e4362 atsetup.bat
first version of a simple setup file.
2024-01-11 20:13:28 +00:00
erew123 1f2ad303a0 Corrected ST setting TTS options 2024-01-11 20:05:16 +00:00
erew123 d4a04096c8 Made Server address more visible on startup 2024-01-10 18:28:55 +00:00
erew123 dd45008e88 Merge pull request #60 from S95Sedan/main
Gui Overhaul
2024-01-10 18:13:06 +00:00
erew123 e9d9f54de6 Update script.py 2024-01-10 18:10:42 +00:00
erew123 3230397a82 Standalone installer script 2024-01-10 18:07:01 +00:00
S95Sedan 840889ac9a Update script.py
- Changed non_quoted_text_is_gr from "Char" to "Character"
2024-01-10 16:08:51 +01:00
S95Sedan d3e061b127 Update script.py
- GUI overhaul/cleanup.
- Temperature and Repetition penalty in GUI (disabled) but not yet parsed to API
2024-01-10 15:35:13 +01:00
erew123 a428f67a2e SillyTavern Support files.
Just kept here for safe keeping.
2024-01-10 14:09:31 +00:00
erew123 b223e7b247 ST Documentation added 2024-01-10 14:04:25 +00:00
erew123 9296843508 Update README.md 2024-01-10 12:48:56 +00:00
erew123 f0c9e3e6bb Update README.md 2024-01-10 12:40:20 +00:00
erew123 22de1bf0c6 Update README.md 2024-01-10 12:39:39 +00:00
erew123 621f5434a7 Update README.md 2024-01-10 12:38:59 +00:00
erew123 81c8354cf8 Update README.md 2024-01-10 11:53:49 +00:00
erew123 3bc55a91e5 Added streaming API & Current settings endpoint 2024-01-10 11:50:35 +00:00
erew123 fc857f464c Merge pull request #59 from erew123/main
merge main to dev
2024-01-10 11:49:34 +00:00
erew123 50aa6de96c Uploading the correct version!! 2024-01-08 18:57:00 +00:00
erew123 10299194f8 Update README.md 2024-01-08 14:33:16 +00:00
erew123 d80d1ace3c Update README.md 2024-01-08 13:31:40 +00:00
erew123 f19f4e9a29 Update README.md 2024-01-08 13:19:16 +00:00
erew123 7e4ceef0e8 Update README.md 2024-01-08 13:00:48 +00:00
erew123 c1bc1f26cd Export split setting
Avoids the 1GB file limit imposed by browsers and also lowers memory requirements per exported block.
2024-01-08 12:54:14 +00:00
erew123 70d385133d JSON import pagination 2024-01-08 01:13:36 +00:00
erew123 13b2eb5fe3 Update README.md 2024-01-08 01:03:06 +00:00
erew123 ff4b9d9e99 Updates to reduce browser load
Pagination of files list.
No Playback option
Better clearing of played back audio from memory
2024-01-08 00:56:36 +00:00
erew123 a22830f700 Update tts_chunk_player.html
bumped sentence splitting
2024-01-07 21:33:33 +00:00
erew123 374c794fa9 Merge pull request #51 from nicobubulle/fix
Fix greedy option for regex in HTML files
2024-01-07 20:59:13 +00:00
nicobubulle d2adbd9c1e Fix greedy option for regex in HTML files 2024-01-07 18:06:32 +01:00
erew123 1dc4b8bf50 Add $ to demo page regex 2024-01-07 08:38:39 +00:00
erew123 0eba72fc47 Merge pull request #50 from nicobubulle/fix
Fix greedy option for regex
2024-01-07 08:32:24 +00:00
nicobubulle f2c87dcdab Fix greedy option for regex 2024-01-07 09:25:52 +01:00
erew123 4a727ce14a Update README.md 2024-01-06 22:32:19 +00:00
erew123 6e15d43e63 Update README.md 2024-01-06 22:21:22 +00:00
erew123 dedc13b3b6 Update README.md 2024-01-06 22:05:10 +00:00
erew123 7cb206e531 Update README.md 2024-01-06 21:19:25 +00:00
erew123 d5fa6bb46d Merge pull request #49 from erew123/main
merge main
2024-01-06 20:28:20 +00:00
erew123 e5acc8bdbd Merge pull request #48 from erew123/main
main to dev pull
2024-01-05 13:31:31 +00:00
erew123 56a7ea1d8f Update README.md 2024-01-05 13:17:38 +00:00
erew123 863a7cd841 Update README.md 2024-01-05 13:08:45 +00:00
erew123 2e1709ab58 Update README.md 2024-01-05 13:06:10 +00:00
erew123 9c4efdc135 Update README.md 2024-01-05 13:03:49 +00:00
erew123 28675c976c Update README.md 2024-01-05 13:02:28 +00:00
erew123 afe3b9fe0b Update README.md 2024-01-05 12:58:16 +00:00
erew123 2e4d52170d Update README.md 2024-01-05 12:53:13 +00:00
erew123 0e2cc25571 Merge pull request #47 from erew123/main
pull from main
2024-01-05 11:44:52 +00:00
erew123 8a2b669da9 Merge pull request #42 from erew123/main
main to dev
2024-01-03 02:31:58 +00:00
erew123 b65291d44d Merge pull request #40 from erew123/main
merge main to dev
2024-01-02 00:59:37 +00:00
23 changed files with 4411 additions and 353 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
ko_fi: erew123
+67
View File
@@ -0,0 +1,67 @@
name: Publish Docker image
on:
push:
branches: [main]
release:
types: [published]
workflow_dispatch:
jobs:
build_and_push:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- dockerfile: "Dockerfile"
platforms: "linux/amd64"
tag_name: "cpu"
- dockerfile: "nvidia.Dockerfile"
platforms: "linux/amd64"
tag_name: "cuda"
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Lowercase Actor and Extract Repo Name
run: |
echo "ACTOR_LOWER=$(echo ${{ github.actor }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
echo "REPO_NAME=$(echo ${{ github.repository }} | cut -d'/' -f 2)" >> $GITHUB_ENV
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ env.ACTOR_LOWER }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./${{ matrix.dockerfile }}
platforms: ${{ matrix.platforms }}
push: true
tags: |
ghcr.io/${{ env.ACTOR_LOWER }}/${{ env.REPO_NAME }}:${{ matrix.tag_name }}-${{ github.sha }}
ghcr.io/${{ env.ACTOR_LOWER }}/${{ env.REPO_NAME }}:${{ matrix.tag_name }}
ghcr.io/${{ env.ACTOR_LOWER }}/${{ env.REPO_NAME }}:latest
${{ vars.DOCKERHUB_USERNAME }}/${{ env.REPO_NAME }}:${{ matrix.tag_name }}-${{ github.sha }}
${{ vars.DOCKERHUB_USERNAME }}/${{ env.REPO_NAME }}:${{ matrix.tag_name }}
${{ vars.DOCKERHUB_USERNAME }}/${{ env.REPO_NAME }}:latest
- name: Docker Hub Description
uses: peter-evans/dockerhub-description@v3.4.2
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
repository: ${{ vars.DOCKERHUB_USERNAME }}/${{ env.REPO_NAME }}
+12
View File
@@ -0,0 +1,12 @@
FROM ubuntu:22.04
ENV HOST 0.0.0.0
RUN apt-get update && apt-get upgrade -y \
&& apt-get install -y git build-essential portaudio19-dev \
python3 python3-pip gcc wget \
&& ln -s /usr/bin/python3 /usr/bin/python
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements_other.txt
EXPOSE 7851
RUN chmod +x launch.sh
ENTRYPOINT ["sh", "-c", "./launch.sh"]
+298 -85
View File
@@ -1,40 +1,91 @@
# AllTalk TTS # AllTalk TTS
AllTalk is an updated version of the Coqui_tts extension for Text Generation web UI. Features include: AllTalk is an updated version of the Coqui_tts extension for Text Generation web UI. Features include:
- **Can be run as a** [standalone](https://github.com/erew123/alltalk_tts?#-running-alltalk-as-a-standalone-app) **or part of** [Text-generation-webui](https://github.com/erew123/alltalk_tts?#-installation-on-text-generation-web-ui) - **Can be run as a** [standalone](https://github.com/erew123/alltalk_tts/#-quick-setup-text-generation-webui--standalone-installation) **or part of** [Text-generation-webui](https://github.com/erew123/alltalk_tts/#-quick-setup-text-generation-webui--standalone-installation) **using the a quick setup utility**
- **Model Finetuning:** Train the model specifically on a voice of your choosing for better reproduction. - **Model Finetuning:** Train the model specifically on a voice of your choosing for better reproduction.
- **Local/Custom models:** Use any of the XTTSv2 models (API Local and XTTSv2 Local). - **Local/Custom models:** Use any of the XTTSv2 models (API Local and XTTSv2 Local).
- **Bulk TTS Generator/Editor:** Generate hours of TTS into one big file or have something read back to you. - **Bulk TTS Generator/Editor:** Generate hours of TTS into one big file or have something read back to you [demo](https://www.youtube.com/watch?v=hunvXn0mLzc).
- **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) - **DeepSpeed:** A 2-3x performance boost generating TTS. [Screenshot](https://github.com/erew123/screenshots/raw/main/deepspeed.jpg)
- **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) - **Low VRAM mode:** Great for people with small GPU memory or if your VRAM is filled by your LLM.
- **Custom Start-up Settings:** Adjust your default start-up settings. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) - **Custom Start-up Settings:** Adjust your default start-up settings. [Screenshot](https://github.com/erew123/screenshots/raw/main/settingsanddocs.jpg)
- **Narrarator:** Use different voices for main character and narration. [Example Narration](https://vocaroo.com/18nrv7FR6wuA) - **Narrarator:** Use different voices for main character and narration. [Example Narration](https://vocaroo.com/18nrv7FR6wuA)
- **Optional wav file maintenance:** Configurable deletion of old output wav files. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) - **Optional wav file maintenance:** Configurable deletion of old output wav files. [Screenshot](https://github.com/erew123/screenshots/raw/main/settingsanddocs.jpg)
- **Documentation:** Fully documented with a built in webpage. [Screenshot](https://github.com/erew123/alltalk_tts#screenshots) - **Documentation:** Fully documented with a built in webpage. [Screenshot](https://github.com/erew123/screenshots/raw/main/settingsanddocs.jpg)
- **Console output:** Clear command line output for any warnings or issues. - **Clear Console output:** Clear command line output for any warnings or issues.
- **API Suite and 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.
- **SillyTavern integration:** Full integration with SillyTavern. [Screenshot](https://github.com/erew123/screenshots/raw/main/sillytavern.jpg)
## Index ### Index
- 🟩 [Installation](https://github.com/erew123/alltalk_tts?#-installation-on-text-generation-web-ui) - 🟩 [Installation](https://github.com/erew123/alltalk_tts/#-quick-setup-text-generation-webui--standalone-installation)
- 🟪 [Updating & problems with updating](https://github.com/erew123/alltalk_tts?#-updating) - 🟪 [Updating & problems with updating](https://github.com/erew123/alltalk_tts?#-updating)
- 🟫 [Screenshots](https://github.com/erew123/alltalk_tts#-screenshots) - 🟫 [Screenshots](https://github.com/erew123/alltalk_tts#-screenshots)
- 🟨 [Help with problems](https://github.com/erew123/alltalk_tts?#-help-with-problems) - 🟨 [Help with problems](https://github.com/erew123/alltalk_tts?#-help-with-problems)
- ⚫ [Finetuning a model](https://github.com/erew123/alltalk_tts?#-finetuning-a-model) - ⚫ [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) - 🔵🟢🟡 [DeepSpeed Installation (Windows & Linux)](https://github.com/erew123/alltalk_tts?#-deepspeed-installation-options)
- 🟦 [Running AllTalk as a standalone app](https://github.com/erew123/alltalk_tts?#-running-alltalk-as-a-standalone-app)
- ⬜ [AllTalk TTS Generator](https://github.com/erew123/alltalk_tts?#-alltalk-tts-generator) - ⬜ [AllTalk TTS Generator](https://github.com/erew123/alltalk_tts?#-alltalk-tts-generator)
- 🟠 [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 ### 🔄 Feature requests, Updates & Bug fixes
Please check the below link to find a list of all recent updates and changes. 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) ####     🔄 **Updates list & bug fixes list** can be found [here](https://github.com/erew123/alltalk_tts/issues/25)
####     🔄 **Current Feature request list** can be found [here](https://github.com/erew123/alltalk_tts/discussions/74)
I welcome your input and ideas for new features, suggestions, and improvements. Feel free to share your thoughts and collaborate in the discussions area. If you find this project valuable and would like to show your appreciation, you can make a donation on my [Ko-fi](https://ko-fi.com/erew123) page. Your support goes a long way in ensuring that I can continue to deliver even better features and experiences.
**ERROR** `ImportError: cannot import name 'SampleOutput' from 'transformers.generation.utils'` please see this issue [here](https://github.com/erew123/alltalk_tts/issues/82)
### 🟩 Quick Setup (Text-generation-webui & Standalone Installation)
For Windows 10/11 and Linux machines there is a quick setup script. Please note, Python on Windows requires you install the C++ development [tools](https://wiki.python.org/moin/WindowsCompilers) to compile packages, further details can be found in the help section.
Click to expand the correct section below:
<details>
<summary>QUICK SETUP - Text-Generation-webui</summary><br>
If you wish to see this as a video, please go [here](https://www.youtube.com/watch?v=icn2XS5rUH8)
1) To download the AllTalk setup you can either:
- A) Go to the [Releases page](https://github.com/erew123/alltalk_tts/releases) and download the latest `alltalk_tts.zip` then extract it to the text-generation-webui extensions folder<br>e.g. `\text-generation-webui\extensions\alltalk_tts\`.<br><br>
- B) Go to a terminal/console, move into the `\text-generation-webui\extensions\` folder<br>and `git clone https://github.com/erew123/alltalk_tts`<br><br>
3) In a terminal/command prompt, in the text-generation-webui folder you will start its Python environment with either `cmd_windows.bat` or `./cmd_linux.sh`
4) Move into the AllTalk folder e.g. `cd extensions` then `cd alltalk_tts`
5) Start the AllTalk setup script `atsetup.bat` or `./atsetup.sh`
6) Follow the on-screen prompts and install the correct requirements files that you need. It's recommended to test AllTalk works before installing DeepSpeed.
Any time you need to make changes to AllTalk, or use Finetuning etc, always start the Text-generation-webui Python environment first.
Please read the `🟩 Other installation notes` (also additional voices are available there).
Finetuning & DeepSpeed have other installation requirements (depending on your OS) so please read any instructions in the setup utility and refer back here to this page for detailed instructions (as needed).<br><br>
</details>
<details>
<summary>QUICK SETUP - Standalone Installation</summary><br>
If you wish to see this as a video, please go [here](https://www.youtube.com/watch?v=AQYCccDRbaY)
1) To download the AllTalk setup you can either:
- A) Go to the [Releases page](https://github.com/erew123/alltalk_tts/releases) and download the latest `alltalk_tts.zip` and extract it to the folder of your choice<br>e.g. `C:\myfiles\alltalk_tts\`.<br><br>
- B) Go to a terminal/console, move into the folder of your choice e.g `C:\myfiles\` folder<br>and `git clone https://github.com/erew123/alltalk_tts`<br><br>
4) In a terminal/command prompt, move into the AllTalk folder e.g. `cd alltalk_tts`
5) Start the AllTalk setup script `atsetup.bat` or `./atsetup.sh`
6) Follow the on-screen prompts and install the correct requirements files that you need. It's recommended to test AllTalk works before installing DeepSpeed.
DeepSpeed on Windows machines will be installed as standard. Linux machines have other requirements which are detailed within the setup utility and on this page.
Please read the `🟩 Other installation notes` (also additional voices are available there).
You cannot have a dash in your folder path e.g. `c:\myfiles\alltalk_tts-main` so please ensure you remove any `-` from your folder path. This is a conda specific requirement and will cause AllTalk not to start at all.
Finetuning has other installation requirements so please read any instructions in the setup utility and refer back here to this page for detailed instructions.<br><br>
</details>
### 🟩 Manual Installation - As part of Text generation web UI
On Mac's or if you wish to perform a manual installation. Click to expand the correct section below:
<details>
<summary>MANUAL INSTALLATION - Text-Generation-webui</summary><br>
## 🟩 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)
If you want to watch a video of how to do the below [link here](https://youtu.be/9BPKuwaav5w) - If you want to watch a video of how to do the below [link here](https://youtu.be/9BPKuwaav5w)<br>
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`
@@ -58,19 +109,77 @@ If you want to watch a video of how to do the below [link here](https://youtu.be
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`. 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`.
8) You can now start move back to the main Text generation webUI folder `cd ..` (a few times), start Text generation webUI with whichever **one** of the startup scripts is correct for your OS (`start_windows.bat`,`./start_linux.sh`, `start_macos.sh` or `start_wsl.bat`) and load the AllTalk extension in the Text generation webUI **session** tab.<br><br> Starting Text-generation-webui with its correct start-up script is $\textcolor{red}{\textsf{VERY IMPORTANT}}$. 8) You can now start move back to the main Text generation webUI folder `cd ..` (a few times), start Text generation webUI with whichever **one** of the startup scripts is correct for your OS (`start_windows.bat`,`./start_linux.sh`, `start_macos.sh` or `start_wsl.bat`) and load the AllTalk extension in the Text generation webUI **session** tab.<br><br> Starting Text-generation-webui with its correct start-up script is $\textcolor{red}{\textsf{VERY IMPORTANT}}$.
10) Please read the note below about start-up times and also the note about ensuring your character cards are set up [correctly](https://github.com/erew123/alltalk_tts#the-one-thing-i-cant-easily-work-around)
11) Some extra voices downloadable [here](https://drive.google.com/file/d/1bYdZdr3L69kmzUN3vSiqZmLRD7-A3M47/view?usp=drive_link) Any time you need to make changes to AllTalk, or use Finetuning etc, always start the Text-generation-webui Python environment first.
Please read the `🟩 Other installation notes` (also additional voices are available there).
Finetuning & DeepSpeed have other installation requirements (depending on your OS) so please read any instructions in the setup utility and refer back here to this page for detailed instructions (as needed).<br><br>
</details>
### 🟩 Manual Installation - As a Standalone Application
On Mac's or if you wish to perform a manual installation. Click to expand the correct section below:
<details>
<summary>MANUAL INSTALLATION - I want to run AllTalk as a standalone when installed with Text-generation-webui</summary><br>
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.
</details>
<details>
<summary>MANUAL INSTALLATION - I wish to do a custom install of AllTalk</summary><br>
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/). AllTalk and its requirements are tested on Python **3.11.x**.
#### 🟩 A very quick understanding of Python Environments.
Different Python applications have different requirements, some of those requirement’s conflict with other Python applications requirements. To work around this problem, you can create different Python environments that remain separated from one another. A simple way of looking at Python environments, is just like how your house has different rooms for specific purposes (Kitchen, Bathroom, Bedroom etc). You can create a Python environment that is built/customised specifically for your current applications needs/purposes and will **not** interfere with any other Python applications environments/installations. <br><br>If you are adept at managing Python environments, have an existing Python environment and know that you won’t cause any conflicts by installing AllTalk's requirements within that Python environment, then load up your Python environment and install the requirements. For everyone else, here is a basic guide on installing AllTalk in its own custom Python environment (there will be small variations between OS's, but the principle is the same).
**Note:** A standard VENV can cause module path issues, hence Conda is the correct method to create a Python environment for AllTalk.
#### 🟩 Building a custom Python Environment with Miniconda
1) Open a terminal/command prompt, and confirm that both `python --version` and `pip` both work. Neither of them should give an error message. If they do you may need to install Python (and maybe Pip).<br><br>[Python Website](https://www.python.org/downloads/)<br>[Pip Website](https://pip.pypa.io/en/stable/installation/)<br><br>Once you have those working you can now continue on.<br><br>
2) Assuming you don't already have Miniconda installed, we will need to download and install Minoconda as this is what we will use to build our custom Python environment.<br><br>[Miniconda Website](https://docs.conda.io/projects/miniconda/en/latest/)<br><br>Download the Miniconda version that is correct for your OS and then install it. Miniconda will create some items in your Start Menu or Application Launcher called something like `Anaconda Prompt`<br><br> You will start the `Anaconda Prompt` and your prompt in your terminal/command prompt will say something like: <br><br>`(base) C:\users\myaccount\>`<br><br> The important bit is that it has the `(base)`, the location after that doesn't matter. `(base)` signifies we are in the base conda Python environment and can now create custom Python environments with Conda.<br><br>
3) In your Anaconda Prompt command prompt/terminal, move into the folder where you want to download AllTalk to and then git clone this repository. For simplicity I am going to assume that location is `c:\myfiles\`. So you will:<br><br>`cd myfiles`<br><br>`git clone https://github.com/erew123/alltalk_tts`<br><br>
4) Now we will create our custom Conda Python 3.11.5 environment and give it the name alltalkenv by typing the following at the prompt:<br><br>`conda create --name alltalkenv python=3.11.5`<br><br>You will be prompted if you want to continue and you say yes.<br><br>Once that process has completed, we now need to change from the `(base)` Conda Python environment, to our newly created `(alltalkenv)` environment. So type the following:<br><br>`conda activate alltalkenv`<br><br>Your prompt should now change from `(base) C:\myfiles\>` to `(alltalkenv) C:\myfiles\>`<br><br>
5) **If you are NOT using an Nvidia card and CUDA, skip to step 6**. To force PyTorch to install with CUDA, perform the following:<br><br>`pip cache purge` (Clear the current Pip cache)<br><br>`pip uninstall torch torchaudio` (Uninstall Torch and Torchaudio from the `alltalkenv` environment)<br><br>
You can now either install the CUDA 11.8 or 12.1 version of Torch and Torchaudio with **one** of the following<br><br>**CUDA 11.8** > `pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118`<br><br>**CUDA 12.1** > `pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121`<br><br>
6) Move into the alltalk_tts folder and install one of the two requirements files. Whichever one of the two is correct for your machine type:<br><br>`cd alltalk_tts`<br><br>
**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`<br><br>
**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt`<br><br>
7) Start AllTalk with `python script.py`<br><br>
🟩 Anytime you wish to use AllTalk, update its requirements, install some other requirements such as DeepSpeed, you will need to start its Conda Python Environment in the terminal/prompt, which you will do with `conda activate alltalkenv` as long as the Conda executable is accessible at the command prompt/terminal you are in.<br><br>It is fully possible to create a batch file or script file that you can use as a launcher from your Start Menu/Application Launcher that will start the environment and AllTalk for you.
Deepspeed and other such things can be installed. Please read the relevant instructions for those items, however, make the relevant changes to load your correct Python environment when installing any requirements files and starting AllTalk.<br><br>
Any time you need to make changes to AllTalk, or use Finetuning etc, always start your Python environment first.
Please read the `🟩 Other installation notes` (also additional voices are available there).
Finetuning & DeepSpeed have other installation requirements (depending on your OS) so please read any instructions in the setup utility and refer back here to this page for detailed instructions (as needed).<br><br>
</details>
#### 🟩 Other installation notes #### 🟩 Other installation notes
On first startup, AllTalk will download the Coqui XTTSv2 2.0.2 model to its **models** folder (1.8GB space required). Check the command prompt/terminal window if you want to know what its doing. After it says "Model Loaded" the Text generation webUI is usually available on its IP address a few seconds later, for you to connect to in your browser. On first startup, AllTalk will download the Coqui XTTSv2 2.0.2 model to its **models** folder (1.8GB space required). Check the command prompt/terminal window if you want to know what its doing. After it says "Model Loaded" the Text generation webUI is usually available on its IP address a few seconds later, for you to connect to in your browser. If you are running a headless system and need to change the IP, please see the Help with problems section down below.
Once the extension is loaded, please find all documentation and settings on the link provided in the interface (as shown in the screenshot below). Once the extension is loaded, please find all documentation and settings on the link provided in the interface (as shown in the screenshot below).
**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 Please read the note below about start-up times and also the note about ensuring your character cards are set up [correctly](https://github.com/erew123/alltalk_tts#-a-note-on-character-cards--greeting-messages)
Some extra voices for AllTalk are downloadable [here](https://drive.google.com/file/d/1bYdZdr3L69kmzUN3vSiqZmLRD7-A3M47/view?usp=drive_link) and [here](https://drive.google.com/file/d/1CPnx1rpkuKvVj5fGr9OiUJHZ_e8DfTzP/view)
#### 🟩 A note on Character Cards & Greeting Messages
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: 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:
`"`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.`"` `*`She walked across the room and picked up her cup of coffee`*`
@@ -79,22 +188,34 @@ Most narrator/character systems switch voices upon encountering an asterisk or q
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). 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
<details>
<summary>UPDATING - I am using Text-Generation-webui</summary><br>
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` and start the Python environment for your OS with whichever **one** of the below is correct for your OS:<br><br> `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> `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 e.g. `cd extensions` then `cd alltalk_tts`
`cd extensions` then `cd alltalk_tts`
3) At the command prompt/terminal, type:<br><br> 3) At the command prompt/terminal, type `git pull`
`git pull`
4) Install the correct requirements for your machine:<br><br> 4) Install the correct requirements for your machine:<br><br>
**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`<br><br> **Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`<br><br>
**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt` **Other machines (mac, amd etc)** - `pip install -r requirements_other.txt`<br><br>
</details>
<details>
<summary>UPDATING - I am running as a Standalone Application</summary><br>
1) In a command prompt/terminal window you need to move into your `alltalk_tts` folder and run `start_environment.bat` or `/start_environment.sh` to load the Python environment.
2) At the command prompt/terminal, type `git pull` and wait for it to complete the download.
3) Install the correct requirements for your machine:<br><br>
**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`<br><br>
**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt`<br><br>
</details>
#### 🟪 Updating "git pull" error #### 🟪 Updating "git pull" error
@@ -146,17 +267,17 @@ You can now start text-generation-webui or AllTalk (standalone) and it should st
Assuming its all working fine and you are happy, you can delete the old alltalk_tts.old folder. Assuming its all working fine and you are happy, you can delete the old alltalk_tts.old folder.
</details> </details>
## 🟫 Screenshots ### 🟫 Screenshots
|![image](https://github.com/erew123/alltalk_tts/assets/35898566/15c6ba0b-e6b0-4570-8253-b920dd76174d) | ![image](https://github.com/erew123/alltalk_tts/assets/35898566/548619c8-5f1b-47d0-a73d-54d2fee3f3db) | |![image](https://github.com/erew123/screenshots/raw/main/textgensettings.jpg) | ![image](https://github.com/erew123/screenshots/raw/main/setuputilitys.jpg) | ![image](https://github.com/erew123/screenshots/raw/main/deepspeed.jpg) |![image](https://github.com/erew123/screenshots/raw/main/textgen.jpg) |
|:---:|:---:| |:---:|:---:|:---:|:---:|
|![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/screenshots/raw/main/settingsanddocs.jpg) | ![image](https://github.com/erew123/screenshots/raw/main/finetune1.jpg) | ![image](https://github.com/erew123/screenshots/raw/main/finetune2.jpg) |![image](https://github.com/erew123/screenshots/raw/main/sillytavern.jpg)|
|![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) |
|![image](https://github.com/erew123/alltalk_tts/assets/35898566/4bd0f02e-298d-4e46-95ea-afc003c1cb70) | ### 🟨 Help with problems
## 🟨 Help with problems
#### &nbsp;&nbsp;&nbsp;&nbsp; 🔄 **Minor updates/bug fixes list** can be found [here](https://github.com/erew123/alltalk_tts/issues/25) #### &nbsp;&nbsp;&nbsp;&nbsp; 🔄 **Minor updates/bug fixes list** can be found [here](https://github.com/erew123/alltalk_tts/issues/25)
#### 🟨 How to make a diagnostics report file #### 🟨 How to make a diagnostics report file
If you are on a Windows machine or a Linux machine, you should be able to use the `atsetup.bat` or `./atsetup.sh` utility to create a diagnositcs file. If you are unable to use the `atsetup` utility, please follow the instructions below.
<details> <details>
<summary>Click to expand</summary> <summary>Click to expand</summary>
@@ -184,7 +305,7 @@ Assuming its all working fine and you are happy, you can delete the old alltalk_
**A)** Its trying to load the voice model into your graphics card VRAM (assuming you have a Nvidia Graphics card, otherwise its your system RAM)<br> **A)** Its trying to load the voice model into your graphics card VRAM (assuming you have a Nvidia Graphics card, otherwise its your system RAM)<br>
**B)** Its trying to start up the mini-webserver and send the "ready" signal back to the main process. **B)** Its trying to start up the mini-webserver and send the "ready" signal back to the main process.
Before giving other possibilities a go, 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). Before giving other possibilities a go, 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 `startup_wait_time = 120` (120 seconds, aka 2 minutes) at the top of the script.py file, to a larger value e.g `startup_wait_time = 240` (240 seconds aka 4 minutes).
**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. **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.
@@ -213,6 +334,21 @@ Other possibilities for this issue are:
11) You have built yourself a custom Python environment and something is funky with it. This is very hard to diagnose as its not a standard environment. You may want to updating text-generation-webui and re installing its requirements file (whichever one you use that comes down with text-generation-webui). 11) You have built yourself a custom Python environment and something is funky with it. This is very hard to diagnose as its not a standard environment. You may want to updating text-generation-webui and re installing its requirements file (whichever one you use that comes down with text-generation-webui).
</details> </details>
#### 🟨 Windows & Python requirements for compiling packages
`ERROR: Microsoft Visual C++ 14.0 or greater is required` or `ERROR: Could not build wheels for TTS.` or `ModuleNotFoundError: No module named 'TTS`
<details>
<summary>Click to expand</summary><br>
Python requires that you install C++ development tools on Windows. This is detailed on the [Python site here](https://wiki.python.org/moin/WindowsCompilers). You would need to install `MSVCv142 - VS 2019 C++ x64/x86 build tools` and `Windows 10/11 SDK` from the C++ Build tools section.
You can get hold of the **Community** edition [here](https://visualstudio.microsoft.com/downloads/) the during installation, selecting `C++ Build tools` and then `MSVCv142 - VS 2019 C++ x64/x86 build tools` and `Windows 10/11 SDK`.
![image](https://github.com/erew123/screenshots/raw/main/pythonrequirementswindows.jpg)
</details>
#### 🟨 I think AllTalks requirements file has installed something another extension doesn't like #### 🟨 I think AllTalks requirements file has installed something another extension doesn't like
<details> <details>
<summary>Click to expand</summary><br> <summary>Click to expand</summary><br>
@@ -235,6 +371,15 @@ You can either follow the [Problems Updating](https://github.com/erew123/alltalk
If you want to use DeepSpeed, you need an Nvidia Graphics card and to install DeepSpeed on your system. Instructions are [here](https://github.com/erew123/alltalk_tts#-deepspeed-installation-options) If you want to use DeepSpeed, you need an Nvidia Graphics card and to install DeepSpeed on your system. Instructions are [here](https://github.com/erew123/alltalk_tts#-deepspeed-installation-options)
</details> </details>
#### 🟨 I am running a Headless system and need to change the IP Address manually as I cannot reach the config page.
<details>
<summary>Click to expand</summary><br>
To do this you can edit the `confignew.json` file within the `alltalk_tts` folder. You would look for `"ip_address": "127.0.0.1",` and change the `127.0.0.1` to your chosen IP address,then save the file and start AllTalk.<br><br>
When doing this, be careful not to impact the formatting of the JSON file. Worst case, you can re-download a fresh copy of `confignew.json` from this website and that will put you back to a factory setting.
</details>
#### 🟨 I am having problems updating/some other issue where it wont start up/Im sure this is a bug #### 🟨 I am having problems updating/some other issue where it wont start up/Im sure this is a bug
<details> <details>
<summary>Click to expand</summary><br> <summary>Click to expand</summary><br>
@@ -244,6 +389,14 @@ Please see [Problems Updating](https://github.com/erew123/alltalk_tts#-problems-
Also, is your text-generation-webui up to date? [instructions here](https://github.com/oobabooga/text-generation-webui?tab=readme-ov-file#how-to-install) Also, is your text-generation-webui up to date? [instructions here](https://github.com/oobabooga/text-generation-webui?tab=readme-ov-file#how-to-install)
</details> </details>
#### 🟨 Standalone Install - start_{youros}.xx opens and closes instantly and AllTalk doesnt start
<details>
<summary>Click to expand</summary><br>
This is more than likely caused by having a `-` in your folder path e.g. `c:\myfiles\alltalk_tts-main`. In this circumstance you would be best renaming the folder to remove the `-` from its name e.g. `c:\myfiles\alltalk_tts`, delete the `alltalk_environment` folder and `start_alltalk.bat` or `start_alltalk.sh` and then re-run `atsetup` to re-create the environment and startup files.
</details>
#### 🟨 I am having problems getting AllTalk to start after changing settings or making a custom setup/model setup. #### 🟨 I am having problems getting AllTalk to start after changing settings or making a custom setup/model setup.
<details> <details>
@@ -279,13 +432,14 @@ Depending on which of your Nvidia GPU's is the more powerful one, you can change
</details> </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. (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). - 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).
- As a side note, many people seem to think that the Whisper v2 model (used on Step 1) is giving better results at generating training datasets, so you may prefer to try that, as opposed to the Whisper 3 model.
#### ⚫ How will this work/How complicated is it? #### ⚫ 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. 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.
@@ -293,9 +447,17 @@ Everything has been done to make this as simple as possible. At its simplest, yo
#### ⚫ The audio you will use #### ⚫ 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. 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.
#### ⚫ A note about anonymous training Telemetry information & disabling it
Portions of Coqui's TTS trainer scripts gather anonymous training information which you can disable. Their statement on this is listed [here](https://github.com/coqui-ai/Trainer?tab=readme-ov-file#anonymized-telemetry). Although I have tried to pass `TRAINER_TELEMETRY=0` through AllTalk, it appears you will have to set this manually if you wish to finetune on a non-internet enabled computer or disable the anonymous data being sent. You can do this by:
- On Windows by typing `set TRAINER_TELEMETRY=0`
- On Linux & Mac by typing `export TRAINER_TELEMETRY=0`
Before you start `finetune.py`. You will now be able to finetune offline and no anonymous training data will be sent.
#### ⚫ Important requirements CUDA 11.8 #### ⚫ 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: 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. This requirement is for Step1 of Finetuning. 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) - Download the **xxx (network)** install of the Nvidia CUDA Toolkit 11.8 from [here](https://developer.nvidia.com/cuda-11-8-0-download-archive)
- Run the installer. At minimum, you need to [minimally] install the `nvcc` compiler and the `CUBLAS` development and runtime libraries: - Run the installer. At minimum, you need to [minimally] install the `nvcc` compiler and the `CUBLAS` development and runtime libraries:
- Select **Custom Advanced** as your installation type. - Select **Custom Advanced** as your installation type.
- Uncheck all the checkboxes in the list. - Uncheck all the checkboxes in the list.
@@ -314,6 +476,8 @@ As mentioned you must have a small portion of the Nvidia CUDA Toolkit **11.8** i
- When you have made the changes, open a **new** terminal/command prompt (in order to load the new search paths) and `nvcc --version`. It should report back `Cuda compilation tools, release 11.8.` at which point, you are good to go. - When you have made the changes, open a **new** terminal/command prompt (in order to load the new search paths) and `nvcc --version`. It should report back `Cuda compilation tools, release 11.8.` at which point, you are good to go.
- If it doesn't report that, check you have correctly set the search environment paths, dont have overlapping other versions of cuda paths etc. - If it doesn't report that, check you have correctly set the search environment paths, dont have overlapping other versions of cuda paths etc.
**Note:** Its also important that your Torch and Torchaudio have cuda installed (of any version). If you run the AllTalk diagnostics you can see your Torch and Torchaudio versions listed there. Cuda 11.8 will be listed as `cu118` and Cuda 12.1 as `cu121`. This Torch and Torchaudio is seperate to the above requirement to have the Nvidia CUDA Toolkit installed, so dont confuse the two different requirements. If you dont have Cuda installed on Torch and Torchaudio, Step 2 of Finetuning will fail.
#### ⚫ Starting Finetuning #### ⚫ Starting Finetuning
**NOTE:** Please make sure you have started AllTalk at least once after updating, so that it downloads the additional files needed for finetuning. **NOTE:** Please make sure you have started AllTalk at least once after updating, so that it downloads the additional files needed for finetuning.
@@ -340,6 +504,19 @@ 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.
#### ⚫ Evaluation Data Percentage
In the process of finetuning, it's crucial to balance the data used for training the model against the data reserved for evaluating its performance. Typically, a portion of the dataset is set aside as an 'evaluation set' to assess the model's capabilities in dealing with unseen data. On Step 1 of finetuning you have the option to adjust this evaluation data percentage, offering more control over your model training process.<br><br>
**Why Adjust the Evaluation Percentage?**<br><br>
Adjusting the evaluation percentage **can** be beneficial in scenarios with limited voice samples. When dealing with a smaller dataset, allocating a slightly larger portion to training could enhance the model's ability to learn from these scarce samples. Conversely, with abundant data, a higher evaluation percentage might be more appropriate to rigorously test the model's performance. There are currently no absolutely optimal split percentages as it varies by dataset.
- **Default Setting:** The default evaluation percentage is set at 15%, which is a balanced choice for most datasets.
- **Adjustable Range:** Users can now adjust this percentage, but it’s generally recommend keeping it between 5% and 30%.
- **Lower Bound:** A minimum of 5% ensures that there's enough data to evaluate model performance.
- **Upper Bound:** Its suggested not exceeding 30% for evaluation to avoid limiting the amount of data available for training.
- **Understanding the Impact:** Before adjusting this setting, it's important to understand its impact on model training and evaluation. Incorrect adjustments can lead to suboptimal model performance.
- **Gradual Adjustments:** For those unfamiliar with the process, we recommend reading up on training data and training sets, then making small, incremental changes and observing their effects.
- **Data Quality:** Regardless of the split, the quality of the audio data is paramount. Ensure that your datasets are built from good quality audio with enough data within them.
#### ⚫ Using a Finetuned model in Text-generation-webui #### ⚫ 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/`. 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/`.
@@ -352,7 +529,7 @@ At the end of the finetune process, you will have an option to `Compact and move
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. 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.
#### 🔵 Linux Installation #### 🔵 Linux Installation
@@ -361,6 +538,8 @@ If you've compacted and moved your model, its highly unlikely you would want to
➡️DeepSpeed requires an Nvidia Graphics card!⬅️ ➡️DeepSpeed requires an Nvidia Graphics card!⬅️
- #### DeepSpeed Installation for Text generation webUI
1) Preferably use your built in package manager to install CUDA tools. Alternatively download and install the Nvidia Cuda Toolkit for Linux [Nvidia Cuda Toolkit 11.8 or 12.1](https://developer.nvidia.com/cuda-toolkit-archive)<br><br> 1) Preferably use your built in package manager to install CUDA tools. Alternatively download and install the Nvidia Cuda Toolkit for Linux [Nvidia Cuda Toolkit 11.8 or 12.1](https://developer.nvidia.com/cuda-toolkit-archive)<br><br>
2) Open a terminal console.<br><br> 2) Open a terminal console.<br><br>
3) Install libaio-dev (however your Linux version installs things) e.g. `sudo apt install libaio-dev`<br><br> 3) Install libaio-dev (however your Linux version installs things) e.g. `sudo apt install libaio-dev`<br><br>
@@ -372,14 +551,37 @@ If you've compacted and moved your model, its highly unlikely you would want to
`export CUDA_HOME=/etc/alternatives/cuda`<br><br> `export CUDA_HOME=/etc/alternatives/cuda`<br><br>
**every** time you run `./cmd_linux.sh`.<br> <br> **every** time you run `./cmd_linux.sh`.<br> <br>
If you try to start DeepSpeed with the CUDA_HOME path set incorrectly, expect an error similar to `[Errno 2] No such file or directory: /home/yourname/text-generation-webui/installer_files/env/bin/nvcc`<br> <br> If you try to start DeepSpeed with the CUDA_HOME path set incorrectly, expect an error similar to `[Errno 2] No such file or directory: /home/yourname/text-generation-webui/installer_files/env/bin/nvcc`<br> <br>
9) Now install deepspeed with pip install deepspeed<br><br> You can also add the `export` line into the start scripts just below the `conda active .......` line, to avoid running the command each time. <br> <br>
10) You can now start Text generation webUI `python server.py` ensuring to activate your extensions.<br><br> 8) Now install deepspeed with pip install deepspeed<br><br>
9) You can now start Text generation webUI `python server.py` ensuring to activate your extensions.<br><br>
Just to reiterate, starting Text-generation-webUI with `./start_linux.sh` will overwrite the CUDA_HOME variable unless you have permanently changed it, hence always starting it with `./cmd_linux.sh` **then** setting the environment variable manually (step 7) and **then** `python server.py`, which is how you would need to run it each time, unless you permanently set the environment variable for CUDA_HOME within Text-generation-webUI's standard Python environment. Just to reiterate, starting Text-generation-webUI with `./start_linux.sh` will overwrite the CUDA_HOME variable unless you have permanently changed it, hence always starting it with `./cmd_linux.sh` **then** setting the environment variable manually (step 7) and **then** `python server.py`, which is how you would need to run it each time, unless you permanently set the environment variable for CUDA_HOME within Text-generation-webUI's standard Python environment.
<br><br> <br><br>
**Removal** - If it became necessary to uninstall DeepSpeed, you can do so with `./cmd_linux.sh` and then `pip uninstall deepspeed`<br><br> **Removal** - If it became necessary to uninstall DeepSpeed, you can do so with `./cmd_linux.sh` and then `pip uninstall deepspeed`<br><br>
- #### DeepSpeed Installation for standalone alltalk_tts app
1) Preferably use your built in package manager to install CUDA tools. Alternatively download and install the Nvidia Cuda Toolkit for Linux [Nvidia Cuda Toolkit 11.8 or 12.1](https://developer.nvidia.com/cuda-toolkit-archive)<br><br>
2) Open a terminal console.<br><br>
3) Install libaio-dev (however your Linux version installs things) e.g. `sudo apt install libaio-dev` If you are using an RPM based distribution the package will probably be named `libaio-devel`.<br><br>
4) Navigate to your alltalk_tts folder e.g. `cd alltext_tts`<br><br>
5) Start the alltalk_tts Python environment `conda activate alltalkenv`<br><br>
6) You will need to set the **CUDA_HOME** environment variable. Details to change it each time are on the next step. Below is a link to Conda's manual and changing environment variables permanently though its possible changing it permanently could affect other extensions, you would have to test.<br> <br>
[Conda manual - Environment variables](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#set-env-vars)<br><br>
7) Set the environment path for CUDA_HOME e.g. `export CUDA_HOME=/usr/local/cuda-12.1/bin` or `export CUDA_HOME=/etc/alternative/cuda`. Verify the path on your Linux distro before setting this variable.<br>
If you try to start DeepSpeed with the CUDA_HOME path set incorrectly, expect an error similar to `[Errno 2] No such file or directory` or `CUDA_HOME does not exist`<br> <br>
If you set the `env` variable and you receive an error of `[Errno 2] No such file or directory: '/usr/local/cuda-12.1/bin/bin/nvcc'` with a double `bin/bin` path, you can remove the env variable with `unset CUDA_HOME` and add the path to your linux PATH env variable with: `export PATH=$PATH:/usr/local/cuda-12.1/bin`. (Verify the path on your Linux distro before setting this variable.) However if you are using other applications that use CUDA, you will want to verify that configuring the path did not break those applications. <br><br>
8) Now install deepspeed with `pip install deepspeed`<br><br>
9) You can now start the alltalk_tts webUI with `python script.py`<br><br>
<br><br>
**Removal** - If it became necessary to uninstall DeepSpeed, you can do so by entering your `alltalkenv` enviroment `conda activate alltalkenv` and then running `pip uninstall deepspeed`<br><br>
</details> </details>
#### 🟢🟡 Windows Installation #### 🟢🟡 Windows Installation
<details>
<summary>Click to Expand: Windows DeepSpeed options</summary><br>
DeepSpeed v11.2 will work on the current default text-generation-webui Python 3.11 environment! You have 2x options for how to setup DeepSpeed on Windows. A quick way (🟢Option 1) and a long way (🟡Option 2). DeepSpeed v11.2 will work on the current default text-generation-webui Python 3.11 environment! You have 2x options for how to setup DeepSpeed on Windows. A quick way (🟢Option 1) and a long way (🟡Option 2).
Thanks to [@S95Sedan](https://github.com/S95Sedan) - They managed to get DeepSpeed 11.2 working on Windows via making some edits to the original Microsoft DeepSpeed v11.2 installation. The original post is [here](https://github.com/oobabooga/text-generation-webui/issues/4734#issuecomment-1843984142). Thanks to [@S95Sedan](https://github.com/S95Sedan) - They managed to get DeepSpeed 11.2 working on Windows via making some edits to the original Microsoft DeepSpeed v11.2 installation. The original post is [here](https://github.com/oobabooga/text-generation-webui/issues/4734#issuecomment-1843984142).
@@ -504,45 +706,13 @@ def get_shm_size():
<br><br> <br><br>
**Removal** - If it became necessary to uninstall DeepSpeed, you can do so with `cmd_windows.bat` and then `pip uninstall deepspeed`<br><br> **Removal** - If it became necessary to uninstall DeepSpeed, you can do so with `cmd_windows.bat` and then `pip uninstall deepspeed`<br><br>
</details> </details>
</details>
## 🟦 Running AllTalk as a standalone app ### ⬜ AllTalk TTS Generator
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 TTS Generator is the solution for converting large volumes of text into speech using the voice of your choice. Whether you're creating audio content or just want to hear text read aloud, the TTS Generator is equipped to handle it all efficiently. Please see here for a quick [demo](https://www.youtube.com/watch?v=hunvXn0mLzc)<br><br>The link to open the TTS generator can be found on the built-in Settings and Documentation page.<br><br>**DeepSpeed** is **highly** recommended to speed up generation. **Low VRAM** would be best turned off and your LLM model unloaded from your GPU VRAM (unload your model). **No Playback** will reduce memory overhead on very large generations (15,000 words or more). Splitting **Export to Wav** into smaller groups will also reduce memory overhead at the point of exporting your wav files (so good for low memory systems).
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**. #### ⬜ Estimated Throughput
This will vary by system for a multitude of reasons, however, while generating a 58,000 word document to TTS, with DeepSpeed enabled, LowVram disabled, splitting size 2 and on an Nvidia RTX 4070, throughput was around 1,000 words per minute. Meaning, this took 1 hour to generate the TTS. Exporting to combined wavs took about 2-3 minutes total.
#### 🟦 (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.
#### 🟦 (Option 2) I wish to do a custom install of AllTalk
#### 🔹 A very quick understanding of Python Environments.
Different Python applications have different requirements, some of those requirement’s conflict with other Python applications requirements. To work around this problem, you can create different Python environments that remain separated from one another. A simple way of looking at Python environments, is just like how your house has different rooms for specific purposes (Kitchen, Bathroom, Bedroom etc). You can create a Python environment that is built/customised specifically for your current applications needs/purposes and will **not** interfere with any other Python applications environments/installations. <br><br>If you are adept at managing Python environments, have an existing Python environment and know that you won’t cause any conflicts by installing AllTalk's requirements within that Python environment, then load up your Python environment and install the requirements. For everyone else, here is a basic guide on installing AllTalk in its own custom Python environment (there will be small variations between OS's, but the principle is the same).
**Note:** A standard VENV can cause module path issues, hence Conda is the correct method to create a Python environment for AllTalk.
#### 🔹 Building a custom Python Environment with Miniconda
1) Open a terminal/command prompt, and confirm that both `python --version` and `pip` both work. Neither of them should give an error message. If they do you may need to install Python (and maybe Pip).<br><br>[Python Website](https://www.python.org/downloads/)<br>[Pip Website](https://pip.pypa.io/en/stable/installation/)<br><br>Once you have those working you can now continue on.<br><br>
2) Assuming you don't already have Miniconda installed, we will need to download and install Minoconda as this is what we will use to build our custom Python environment.<br><br>[Miniconda Website](https://docs.conda.io/projects/miniconda/en/latest/)<br><br>Download the Miniconda version that is correct for your OS and then install it. Miniconda will create some items in your Start Menu or Application Launcher called something like `Anaconda Prompt`<br><br> You will start the `Anaconda Prompt` and your prompt in your terminal/command prompt will say something like: <br><br>`(base) C:\users\myaccount\>`<br><br> The important bit is that it has the `(base)`, the location after that doesn't matter. `(base)` signifies we are in the base conda Python environment and can now create custom Python environments with Conda.<br><br>
3) In your Anaconda Prompt command prompt/terminal, move into the folder where you want to download AllTalk to and then git clone this repository. For simplicity I am going to assume that location is `c:\myfiles\`. So you will:<br><br>`cd myfiles`<br><br>`git clone https://github.com/erew123/alltalk_tts`<br><br>
4) Now we will create our custom Conda Python 3.11.5 environment and give it the name alltalkenv by typing the following at the prompt:<br><br>`conda create --name alltalkenv python=3.11.5`<br><br>You will be prompted if you want to continue and you say yes.<br><br>Once that process has completed, we now need to change from the `(base)` Conda Python environment, to our newly created `(alltalkenv)` environment. So type the following:<br><br>`conda activate alltalkenv`<br><br>Your prompt should now change from `(base) C:\myfiles\>` to `(alltalkenv) C:\myfiles\>`<br><br>
5) **If you are NOT using an Nvidia card and CUDA, skip to step 6**. To force PyTorch to install with CUDA, perform the following:<br><br>`pip cache purge` (Clear the current Pip cache)<br><br>`pip uninstall torch torchaudio` (Uninstall Torch and Torchaudio from the `alltalkenv` environment)<br><br>
You can now either install the CUDA 11.8 or 12.1 version of Torch and Torchaudio with **one** of the following<br><br>**CUDA 11.8** > `pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118`<br><br>**CUDA 12.1** > `pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121`<br><br>
6) Move into the alltalk_tts folder and install one of the two requirements files. Whichever one of the two is correct for your machine type:<br><br>`cd alltalk_tts`<br><br>
**Nvidia graphics card machines** - `pip install -r requirements_nvidia.txt`<br><br>
**Other machines (mac, amd etc)** - `pip install -r requirements_other.txt`<br><br>
7) Start AllTalk with `python script.py`<br><br>
🔹Anytime you wish to use AllTalk, update its requirements, install some other requirements such as DeepSpeed, you will need to start its Conda Python Environment in the terminal/prompt, which you will do with `conda activate alltalkenv` as long as the Conda executable is accessible at the command prompt/terminal you are in.<br><br>It is fully possible to create a batch file or script file that you can use as a launcher from your Start Menu/Application Launcher that will start the environment and AllTalk for you.
Deepspeed and other such things can be installed. Please read the relevant instructions for those items, however, make the relevant changes to load your correct Python environment when installing any requirements files and starting AllTalk.<br><br>
## ⬜ AllTalk TTS Generator
AllTalk TTS Generator is the solution for converting large volumes of text into speech using the voice of your choice. Whether you're creating audio content or just want to hear text read aloud, the TTS Generator is equipped to handle it all efficiently.<br><br>The link to open the TTS generator can be found on the built-in Settings and Documentation page.
#### ⬜ Quick Start #### ⬜ Quick Start
- **Text Input:** Enter the text you wish to convert into speech in the 'Text Input' box. - **Text Input:** Enter the text you wish to convert into speech in the 'Text Input' box.
@@ -553,15 +723,16 @@ Once you have sent text off to be generated, either as a stream or wav file gene
If you are generating wav files and populating the queue, you can generate one lot of text to speech, then input your next lot of text and it will continue adding to the list. If you are generating wav files and populating the queue, you can generate one lot of text to speech, then input your next lot of text and it will continue adding to the list.
#### ⬜ TTS Generation Modes #### ⬜ TTS Generation Modes
- **Wav Chunks:** Perfect for creating audio books, or anything you want to keep long term. Breaks down your text into manageable wav files and queues them up. Generation begins automatically, and playback will start after a few chunks have been prepared ahead. You can set the volume to 0 if you don’t want to hear playback. With Wav chunks, you can edit and/or regenerate portions of the TTS as needed. - **Wav Chunks:** Perfect for creating audio books, or anything you want to keep long term. Breaks down your text into manageable wav files and queues them up. Generation begins automatically, and playback will start after a few chunks have been prepared ahead. You can set the volume to 0 if you don’t want to hear playback. With Wav chunks, you can edit and/or regenerate portions of the TTS as needed.
- **Streaming:** For immediate playback without the ability to save. Ideal for on-the-fly speech generation and listening. This will not generate wav files and it will play back through your browser. You cannot stop the server generating the TTS once it has been sent. - **Streaming:** For immediate playback without the ability to save. Ideal for on-the-fly speech generation and listening. This will not generate wav files and it will play back through your browser. You cannot stop the server generating the TTS once it has been sent.<br><br>
With wav chunks you can either playback “In Browser” which is the web page you are on, or “On Server” which is through the console/terminal where AllTalk is running from. Only generation “In Browser” can play back smoothly and populate the Generated TTS List. Setting the Volume will affect the volume level played back both “In Browser” and “On Server”. With wav chunks you can either playback “In Browser” which is the web page you are on, or “On Server” which is through the console/terminal where AllTalk is running from, or "No Playback". Only generation “In Browser” can play back smoothly and populate the Generated TTS List. Setting the Volume will affect the volume level played back both “In Browser” and “On Server”.<br><br>
For generating **large amounts of TTS**, it's recommended to select the **No Playback** option. This setting minimizes the memory usage in your web browser by avoiding the loading and playing of audio files directly within the browser, which is particularly beneficial for handling extensive audio generations. The definition of large will vary depending on your system RAM availability (will update when I have more information as to guidelines). Once the audio is generated, you can export your list to JSON (for safety) and use the **Play List** option to play back your audio.
#### ⬜ Playback and List Management #### ⬜ Playback and List Management
- **Playback Controls:** Utilize 'Play List' to start from the beginning or 'Stop Playback' to halt at any time. - **Playback Controls:** Utilize 'Play List' to start from the beginning or 'Stop Playback' to halt at any time.
- **Custom Start:** Jump into your list at a specific ID to hear a particular section. - **Custom Start:** Jump into your list at a specific ID to hear a particular section.
- **Regeneration and Editing:** If a chunk isn't quite right, you can opt to regenerate it or edit the text directly. Click off the text to save changes and hit regenerate for the specific line. - **Regeneration and Editing:** If a chunk isn't quite right, you can opt to regenerate it or edit the text directly. Click off the text to save changes and hit regenerate for the specific line.
- **Export/Import List:** Save your TTS list as a JSON file or import one. Note: Existing wav files are needed for playback. Exporting is handy if you want to take your files away into another program and have a list of which wav is which, or if you keep your audio files, but want to come back at a later date, edit one or two lines, regenerate the speech and re-combine the wav’s into one new long wav. - **Export/Import List:** Save your TTS list as a JSON file or import one. Note: Existing wav files are needed for playback. Exporting is handy if you want to take your files away into another program and have a list of which wav is which, or if you keep your audio files, but want to come back at a later date, edit one or two lines, regenerate the speech and re-combine the wav’s into one new long wav.
#### ⬜ Exporting Your Audio #### ⬜ Exporting Your Audio
- **Export to WAV:** Combine all generated TTS from the list, into one single WAV file for easy download and distribution. - **Export to WAV:** Combine all generated TTS from the list, into one single WAV file for easy download and distribution. Its always recommended to export your list to a JSON before exporting, so that you have a backup, should something go wrong. You can simply re-import the list and try exporting again.<br><br>When exporting, there is a file size limit of 1GB and as such you have the option to choose how many files to include in each block of audio exported. 600 is just on the limit of 1GB, depending on the average file size, so 500 or less is a good amount to work with. You can combine the generated files after if you wish, in Audacity or similar.<br><br>Additionally, lower export batches will lower the memory requirements, so if your system is low on memory (maybe 8 or 16GB system), you can use smaller export batches to keep the memory requirement down.
#### ⬜ Customization and Preferences #### ⬜ Customization and Preferences
- **Character Voice:** Choose the voice that will read your text. - **Character Voice:** Choose the voice that will read your text.
- **Language:** Select the language of your text. - **Language:** Select the language of your text.
@@ -574,7 +745,7 @@ With wav chunks you can either playback “In Browser” which is the web page y
- Generated audio can be played back from the list, which also highlights the currently playing chunk. - Generated audio can be played back from the list, which also highlights the currently playing chunk.
- The TTS Generator remembers your settings, so you can pick up where you left off even after refreshing the page. - The TTS Generator remembers your settings, so you can pick up where you left off even after refreshing the page.
## 🟠 API Suite and JSON-CURL ### 🟠 API Suite and JSON-CURL
### 🟠Overview ### 🟠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. 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.
@@ -596,6 +767,22 @@ Retrieve a list of available voices for generating speech.
JSON return: `{"voices": ["voice1.wav", "voice2.wav", "voice3.wav"]}` JSON return: `{"voices": ["voice1.wav", "voice2.wav", "voice3.wav"]}`
#### 🟠 Current Settings Endpoint<br>
Retrieve a list of available voices for generating speech.
- URL: `http://127.0.0.1:7851/api/currentsettings`<br> - Method: `GET`<br>
`curl -X GET "http://127.0.0.1:7851/api/currentsettings"`
JSON return: ```{"models_available":[{"name":"Coqui","model_name":"API TTS"},{"name":"Coqui","model_name":"API Local"},{"name":"Coqui","model_name":"XTTSv2 Local"}],"current_model_loaded":"XTTSv2 Local","deepspeed_available":true,"deepspeed_status":true,"low_vram_status":true,"finetuned_model":false}```
`name & model_name` = listing the currently available models.<br>
`current_model_loaded` = what model is currently loaded into VRAM.<br>
`deepspeed_available` = was DeepSpeed detected on startup and available to be activated.<br>
`deepspeed_status` = If DeepSpeed was detected, is it currently activated.<br>
`low_vram_status` = Is Low VRAM currently enabled.<br>
`finetuned_model` = Was a finetuned model detected. (XTTSv2 FT).<br>
#### 🟠 Preview Voice Endpoint #### 🟠 Preview Voice Endpoint
Generate a preview of a specified voice with hardcoded settings. Generate a preview of a specified voice with hardcoded settings.
@@ -640,12 +827,13 @@ Generate a preview of a specified voice with hardcoded settings.
JSON return `{"status": "lowvram-success"}` JSON return `{"status": "lowvram-success"}`
### 🟠 TTS Generation Endpoint ### 🟠 TTS Generation Endpoint (Standard Generation)
Streaming endpoint details are further down the page.
- URL: `http://127.0.0.1:7851/api/tts-generate`<br> - Method: `POST`<br> - Content-Type: `application/x-www-form-urlencoded`<br> - URL: `http://127.0.0.1:7851/api/tts-generate`<br> - Method: `POST`<br> - Content-Type: `application/x-www-form-urlencoded`<br>
### 🟠 Example command lines ### 🟠 Example command lines (Standard Generation)
Standard TTS speech Example (standard text) generating a time-stamped file<br> Standard TTS generation supports Narration and will generate a wav file/blob. Standard TTS speech Example (standard text) generating a time-stamped file<br>
`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"`<br> `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"`<br>
@@ -748,7 +936,32 @@ Example JSON TTS Generation Response:
`{"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"}` `{"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"}`
### 🟠 TTS Generation Endpoint (Streaming Generation)
Streaming TTS generation does NOT support Narration and will generate an audio stream. Streaming TTS speech JavaScript Example:<br>
- URL: `http://localhost:7851/api/tts-generate-streaming`<br> - Method: `POST`<br> - Content-Type: `application/x-www-form-urlencoded`<br><br>
```
// Example parameters
const text = "Here is some text";
const voice = "female_01.wav";
const language = "en";
const outputFile = "stream_output.wav";
// Encode the text for URL
const encodedText = encodeURIComponent(text);
// Create the streaming URL
const streamingUrl = `http://localhost:7851/api/tts-generate-streaming?text=${encodedText}&voice=${voice}&language=${language}&output_file=${outputFile}`;
// Create and play the audio element
const audioElement = new Audio(streamingUrl);
audioElement.play(); // Play the audio stream directly
```
- **Text (text):** This is the actual text you want to convert to speech. It should be a string and must be URL-encoded to ensure that special characters (like spaces and punctuation) are correctly transmitted in the URL. Example: `Hello World` becomes `Hello%20World` when URL-encoded.<br>
- **Voice (voice):** This parameter specifies the voice type to be used for the TTS. The value should match one of the available voice options in AllTalks voices folder. This is a string representing the file, like `female_01.wav`.<br>
- **Language (language):** This setting determines the language in which the text should be spoken. A two-letter language code (like `en` for English, `fr` for French, etc.).<br>
- **Output File (output_file):** This parameter names the output file where the audio will be streamed. It should be a string representing the file name, such as `stream_output.wav`. AllTalk will not save this as a file in its outputs folder.<br>
<br>
### 🔴 Future to-do list ### 🔴 Future to-do list
- SillyTavern Support - I am maintaining a list of things people request [here](https://github.com/erew123/alltalk_tts/discussions/74)
- Possibly add some additional TTS engines (TBD). - Possibly add some additional TTS engines (TBD).
- Have a break! - Have a break!
+504
View File
@@ -0,0 +1,504 @@
@echo off
cd /D "%~dp0"
set PATH=%PATH%;%SystemRoot%\system32
:: Generate the ESC character
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
:: Standard Colors
set "BLACK=%ESC%[30m"
set "RED=%ESC%[31m"
set "GREEN=%ESC%[32m"
set "YELLOW=%ESC%[33m"
set "BLUE=%ESC%[34m"
set "MAGENTA=%ESC%[35m"
set "CYAN=%ESC%[36m"
set "WHITE=%ESC%[37m"
set "L_BLACK=%ESC%[90m"
set "L_RED=%ESC%[91m"
set "L_GREEN=%ESC%[92m"
set "L_YELLOW=%ESC%[93m"
set "L_BLUE=%ESC%[94m"
set "L_MAGENTA=%ESC%[95m"
set "L_CYAN=%ESC%[96m"
set "L_WHITE=%ESC%[97m"
set "RESET=%ESC%[0m"
@rem Check if curl is available
curl --version >nul 2>&1
if "%ERRORLEVEL%" NEQ "0" (
echo curl is not available on this system. Please install curl then re-run the script https://curl.se/
echo or perform a manual installation of a Conda Python environment.
goto end
)
:MainMenu
cls
echo.
echo %L_BLUE%ALLTALK WINDOWS SETUP UTILITY%RESET%
echo.
echo INSTALLATION TYPE
echo 1) I am using AllTalk as part of %L_GREEN%Text-generation-webui%RESET%
echo 2) I am using AllTalk as a %L_GREEN%Standalone Application%RESET%
echo.
echo 9) %L_RED%Exit/Quit%RESET%
echo.
set /p UserOption=" Enter your choice: "
if "%UserOption%"=="1" goto WebUIMenu
if "%UserOption%"=="2" goto StandaloneMenu
if "%UserOption%"=="9" goto End
goto MainMenu
:WebUIMenu
cls
echo.
echo %L_BLUE%TEXT-GENERATION-WEBUI SETUP%RESET%
echo.
echo Please ensure you have started your Text-generation-webui Python
echo environment. If you have NOT done this, please run %L_GREEN%cmd_windows.bat%RESET%
echo in the %L_GREEN%text-generation-webui%RESET% folder and then re-run this script.
echo.
echo BASE REQUIREMENTS
echo 1) Install the requirements for a %L_GREEN%Nvidia machine%RESET%.
echo 2) Install the requirements for a %L_GREEN%AMD or MAC machine%RESET%.
echo.
echo OPTIONAL
echo 3) Install the Finetuning requirements.
echo 4) Install DeepSpeed v11.2 for CUDA %L_GREEN%11.8%RESET% and Python-3.11.x.
echo 5) Install DeepSpeed v11.2 for CUDA %L_GREEN%12.1%RESET% and Python-3.11.x.
echo 6) Uninstall DeepSpeed.
echo.
echo. OTHER
echo 7) Generate a diagnostics file.
echo.
echo 9) %L_RED%Exit/Quit%RESET%
echo.
set /p WebUIOption="Enter your choice: "
if "%WebUIOption%"=="1" goto InstallNvidiaTextGen
if "%WebUIOption%"=="2" goto InstallOtherTextGen
if "%WebUIOption%"=="3" goto InstallFinetuneTextGen
if "%WebUIOption%"=="4" goto InstallDeepSpeed118TextGen
if "%WebUIOption%"=="5" goto InstallDeepSpeed121TextGen
if "%WebUIOption%"=="6" goto UnInstallDeepSpeed
if "%WebUIOption%"=="7" goto GenerateDiagsTextGen
if "%WebUIOption%"=="9" goto End
goto WebUIMenu
:StandaloneMenu
cls
echo.
echo %L_BLUE%ALLTALK STANDALONE APPLICATION SETUP%RESET%
echo.
echo BASE REQUIREMENTS
echo 1) Install AllTalk as a Standalone Application
echo.
echo OPTIONAL
echo 2) Delete AllTalk's custom Python environment
echo 3) Install the Finetuning requirements
echo.
echo. OTHER
echo 4) Generate a diagnostics file
echo.
echo 9) %L_RED%Exit/Quit%RESET%
echo.
set /p StandaloneOption="Enter your choice: "
if "%StandaloneOption%"=="1" goto InstallCustomStandalone
if "%StandaloneOption%"=="2" goto DeleteCustomStandalone
if "%StandaloneOption%"=="3" goto InstallFinetuneStandalone
if "%StandaloneOption%"=="4" goto GenerateDiagsStandalone
if "%StandaloneOption%"=="9" goto End
goto StandaloneMenu
:InstallNvidiaTextGen
pip install -r requirements_nvidia.txt
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error installing the Nvidia requirements.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
Echo.
echo.
Echo Nvidia machine requirements installed successfully.
Echo.
pause
goto WebUIMenu
:InstallOtherTextGen
pip install -r requirements_other.txt
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error installing the Other requirements.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
Echo.
echo.
Echo Other machine requirements installed successfully.
Echo.
pause
goto WebUIMenu
:InstallFinetuneTextGen
pip install -r requirements_finetune.txt
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error installing the Finetune requirements.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
Echo.
Echo Finetune requirements installed successfully. Please ensure you have installed CUDA 11.8.
Echo Finetune needs access to %L_GREEN%cublas64_11.dll%RESET% and will error if this is not setup correctly.
Echo Please see here for details %L_GREEN%https://github.com/erew123/alltalk_tts#-finetuning-a-model%RESET%
Echo.
pause
goto WebUIMenu
:InstallDeepSpeed118TextGen
echo Downloading DeepSpeed...
curl -LO https://github.com/erew123/alltalk_tts/releases/download/deepspeed/deepspeed-0.11.2+cuda118-cp311-cp311-win_amd64.whl
if %ERRORLEVEL% neq 0 (
echo.
echo Failed to download DeepSpeed wheel file.
echo Please check your internet connection or try again later.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
echo DeepSpeed wheel file downloaded successfully.
echo Installing DeepSpeed...
pip install deepspeed-0.11.2+cuda118-cp311-cp311-win_amd64.whl
if %ERRORLEVEL% neq 0 (
echo.
echo Failed to install DeepSpeed.
echo Please check if the wheel file is compatible with your system.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
Echo.
echo.
Echo DeepSpeed installed successfully.
Echo.
del deepspeed-0.11.2+cuda118-cp311-cp311-win_amd64.whl
pause
goto WebUIMenu
:InstallDeepSpeed121TextGen
echo Downloading DeepSpeed...
curl -LO https://github.com/erew123/alltalk_tts/releases/download/deepspeed/deepspeed-0.11.2+cuda121-cp311-cp311-win_amd64.whl
if %ERRORLEVEL% neq 0 (
echo.
echo Failed to download DeepSpeed wheel file.
echo Please check your internet connection or try again later.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
echo DeepSpeed wheel file downloaded successfully.
echo Installing DeepSpeed...
pip install deepspeed-0.11.2+cuda121-cp311-cp311-win_amd64.whl
if %ERRORLEVEL% neq 0 (
echo.
echo Failed to install DeepSpeed.
echo Please check if the wheel file is compatible with your system.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
Echo.
echo.
Echo DeepSpeed installed successfully.
Echo.
del deepspeed-0.11.2+cuda121-cp311-cp311-win_amd64.whl
pause
goto WebUIMenu
:UnInstallDeepSpeed
pip uninstall deepspeed
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error uninstalling DeepSpeed.
echo Press any key to return to the menu.
echo.
pause
goto WebUIMenu
)
echo.
Echo DeepSpeed uninstalled successfully.
Echo.
pause
goto WebUIMenu
:GenerateDiagsTextGen
Python diagnostics.py
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error running diagnostics. Have you correctly started your
echo Text-generation-webui Python environment with %L_GREEN%cmd_windows.bat%RESET%?
echo.
pause
goto WebUIMenu
)
Echo.
echo.
Echo Diagnostics.log generated. Please scroll up to look over the log.
Echo.
pause
goto WebUIMenu
:InstallCustomStandalone
set PATH=%PATH%;%SystemRoot%\system32
@rem Check if curl is available
curl --version >nul 2>&1
if "%ERRORLEVEL%" NEQ "0" (
echo curl is not available on this system. Please install curl then re-run the script https://curl.se/
echo or perform a manual installation of a Conda Python environment.
goto end
)
echo "%CD%"| findstr /C:" " >nul && echo This script relies on Miniconda which can not be silently installed under a path with spaces. Please correct your folder names and re-try installation. && goto exit
@rem Check for special characters in installation path
set "SPCHARMESSAGE=WARNING: Special characters were detected in the installation path! This can cause the installation to fail!"
echo "%CD%"| findstr /R /C:"[!#\$%&()\*+,;<=>?@\[\]\^`{|}~]" >nul && (
call :PrintBigMessage %SPCHARMESSAGE%
)
set SPCHARMESSAGE=
@rem fix failed install when installing to a separate drive
set TMP=%cd%\alltalk_environment
set TEMP=%cd%\alltalk_environment
@rem deactivate existing conda envs as needed to avoid conflicts
(call conda deactivate && call conda deactivate && call conda deactivate) 2>nul
@rem config
set INSTALL_DIR=%cd%\alltalk_environment
set CONDA_ROOT_PREFIX=%cd%\alltalk_environment\conda
set INSTALL_ENV_DIR=%cd%\alltalk_environment\env
set MINICONDA_DOWNLOAD_URL=https://repo.anaconda.com/miniconda/Miniconda3-py310_23.3.1-0-Windows-x86_64.exe
set conda_exists=F
@rem figure out whether git and conda need to be installed
call "%CONDA_ROOT_PREFIX%\_conda.exe" --version >nul 2>&1
if "%ERRORLEVEL%" EQU "0" (
set conda_exists=T
call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%"
goto RunScript
)
@rem download and install conda if not installed
echo Downloading Miniconda from %MINICONDA_DOWNLOAD_URL% to %INSTALL_DIR%\miniconda_installer.exe
mkdir "%INSTALL_DIR%"
call curl -Lk "%MINICONDA_DOWNLOAD_URL%" > "%INSTALL_DIR%\miniconda_installer.exe" || ( echo. && echo Miniconda failed to download. && goto end )
echo Installing Miniconda to %CONDA_ROOT_PREFIX%
start /wait "" "%INSTALL_DIR%\miniconda_installer.exe" /InstallationType=JustMe /NoShortcuts=1 /AddToPath=0 /RegisterPython=0 /NoRegistry=1 /S /D=%CONDA_ROOT_PREFIX%
echo Miniconda version:
call "%CONDA_ROOT_PREFIX%\_conda.exe" --version || ( echo. && echo Miniconda not found. && goto end )
@rem create the installer env
echo Packages to install: %PACKAGES_TO_INSTALL%
call "%CONDA_ROOT_PREFIX%\_conda.exe" create --no-shortcuts -y -k --prefix "%INSTALL_ENV_DIR%" python=3.11 || ( echo. && echo Conda environment creation failed. && goto end )
@rem check if conda environment was actually created
if not exist "%INSTALL_ENV_DIR%\python.exe" ( echo. && echo Conda environment is empty. && goto end )
@rem activate installer env
call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" || ( echo. && echo Miniconda hook not found. && goto end )
@rem Ask user for the type of requirements to install
echo.
echo %L_BLUE%Choose the type of requirements to install%RESET%
echo.
echo 1. Nvidia graphics card machines
echo 2. Other machines (mac, amd, etc)
echo.
set /p UserChoice="Enter your choice (1 or 2): "
@rem Install requirements based on user choice
if "%UserChoice%" == "1" (
echo.
echo Installing Nvidia requirements...
echo Downloading Pytorch with CUDA..
pip install torch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 --upgrade --force-reinstall --index-url https://download.pytorch.org/whl/cu121
pip install numpy==1.24.4
pip install typing-extensions>=4.8.0
pip install networkx<3.0.0,>=2.5.0
pip install fsspec>=2023.6.0
pip install soundfile==0.12.1
pip install uvicorn==0.24.0.post1
pip install transformers>=4.37.1
pip install TTS==0.21.3
pip install fastapi==0.104.1
pip install Jinja2==3.1.2
pip install requests==2.31.0
pip install tqdm==4.66.1
pip install importlib-metadata==4.8.1
pip install packaging==23.2
pip install pydantic==1.10.13
pip install sounddevice==0.4.6
pip install python-multipart==0.0.6
pip install cutlet>=0.3.0
pip install unidic-lite>=1.0.8
echo Downloading DeepSpeed...
curl -LO https://github.com/erew123/alltalk_tts/releases/download/DeepSpeed-12.7/deepspeed-0.12.7+d058d4b-cp311-cp311-win_amd64.whl
echo Installing DeepSpeed...
pip install deepspeed-0.12.7+d058d4b-cp311-cp311-win_amd64.whl
del deepspeed-0.12.7+d058d4b-cp311-cp311-win_amd64.whl
) else (
echo Installing requirements for other machines...
pip install -r requirements_other.txt
)
@rem Create start_environment.bat to run AllTalk environment
echo @echo off > start_environment.bat
echo cd /D "%~dp0" >> start_environment.bat
echo set CONDA_ROOT_PREFIX=%cd%\alltalk_environment\conda >> start_environment.bat
echo set INSTALL_ENV_DIR=%cd%\alltalk_environment\env >> start_environment.bat
echo call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" >> start_environment.bat
@rem Create start_alltalk.bat to run AllTalk
echo @echo off > start_alltalk.bat
echo cd /D "%~dp0" >> start_alltalk.bat
echo set CONDA_ROOT_PREFIX=%cd%\alltalk_environment\conda >> start_alltalk.bat
echo set INSTALL_ENV_DIR=%cd%\alltalk_environment\env >> start_alltalk.bat
echo call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" >> start_alltalk.bat
echo call python script.py >> start_alltalk.bat
Echo.
Echo start_alltalk.bat has been created.
Echo You can now start AllTalk with %L_YELLOW%start_alltalk.bat%RESET%
Echo.
pause
goto StandaloneMenu
:DeleteCustomStandalone
@rem Check if the alltalk_environment directory exists
if not exist "%cd%\alltalk_environment\" (
echo.
echo %L_GREEN%alltalk_environment%RESET% directory does not exist. No need to delete.
echo.
pause
goto StandaloneMenu
)
@rem Check if a Conda environment is active
if not defined CONDA_PREFIX goto NoCondaEnvDeleteCustomStandalone
@rem Deactivate Conda environment if it's active
Echo Exiting the Conda Environment. Please run %L_GREEN%atsetup.bat%RESET% again and delete the environment.
conda deactivate
:NoCondaEnvDeleteCustomStandalone
echo Deleting "alltalk_environment". Please wait.
rd /s /q "alltalk_environment"
del start_alltalk.bat
del start_environment.bat
if %ERRORLEVEL% neq 0 (
echo.
echo Failed to delete alltalk_environment folder.
echo Please make sure it is not in use and try again.
echo.
pause
goto StandaloneMenu
)
echo.
Echo.
echo Environment %L_GREEN%alltalk_environment%RESET% deleted. Please set up the environment again.
Echo.
pause
goto StandaloneMenu
:InstallFinetuneStandalone
cd /D "%~dp0"
set CONDA_ROOT_PREFIX=%cd%\alltalk_environment\conda
set INSTALL_ENV_DIR=%cd%\alltalk_environment\env
@rem Check if the Conda environment exists
if not exist "%INSTALL_ENV_DIR%\python.exe" (
echo.
echo The Conda environment at "%INSTALL_ENV_DIR%" does not exist.
echo Please install the environment before proceeding.
echo.
pause
goto StandaloneMenu
)
@rem Attempt to activate the Conda environment
call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%"
if errorlevel 1 (
echo.
echo Failed to activate the Conda environment.
echo Please check your installation and try again.
echo.
pause
goto StandaloneMenu
)
@rem Proceed with installing requirements
pip install -r requirements_finetune.txt
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error installing the Finetune requirements.
echo Press any key to return to the menu.
echo.
pause
goto StandaloneMenu
)
Echo.
Echo Finetune requirements installed successfully. Please ensure you have installed CUDA 11.8.
Echo Finetune needs access to %L_GREEN%cublas64_11.dll%RESET% and will error if this is not setup correctly.
Echo Please see here for details %L_GREEN%https://github.com/erew123/alltalk_tts#-finetuning-a-model%RESET%
Echo.
pause
goto StandaloneMenu
:GenerateDiagsStandalone
cd /D "%~dp0"
set CONDA_ROOT_PREFIX=%cd%\alltalk_environment\conda
set INSTALL_ENV_DIR=%cd%\alltalk_environment\env
@rem Check if the Conda environment exists
if not exist "%INSTALL_ENV_DIR%\python.exe" (
echo.
echo The Conda environment at "%INSTALL_ENV_DIR%" does not exist.
echo Please install the environment before proceeding.
echo.
pause
goto StandaloneMenu
)
@rem Attempt to activate the Conda environment
call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%"
if errorlevel 1 (
echo.
echo Failed to activate the Conda environment.
echo Please check your installation and try again.
echo.
pause
goto StandaloneMenu
)
@rem Run diagnostics
Python diagnostics.py
if %ERRORLEVEL% neq 0 (
echo.
echo There was an error running diagnostics.
echo Press any key to return to the menu.
echo.
pause
goto StandaloneMenu
)
Echo.
Echo.
Echo Diagnostics.log generated. Please scroll up to look over the log.
Echo.
pause
goto StandaloneMenu
:End
echo Exiting AllTalk Setup Utility...
exit /b
+443
View File
@@ -0,0 +1,443 @@
#!/bin/bash
# ANSI color codes
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
CYAN='\033[1;36m'
MAGENTA='\033[1;35m'
WHITE='\033[1;37m'
L_RED='\033[1;91m'
L_GREEN='\033[1;92m'
L_YELLOW='\033[1;93m'
L_BLUE='\033[1;94m'
L_CYAN='\033[1;96m'
L_MAGENTA='\033[1;95m'
NC='\033[0m' # No Color
# Navigate to the script's directory
cd "$(dirname "$0")"
# Function to check if curl is installed
check_curl() {
if ! command -v curl &> /dev/null; then
echo "curl is not available on this system. Please install curl then re-run the script https://curl.se/"
echo "or perform a manual installation of a Conda Python environment."
exit 1
fi
}
# Main Menu
main_menu() {
while true; do
clear
echo
echo -e " ${L_BLUE}ALLTALK LINUX SETUP UTILITY${NC}"
echo
echo " INSTALLATION TYPE"
echo -e " 1) I am using AllTalk as part of ${L_GREEN}Text-generation-webui${NC}"
echo -e " 2) I am using AllTalk as a ${L_GREEN}Standalone Application${NC}"
echo
echo -e " 9)${L_RED} Exit/Quit${NC}"
echo
read -p " Enter your choice: " user_option
case $user_option in
1) webui_menu ;;
2) standalone_menu ;;
9) exit 0 ;;
*) echo "Invalid option"; sleep 2 ;;
esac
done
}
# Text-generation-webui Menu
webui_menu() {
while true; do
clear
echo
echo -e " ${L_BLUE}TEXT-GENERATION-WEBUI SETUP${NC}"
echo
echo -e " Please ensure you have started your Text-generation-webui Python"
echo -e " environment. If you have NOT done this, please run ${L_GREEN}/cmd_linux.sh${NC}"
echo -e " in the ${L_GREEN}text-generation-webui${NC} folder and then re-run this script."
echo
echo " BASE REQUIREMENTS"
echo -e " 1) Install the AllTalk requirements for an ${L_GREEN}Nvidia GPU machine.${NC}"
echo -e " 2) Install the AllTalk requirements for an ${L_GREEN}AMD or MAC machine.${NC}"
echo
echo " OPTIONAL"
echo " 3) Install the Finetuning requirements."
echo " 4) Install DeepSpeed."
echo " 5) Uninstall DeepSpeed."
echo
echo " OTHER"
echo " 6) Generate a diagnostics file."
echo
echo -e " 9)${L_RED} Exit/Quit${NC}"
echo
read -p " Enter your choice: " webui_option
case $webui_option in
1) install_nvidia_textgen ;;
2) install_other_textgen ;;
3) install_finetune_textgen ;;
4) install_deepspeed ;;
5) uninstall_deepspeed ;;
6) generate_diagnostics_textgen ;;
9) exit 0 ;;
*) echo "Invalid option"; sleep 2 ;;
esac
done
}
install_nvidia_textgen() {
local requirements_file="requirements_nvidia.txt"
echo " Installing Finetune requirements from $requirements_file..."
if ! pip install -r "$requirements_file"; then
echo " There was an error installing the Nvidia requirements."
echo " Please check the output for details."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
echo " Nvidia requirements installed successfully."
read -p " Press any key to continue. " -n 1
echo
}
install_other_textgen() {
local requirements_file="requirements_other.txt"
echo " Installing Other machine requirements from $requirements_file..."
if ! pip install -r "$requirements_file"; then
echo " There was an error installing the Other requirements."
echo " Please check the output for details."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
echo " Other machine requirements installed successfully."
read -p " Press any key to continue. " -n 1
echo
}
install_finetune_textgen() {
local requirements_file="requirements_finetune.txt"
echo " Installing Finetune requirements from $requirements_file..."
if ! pip install -r "$requirements_file"; then
echo " There was an error installing the Finetune requirements."
echo " Please check the output for details."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
echo
echo " Finetune base requirements installed successfully."
echo
echo -e " Finetuning requires access to ${GREEN}Cublas${NC} from the ${GREEN}Nvidia CUDA Toolkit${NC}, so will need installing."
echo
echo -e " Instructions can be found here:"
echo -e " ${GREEN}https://github.com/erew123/alltalk_tts?#-finetuning-a-model${NC}"
echo
read -p " Press any key to continue. " -n 1
echo
}
# Function to install DeepSpeed
install_deepspeed() {
clear
echo
echo -e " ${L_BLUE}DEEPSPEED INSTALLATION REQUIREMENTS${NC}"
echo
echo -e " - NVIDIA CUDA Toolkit must be installed from your ${L_GREEN}Linux package manager${NC}"
echo -e " or ${L_GREEN}https://developer.nvidia.com/cuda-toolkit-archive${NC}"
echo -e " - The environment variable ${L_GREEN}CUDA_HOME${NC} must be set in your Python env"
echo -e " e.g. export CUDA_HOME=/usr/local/cuda."
echo -e " - ${L_GREEN}libaio-dev${NC} must be installed."
echo
echo -e " See the following link for full instructions:"
echo -e " ${L_GREEN}https://github.com/erew123/alltalk_tts?#-deepspeed-installation-options${NC}"
echo
echo -e " ${L_BLUE}Please ${L_RED}confirm${L_BLUE} that you have completed these steps before continuing"
echo -e " with the DeepSpeed installation, or the install ${L_RED}will fail.${NC}"
echo
read -p " Have you completed all the above steps? (y/n): " confirm
if [ "$confirm" != "y" ]; then
echo -e " ${RED}DeepSpeed installation cannot proceed without completing the prerequisites.${NC}"
return
fi
echo -e "\n ${GREEN}Proceeding with DeepSpeed installation...${NC}"
pip install deepspeed
if [ $? -ne 0 ]; then
echo -e " ${RED}There was an error installing DeepSpeed.${NC}"
return
fi
echo -e " ${GREEN}DeepSpeed installed successfully.${NC}"
read -p " Press any key to continue. " -n 1
echo
}
uninstall_deepspeed() {
echo "Uninstalling DeepSpeed..."
pip uninstall -y deepspeed
if [ $? -ne 0 ]; then
echo " There was an error uninstalling DeepSpeed."
echo " Press any key to return to the menu."
read -n 1
return
fi
echo " DeepSpeed uninstalled successfully."
echo " Press any key to continue."
read -n 1
}
generate_diagnostics_textgen() {
# Run diagnostics
if ! python diagnostics.py; then
echo " There was an error running diagnostics."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
echo " Diagnostics completed successfully."
read -p " Press any key to continue. " -n 1
echo
}
# Standalone Menu
standalone_menu() {
while true; do
clear
echo
echo -e " ${L_BLUE}ALLTALK STANDALONE APPLICATION SETUP${NC}"
echo
echo " BASE REQUIREMENTS"
echo " 1) Install AllTalk as a Standalone Application"
echo
echo " OPTIONAL"
echo " 2) Delete AllTalk's custom Python environment"
echo " 3) Install the Finetuning requirements"
echo " 4) Install DeepSpeed."
echo
echo " OTHER"
echo " 5) Generate a diagnostics file"
echo
echo -e " 9)${L_RED} Exit/Quit${NC}"
echo
read -p " Enter your choice: " standalone_option
case $standalone_option in
1) install_custom_standalone ;;
2) delete_custom_standalone ;;
3) install_finetune_standalone ;;
4) install_deepspeed ;;
5) generate_diagnostics_standalone ;;
9) exit 0 ;;
*) echo "Invalid option"; sleep 2 ;;
esac
done
}
install_custom_standalone() {
cd "$(dirname "${BASH_SOURCE[0]}")"
if [[ "$(pwd)" =~ " " ]]; then
echo "This script relies on Miniconda which can not be silently installed under a path with spaces."
exit
fi
# Deactivate existing conda envs as needed to avoid conflicts
{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
OS_ARCH=$(uname -m)
case "${OS_ARCH}" in
x86_64*) OS_ARCH="x86_64" ;;
arm64* | aarch64*) OS_ARCH="aarch64" ;;
*) echo "Unknown system architecture: $OS_ARCH! This script runs only on x86_64 or arm64" && exit ;;
esac
# Config
INSTALL_DIR="$(pwd)/alltalk_environment"
CONDA_ROOT_PREFIX="${INSTALL_DIR}/conda"
INSTALL_ENV_DIR="${INSTALL_DIR}/env"
MINICONDA_DOWNLOAD_URL="https://repo.anaconda.com/miniconda/Miniconda3-py310_23.3.1-0-Linux-${OS_ARCH}.sh"
if [ ! -x "${CONDA_ROOT_PREFIX}/bin/conda" ]; then
echo "Downloading Miniconda from $MINICONDA_DOWNLOAD_URL to ${INSTALL_DIR}/miniconda_installer.sh"
mkdir -p "${INSTALL_DIR}"
curl -L "${MINICONDA_DOWNLOAD_URL}" -o "${INSTALL_DIR}/miniconda_installer.sh"
chmod +x "${INSTALL_DIR}/miniconda_installer.sh"
bash "${INSTALL_DIR}/miniconda_installer.sh" -b -p "${CONDA_ROOT_PREFIX}"
echo "Miniconda installed."
fi
if [ ! -d "${INSTALL_ENV_DIR}" ]; then
"${CONDA_ROOT_PREFIX}/bin/conda" create -y --prefix "${INSTALL_ENV_DIR}" python=3.11
echo "Conda environment created at ${INSTALL_ENV_DIR}."
fi
# Activate the environment and install requirements
source "${CONDA_ROOT_PREFIX}/etc/profile.d/conda.sh"
conda activate "${INSTALL_ENV_DIR}"
echo
echo -e " ${L_BLUE}Choose the type of requirements to install${NC}"
echo
echo " 1. Nvidia graphics card machines"
echo " 2. Other machines (mac, amd, etc)"
echo
read -p " Enter your choice (1 or 2): " user_choice
if [ "$user_choice" == "1" ]; then
pip install torch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 --upgrade --force-reinstall --index-url https://download.pytorch.org/whl/cu121
pip install numpy==1.24.4
pip install typing-extensions>=4.8.0
pip install networkx<3.0.0,>=2.5.0
pip install fsspec>=2023.6.0
pip install soundfile==0.12.1
pip install uvicorn==0.24.0.post1
pip install transformers>=4.37.1
pip install TTS==0.21.3
pip install fastapi==0.104.1
pip install Jinja2==3.1.2
pip install requests==2.31.0
pip install tqdm==4.66.1
pip install importlib-metadata==4.8.1
pip install packaging==23.2
pip install pydantic==1.10.13
pip install sounddevice==0.4.6
pip install python-multipart==0.0.6
pip install cutlet>=0.3.0
pip install unidic-lite>=1.0.8
else
pip install -r requirements_other.txt
fi
# Create start_environment.sh to run AllTalk
cat << EOF > start_environment.sh
#!/bin/bash
cd "$(dirname "${BASH_SOURCE[0]}")"
if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniconda which can not be silently installed under a path with spaces. && exit; fi
# deactivate existing conda envs as needed to avoid conflicts
{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
# config
CONDA_ROOT_PREFIX="$(pwd)/alltalk_environment/conda"
INSTALL_ENV_DIR="$(pwd)/alltalk_environment/env"
# environment isolation
export PYTHONNOUSERSITE=1
unset PYTHONPATH
unset PYTHONHOME
export CUDA_PATH="$INSTALL_ENV_DIR"
export CUDA_HOME="$CUDA_PATH"
# activate env
bash --init-file <(echo "source \"$CONDA_ROOT_PREFIX/etc/profile.d/conda.sh\" && conda activate \"$INSTALL_ENV_DIR\"")
EOF
# Create start_alltalk.sh to run AllTalk
cat << EOF > start_alltalk.sh
#!/bin/bash
source "${CONDA_ROOT_PREFIX}/etc/profile.d/conda.sh"
conda activate "${INSTALL_ENV_DIR}"
python script.py
EOF
chmod +x start_alltalk.sh
chmod +x start_environment.sh
echo
echo
echo -e " start_alltalk.sh has been created."
echo -e " You can now start AllTalk with ${L_YELLOW}./start_alltalk.sh${NC}"
echo
read -p " Press any key to continue. " -n 1
}
delete_custom_standalone() {
local env_dir="$PWD/alltalk_environment"
# Check if the alltalk_environment directory exists
if [ ! -d "$env_dir" ]; then
echo " \"$env_dir\" directory does not exist. No need to delete."
read -p " Press any key to continue. " -n 1
echo
return
fi
# Check if a Conda environment is active and deactivate it
if [ -n "$CONDA_PREFIX" ]; then
echo " Exiting the Conda environment. You may need to start ./atstart.sh again"
conda deactivate
fi
echo "Deleting \"$env_dir\". Please wait."
rm -rf "$env_dir"
if [ -d "$env_dir" ]; then
echo " Failed to delete \"$env_dir\" folder."
echo " Please make sure it is not in use and try again."
else
echo " Environment \"$env_dir\" deleted successfully."
fi
read -p " Press any key to continue. " -n 1
echo
}
install_finetune_standalone() {
local env_dir="$PWD/alltalk_environment"
local conda_root_prefix="${env_dir}/conda"
local install_env_dir="${env_dir}/env"
if [ ! -d "${install_env_dir}" ]; then
echo " The Conda environment at '${install_env_dir}' does not exist."
echo " Please install the environment before proceeding."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
source "${conda_root_prefix}/etc/profile.d/conda.sh"
conda activate "${install_env_dir}"
local requirements_file="requirements_finetune.txt"
echo "Installing Finetune requirements from $requirements_file..."
if ! pip install -r "$requirements_file"; then
echo " There was an error installing the Finetune requirements."
echo " Please check the output for details."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
echo
echo " Finetune base requirements installed successfully."
echo
echo -e " Finetuning requires access to ${GREEN}Cublas${NC} from the ${GREEN}Nvidia CUDA Toolkit${NC}, so will need installing."
echo
echo -e " Instructions can be found here:"
echo -e " ${GREEN}https://github.com/erew123/alltalk_tts?#-finetuning-a-model${NC}"
echo
read -p " Press any key to continue. " -n 1
echo
}
generate_diagnostics_standalone() {
local env_dir="$PWD/alltalk_environment"
local conda_root_prefix="${env_dir}/conda"
local install_env_dir="${env_dir}/env"
if [ ! -d "${install_env_dir}" ]; then
echo " The Conda environment at '${install_env_dir}' does not exist."
echo " Please install the environment before proceeding."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
source "${conda_root_prefix}/etc/profile.d/conda.sh"
conda activate "${install_env_dir}"
if ! python diagnostics.py; then
echo " There was an error running diagnostics."
read -p " Press any key to return to the menu. " -n 1
echo
return
fi
echo " Diagnostics completed successfully."
read -p " Press any key to continue. " -n 1
echo
}
# Start the main menu
main_menu
+25 -1
View File
@@ -1 +1,25 @@
{"activate": true, "autoplay": true, "branding": "AllTalk ", "narrator_enabled": false, "deepspeed_activate": false, "delete_output_wavs": "Disabled", "ip_address": "127.0.0.1", "language": "English", "low_vram": false, "local_temperature": "0.7", "local_repetition_penalty": "10.0", "tts_model_loaded": true, "tts_model_name": "tts_models/multilingual/multi-dataset/xtts_v2", "narrator_voice": "female_01.wav", "output_folder_wav": "extensions/alltalk_tts/outputs/", "output_folder_wav_standalone": "outputs/", "port_number": "7851", "remove_trailing_dots": false, "show_text": true, "tts_method_api_local": false, "tts_method_api_tts": false, "tts_method_xtts_local": true, "voice": "female_01.wav"} {
"activate": true,
"autoplay": true,
"branding": "AllTalk ",
"narrator_enabled": false,
"deepspeed_activate": false,
"delete_output_wavs": "Disabled",
"ip_address": "127.0.0.1",
"language": "English",
"low_vram": false,
"local_temperature": "0.7",
"local_repetition_penalty": "10.0",
"tts_model_loaded": true,
"tts_model_name": "tts_models/multilingual/multi-dataset/xtts_v2",
"narrator_voice": "female_01.wav",
"output_folder_wav": "extensions/alltalk_tts/outputs/",
"output_folder_wav_standalone": "outputs/",
"port_number": "7851",
"remove_trailing_dots": false,
"show_text": true,
"tts_method_api_local": false,
"tts_method_api_tts": false,
"tts_method_xtts_local": true,
"voice": "female_01.wav"
}
+7
View File
@@ -215,6 +215,13 @@ def log_system_info():
# Print colored output # Print colored output
print(f"{package_name.ljust(max_package_length)} Required: {color_required}{operator} {required_version.ljust(12)}\033[0m Installed: {color_installed}{installed_version}\033[0m") print(f"{package_name.ljust(max_package_length)} Required: {color_required}{operator} {required_version.ljust(12)}\033[0m Installed: {color_installed}{installed_version}\033[0m")
print("\nOn Nvidia Graphics cards machines, if your \033[92mInstalled\033[0m version of \033[92mTorch\033[0m and \033[92mTorchaudio\033[0m does")
print("not have \033[92m+cu118\033[0m (Cuda 11.8) or \033[92m+cu121\033[0m (Cuda 12.1) listed after them, you do not have CUDA")
print("installed for Torch or Torchaudio in this Python environment. This will cause you problems")
print("with \033[94mAllTalk\033[0m and \033[94mFinetuning.\033[0m You may have to 'pip install' a new version of torch and")
print("torchaudio, using '\033[94m--upgrade --force-reinstall\033[0m' with the correct version of PyTorch for\033[0m")
print("your Python environment.\033[0m")
print("\033[94m\nRequirements file specifier meanings:\033[0m") print("\033[94m\nRequirements file specifier meanings:\033[0m")
explanation = textwrap.dedent(""" explanation = textwrap.dedent("""
== Exact version != Any version except < Less than == Exact version != Any version except < Less than
+20
View File
@@ -0,0 +1,20 @@
version: '3.8'
services:
alltalk-tts:
image: erew123/alltalk_tts:cuda
restart: unless-stopped
ports:
- "7851:7851"
volumes:
- ./outputs:/app/outputs/
- ./models:/app/models/
- ./voices:/app/voices/
- ./finetune/put-voice-samples-in-here:/app/finetune/put-voice-samples-in-here
- ./dockerconfig.json:/app/confignew.json
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [ gpu ]
+13
View File
@@ -0,0 +1,13 @@
version: '3.8'
services:
alltalk-tts:
image: erew123/alltalk_tts:cpu
restart: unless-stopped
ports:
- "7851:7851"
volumes:
- ./outputs:/app/outputs/
- ./models:/app/models/
- ./voices:/app/voices/
- ./finetune/put-voice-samples-in-here:/app/finetune/put-voice-samples-in-here
- ./dockerconfig.json:/app/confignew.json
+25
View File
@@ -0,0 +1,25 @@
{
"activate": true,
"autoplay": true,
"branding": "AllTalk ",
"narrator_enabled": false,
"deepspeed_activate": true,
"delete_output_wavs": "Disabled",
"ip_address": "127.0.0.1",
"language": "English",
"low_vram": false,
"local_temperature": "0.7",
"local_repetition_penalty": "10.0",
"tts_model_loaded": true,
"tts_model_name": "tts_models/multilingual/multi-dataset/xtts_v2",
"narrator_voice": "female_01.wav",
"output_folder_wav": "extensions/alltalk_tts/outputs/",
"output_folder_wav_standalone": "outputs/",
"port_number": "7851",
"remove_trailing_dots": false,
"show_text": true,
"tts_method_api_local": false,
"tts_method_api_tts": false,
"tts_method_xtts_local": true,
"voice": "female_01.wav"
}
+17 -5
View File
@@ -75,10 +75,10 @@ def create_temporary_file(folder, suffix=".wav"):
unique_filename = f"custom_tempfile_{int(time.time())}_{random.randint(1, 1000)}{suffix}" unique_filename = f"custom_tempfile_{int(time.time())}_{random.randint(1, 1000)}{suffix}"
return os.path.join(folder, unique_filename) return os.path.join(folder, unique_filename)
def format_audio_list(target_language, whisper_model, out_path, gradio_progress=progress): def format_audio_list(target_language, whisper_model, out_path, eval_split_number, gradio_progress=progress):
audio_files = [os.path.join(audio_folder, file) for file in os.listdir(audio_folder) if file.endswith(('.mp3', '.flac', '.wav'))] audio_files = [os.path.join(audio_folder, file) for file in os.listdir(audio_folder) if file.endswith(('.mp3', '.flac', '.wav'))]
buffer=0.2 buffer=0.2
eval_percentage=0.15 eval_percentage = eval_split_number / 100.0
speaker_name="coqui" speaker_name="coqui"
audio_total_size = 0 audio_total_size = 0
os.makedirs(out_path, exist_ok=True) os.makedirs(out_path, exist_ok=True)
@@ -87,6 +87,7 @@ def format_audio_list(target_language, whisper_model, out_path, gradio_progress=
print("[FINETUNE] \033[94mPart of AllTalk\033[0m https://github.com/erew123/alltalk_tts/") 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[94mCoqui Public Model License\033[0m")
print("[FINETUNE] \033[94mhttps://coqui.ai/cpml.txt\033[0m") print("[FINETUNE] \033[94mhttps://coqui.ai/cpml.txt\033[0m")
print(f"[FINETUNE] \033[94mWhisper model: \033[92m{whisper_model} \033[94mLanguage: \033[92m{target_language} \033[94mEvaluation data percentage: \033[92m{eval_split_number}%\033[0m")
print("[FINETUNE] \033[94mStarting Step 1\033[0m - Preparing Audio/Generating the dataset") print("[FINETUNE] \033[94mStarting Step 1\033[0m - Preparing Audio/Generating the dataset")
# Write the target language to lang.txt in the output directory # Write the target language to lang.txt in the output directory
lang_file_path = os.path.join(out_path, "lang.txt") lang_file_path = os.path.join(out_path, "lang.txt")
@@ -917,7 +918,9 @@ if __name__ == "__main__":
#### &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. Very small sample files cause errors, so I would suggest 30 seconds and longer samples. #### &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".
#### &nbsp;&nbsp;&nbsp;&nbsp; - FYI Anecdotal evidence suggests that the Whisper 2 model may yield superior results in audio splitting and dataset creation.
#### &nbsp;&nbsp;&nbsp;&nbsp; - If this step is failing, it will be worth running the diagnostics with atsetup and confirming you have cu118 or cu112 listed against your torch and torchaudio.<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.
@@ -966,6 +969,14 @@ if __name__ == "__main__":
"ja" "ja"
], ],
) )
eval_split_number = gr.Number(
label="Evaluation data Split (the % to use for Evaluation data)",
value=15, # Default value
minimum=5, # Minimum value
maximum=95, # Maximum value
step=1, # Increment step
)
progress_data = gr.Label( progress_data = gr.Label(
label="Progress:" label="Progress:"
) )
@@ -977,14 +988,14 @@ if __name__ == "__main__":
prompt_compute_btn = gr.Button(value="Step 1 - Create dataset") prompt_compute_btn = gr.Button(value="Step 1 - Create dataset")
def preprocess_dataset(language, whisper_model, out_path, progress=gr.Progress(track_tqdm=True)): def preprocess_dataset(language, whisper_model, out_path, eval_split_number, progress=gr.Progress(track_tqdm=True)):
clear_gpu_cache() 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'])] 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: 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'", "", "" return "I cannot find any mp3, wav or flac files in the folder called 'put-voice-samples-in-here'", "", ""
else: else:
try: 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) train_meta, eval_meta, audio_total_size = format_audio_list(target_language=language, whisper_model=whisper_model, out_path=out_path, eval_split_number=eval_split_number, gradio_progress=progress)
except: except:
traceback.print_exc() traceback.print_exc()
error = traceback.format_exc() error = traceback.format_exc()
@@ -1272,6 +1283,7 @@ if __name__ == "__main__":
lang, lang,
whisper_model, whisper_model,
out_path, out_path,
eval_split_number,
], ],
outputs=[ outputs=[
progress_data, progress_data,
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
python modeldownload.py
uvicorn tts_server:app --host 0.0.0.0 --port 7851 --workers 1 --proxy-headers &
sleep 5
python script.py
+20
View File
@@ -0,0 +1,20 @@
FROM nvidia/cuda:12.1.1-devel-ubuntu22.04
ENV HOST 0.0.0.0
RUN apt-get update && apt-get upgrade -y \
&& apt-get install -y git build-essential portaudio19-dev \
python3 python3-pip gcc wget \
ocl-icd-opencl-dev opencl-headers clinfo \
libclblast-dev libopenblas-dev \
&& mkdir -p /etc/OpenCL/vendors && echo "libnvidia-opencl.so.1" > /etc/OpenCL/vendors/nvidia.icd \
&& ln -s /usr/bin/python3 /usr/bin/python
WORKDIR /app
COPY . .
ENV CUDA_DOCKER_ARCH=all
RUN pip install --no-cache-dir -r requirements_nvidia.txt && \
pip install --no-cache-dir -r requirements_finetune.txt && \
pip install --no-cache-dir -r requirements_other.txt && \
pip install --no-cache-dir deepspeed
EXPOSE 7851
RUN chmod +x launch.sh
ENTRYPOINT ["sh", "-c", "./launch.sh"]
+3
View File
@@ -1,6 +1,7 @@
numpy>=1.22.0 numpy>=1.22.0
soundfile>=0.12.1 soundfile>=0.12.1
uvicorn>=0.24.0.post1 uvicorn>=0.24.0.post1
transformers>=4.37.1
TTS>=0.21.3 TTS>=0.21.3
torch>=2.1.0+cu118 torch>=2.1.0+cu118
torchaudio>=2.1.0+cu118 torchaudio>=2.1.0+cu118
@@ -13,3 +14,5 @@ packaging>=23.2
pydantic>=1.10.13 pydantic>=1.10.13
sounddevice>=0.4.6 sounddevice>=0.4.6
python-multipart>=0.0.6 python-multipart>=0.0.6
cutlet>=0.3.0
unidic-lite>=1.0.8
+3
View File
@@ -1,6 +1,7 @@
numpy>=1.22.0 numpy>=1.22.0
soundfile>=0.12.1 soundfile>=0.12.1
uvicorn>=0.24.0.post1 uvicorn>=0.24.0.post1
transformers>=4.37.1
TTS>=0.21.3 TTS>=0.21.3
torch>=2.1.0 torch>=2.1.0
torchaudio>=2.1.0 torchaudio>=2.1.0
@@ -13,3 +14,5 @@ packaging>=23.2
pydantic>=1.10.13 pydantic>=1.10.13
sounddevice>=0.4.6 sounddevice>=0.4.6
python-multipart>=0.0.6 python-multipart>=0.0.6
cutlet>=0.3.0
unidic-lite>=1.0.8
+256 -138
View File
@@ -16,18 +16,28 @@ import numpy as np
import soundfile as sf import soundfile as sf
import uuid import uuid
######################################
#### ALLTALK ALLOWED STARTUP TIME ####
######################################
startup_wait_time = 120
# You can change the above setting to a larger number to allow AllTAlk more time to start up. The default setting is 120 seconds (2 minutes).
# On some older systems you may need to allow AllTalk more time. So you could set it to 240 (4 minutes) which will give AllTalk more to load.
################################################################# #################################################################
#### LOAD PARAMS FROM confignew.json - REQUIRED FOR BRANDING #### #### LOAD PARAMS FROM confignew.json - REQUIRED FOR BRANDING ####
################################################################# #################################################################
# STARTUP VARIABLE - Create "this_dir" variable as the current script directory # STARTUP VARIABLE - Create "this_dir" variable as the current script directory
this_dir = Path(__file__).parent.resolve() this_dir = Path(__file__).parent.resolve()
# load config file in and get settings # load config file in and get settings
def load_config(file_path): def load_config(file_path):
with open(file_path, "r") as config_file: with open(file_path, "r") as config_file:
config = json.load(config_file) config = json.load(config_file)
return config return config
config_file_path = this_dir / "confignew.json" config_file_path = this_dir / "confignew.json"
# Load the params dictionary from the confignew.json file # Load the params dictionary from the confignew.json file
params = load_config(config_file_path) params = load_config(config_file_path)
@@ -48,6 +58,7 @@ except ModuleNotFoundError:
# IMPORT - Attempt Importing DeepSpeed (required for displaying Deepspeed checkbox in gradio) # IMPORT - Attempt Importing DeepSpeed (required for displaying Deepspeed checkbox in gradio)
try: try:
import deepspeed import deepspeed
deepspeed_installed = True deepspeed_installed = True
except ImportError: except ImportError:
deepspeed_installed = False deepspeed_installed = False
@@ -60,6 +71,7 @@ try:
from modules.logging_colors import logger from modules.logging_colors import logger
from modules.ui import create_refresh_button from modules.ui import create_refresh_button
from modules.utils import gradio 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 # 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 running_in_standalone = False
output_folder_wav = params["output_folder_wav"] output_folder_wav = params["output_folder_wav"]
@@ -80,10 +92,12 @@ process_lock = threading.Lock()
# Base setting for a possible FineTuned model existing and the loader being available # Base setting for a possible FineTuned model existing and the loader being available
tts_method_xtts_ft = False tts_method_xtts_ft = False
# Gather the voice files # Gather the voice files
def get_available_voices(): def get_available_voices():
return sorted([voice.name for voice in Path(f"{this_dir}/voices").glob("*.wav")]) return sorted([voice.name for voice in Path(f"{this_dir}/voices").glob("*.wav")])
######################### #########################
#### LICENSE DISPLAY #### #### LICENSE DISPLAY ####
######################### #########################
@@ -141,6 +155,7 @@ 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()
@@ -155,7 +170,9 @@ finetuned_model = trained_model_directory.exists()
# If true, this will add a extra option in the Gradio interface for loading Xttsv2 FT # If true, this will add a extra option in the Gradio interface for loading Xttsv2 FT
if finetuned_model: if finetuned_model:
required_files = ["model.pth", "config.json", "vocab.json"] required_files = ["model.pth", "config.json", "vocab.json"]
finetuned_model = all((trained_model_directory / file).exists() for file in required_files) finetuned_model = all(
(trained_model_directory / file).exists() for file in required_files
)
if finetuned_model: if finetuned_model:
print(f"[{params['branding']}Startup] Finetuned model \033[93mDetected\033[0m") print(f"[{params['branding']}Startup] Finetuned model \033[93mDetected\033[0m")
@@ -173,6 +190,7 @@ elif params["tts_method_xtts_local"] == True:
# Set the default for Narrated text without asterisk or quotes to be Narrator # Set the default for Narrated text without asterisk or quotes to be Narrator
non_quoted_text_is = True non_quoted_text_is = True
###################### ######################
#### GRADIO STUFF #### #### GRADIO STUFF ####
###################### ######################
@@ -230,62 +248,80 @@ def signal_handler(sig, frame):
# Attach the signal handler to the SIGINT signal (Ctrl+C) # Attach the signal handler to the SIGINT signal (Ctrl+C)
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
# Check if we're running in docker
# Start the subprocess if os.path.isfile("/.dockerenv"):
process = subprocess.Popen(["python", script_path])
# Check if the subprocess has started successfully
if process.poll() is None:
print(f"[{params['branding']}Startup] TTS Subprocess starting")
print( print(
f"[{params['branding']}Startup] Readme available here:", f"[{params['branding']}Startup] \033[94mRunning in Docker. Please wait.\033[0m"
f"http://{params['ip_address']}:{params['port_number']}",
) )
else: else:
print( # Start the subprocess
f"[{params['branding']}Startup] \033[91mWarning\033[0m TTS Subprocess Webserver failing to start process" process = subprocess.Popen(["python", script_path])
) # Check if the subprocess has started successfully
print( if process.poll() is None:
f"[{params['branding']}Startup] \033[91mWarning\033[0m It could be that you have something on port:", print(f"[{params['branding']}Startup] TTS Subprocess starting")
params["port_number"], print(f"[{params['branding']}Startup]")
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m Or you have not started in a Python environement with all the necesssary bits installed"
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m Check you are starting Text-generation-webui with either the start_xxxxx file or the Python environment with cmd_xxxxx file."
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m xxxxx is the type of OS you are on e.g. windows, linux or mac."
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m Alternatively, you could check no other Python processes are running that shouldnt be e.g. Restart your computer is the simple way."
)
# Cleanly kill off this script, but allow text-generation-webui to keep running, albeit without this alltalk_tts
sys.exit(1)
timeout = 120 # Adjust the timeout as needed
# Introduce a delay before starting the check loop
time.sleep(26) # Wait 26 secs before checking if the tts_server.py has started up.
start_time = time.time()
while time.time() - start_time < timeout:
try:
response = requests.get(f"{base_url}/ready")
if response.status_code == 200:
break
except requests.RequestException as e:
# Print the exception for debugging purposes
print( print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m TTS Subprocess has NOT started up yet, Will keep trying for 120 seconds maximum. Please wait." f"[{params['branding']}Startup] \033[94m {params['branding']}Settings & Documentation:\033[00m",
f"\033[92mhttp://{params['ip_address']}:{params['port_number']}\033[00m",
) )
time.sleep(4) print(f"[{params['branding']}Startup]")
else: else:
print( print(
f"[{params['branding']}Startup] Startup timed out. Check the server logs for more information." f"[{params['branding']}Startup] \033[91mWarning\033[0m TTS Subprocess Webserver failing to start process"
) )
# Cleanly kill off this script, but allow text-generation-webui to keep running, albeit without this alltalk_tts print(
sys.exit(1) f"[{params['branding']}Startup] \033[91mWarning\033[0m It could be that you have something on port:",
params["port_number"],
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m Or you have not started in a Python environement with all the necesssary bits installed"
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m Check you are starting Text-generation-webui with either the start_xxxxx file or the Python environment with cmd_xxxxx file."
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m xxxxx is the type of OS you are on e.g. windows, linux or mac."
)
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m Alternatively, you could check no other Python processes are running that shouldnt be e.g. Restart your computer is the simple way."
)
# Cleanly kill off this script, but allow text-generation-webui to keep running, albeit without this alltalk_tts
sys.exit(1)
timeout = startup_wait_time # Gather timeout setting from startup_wait_time
# Introduce a delay before starting the check loop
time.sleep(26) # Wait 26 secs before checking if the tts_server.py has started up.
start_time = time.time()
while time.time() - start_time < timeout:
try:
response = requests.get(f"{base_url}/ready")
if response.status_code == 200:
break
except requests.RequestException as e:
# Print the exception for debugging purposes
print(
f"[{params['branding']}Startup] \033[91mWarning\033[0m TTS Subprocess has NOT started up yet, Will keep trying for {timeout} seconds maximum. Please wait."
)
time.sleep(5)
else:
print(
f"\n[{params['branding']}Startup] Startup timed out. Full help available here \033[92mhttps://github.com/erew123/alltalk_tts#-help-with-problems\033[0m"
)
print(
f"[{params['branding']}Startup] On older system you may wish to open and edit \033[94mscript.py\033[0m with a text editor and changing the"
)
print(
f"[{params['branding']}Startup] \033[94mstartup_wait_time = 120\033[0m setting to something like \033[94mstartup_wait_time = 240\033[0m as this will allow"
)
print(
f"[{params['branding']}Startup] AllTalk more time to try load the model into your VRAM. Otherise please visit the Github for"
)
print(
f"[{params['branding']}Startup] a list of other possible troubleshooting options."
)
# Cleanly kill off this script, but allow text-generation-webui to keep running, albeit without this alltalk_tts
sys.exit(1)
##################################### #####################################
@@ -340,6 +376,7 @@ def send_reload_request(tts_method):
) )
return {"status": "error", "message": str(e)} return {"status": "error", "message": str(e)}
################## ##################
#### LOW VRAM #### #### LOW VRAM ####
################## ##################
@@ -380,7 +417,7 @@ def send_deepspeed_request(deepspeed_param):
audio_path = this_dir / "templates" / "deepspeedenabled.wav" audio_path = this_dir / "templates" / "deepspeedenabled.wav"
else: else:
audio_path = this_dir / "templates" / "deepspeeddisabled.wav" audio_path = this_dir / "templates" / "deepspeeddisabled.wav"
url = f"{base_url}/api/deepspeed?new_deepspeed_value={deepspeed_param}" url = f"{base_url}/api/deepspeed?new_deepspeed_value={deepspeed_param}"
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers) response = requests.post(url, headers=headers)
@@ -454,9 +491,13 @@ def combine(audio_files, output_folder, state):
# Save the combined audio to a file with a specified sample rate # Save the combined audio to a file with a specified sample rate
if "character_menu" in state: if "character_menu" in state:
output_file_path = os.path.join(output_folder, f'{state["character_menu"]}_{int(time.time())}_combined.wav') output_file_path = os.path.join(
output_folder, f'{state["character_menu"]}_{int(time.time())}_combined.wav'
)
else: else:
output_file_path = os.path.join(output_folder, f'TTSOUT_{int(time.time())}_combined.wav') output_file_path = os.path.join(
output_folder, f"TTSOUT_{int(time.time())}_combined.wav"
)
sf.write(output_file_path, audio, samplerate=sample_rate) sf.write(output_file_path, audio, samplerate=sample_rate)
# Clean up unnecessary files # Clean up unnecessary files
for audio_file in audio_files: for audio_file in audio_files:
@@ -487,12 +528,19 @@ def voice_preview(string):
output_file = Path(params["output_folder_wav"]) / "voice_preview.wav" output_file = Path(params["output_folder_wav"]) / "voice_preview.wav"
# Generate the audio # Generate the audio
language_code = languages.get(params["language"]) language_code = languages.get(params["language"])
temperature = params["local_temperature"]
repetition_penalty = params["local_repetition_penalty"]
# Convert the WindowsPath object to a string before using it in JSON payload # Convert the WindowsPath object to a string before using it in JSON payload
output_file_str = output_file.as_posix() output_file_str = output_file.as_posix()
# Lock before making the generate request # Lock before making the generate request
with process_lock: with process_lock:
generate_response = send_generate_request( generate_response = send_generate_request(
string, params["voice"], language_code, output_file_str string,
params["voice"],
language_code,
temperature,
repetition_penalty,
output_file_str,
) )
# Check if lock is already acquired # Check if lock is already acquired
if process_lock.locked(): if process_lock.locked():
@@ -514,7 +562,7 @@ def process_text(text):
text = html.unescape(text) text = html.unescape(text)
# Replace ellipsis with a single dot # Replace ellipsis with a single dot
text = re.sub(r'\.{3,}', '.', text) text = re.sub(r"\.{3,}", ".", text)
# Pattern to identify combined narrator and character speech # Pattern to identify combined narrator and character speech
combined_pattern = r'(\*[^*"]+\*|"[^"*]+")' combined_pattern = r'(\*[^*"]+\*|"[^"*]+")'
@@ -529,22 +577,22 @@ def process_text(text):
for match in re.finditer(combined_pattern, text): for match in re.finditer(combined_pattern, text):
# Add the text before the match, if any, as ambiguous # Add the text before the match, if any, as ambiguous
if start < match.start(): if start < match.start():
ambiguous_text = text[start:match.start()].strip() ambiguous_text = text[start : match.start()].strip()
if ambiguous_text: if ambiguous_text:
ordered_parts.append(('ambiguous', ambiguous_text)) ordered_parts.append(("ambiguous", ambiguous_text))
# Add the matched part as either narrator or character # Add the matched part as either narrator or character
matched_text = match.group(0) matched_text = match.group(0)
if matched_text.startswith('*') and matched_text.endswith('*'): if matched_text.startswith("*") and matched_text.endswith("*"):
ordered_parts.append(('narrator', matched_text.strip('*').strip())) ordered_parts.append(("narrator", matched_text.strip("*").strip()))
elif matched_text.startswith('"') and matched_text.endswith('"'): elif matched_text.startswith('"') and matched_text.endswith('"'):
ordered_parts.append(('character', matched_text.strip('"').strip())) ordered_parts.append(("character", matched_text.strip('"').strip()))
else: else:
# In case of mixed or improperly formatted parts # In case of mixed or improperly formatted parts
if '*' in matched_text: if "*" in matched_text:
ordered_parts.append(('narrator', matched_text.strip('*').strip('"'))) ordered_parts.append(("narrator", matched_text.strip("*").strip('"')))
else: else:
ordered_parts.append(('character', matched_text.strip('"').strip('*'))) ordered_parts.append(("character", matched_text.strip('"').strip("*")))
# Update the start of the next segment # Update the start of the next segment
start = match.end() start = match.end()
@@ -553,10 +601,11 @@ def process_text(text):
if start < len(text): if start < len(text):
ambiguous_text = text[start:].strip() ambiguous_text = text[start:].strip()
if ambiguous_text: if ambiguous_text:
ordered_parts.append(('ambiguous', ambiguous_text)) ordered_parts.append(("ambiguous", ambiguous_text))
return ordered_parts return ordered_parts
################################# #################################
#### TTS STANDARD GENERATION #### #### TTS STANDARD GENERATION ####
################################# #################################
@@ -565,12 +614,14 @@ def output_modifier(string, state):
if not params["activate"]: if not params["activate"]:
return string return string
original_string = string original_string = string
#print("ORIGINAL STRING IS:", 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
string = cleaned_string string = cleaned_string
language_code = languages.get(params["language"]) language_code = languages.get(params["language"])
temperature = params["local_temperature"]
repetition_penalty = params["local_repetition_penalty"]
# Create a list to store generated audio paths # Create a list to store generated audio paths
audio_files = [] audio_files = []
if process_lock.acquire(blocking=False): if process_lock.acquire(blocking=False):
@@ -585,29 +636,46 @@ def output_modifier(string, state):
continue continue
# Determine the voice to use based on the part type # Determine the voice to use based on the part type
if part_type == 'narrator': if part_type == "narrator":
voice_to_use = params["narrator_voice"] voice_to_use = params["narrator_voice"]
print(f"[{params['branding']}TTSGen] \033[92mNarrator\033[0m") # Green print(
elif part_type == 'character': f"[{params['branding']}TTSGen] \033[92mNarrator\033[0m"
) # Green
elif part_type == "character":
voice_to_use = params["voice"] voice_to_use = params["voice"]
print(f"[{params['branding']}TTSGen] \033[36mCharacter\033[0m") # Yellow print(
f"[{params['branding']}TTSGen] \033[36mCharacter\033[0m"
) # Yellow
else: else:
# Handle ambiguous parts based on user preference # Handle ambiguous parts based on user preference
voice_to_use = params["voice"] if non_quoted_text_is else params["narrator_voice"] voice_to_use = (
voice_description = "\033[36mCharacter (Text-not-inside)\033[0m" if non_quoted_text_is else "\033[92mNarrator (Text-not-inside)\033[0m" params["voice"]
if non_quoted_text_is
else params["narrator_voice"]
)
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}") print(f"[{params['branding']}TTSGen] {voice_description}")
# Replace multiple exclamation marks, question marks, or other punctuation with a single instance # Replace multiple exclamation marks, question marks, or other punctuation with a single instance
cleaned_part = re.sub(r'([!?.])\1+', r'\1', part) cleaned_part = re.sub(r"([!?.])\1+", r"\1", part)
# Further clean to remove any other unwanted characters # Further clean to remove any other unwanted characters
cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\$]', '', cleaned_part) cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0100-\u017F\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\u4E00-\u9FFF\u3400-\u4DBF\u20000-\u2A6DF\u3000-\u303F\$]', '', cleaned_part)
# Remove all newline characters (single or multiple) # Remove all newline characters (single or multiple)
cleaned_part = re.sub(r'\n+', ' ', cleaned_part) cleaned_part = re.sub(r"\n+", " ", cleaned_part)
# Generate TTS and output to a file # 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,
temperature,
repetition_penalty,
output_filename,
) )
audio_path = generate_response.get("data", {}).get("audio_path") audio_path = generate_response.get("data", {}).get("audio_path")
audio_files_all_paragraphs.append(audio_path) audio_files_all_paragraphs.append(audio_path)
@@ -620,20 +688,29 @@ def output_modifier(string, state):
# Decode HTML entities first # Decode HTML entities first
cleaned_part = html.unescape(original_string) cleaned_part = html.unescape(original_string)
# Replace multiple instances of certain punctuation marks with a single instance # Replace multiple instances of certain punctuation marks with a single instance
cleaned_part = re.sub(r'([!?.])\1+', r'\1', cleaned_part) cleaned_part = re.sub(r"([!?.])\1+", r"\1", cleaned_part)
# Further clean to remove any other unwanted characters # Further clean to remove any other unwanted characters
cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\$]', '', cleaned_part) cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0100-\u017F\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\u4E00-\u9FFF\u3400-\u4DBF\u20000-\u2A6DF\u3000-\u303F\$]', '', cleaned_part)
# Remove all newline characters (single or multiple) # Remove all newline characters (single or multiple)
cleaned_part = re.sub(r'\n+', ' ', cleaned_part) cleaned_part = re.sub(r"\n+", " ", cleaned_part)
# 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'
)
else: else:
output_file = Path(f'{params["output_folder_wav"]}/TTSOUT_{int(time.time())}.wav') output_file = Path(
f'{params["output_folder_wav"]}/TTSOUT_{int(time.time())}.wav'
)
output_file_str = output_file.as_posix() output_file_str = output_file.as_posix()
output_file = get_output_filename(state) output_file = get_output_filename(state)
generate_response = send_generate_request( generate_response = send_generate_request(
cleaned_part, params["voice"], language_code, output_file_str cleaned_part,
params["voice"],
language_code,
temperature,
repetition_penalty,
output_file_str,
) )
audio_path = generate_response.get("data", {}).get("audio_path") audio_path = generate_response.get("data", {}).get("audio_path")
final_output_file = audio_path final_output_file = audio_path
@@ -674,20 +751,28 @@ def output_modifier(string, state):
def get_output_filename(state): def get_output_filename(state):
if "character_menu" in state: if "character_menu" in state:
return Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{str(uuid.uuid4())[:8]}.wav').as_posix() return Path(
f'{params["output_folder_wav"]}/{state["character_menu"]}_{str(uuid.uuid4())[:8]}.wav'
).as_posix()
else: else:
return Path(f'{params["output_folder_wav"]}/TTSOUT_{str(uuid.uuid4())[:8]}.wav').as_posix() return Path(
f'{params["output_folder_wav"]}/TTSOUT_{str(uuid.uuid4())[:8]}.wav'
).as_posix()
############################################### ###############################################
#### SEND GENERATION REQUEST TO TTS ENGINE #### #### SEND GENERATION REQUEST TO TTS ENGINE ####
############################################### ###############################################
def send_generate_request(text, voice, language, output_file): def send_generate_request(
text, voice, language, temperature, repetition_penalty, output_file
):
url = f"{base_url}/api/generate" url = f"{base_url}/api/generate"
payload = { payload = {
"text": text, "text": text,
"voice": voice, "voice": voice,
"language": language, "language": language,
"temperature": temperature,
"repetition_penalty": repetition_penalty,
"output_file": output_file, "output_file": output_file,
} }
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
@@ -712,12 +797,14 @@ def state_modifier(state):
state["stream"] = False state["stream"] = False
return state return state
def update_narrator_enabled(value): def update_narrator_enabled(value):
if value == "Enabled": if value == "Enabled":
params["narrator_enabled"] = True params["narrator_enabled"] = True
elif value == "Disabled": elif value == "Disabled":
params["narrator_enabled"] = False params["narrator_enabled"] = False
def update_non_quoted_text_is(value): def update_non_quoted_text_is(value):
global non_quoted_text_is global non_quoted_text_is
if value == "Narrator": if value == "Narrator":
@@ -725,6 +812,7 @@ def update_non_quoted_text_is(value):
elif value == "Char": elif value == "Char":
non_quoted_text_is = True non_quoted_text_is = True
def input_modifier(string, state): def input_modifier(string, state):
if not params["activate"]: if not params["activate"]:
return string return string
@@ -735,35 +823,53 @@ def input_modifier(string, state):
def ui(): def ui():
with gr.Accordion(params["branding"] + " TTS (XTTSv2)"): with gr.Accordion(params["branding"] + " TTS (XTTSv2)"):
# Activate alltalk_tts, Enable autoplay, Show text
with gr.Row(): with gr.Row():
activate = gr.Checkbox(value=params["activate"], label="Activate TTS") activate = gr.Checkbox(value=params["activate"], label="Enable TTS")
autoplay = gr.Checkbox( autoplay = gr.Checkbox(value=params["autoplay"], label="Autoplay TTS")
value=params["autoplay"], label="Play TTS automatically" show_text = gr.Checkbox(value=params["show_text"], label="Show Text")
)
# Low vram enable, Deepspeed enable, Remove trailing dots
with gr.Row(): with gr.Row():
show_text = gr.Checkbox( low_vram = gr.Checkbox(
value=params["show_text"], label="Show message text under audio player" value=params["low_vram"], label="Enable Low VRAM Mode"
) )
low_vram_play = gr.HTML(visible=False)
deepspeed_checkbox = gr.Checkbox(
value=params["deepspeed_activate"],
label="Enable DeepSpeed",
visible=deepspeed_installed,
)
deepspeed_checkbox_play = gr.HTML(visible=False)
remove_trailing_dots = gr.Checkbox( remove_trailing_dots = gr.Checkbox(
value=params["remove_trailing_dots"], value=params["remove_trailing_dots"], label='Remove trailing "."'
label='Remove trailing "." from text segments before generation',
) )
# TTS method, Character voice selection
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(
choices=model_loader_choices,
label="TTS Method (Each method sounds slightly different)",
value=gr_modelchoice, # Set the default value
)
tts_radio_buttons_play = gr.HTML(visible=False)
with gr.Row(): with gr.Row():
available_voices = get_available_voices() available_voices = get_available_voices()
default_voice = params["voice"] default_voice = params[
# Check if the default voice is in the list of available voices "voice"
] # Check if the default voice is in the list of available voices
if default_voice not in available_voices: if default_voice not in available_voices:
# Handle the case where the default voice is not in the list (choose a default value or update it)
default_voice = available_voices[ default_voice = available_voices[
0 0
] # Choose the first available voice as the default ] # Choose the first available voice as the default
# Add allow_custom_value=True to the Dropdown # Add allow_custom_value=True to the Dropdown
voice = gr.Dropdown( voice = gr.Dropdown(
available_voices, available_voices,
label="Default Voice", label="Character Voice",
value=default_voice, value=default_voice,
allow_custom_value=True, allow_custom_value=True,
) )
@@ -777,14 +883,11 @@ def ui():
"refresh-button", "refresh-button",
) )
language = gr.Dropdown( # Language, Narrator voice
languages.keys(),
label="Language",
allow_custom_value=True,
value=params["language"],
)
with gr.Row(): with gr.Row():
language = gr.Dropdown(
languages.keys(), label="Language", value=params["language"]
)
with gr.Row(): with gr.Row():
narrator_voice_gr = gr.Dropdown( narrator_voice_gr = gr.Dropdown(
get_available_voices(), get_available_voices(),
@@ -801,43 +904,42 @@ def ui():
}, },
"refresh-button", "refresh-button",
) )
# Temperature, Repetition Penalty
with gr.Row():
local_temperature_gr = gr.Slider(
minimum=0.05,
maximum=1,
step=0.05,
label="Temperature",
value=params["local_temperature"],
)
local_repetition_penalty_gr = gr.Slider(
minimum=0.5,
maximum=20,
step=0.5,
label="Repetition Penalty",
value=params["local_repetition_penalty"],
)
# Narrator enable, Non quoted text, Explanation text
with gr.Row():
with gr.Row():
narrator_enabled_gr = gr.Radio( narrator_enabled_gr = gr.Radio(
choices={"Enabled": "true", "Disabled": "false"}, choices={"Enabled": "true", "Disabled": "false"},
label="Narrator Activation", label="Narrator",
value="Enabled" if params.get("narrator_enabled") else "Disabled", value="Enabled" if params.get("narrator_enabled") else "Disabled",
) )
non_quoted_text_is_gr = gr.Radio( non_quoted_text_is_gr = gr.Radio(
choices={"Char": "true", "Narrator": "false"}, choices={"Character": "true", "Narrator": "false"},
label='Text NOT inside of * or " is', label='Unmarked text NOT inside of * or " is',
value="Char" if non_quoted_text_is else "Narrator", value="Character" if non_quoted_text_is else "Narrator",
)
explanation_text = gr.HTML(
f"<p>⚙️ <a href='http://{params['ip_address']}:{params['port_number']}'>Settings and Documentation Page</a><a href='http://{params['ip_address']}:{params['port_number']}'></a>⚙️<br>- Low VRAM Mode and Deepspeed take 15 seconds to be enabled or disabled.<br>- The DeepSpeed checkbox is only visible if DeepSpeed is present.</p>"
) )
with gr.Row(): # Preview speech
low_vram = gr.Checkbox(
value=params["low_vram"], label="Low VRAM mode (Read NOTE)"
)
low_vram_play = gr.HTML(visible=False)
deepspeed_checkbox = gr.Checkbox(
value=params["deepspeed_activate"],
label="Activate DeepSpeed (Read NOTE)",
visible=deepspeed_installed,
)
deepspeed_checkbox_play = gr.HTML(visible=False)
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(
choices=model_loader_choices,
label="Select TTS Generation Method (Read NOTE)",
value=gr_modelchoice, # Set the default value
)
tts_radio_buttons_play = gr.HTML(visible=False)
explanation_text = gr.HTML(
f"<p>⚙️ <a href='http://{params['ip_address']}:{params['port_number']}'>Click here for the Settings page, help & instructions</a><a href='http://{params['ip_address']}:{params['port_number']}'></a>⚙️<br>NOTE: Switching Model Type, Low VRAM & DeepSpeed, each takes 15 seconds. Each TTS generation method has a slightly different sound. DeepSpeed checkbox is only visible if DeepSpeed is installed on your system."
)
with gr.Row(): with gr.Row():
preview_text = gr.Text( preview_text = gr.Text(
show_label=False, show_label=False,
@@ -907,18 +1009,34 @@ def ui():
autoplay.change(lambda x: params.update({"autoplay": x}), autoplay, None) autoplay.change(lambda x: params.update({"autoplay": x}), autoplay, None)
low_vram.change(lambda x: params.update({"low_vram": x}), low_vram, None) low_vram.change(lambda x: params.update({"low_vram": x}), low_vram, None)
low_vram.change(lambda x: send_lowvram_request(x), low_vram, low_vram_play, None) low_vram.change(lambda x: send_lowvram_request(x), low_vram, low_vram_play, None)
tts_radio_buttons.change(send_reload_request, tts_radio_buttons, tts_radio_buttons_play, None) tts_radio_buttons.change(
deepspeed_checkbox.change(send_deepspeed_request, deepspeed_checkbox, deepspeed_checkbox_play, None) send_reload_request, tts_radio_buttons, tts_radio_buttons_play, None
)
deepspeed_checkbox.change(
send_deepspeed_request, deepspeed_checkbox, deepspeed_checkbox_play, None
)
remove_trailing_dots.change( remove_trailing_dots.change(
lambda x: params.update({"remove_trailing_dots": x}), remove_trailing_dots, None lambda x: params.update({"remove_trailing_dots": x}), remove_trailing_dots, None
) )
voice.change(lambda x: params.update({"voice": x}), voice, None) voice.change(lambda x: params.update({"voice": x}), voice, None)
language.change(lambda x: params.update({"language": x}), language, None) language.change(lambda x: params.update({"language": x}), language, None)
# TSS Settings
local_temperature_gr.change(
lambda x: params.update({"local_temperature": x}), local_temperature_gr, None
)
local_repetition_penalty_gr.change(
lambda x: params.update({"local_repetition_penalty": x}),
local_repetition_penalty_gr,
None,
)
# Narrator selection actions # Narrator selection actions
narrator_enabled_gr.change(update_narrator_enabled, narrator_enabled_gr, None) narrator_enabled_gr.change(update_narrator_enabled, narrator_enabled_gr, None)
non_quoted_text_is_gr.change(update_non_quoted_text_is, non_quoted_text_is_gr, None) non_quoted_text_is_gr.change(update_non_quoted_text_is, non_quoted_text_is_gr, None)
narrator_voice_gr.change(lambda x: params.update({"narrator_voice": x}), narrator_voice_gr, None) narrator_voice_gr.change(
lambda x: params.update({"narrator_voice": x}), narrator_voice_gr, None
)
# Play preview # Play preview
preview_text.submit(voice_preview, preview_text, preview_audio) preview_text.submit(voice_preview, preview_text, preview_audio)
+833
View File
@@ -0,0 +1,833 @@
import { doExtrasFetch, getApiUrl, modules } from '../../extensions.js';
import { saveTtsProviderSettings } from './index.js';
export { AllTalkTtsProvider };
class AllTalkTtsProvider {
//########//
// Config //
//########//
settings = {};
constructor() {
// Initialize with default settings if they are not already set
this.settings = {
provider_endpoint: this.settings.provider_endpoint || 'http://localhost:7851',
language: this.settings.language || 'en',
voiceMap: this.settings.voiceMap || {},
at_generation_method: this.settings.at_generation_method || 'standard_generation',
narrator_enabled: this.settings.narrator_enabled || 'false',
at_narrator_text_not_inside: this.settings.at_narrator_text_not_inside || 'narrator',
narrator_voice_gen: this.settings.narrator_voice_gen || 'female_01.wav',
finetuned_model: this.settings.finetuned_model || 'false'
};
// Separate property for dynamically updated settings from the server
this.dynamicSettings = {
modelsAvailable: [],
currentModel: '',
deepspeed_available: false,
deepSpeedEnabled: false,
lowVramEnabled: false,
};
}
ready = false;
voices = [];
separator = '. ';
audioElement = document.createElement('audio');
languageLabels = {
'Arabic': 'ar',
'Brazilian Portuguese': 'pt',
'Chinese': 'zh-cn',
'Czech': 'cs',
'Dutch': 'nl',
'English': 'en',
'French': 'fr',
'German': 'de',
'Italian': 'it',
'Polish': 'pl',
'Russian': 'ru',
'Spanish': 'es',
'Turkish': 'tr',
'Japanese': 'ja',
'Korean': 'ko',
'Hungarian': 'hu',
'Hindi': 'hi',
};
get settingsHtml() {
let html = `<div class="at-settings-separator">AllTalk Settings</div>`;
html += `<div class="at-settings-row">
<div class="at-settings-option">
<label for="at_generation_method">AllTalk TTS Generation Method</label>
<select id="at_generation_method">
<option value="standard_generation">Standard Audio Generation (AT Narrator - Optional)</option>
<option value="streaming_enabled">Streaming Audio Generation (AT Narrator - Disabled)</option>
</select>
</div>
</div>`;
html += `<div class="at-settings-row">
<div class="at-settings-option">
<label for="at_narrator_enabled">AT Narrator</label>
<select id="at_narrator_enabled">
<option value="true">Enabled</option>
<option value="false">Disabled</option>
</select>
</div>
<div class="at-settings-option">
<label for="at_narrator_text_not_inside">Text Not Inside * or " is</label>
<select id="at_narrator_text_not_inside">
<option value="narrator">Narrator</option>
<option value="character">Character</option>
</select>
</div>
</div>`;
html += `<div class="at-settings-row">
<div class="at-settings-option">
<label for="narrator_voice">Narrator Voice</label>
<select id="narrator_voice">`;
if (this.voices) {
for (let voice of this.voices) {
html += `<option value="${voice.voice_id}">${voice.name}</option>`;
}
}
html += `</select>
</div>
<div class="at-settings-option">
<label for="language_options">Language</label>
<select id="language_options">`;
for (let language in this.languageLabels) {
html += `<option value="${this.languageLabels[language]}" ${this.languageLabels[language] === this.settings?.language ? 'selected="selected"' : ''}>${language}</option>`;
}
html += `</select>
</div>
</div>`;
html += `<div class="at-model-endpoint-row">
<div class="at-model-option">
<label for="switch_model">Switch Model</label>
<select id="switch_model">
<option value="api_tts">API TTS</option>
<option value="api_local">API Local</option>
<option value="xttsv2_local">XTTSv2 Local</option>
</select>
</div>
<div class="at-endpoint-option">
<label for="at_server">AllTalk Endpoint:</label>
<input id="at_server" type="text" class="text_pole" maxlength="80" value="${this.settings.provider_endpoint}"/>
</div>
</div>`;
html += `<div class="at-model-endpoint-row">
<div class="at-settings-option">
<label for="low_vram">Low VRAM</label>
<input id="low_vram" type="checkbox"/>
</div>
<div class="at-settings-option">
<label for="deepspeed">DeepSpeed</label>
<input id="deepspeed" type="checkbox"/>
</div>
<div class="at-settings-option status-option">
<span>Status: <span id="status_info">Ready</span></span>
</div>
<div class="at-settings-option empty-option">
<!-- This div remains empty for spacing -->
</div>
</div>`;
html += `<div class="at-website-row">
<div class="at-website-option">
<span>AllTalk <a target="_blank" href="${this.settings.provider_endpoint}">Config & Docs</a>.</span>
</div>
<div class="at-website-option">
<span>AllTalk <a target="_blank" href="https://github.com/erew123/alltalk_tts/">Website</a>.</span>
</div>
</div>`;
html += `<div class="at-website-row">
<div class="at-website-option">
<span><strong>Text-generation-webui</strong> users - Uncheck <strong>Enable TTS</strong> in Text-generation-webui.</span>
</div>
</div>`;
return html;
}
//#################//
// Startup ST & AT //
//#################//
async loadSettings(settings) {
updateStatus('Offline');
if (Object.keys(settings).length === 0) {
console.info('Using default AllTalk TTS Provider settings');
} else {
// Populate settings with provided values, ignoring server-provided settings
for (const key in settings) {
if (key in this.settings) {
this.settings[key] = settings[key];
} else {
console.debug(`Ignoring non-user-configurable setting: ${key}`);
}
}
}
// Update UI elements to reflect the loaded settings
$('#at_server').val(this.settings.provider_endpoint);
$('#language_options').val(this.settings.language);
//$('#voicemap').val(this.settings.voiceMap);
$('#at_generation_method').val(this.settings.at_generation_method);
$('#at_narrator_enabled').val(this.settings.narrator_enabled);
$('#at_narrator_text_not_inside').val(this.settings.at_narrator_text_not_inside);
$('#narrator_voice').val(this.settings.narrator_voice_gen);
console.debug('AllTalkTTS: Settings loaded');
try {
// Check if TTS provider is ready
await this.checkReady();
await this.updateSettingsFromServer(); // Fetch dynamic settings from the TTS server
await this.fetchTtsVoiceObjects(); // Fetch voices only if service is ready
this.updateNarratorVoicesDropdown();
this.updateLanguageDropdown();
this.setupEventListeners();
this.applySettingsToHTML();
updateStatus('Ready');
} catch (error) {
console.error("Error loading settings:", error);
updateStatus('Offline');
}
}
applySettingsToHTML() {
// Apply loaded settings or use defaults
const narratorVoiceSelect = document.getElementById('narrator_voice');
const atNarratorSelect = document.getElementById('at_narrator_enabled');
const textNotInsideSelect = document.getElementById('at_narrator_text_not_inside');
const generationMethodSelect = document.getElementById('at_generation_method');
this.settings.narrator_voice = this.settings.narrator_voice_gen;
// Apply settings to Narrator Voice dropdown
if (narratorVoiceSelect && this.settings.narrator_voice) {
narratorVoiceSelect.value = this.settings.narrator_voice.replace('.wav', '');
}
// Apply settings to AT Narrator Enabled dropdown
if (atNarratorSelect) {
// Sync the state with the checkbox in index.js
const ttsPassAsterisksCheckbox = document.getElementById('tts_pass_asterisks'); // Access the checkbox from index.js
const ttsNarrateQuotedCheckbox = document.getElementById('tts_narrate_quoted'); // Access the checkbox from index.js
const ttsNarrateDialoguesCheckbox = document.getElementById('tts_narrate_dialogues'); // Access the checkbox from index.js
// Sync the state with the checkbox in index.js
if (this.settings.narrator_enabled) {
ttsPassAsterisksCheckbox.checked = false;
$('#tts_pass_asterisks').click(); // Simulate a click event
$('#tts_pass_asterisks').trigger('change');
}
if (!this.settings.narrator_enabled) {
ttsPassAsterisksCheckbox.checked = true;
$('#tts_pass_asterisks').click(); // Simulate a click event
$('#tts_pass_asterisks').trigger('change');
}
// Uncheck and set tts_narrate_quoted to false if narrator is enabled
if (this.settings.narrator_enabledd) {
ttsNarrateQuotedCheckbox.checked = true;
ttsNarrateDialoguesCheckbox.checked = true;
// Trigger click events instead of change events
$('#tts_narrate_quoted').click();
$('#tts_narrate_quoted').trigger('change');
$('#tts_narrate_dialogues').click();
$('#tts_narrate_dialogues').trigger('change');
}
atNarratorSelect.value = this.settings.narrator_enabled.toString();
this.settings.narrator_enabled = this.settings.narrator_enabled.toString();
}
// Apply settings to the Language dropdown
const languageSelect = document.getElementById('language_options');
if (languageSelect && this.settings.language) {
languageSelect.value = this.settings.language;
}
// Apply settings to Text Not Inside dropdown
if (textNotInsideSelect && this.settings.text_not_inside) {
textNotInsideSelect.value = this.settings.text_not_inside;
this.settings.at_narrator_text_not_inside = this.settings.text_not_inside;
}
// Apply settings to Generation Method dropdown
if (generationMethodSelect && this.settings.at_generation_method) {
generationMethodSelect.value = this.settings.at_generation_method;
}
// Additional logic to disable/enable dropdowns based on the selected generation method
const isStreamingEnabled = this.settings.at_generation_method === 'streaming_enabled';
if (isStreamingEnabled) {
// Disable certain dropdowns when streaming is enabled
if (atNarratorSelect) atNarratorSelect.disabled = true;
if (textNotInsideSelect) textNotInsideSelect.disabled = true;
if (narratorVoiceSelect) narratorVoiceSelect.disabled = true;
} else {
// Enable dropdowns for standard generation
if (atNarratorSelect) atNarratorSelect.disabled = false;
if (textNotInsideSelect) textNotInsideSelect.disabled = !this.settings.narrator_enabled;
if (narratorVoiceSelect) narratorVoiceSelect.disabled = !this.settings.narrator_enabled;
}
const modelSelect = document.getElementById('switch_model');
if (this.settings.finetuned_model === 'true') {
const ftOption = document.createElement('option');
ftOption.value = 'XTTSv2 FT';
ftOption.textContent = 'XTTSv2 FT';
modelSelect.appendChild(ftOption);
}
}
//##############################//
// Check AT Server is Available //
//##############################//
async checkReady() {
try {
const response = await fetch(`${this.settings.provider_endpoint}/api/ready`);
// Check if the HTTP request was successful
if (!response.ok) {
throw new Error(`HTTP Error Response: ${response.status} ${response.statusText}`);
}
const statusText = await response.text();
// Check if the response is 'Ready'
if (statusText === 'Ready') {
this.ready = true; // Set the ready flag to true
console.log('TTS service is ready.');
} else {
this.ready = false;
console.log('TTS service is not ready.');
}
} catch (error) {
console.error('Error checking TTS service readiness:', error);
this.ready = false; // Ensure ready flag is set to false in case of error
}
}
//######################//
// Get Available Voices //
//######################//
async fetchTtsVoiceObjects() {
const response = await fetch(`${this.settings.provider_endpoint}/api/voices`);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
const voices = data.voices.map(filename => {
const voiceName = filename.replace('.wav', '');
return {
name: voiceName,
voice_id: voiceName,
preview_url: null, // Preview URL will be dynamically generated
lang: 'en' // Default language
};
});
this.voices = voices; // Assign to the class property
return voices; // Also return this list
}
//##########################################//
// Get Current AT Server Config & Update ST //
//##########################################//
async updateSettingsFromServer() {
try {
// Fetch current settings
const response = await fetch(`${this.settings.provider_endpoint}/api/currentsettings`);
if (!response.ok) {
throw new Error(`Failed to fetch current settings: ${response.statusText}`);
}
const currentSettings = await response.json();
// Update internal settings
this.settings.modelsAvailable = currentSettings.models_available;
this.settings.currentModel = currentSettings.current_model_loaded;
this.settings.deepspeed_available = currentSettings.deepspeed_available;
this.settings.deepSpeedEnabled = currentSettings.deepspeed_status;
this.settings.lowVramEnabled = currentSettings.low_vram_status;
this.settings.finetuned_model = currentSettings.finetuned_model
// Update HTML elements
this.updateModelDropdown();
this.updateCheckboxes();
} catch (error) {
console.error(`Error updating settings from server: ${error}`);
}
}
//###################################################//
// Get Current AT Server Config & Update ST (Models) //
//###################################################//
updateModelDropdown() {
const modelSelect = document.getElementById('switch_model');
if (modelSelect) {
modelSelect.innerHTML = ''; // Clear existing options
this.settings.modelsAvailable.forEach(model => {
const option = document.createElement('option');
option.value = model.model_name;
option.textContent = model.model_name; // Use model_name instead of name
option.selected = model.model_name === this.settings.currentModel;
modelSelect.appendChild(option);
});
}
}
//#######################################################//
// Get Current AT Server Config & Update ST (DS and LVR) //
//#######################################################//
updateCheckboxes() {
const deepspeedCheckbox = document.getElementById('deepspeed');
const lowVramCheckbox = document.getElementById('low_vram');
if (lowVramCheckbox) lowVramCheckbox.checked = this.settings.lowVramEnabled;
if (deepspeedCheckbox) {
deepspeedCheckbox.checked = this.settings.deepSpeedEnabled;
deepspeedCheckbox.disabled = !this.settings.deepspeed_available; // Disable checkbox if deepspeed is not available
}
}
//###############################################################//
// Get Current AT Server Config & Update ST (AT Narrator Voices) //
//###############################################################//
updateNarratorVoicesDropdown() {
const narratorVoiceSelect = document.getElementById('narrator_voice');
if (narratorVoiceSelect && this.voices) {
// Clear existing options
narratorVoiceSelect.innerHTML = '';
// Add new options
for (let voice of this.voices) {
const option = document.createElement('option');
option.value = voice.voice_id;
option.textContent = voice.name;
narratorVoiceSelect.appendChild(option);
}
}
}
//######################################################//
// Get Current AT Server Config & Update ST (Languages) //
//######################################################//
updateLanguageDropdown() {
const languageSelect = document.getElementById('language_options');
if (languageSelect) {
// Ensure default language is set
this.settings.language = this.settings.language;
languageSelect.innerHTML = '';
for (let language in this.languageLabels) {
const option = document.createElement('option');
option.value = this.languageLabels[language];
option.textContent = language;
if (this.languageLabels[language] === this.settings.language) {
option.selected = true;
}
languageSelect.appendChild(option);
}
}
}
//########################################//
// Start AT TTS extenstion page listeners //
//########################################//
setupEventListeners() {
let debounceTimeout;
const debounceDelay = 500; // Milliseconds
// Define the event handler function
const onModelSelectChange = async (event) => {
console.log("Model select change event triggered"); // Debugging statement
const selectedModel = event.target.value;
console.log(`Selected model: ${selectedModel}`); // Debugging statement
// Set status to Processing
updateStatus('Processing');
try {
const response = await fetch(`${this.settings.provider_endpoint}/api/reload?tts_method=${encodeURIComponent(selectedModel)}`, {
method: 'POST'
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
console.log("POST response data:", data); // Debugging statement
// Set status to Ready if successful
updateStatus('Ready');
} catch (error) {
console.error("POST request error:", error); // Debugging statement
// Set status to Error in case of failure
updateStatus('Error');
}
// Handle response or error
};
const debouncedModelSelectChange = (event) => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
onModelSelectChange(event);
}, debounceDelay);
};
// Switch Model Listener
const modelSelect = document.getElementById('switch_model');
if (modelSelect) {
// Remove the event listener if it was previously added
modelSelect.removeEventListener('change', debouncedModelSelectChange);
// Add the debounced event listener
modelSelect.addEventListener('change', debouncedModelSelectChange);
}
// DeepSpeed Listener
const deepspeedCheckbox = document.getElementById('deepspeed');
if (deepspeedCheckbox) {
deepspeedCheckbox.addEventListener('change', async (event) => {
const deepSpeedValue = event.target.checked ? 'True' : 'False';
// Set status to Processing
updateStatus('Processing');
try {
const response = await fetch(`${this.settings.provider_endpoint}/api/deepspeed?new_deepspeed_value=${deepSpeedValue}`, {
method: 'POST'
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
console.log("POST response data:", data); // Debugging statement
// Set status to Ready if successful
updateStatus('Ready');
} catch (error) {
console.error("POST request error:", error); // Debugging statement
// Set status to Error in case of failure
updateStatus('Error');
}
});
}
// Low VRAM Listener
const lowVramCheckbox = document.getElementById('low_vram');
if (lowVramCheckbox) {
lowVramCheckbox.addEventListener('change', async (event) => {
const lowVramValue = event.target.checked ? 'True' : 'False';
// Set status to Processing
updateStatus('Processing');
try {
const response = await fetch(`${this.settings.provider_endpoint}/api/lowvramsetting?new_low_vram_value=${lowVramValue}`, {
method: 'POST'
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
console.log("POST response data:", data); // Debugging statement
// Set status to Ready if successful
updateStatus('Ready');
} catch (error) {
console.error("POST request error:", error); // Debugging statement
// Set status to Error in case of failure
updateStatus('Error');
}
});
}
// Narrator Voice Dropdown Listener
const narratorVoiceSelect = document.getElementById('narrator_voice');
if (narratorVoiceSelect) {
narratorVoiceSelect.addEventListener('change', (event) => {
this.settings.narrator_voice_gen = `${event.target.value}.wav`;
this.onSettingsChange(); // Save the settings after change
});
}
const textNotInsideSelect = document.getElementById('at_narrator_text_not_inside');
if (textNotInsideSelect) {
textNotInsideSelect.addEventListener('change', (event) => {
this.settings.text_not_inside = event.target.value;
this.onSettingsChange(); // Save the settings after change
});
}
// AT Narrator Dropdown Listener
const atNarratorSelect = document.getElementById('at_narrator_enabled');
const ttsPassAsterisksCheckbox = document.getElementById('tts_pass_asterisks'); // Access the checkbox from index.js
const ttsNarrateQuotedCheckbox = document.getElementById('tts_narrate_quoted'); // Access the checkbox from index.js
const ttsNarrateDialoguesCheckbox = document.getElementById('tts_narrate_dialogues'); // Access the checkbox from index.js
if (atNarratorSelect && textNotInsideSelect && narratorVoiceSelect) {
atNarratorSelect.addEventListener('change', (event) => {
const isNarratorEnabled = event.target.value === 'true';
this.settings.narrator_enabled = isNarratorEnabled; // Update the setting here
textNotInsideSelect.disabled = !isNarratorEnabled;
narratorVoiceSelect.disabled = !isNarratorEnabled;
// Sync the state with the checkbox in index.js
if (isNarratorEnabled) {
ttsPassAsterisksCheckbox.checked = false;
$('#tts_pass_asterisks').click(); // Simulate a click event
$('#tts_pass_asterisks').trigger('change');
}
if (!isNarratorEnabled) {
ttsPassAsterisksCheckbox.checked = true;
$('#tts_pass_asterisks').click(); // Simulate a click event
$('#tts_pass_asterisks').trigger('change');
}
// Uncheck and set tts_narrate_quoted to false if narrator is enabled
if (isNarratorEnabled) {
ttsNarrateQuotedCheckbox.checked = true;
ttsNarrateDialoguesCheckbox.checked = true;
// Trigger click events instead of change events
$('#tts_narrate_quoted').click();
$('#tts_narrate_quoted').trigger('change');
$('#tts_narrate_dialogues').click();
$('#tts_narrate_dialogues').trigger('change');
}
this.onSettingsChange(); // Save the settings after change
});
}
// Event Listener for AT Generation Method Dropdown
const atGenerationMethodSelect = document.getElementById('at_generation_method');
const atNarratorEnabledSelect = document.getElementById('at_narrator_enabled');
if (atGenerationMethodSelect) {
atGenerationMethodSelect.addEventListener('change', (event) => {
const selectedMethod = event.target.value;
if (selectedMethod === 'streaming_enabled') {
// Disable and unselect AT Narrator
atNarratorEnabledSelect.disabled = true;
atNarratorEnabledSelect.value = 'false';
textNotInsideSelect.disabled = true;
narratorVoiceSelect.disabled = true;
} else if (selectedMethod === 'standard_generation') {
// Enable AT Narrator
atNarratorEnabledSelect.disabled = false;
}
this.settings.at_generation_method = selectedMethod; // Update the setting here
this.onSettingsChange(); // Save the settings after change
});
}
// Listener for Language Dropdown
const languageSelect = document.getElementById('language_options');
if (languageSelect) {
languageSelect.addEventListener('change', (event) => {
this.settings.language = event.target.value;
this.onSettingsChange(); // Save the settings after change
});
}
// Listener for AllTalk Endpoint Input
const atServerInput = document.getElementById('at_server');
if (atServerInput) {
atServerInput.addEventListener('input', (event) => {
this.settings.provider_endpoint = event.target.value;
this.onSettingsChange(); // Save the settings after change
});
}
}
//#############################//
// Store ST interface settings //
//#############################//
onSettingsChange() {
// Update settings based on the UI elements
//this.settings.provider_endpoint = $('#at_server').val();
this.settings.language = $('#language_options').val();
//this.settings.voiceMap = $('#voicemap').val();
this.settings.at_generation_method = $('#at_generation_method').val();
this.settings.narrator_enabled = $('#at_narrator_enabled').val();
this.settings.at_narrator_text_not_inside = $('#at_narrator_text_not_inside').val();
this.settings.narrator_voice_gen = $('#narrator_voice').val();
// Save the updated settings
saveTtsProviderSettings();
}
//#########################//
// ST Handle Reload button //
//#########################//
async onRefreshClick() {
await this.checkReady(); // Check if the TTS provider is ready
await this.loadSettings(this.settings); // Reload the settings
// Additional actions as needed
}
//##################//
// Preview AT Voice //
//##################//
async previewTtsVoice(voiceName) {
try {
// Prepare data for POST request
const postData = new URLSearchParams();
postData.append("voice", `${voiceName}.wav`);
// Making the POST request
const response = await fetch(`${this.settings.provider_endpoint}/api/previewvoice/`, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: postData,
});
if (!response.ok) {
const errorText = await response.text();
console.error(`[previewTtsVoice] Error Response Text:`, errorText);
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
// Assuming the server returns a URL to the .wav file
const data = await response.json();
if (data.output_file_url) {
// Use an audio element to play the .wav file
const audioElement = new Audio(data.output_file_url);
audioElement.play().catch(e => console.error("Error playing audio:", e));
} else {
console.warn("[previewTtsVoice] No output file URL received in the response");
throw new Error("No output file URL received in the response");
}
} catch (error) {
console.error("[previewTtsVoice] Exception caught during preview generation:", error);
throw error;
}
}
//#####################//
// Populate ST voices //
//#####################//
async getVoice(voiceName, generatePreview = false) {
// Ensure this.voices is populated
if (this.voices.length === 0) {
// Fetch voice objects logic
}
// Find the object where the name matches voiceName
const match = this.voices.find(voice => voice.name === voiceName);
if (!match) {
// Error handling
}
// Generate preview URL only if requested
if (!match.preview_url && generatePreview) {
// Generate preview logic
}
return match; // Return the found voice object
}
//##########################################//
// Generate TTS Streaming or call Standard //
//##########################################//
async generateTts(inputText, voiceId) {
try {
if (this.settings.at_generation_method === 'streaming_enabled') {
// Construct the streaming URL
const streamingUrl = `${this.settings.provider_endpoint}/api/tts-generate-streaming?text=${encodeURIComponent(inputText)}&voice=${encodeURIComponent(voiceId)}.wav&language=${encodeURIComponent(this.settings.language)}&output_file=stream_output.wav`;
console.log("Streaming URL:", streamingUrl);
// Return the streaming URL directly
return streamingUrl;
} else {
// For standard method
const outputUrl = await this.fetchTtsGeneration(inputText, voiceId);
const audioResponse = await fetch(outputUrl);
if (!audioResponse.ok) {
throw new Error(`HTTP ${audioResponse.status}: Failed to fetch audio data`);
}
return audioResponse; // Return the fetch response directly
}
} catch (error) {
console.error("Error in generateTts:", error);
throw error;
}
}
//####################//
// Generate Standard //
//####################//
async fetchTtsGeneration(inputText, voiceId) {
// Prepare the request payload
const requestBody = new URLSearchParams({
'text_input': inputText,
'text_filtering': "standard",
'character_voice_gen': voiceId + ".wav",
'narrator_enabled': this.settings.narrator_enabled,
'narrator_voice_gen': this.settings.narrator_voice_gen + ".wav",
'text_not_inside': this.settings.at_narrator_text_not_inside,
'language': this.settings.language,
'output_file_name': "st_output",
'output_file_timestamp': "true",
'autoplay': "false",
'autoplay_volume': "0.8"
}).toString();
try {
const response = await doExtrasFetch(
`${this.settings.provider_endpoint}/api/tts-generate`,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache',
},
body: requestBody
}
);
if (!response.ok) {
const errorText = await response.text();
console.error(`[fetchTtsGeneration] Error Response Text:`, errorText);
// toastr.error(response.statusText, 'TTS Generation Failed');
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
const outputUrl = data.output_file_url;
return outputUrl; // Return only the output_file_url
} catch (error) {
console.error("[fetchTtsGeneration] Exception caught:", error);
throw error; // Rethrow the error for further handling
}
}
}
//#########################//
// Update Status Messages //
//#########################//
function updateStatus(message) {
const statusElement = document.getElementById('status_info');
if (statusElement) {
statusElement.textContent = message;
switch (message) {
case 'Offline':
statusElement.style.color = 'red';
break;
case 'Ready':
statusElement.style.color = 'lightgreen';
break;
case 'Processing':
statusElement.style.color = 'blue';
break;
case 'Error':
statusElement.style.color = 'red';
break;
}
}
}
File diff suppressed because it is too large. Load diff
+159
View File
@@ -0,0 +1,159 @@
#tts_media_control {
/* order: 100; */
/* width: 40px;
height: 40px;
margin: 0;
padding: 1px; */
outline: none;
border: none;
cursor: pointer;
/* transition: 0.3s;
opacity: 0.7; */
display: flex;
align-items: center;
/* justify-content: center; */
}
#ttsExtensionMenuItem {
transition: 0.3s;
opacity: 0.7;
}
#ttsExtensionMenuItem:hover {
opacity: 1;
filter: brightness(1.2);
}
#tts_media_control:hover {
opacity: 1;
filter: brightness(1.2);
}
.voice_preview {
margin: 0.25rem 0.5rem;
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
}
.voice_preview .voice_name {
text-align: left;
flex: 1;
}
.voice_preview .voice_lang {
width: 4rem;
text-align: left;
}
.voice_preview .fa-play {
cursor: pointer;
}
.tts-button {
margin: 0;
outline: none;
border: none;
cursor: pointer;
transition: 0.3s;
opacity: 0.7;
align-items: center;
justify-content: center;
}
.tts-button:hover {
opacity: 1;
}
.tts_block {
display: flex;
align-items: baseline;
column-gap: 5px;
flex-wrap: wrap;
}
.tts_custom_voices {
display: flex;
align-items: baseline;
gap: 5px;
}
.novel_tts_hints {
font-size: calc(0.9 * var(--mainFontSize));
display: flex;
flex-direction: column;
gap: 5px;
margin-bottom: 5px;
}
.at-settings-row {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.at-settings-option {
flex: 1;
margin: 0 10px;
}
.at-endpoint-option {
flex: 1;
margin: 0 10px;
margin-right: 25px;
width: 38%;
}
.at-website-row {
display: flex;
justify-content: start;
align-items: center;
margin-top: 10px;
margin-bottom: 10px;
}
.at-website-option {
flex: 1;
margin-right: 10px;
margin-left: 10px;
}
.at-settings-separator {
margin-top: 10px;
margin-bottom: 10px;
padding: 18x;
font-weight: bold;
border-top: 1px solid #e1e1e1; /* Grey line */
border-bottom: 1px solid #e1e1e1; /* Grey line */
text-align: center;
}
.at-status-message {
flex: 1;
margin: 0 10px;
}
.at-model-endpoint-row {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.at-model-option, .endpoint-option {
flex: 1;
margin: 0 10px;
margin-left: 10px;
}
.at-endpoint-option {
width: 38%;
}
#at-status_info {
color: lightgreen;
}
+118 -6
View File
@@ -222,6 +222,7 @@
<li><a href="#using-voice-samples">Using Voice Samples</a></li> <li><a href="#using-voice-samples">Using Voice Samples</a></li>
<li><a href="#text-not-inside">Text Not inside</a></li> <li><a href="#text-not-inside">Text Not inside</a></li>
<li><a href="#low-vram">Low VRAM</a></li> <li><a href="#low-vram">Low VRAM</a></li>
<li><a href="#sillytavern-support">Silly Tavern Support</a></li>
<li><a href="#finetune">Finetuning (Training the model)</a></li> <li><a href="#finetune">Finetuning (Training the model)</a></li>
<li><a href="#deepspeed">DeepSpeed</a> <li><a href="#deepspeed">DeepSpeed</a>
<ul> <ul>
@@ -272,8 +273,8 @@
here</a><br />Update instructions <a href="https://github.com/erew123/alltalk_tts?#-updating" here</a><br />Update instructions <a href="https://github.com/erew123/alltalk_tts?#-updating"
target="_blank" rel="noopener">link here</a><br />Help and issues <a target="_blank" rel="noopener">link here</a><br />Help and issues <a
href="https://github.com/erew123/alltalk_tts?#-help-with-problems" target="_blank" rel="noopener">link href="https://github.com/erew123/alltalk_tts?#-help-with-problems" target="_blank" rel="noopener">link
here</a><br />TTS Generator <a here</a><br />TTS Generator <a href="http://127.0.0.1:7851/static/tts_chunk_player/tts_chunk_player.html"
href="http://127.0.0.1:7851/static/tts_chunk_player/tts_chunk_player.html" target="_blank" rel="noopener">link target="_blank" rel="noopener">link
here<br /><br /></a><span style="text-decoration: underline;"><strong>Text generation webUI</strong></span> here<br /><br /></a><span style="text-decoration: underline;"><strong>Text generation webUI</strong></span>
<br />Web interface&nbsp;<a href="http://{{ params.ip_address }}:7860" target="_blank" rel="noopener">link <br />Web interface&nbsp;<a href="http://{{ params.ip_address }}:7860" target="_blank" rel="noopener">link
here</a> <br />Documentation <a href="https://github.com/oobabooga/text-generation-webui/wiki" here</a> <br />Documentation <a href="https://github.com/oobabooga/text-generation-webui/wiki"
@@ -291,7 +292,8 @@
<p style="padding-left: 30px;"><a href="#toc">Back to top of page</a></p> <p style="padding-left: 30px;"><a href="#toc">Back to top of page</a></p>
<h2 id="demotesttts">Demo/Test TTS</h2> <h2 id="demotesttts">Demo/Test TTS</h2>
<p style="padding-left: 30px;">If you are wanting to generate bulk quantites of TTS and have control over them, please see the <a href="#tts-generator">AllTalk TTS Generator</a> below.</p> <p style="padding-left: 30px;">If you are wanting to generate bulk quantities of TTS and have control over them,
please see the <a href="#tts-generator">AllTalk TTS Generator</a> below.</p>
<div id="container"> <div id="container">
<form method="post" action="/tts-demo-request" id="ttsForm"> <form method="post" action="/tts-demo-request" id="ttsForm">
<label for="text">Text:</label> <label for="text">Text:</label>
@@ -420,7 +422,8 @@
let cleanedText = textInput.replace(/ \- | \– /g, ' '); // Replace hyphens let cleanedText = textInput.replace(/ \- | \– /g, ' '); // Replace hyphens
cleanedText = cleanedText.replace(/%/g, " percent"); cleanedText = cleanedText.replace(/%/g, " percent");
//cleanedText = cleanedText.replace(/([!?.])\1+/g, '$1'); //cleanedText = cleanedText.replace(/([!?.])\1+/g, '$1');
cleanedText = cleanedText.replace(/[^a-zA-Z0-9\s\.,;:!?\-\'"À-ÿ\u0400-\u04FF]/g, ''); //cleanedText = cleanedText.replace(/[^a-zA-Z0-9\s\.,;:!?\-\'"À-ÿ\u0400-\u04FF]/g, '');
cleanedText = cleanedText.replace(/[^a-zA-Z0-9\s\.,;:!?\-\'"À-ÿ\u0400-\u04FF]\$/g, '')
cleanedText = cleanedText.replace(/\n+/g, ' '); cleanedText = cleanedText.replace(/\n+/g, ' ');
cleanedText = cleanedText.replace(/\.\s'/g, ".'"); // Remove space between period and single quote cleanedText = cleanedText.replace(/\.\s'/g, ".'"); // Remove space between period and single quote
//cleanedText = cleanedText.replace(/'/g, ""); // Remove all single quotes //cleanedText = cleanedText.replace(/'/g, ""); // Remove all single quotes
@@ -433,11 +436,11 @@
if (formData.get('streaming') === 'true') { if (formData.get('streaming') === 'true') {
// For streaming, update the audio player src // For streaming, update the audio player src
const searchParams = new URLSearchParams(formData).toString(); const searchParams = new URLSearchParams(formData).toString();
audioPlayer.src = baseurl + "/tts-demo-request?" + searchParams; audioPlayer.src = baseurl + "/api/tts-generate-streaming?" + searchParams;
audioPlayer.load(); // Reload the audio player audioPlayer.load(); // Reload the audio player
} else { } else {
// For non-streaming, send a POST request // For non-streaming, send a POST request
const response = await fetch('/tts-demo-request', { const response = await fetch('/api/tts-generate-streaming', {
method: 'POST', method: 'POST',
body: formData, body: formData,
cache: "no-store" cache: "no-store"
@@ -657,6 +660,113 @@
<p style="padding-left: 30px;"><a href="#toc">Back to top of page</a></p> <p style="padding-left: 30px;"><a href="#toc">Back to top of page</a></p>
<h2 id="sillytavern-support"><strong>SillyTavern Support</strong></h2>
<h4>Important note for Text-generation-webui users</h4>
<p style="padding-left: 30px;">You <strong><span style="color: #3366ff;">HAVE</span></strong> to disable
<strong>Enable TTS</strong> within the Text-generation-webui AllTalk interface,
otherwise&nbsp;Text-generation-webui will also generate TTS due to the way it sends out text. You can do this
each time you start up&nbsp;Text-generation-webui or set it in the start-up settings at the top of this page.
</p>
<h4>Quick Tips</h4>
<ul>
<li>Only change DeepSpeed, Low VRAM or Model one at a time. Wait for it to say Ready before changing something
else.</li>
<li>You can permanently change the AllTalk startup settings or DeepSpeed, Low VRAM and Model at the top of this
page.</li>
<li>Different AI models use quotes and asterisks differently, so you may need to change "Text not inside"
depending on model.</li>
<li>Add new voice samples to the voices folder. You can Finetune a model to make it sound even closer to the
original sample.</li>
<li>DeepSpeed will improve processing time to TTS to be 2-3x faster.</li>
<li>Low VRAM can be very beneficial if you don't have much memory left after loading your LLM.</li>
</ul>
<h4>TTS Generation Methods in SilllyTavern</h4>
<p style="padding-left: 30px;">You have 2 types of audio generation options, Streaming and Standard.</p>
<p style="padding-left: 30px; text-align: justify;">The Streaming Audio Generation method is designed for speed and
is best suited for situations where you just want quick audio playback. This method, however, is limited to
using just one voice per TTS generation request. This means a limitation of the Streaming method is the
inability to utilize the AllTalk narrator function, making it a straightforward but less nuanced option.</p>
<p style="padding-left: 30px; text-align: justify;">On the other hand, the Standard Audio Generation method provides
a richer auditory experience. It's slightly slower than the Streaming method but compensates for this with its
ability to split text into multiple voices. This functionality is particularly useful in scenarios where
differentiating between character dialogues and narration can enhance the storytelling and delivery. The
inclusion of the AllTalk narrator functionality in the Standard method allows for a more layered and immersive
experience, making it ideal for content where depth and variety in voice narration add significant value.</p>
<p style="padding-left: 30px; text-align: justify;">In summary, the choice between Streaming and Standard methods in
AllTalk TTS depends on what you want. Streaming is great for quick and simple audio generation, while Standard
is preferable for a more dynamic and engaging audio experience.</p>
<ul>
<li><strong>AllTalk TTS Generation Method:</strong>
<ul>
<li>Select between Standard and Streaming Audio Generation methods.</li>
<li>This setting impacts the AllTalk narrator functionality.</li>
</ul>
</li>
<li><strong>Language Selection:</strong><br />
<ul>
<li>Select your preferred TTS generation language from the "Language" dropdown.</li>
</ul>
</li>
<li><strong>Model Switching:</strong>
<ul>
<li>Switch between different TTS models like API TTS, API Local, XTTSv2 Local, and optionally XTTSv2 FT
if you have a finetuned model available.</li>
<li>Fine-tuned model availability (XTTSv2 FT) will only show when a finetuned model is detected by
AllTalk.</li>
<li>See TTS Models/Methods for more information (though most people will want to stick with XTTSv2
Local).</li>
</ul>
</li>
<li><strong>DeepSpeed and Low VRAM Options:</strong>
<ul>
<li>Optimize performance with DeepSpeed and Low VRAM settings.</li>
<li>DeepSpeed can offer a 2-3x performance boost on TTS generation. (Requires installation)</li>
<li>See the relevant sections in this documentation for details.</li>
</ul>
</li>
</ul>
<p style="padding-left: 30px;">Changing model or DeepSpeed or Low VRAM <span
style="color: #0000ff;"><strong>each</strong></span> take about 15 seconds so you should only change one at
a time and wait for <span style="color: #99cc00;">Ready</span> before changing the next setting. To set these
options long term you can apply the settings at the top of this page.</p>
<h4>AllTalk Narrator</h4>
<p style="padding-left: 30px;">Only available on the Standard Audo Generation method.</p>
<ul>
<li><strong>Narrator Voice Selection:</strong>
<ul>
<li>Allows users to choose different narrator voices.</li>
<li>Access via the "Narrator Voice" dropdown.</li>
</ul>
</li>
<li><strong>AllTalk Narrator:</strong>
<ul>
<li>Toggle the AllTalk narrator feature.</li>
<li>Access via "AT Narrator" dropdown with Enabled/Disabled options.</li>
</ul>
</li>
<li><strong>Text Outside Asterisks Handling:</strong>
<ul>
<li>Choose how text outside asterisks is interpreted (as Narrator or Character voice).</li>
<li>Managed via the "Text Not Inside * or "" dropdown.</li>
<li>Note, only available when the AllTalk Narrator is enabled.</li>
</ul>
</li>
</ul>
<h4>Usage Notes:</h4>
<ul>
<li>On startup of SillyTavern, it will pull your current settings from AllTalk (Current model, DeepSpeed status,
Low VRAM status and Finetuned model availability).</li>
<li>Enabling the narrator automatically unchecks certain checkboxes related to text handling.</li>
<li>Changes in model or settings might trigger multiple requests to the server; patience is advised.</li>
</ul>
<h4>Troubleshooting:</h4>
<ul>
<li>If experiencing issues, use the Reload button in SillyTavern's TTS extension to reinitialize the connection
to AllTalk and check if AllTalk is started correctly.</li>
</ul>
<p style="padding-left: 30px;"><a href="#toc">Back to top of page</a></p>
<h2 id="finetune"><strong>Finetuning (Training the model)</strong></h2> <h2 id="finetune"><strong>Finetuning (Training the model)</strong></h2>
<p style="margin-left:40px; text-align:justify">If you have a voice that the model doesnt quite reproduce correctly, <p style="margin-left:40px; text-align:justify">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 &quot;XTTSv2 or indeed you just want to improve the reproduced voice, then finetuning is a way to train your &quot;XTTSv2
@@ -836,6 +946,8 @@
<h3 id="deepspeed-windows">DeepSpeed Setup - Windows</h3> <h3 id="deepspeed-windows">DeepSpeed Setup - Windows</h3>
<p style="padding-left: 30px;">➡️DeepSpeed requires an Nvidia Graphics card!⬅️</p> <p style="padding-left: 30px;">➡️DeepSpeed requires an Nvidia Graphics card!⬅️</p>
<p style="padding-left: 30px;">The atsetup utility for Windows can install DeepSpeed for you (Stanalone users whom
installed via the atsetup utility will already have DeepSpeed installed).</p>
<p style="padding-left: 30px;">DeepSpeed v11.2 will work on the current default text-generation-webui Python 3.11 <p style="padding-left: 30px;">DeepSpeed v11.2 will work on the current default text-generation-webui Python 3.11
environment! You have 2x options for how to setup DeepSpeed on Windows. A quick way <span environment! You have 2x options for how to setup DeepSpeed on Windows. A quick way <span
style="color: #339966;"><strong>Option 1</strong></span>&nbsp;and a long way <span style="color: #339966;"><strong>Option 1</strong></span>&nbsp;and a long way <span
+415 -85
View File
@@ -6,7 +6,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="./favicon.ico" type="image/x-icon"> <link rel="icon" href="./favicon.ico" type="image/x-icon">
<title>AllTalk TTS Generator</title> <title>AllTalk TTS Generator</title>
<style> <style>
body, body,
textarea, textarea,
@@ -175,27 +174,32 @@
} }
.progress-overlay { .progress-overlay {
position: absolute; position: absolute;
top: 10px; top: 10px;
right: 10px; right: 10px;
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
border-radius: 5px; border-radius: 5px;
padding: 10px; padding: 10px;
display: flex; display: flex;
flex-direction: column; /* Stack items vertically */ flex-direction: column;
align-items: center; /* Center items horizontally within the container */ /* Stack items vertically */
justify-content: center; /* Center items vertically within the container */ align-items: center;
z-index: 10; /* Center items horizontally within the container */
} justify-content: center;
/* Center items vertically within the container */
z-index: 10;
}
/* Ensure the text is wrapped in a container with a class, e.g., .progress-text */ /* Ensure the text is wrapped in a container with a class, e.g., .progress-text */
.progress-text { .progress-text {
text-align: right; /* Center the text horizontally */ text-align: right;
margin-top: 10px; /* Add space between the spinner and the text */ /* Center the text horizontally */
} margin-top: 10px;
/* Add space between the spinner and the text */
}
#progressIndicator { #progressIndicator {
/* Adjust this if you want to position the spinning disk differently */ /* Adjust this if you want to position the spinning disk differently */
display: inline-block; display: inline-block;
margin-left: 20px; margin-left: 20px;
@@ -413,6 +417,78 @@
margin-left: 45px; margin-left: 45px;
/* Adjust the value as needed */ /* Adjust the value as needed */
} }
/* Pagination Buttons Styling */
.pagination-btn {
padding: 5px 10px;
/* Adjust padding to reduce height */
font-size: 0.8em;
/* Adjust font size for smaller buttons */
line-height: 1;
/* Adjust line height to match the smaller size */
margin: 2px;
/* Optional: adjust spacing between buttons */
}
/* Smaller input field for jump-to-page */
.pagination-input {
height: 20px;
/* Adjust height for smaller input field */
padding: 2px 5px;
/* Adjust padding for smaller input field */
font-size: 0.8em;
/* Adjust font size for smaller input field */
line-height: 1;
/* Adjust line height to match the smaller size */
vertical-align: middle;
/* Align with buttons if necessary */
}
/* Apply the styles to your pagination controls */
#paginationControls button {
/* Apply the button styling */
height: auto;
/* Let padding control the height */
min-height: 20px;
/* Set a minimum height if needed */
}
#paginationControls input[type="number"] {
/* Apply the input styling */
}
/* Smaller input field for jump-to-page */
.pagination-input {
height: 2px;
/* Reduce the height */
padding: 0px 0px;
/* Reduce the padding to decrease overall height */
font-size: 0.8em;
/* Optionally reduce the font size */
margin-bottom: 13px;
margin-top: 2px;
border: 0px solid #ccc;
/* Adjust border styling if needed */
line-height: normal;
/* Adjust line height to match the new size */
vertical-align: top;
/* Align vertically with buttons */
}
/* Apply the styles to your pagination controls */
#paginationControls1 button {
/* Apply the button styling */
height: auto;
/* Let padding control the height */
min-height: 20px;
/* Set a minimum height if needed */
margin-top: 15px
}
#paginationControls1 input[type="number"] {
/* Apply the input styling */
margin-top: 15px
}
</style> </style>
@@ -469,6 +545,7 @@
<select id="playMode" name="playMode" class="fixed-size-dropdown"> <select id="playMode" name="playMode" class="fixed-size-dropdown">
<option value="local" selected>In Browser</option> <option value="local" selected>In Browser</option>
<option value="remote">On Server</option> <option value="remote">On Server</option>
<option value="none">No Playback</option>
</select> </select>
</div> </div>
@@ -524,54 +601,93 @@
<button onclick="exportToJSON()" style="margin-right: 10px;">Export List as JSON</button> <button onclick="exportToJSON()" style="margin-right: 10px;">Export List as JSON</button>
<button onclick="importFromJSON()" style="margin-right: 10px;">Import JSON to list</button> <button onclick="importFromJSON()" style="margin-right: 10px;">Import JSON to list</button>
<button onclick="exportMP3()" style="margin-right: 10px;">Export to Wav</button> <button onclick="exportMP3()" style="margin-right: 10px;">Export to Wav</button>
<label for="splitEvery">Split every:</label>
<select id="splitEvery" name="splitEvery">
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
<option value="500" selected>500</option>
<option value="600">600</option>
</select>
<div id="paginationControls">
<button id="prevPage" class="pagination-btn">Previous</button>
<span id="pageIndicator">Page 1 of X</span>
<button id="nextPage" class="pagination-btn">Next</button>
<input type="number" id="jumpToPage" class="pagination-input" min="1" placeholder="Jump to Page">
<button id="jumpButton" class="pagination-btn">Go</button>
</div>
<div id="ttsListDisplay" class="tts-list-display"> <div id="ttsListDisplay" class="tts-list-display">
<!-- Dynamically populated TTS details will go here --> <!-- Dynamically populated TTS details will go here -->
</div> </div>
<div id="paginationControls1">
<button id="prevPage1" class="pagination-btn">Previous</button>
<span id="pageIndicator1">Page 1 of X</span>
<button id="nextPage1" class="pagination-btn">Next</button>
<input type="number" id="jumpToPage1" class="pagination-input" min="1" placeholder="Jump to Page">
<button id="jumpButton1" class="pagination-btn">Go</button>
</div>
</div> </div>
</div> </div>
<!-- Howler.js script inclusion --> <!-- Howler.js script inclusion -->
<script src="./howler.min.js"></script> <script src="./howler.min.js"></script>
<script type="module"> <script type="module">
// Import Crunker from the CDN
import Crunker from './crunker.esm.js'; import Crunker from './crunker.esm.js';
async function exportMP3() { async function exportMP3() {
const crunker = new Crunker(); const crunker = new Crunker();
const fileUrls = ttsList.map(item => item.fileUrl); const fileUrls = ttsList.map(item => item.fileUrl);
const progressIndicator = document.getElementById('progressIndicator'); const splitEvery = parseInt(document.getElementById('splitEvery').value) || 500;
const progressText = document.getElementById('progressText'); const progressIndicator = document.getElementById('progressIndicator');
const progressText = document.getElementById('progressText');
// Show progress indicator and update text if (progressIndicator && progressText) {
if (progressIndicator && progressText) { progressIndicator.style.display = 'block';
progressText.textContent = 'Export'; progressText.textContent = 'Starting export...';
progressText.style.color = 'black'; // Set the text color to black
progressIndicator.style.display = 'block';
}
try {
const audioBuffers = await crunker.fetchAudio(...fileUrls);
const combined = crunker.concatAudio(audioBuffers);
const output = crunker.export(combined, "audio/wav");
crunker.download(output.blob, "combined_audio"); // This will download the file as 'combined_audio.mp3'
} catch (error) {
console.error('Error combining files:', error);
if (progressText) {
progressText.textContent = 'Error during export!';
} }
} finally {
// Hide progress indicator after completion or error try {
if (progressIndicator) { for (let i = 0; i < fileUrls.length; i += splitEvery) {
progressIndicator.style.display = 'none'; const currentBatch = Math.floor(i / splitEvery) + 1;
const totalBatches = Math.ceil(fileUrls.length / splitEvery);
if (progressText) {
progressText.textContent = `Processing batch ${currentBatch} of ${totalBatches}`;
progressText.style.color = 'black'; // Set the text color to black
}
const batchUrls = fileUrls.slice(i, Math.min(i + splitEvery, fileUrls.length));
const audioBuffers = await crunker.fetchAudio(...batchUrls);
const combined = crunker.concatAudio(audioBuffers);
const output = crunker.export(combined, "audio/wav");
crunker.download(output.blob, `combined_audio_part_${currentBatch}.wav`);
// Clear audioBuffers array to free up memory
audioBuffers.length = 0;
console.log(`Exported batch ${currentBatch} of ${totalBatches}`);
}
} catch (error) {
console.error('Error combining files:', error);
if (progressText) {
progressText.textContent = 'Error during export!';
}
} finally {
if (progressIndicator && progressText) {
progressIndicator.style.display = 'none';
progressText.textContent = ''; // Reset progress text
}
} }
} }
}
// Attach exportMP3 to the window object to make it globally accessible
window.exportMP3 = exportMP3; window.exportMP3 = exportMP3;
</script> </script>
<script> <script>
///////////////////////////////////////// /////////////////////////////////////////
@@ -582,7 +698,7 @@
let audioQueue = []; let audioQueue = [];
let currentlyPlayingIndex = 0; let currentlyPlayingIndex = 0;
let isPlaying = false; let isPlaying = false;
let playModeValue = 'local'; let playModeValue = localStorage.getItem('playMode') || 'local';
let currentSound = null; let currentSound = null;
let preloadThreshold = 2; // Number of files to preload before starting playback let preloadThreshold = 2; // Number of files to preload before starting playback
let isStreamInitialized = false; let isStreamInitialized = false;
@@ -591,6 +707,12 @@
const howlInstances = {}; const howlInstances = {};
let listPlaying = false; let listPlaying = false;
let listPlayIndex = 0; let listPlayIndex = 0;
let currentPage = 1;
let itemsPerPage = 100; // Adjust as needed
var protocol = window.location.protocol;
var host = window.location.hostname;
var port = window.location.port;
var baseUrl = protocol + "//" + host + (port ? ':' + port : '');
//////////////////////////////////// ////////////////////////////////////
//////// Progress Indicator //////// //////// Progress Indicator ////////
@@ -602,7 +724,7 @@
if (progressIndicator && generationProgress) { if (progressIndicator && generationProgress) {
let message = ''; let message = '';
console.log("PlayType is:", playType); //console.log("PlayType is:", playType);
if (playType === 'stream') { if (playType === 'stream') {
// When streaming, display a different message // When streaming, display a different message
message = '<span class="highlight-count">&nbsp&nbsp&nbsp&nbsp&nbsp&nbspStreaming...</span>'; message = '<span class="highlight-count">&nbsp&nbsp&nbsp&nbsp&nbsp&nbspStreaming...</span>';
@@ -650,13 +772,13 @@
const volume = parseFloat(document.getElementById("volume").value); const volume = parseFloat(document.getElementById("volume").value);
const chunkSize = parseInt(document.getElementById("chunkSize").value); const chunkSize = parseInt(document.getElementById("chunkSize").value);
const playType = document.getElementById('playType').value; // Play type (chunk or stream) const playType = document.getElementById('playType').value; // Play type (chunk or stream)
playModeValue = document.getElementById('playMode').value;
let cleanedText = textInput.replace(/ \- | \– /g, ' '); let cleanedText = textInput.replace(/ \- | \– /g, ' ');
cleanedText = cleanedText.replace(/%/g, " percent"); cleanedText = cleanedText.replace(/%/g, " percent");
cleanedText = cleanedText.replace(/\.\s'/g, ".'"); cleanedText = cleanedText.replace(/\.\s'/g, ".'");
cleanedText = cleanedText.replace(/[^a-zA-Z0-9\s\.,;:!?\-\'"À-ÿ\u0400-\u04FF\u0150\u0151\u0170\u0171]/g, ''); cleanedText = cleanedText.replace(/[^a-zA-Z0-9\s\.,;:!?\-\'"À-ÿ\u0400-\u04FF\u0150\u0151\u0170\u0171]\$/g, '');
//let sentences = cleanedText.match(/("[^"]+"|[^.!?]+[.!?]+)/g); let sentences = cleanedText.split(/(?<=[.!?:])\s+/);
let sentences = cleanedText.match(/(?:\d+\.\d+|[^\d.!?])+\b[.!?]+(?=\s|$)/g);
if (!sentences) { if (!sentences) {
console.error("No sentences found in the input text."); console.error("No sentences found in the input text.");
@@ -686,9 +808,14 @@
if (stopTTSGeneration) break; if (stopTTSGeneration) break;
showProgress(i + 1, totalChunks, playType); showProgress(i + 1, totalChunks, playType);
if (playModeValue === 'local') { if (playModeValue === 'local') {
// Generate the chunk and play it locally
await generateAndCache(chunks[i], language, characterVoice, volume); await generateAndCache(chunks[i], language, characterVoice, volume);
} else { } else if (playModeValue === 'remote') {
// Generate the chunk and play it remotely
await generateAndPlayRemote(chunks[i], language, characterVoice, volume); await generateAndPlayRemote(chunks[i], language, characterVoice, volume);
} else if (playModeValue === 'none') {
// Generate the chunk but do not play it
await generateWithoutPlayback(chunks[i], language, characterVoice);
} }
} }
} }
@@ -726,7 +853,7 @@
autoplay_volume: volume autoplay_volume: volume
}); });
const response = await fetch("http://127.0.0.1:7851/api/tts-generate", { const response = await fetch(baseUrl + "/api/tts-generate", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
@@ -736,6 +863,7 @@
const result = await response.json(); const result = await response.json();
if (result.output_file_url) { if (result.output_file_url) {
//console.log('TTS Generation Result:', result);
// If an ID was passed in, we're regenerating an existing item // If an ID was passed in, we're regenerating an existing item
if (id !== null) { if (id !== null) {
let itemIndex = ttsList.findIndex(item => item.id === id); let itemIndex = ttsList.findIndex(item => item.id === id);
@@ -749,6 +877,15 @@
// No ID was passed in, so we add a new item to the list // No ID was passed in, so we add a new item to the list
addToTTSList(result.output_file_url, chunk, characterVoice, language); addToTTSList(result.output_file_url, chunk, characterVoice, language);
} }
const newPage = Math.ceil(ttsList.length / itemsPerPage);
//console.log('New Page Calculated:', newPage);
if (currentPage !== newPage) {
currentPage = newPage; // Move to the new page where the item was added
//console.log('Updating Current Page to:', currentPage);
}
// Refresh the list display to reflect the new pagination state
updateUIList();
// Update the audio queue and UI // Update the audio queue and UI
const sound = new Howl({ const sound = new Howl({
@@ -770,6 +907,56 @@
} }
} }
async function generateWithoutPlayback(chunk, language, characterVoice, id = null) {
// Perform the generation process as usual but do not play the audio
try {
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: "TTS",
output_file_timestamp: "true",
autoplay: "false",
autoplay_volume: "0.1"
});
const response = await fetch(baseUrl + "/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) {
// If an ID was passed in, we're regenerating an existing item
if (id !== null) {
let itemIndex = ttsList.findIndex(item => item.id === id);
if (itemIndex !== -1) {
ttsList[itemIndex].fileUrl = result.output_file_url;
// Other properties can be updated as needed, e.g., in case the language or voice has changed
ttsList[itemIndex].language = language;
ttsList[itemIndex].characterVoice = characterVoice;
}
} else {
// No ID was passed in, so we add a new item to the list
addToTTSList(result.output_file_url, chunk, characterVoice, language);
}
const newPage = Math.ceil(ttsList.length / itemsPerPage);
if (currentPage !== newPage) {
currentPage = newPage; // Move to the new page where the item was added
}
updateUIList();
}
} catch (error) {
console.error("Error in generateWithoutPlayback:", error);
}
}
function addToTTSList(fileUrl, text, characterVoice, language) { function addToTTSList(fileUrl, text, characterVoice, language) {
try { try {
ttsList.push({ ttsList.push({
@@ -785,6 +972,7 @@
} }
} }
async function regenerateTTS(id) { async function regenerateTTS(id) {
// Find the details of the TTS to regenerate // Find the details of the TTS to regenerate
const ttsDetails = ttsList.find(item => item.id === id); const ttsDetails = ttsList.find(item => item.id === id);
@@ -805,7 +993,13 @@
} }
listDisplay.innerHTML = ''; // Clear the current list listDisplay.innerHTML = ''; // Clear the current list
ttsList.forEach(item => { // Determine the range of items to display for pagination
const start = (currentPage - 1) * itemsPerPage;
const end = start + itemsPerPage;
const paginatedItems = ttsList.slice(start, end);
// Add items to the display for the current page
paginatedItems.forEach(item => {
// Extract just the file name from the URL // Extract just the file name from the URL
const wavFileName = item.fileUrl.split('/').pop(); const wavFileName = item.fileUrl.split('/').pop();
@@ -815,30 +1009,36 @@
const entryDiv = document.createElement('div'); const entryDiv = document.createElement('div');
entryDiv.id = `item-${item.id}`; // Assign an ID to the div for highlighting entryDiv.id = `item-${item.id}`; // Assign an ID to the div for highlighting
entryDiv.classList.add('ttsListItem'); // Add a class for styling entryDiv.classList.add('ttsListItem'); // Add a class for styling
entryDiv.id = `item-${item.id}`; // Make sure this is unique and correct
// Update the Play/Stop button's onclick to call a function that handles playing and highlighting // Update the Play/Stop button's onclick to call a function that handles playing and highlighting
entryDiv.innerHTML = ` entryDiv.innerHTML = `
<button onclick="regenerateTTS(${item.id})">Regenerate</button> <button onclick="regenerateTTS(${item.id})">Regenerate</button>
<button onclick="playSound('${item.fileUrl}', ${item.id})">Play/Stop</button> <button onclick="playSound('${item.fileUrl}', ${item.id})">Play/Stop</button>
<span class="label">ID:</span> <span class="value">${item.id}</span> <span class="label">ID:</span> <span class="value">${item.id}</span>
<span class="label">Voice:</span> <span class="value">${item.characterVoice}</span> <span class="label">Voice:</span> <span class="value">${item.characterVoice}</span>
<span class="label">Language:</span> <span class="value">${item.language}</span> <span class="label">Language:</span> <span class="value">${item.language}</span>
<span class="label">Wav:</span> <span class="value">${wavFileName}</span> <span class="label">Wav:</span> <span class="value">${wavFileName}</span>
<button id="edit-btn-${item.id}" class="edit-btn" onclick="editText(${item.id})">Edit</button> <button id="edit-btn-${item.id}" class="edit-btn" onclick="editText(${item.id})">Edit</button>
<span class="item-field text-preview value" title="${item.text}" data-fulltext="${item.text}">${displayText}</span> <span class="item-field text-preview value" title="${item.text}" data-fulltext="${item.text}">${displayText}</span>
`; `;
listDisplay.appendChild(entryDiv); listDisplay.appendChild(entryDiv);
}); });
// Update pagination controls
const lastPage = Math.ceil(ttsList.length / itemsPerPage);
document.getElementById('pageIndicator').innerText = `Page ${currentPage} of ${lastPage}`;
document.getElementById('pageIndicator1').innerText = `Page ${currentPage} of ${lastPage}`;
document.getElementById('prevPage').disabled = (currentPage === 1);
document.getElementById('nextPage').disabled = (currentPage === lastPage);
} }
async function generateAndPlayRemote(chunk, language, characterVoice, volume) { async function generateAndPlayRemote(chunk, language, characterVoice, volume) {
try { try {
if (stopTTSGeneration) { if (stopTTSGeneration) {
console.log("TTS generation stopped."); console.log("TTS generation stopped.");
return; // Early return if stop flag is set return; // Early return if stop flag is set
} }
console.log("generateAndPlayRemote:", chunk);
const data = new URLSearchParams({ const data = new URLSearchParams({
text_input: chunk.trim(), text_input: chunk.trim(),
text_filtering: "standard", text_filtering: "standard",
@@ -853,7 +1053,7 @@
autoplay_volume: volume, autoplay_volume: volume,
}); });
const response = await fetch("http://127.0.0.1:7851/api/tts-generate", { const response = await fetch(baseUrl + "/api/tts-generate", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
@@ -883,8 +1083,9 @@
}); });
// Reinitialize currentSound every time // Reinitialize currentSound every time
var srcUrl = baseUrl + "/tts-demo-request?" + queryParams.toString();
currentSound = new Howl({ currentSound = new Howl({
src: [`http://127.0.0.1:7851/tts-demo-request?${queryParams.toString()}`], src: [srcUrl],
volume: volume, volume: volume,
html5: true // Force HTML5 Audio to enable streaming html5: true // Force HTML5 Audio to enable streaming
}); });
@@ -914,13 +1115,10 @@
src: [fileUrl], src: [fileUrl],
volume: parseFloat(document.getElementById("volume").value), volume: parseFloat(document.getElementById("volume").value),
onplay: function () { onplay: function () {
console.log('Playback started for', fileUrl);
}, },
onend: function () { onend: function () {
console.log('Playback finished for', fileUrl);
}, },
onpause: function () { onpause: function () {
console.log('Playback paused for', fileUrl);
}, },
onloaderror: function (e) { onloaderror: function (e) {
console.error('Load error for', fileUrl, ':', e); console.error('Load error for', fileUrl, ':', e);
@@ -946,7 +1144,7 @@
const formData = new FormData(); const formData = new FormData();
formData.append("voice", characterVoice); formData.append("voice", characterVoice);
const response = await fetch("http://127.0.0.1:7851/api/previewvoice/", { const response = await fetch(baseUrl + "/api/previewvoice/", {
method: "POST", method: "POST",
body: formData, body: formData,
}); });
@@ -1055,15 +1253,26 @@
function playNextLocalChunk() { function playNextLocalChunk() {
if (audioQueue.length > 0 && currentlyPlayingIndex < audioQueue.length) { if (audioQueue.length > 0 && currentlyPlayingIndex < audioQueue.length) {
isPlaying = true; isPlaying = true;
audioQueue[currentlyPlayingIndex++].play(); let currentSound = audioQueue[currentlyPlayingIndex];
currentSound.play();
// Once a sound finishes playing, unload it
currentSound.on('end', () => {
currentSound.unload();
});
currentlyPlayingIndex++;
} else { } else {
isPlaying = false; isPlaying = false;
} }
} }
function stopPlayback() { function stopPlayback() {
Howler.stop(); Howler.stop();
audioQueue = []; audioQueue = [];
// Unload each sound in the queue
audioQueue.forEach(sound => sound.unload());
currentlyPlayingIndex = 0; currentlyPlayingIndex = 0;
isPlaying = false; isPlaying = false;
} }
@@ -1103,7 +1312,6 @@
const startFromIdElement = document.getElementById('startFromId'); const startFromIdElement = document.getElementById('startFromId');
if (startFromIdElement) { if (startFromIdElement) {
startFromIdElement.setAttribute('value', '1'); startFromIdElement.setAttribute('value', '1');
console.log('Start From ID set to 1');
} }
// Other initializations... // Other initializations...
}); });
@@ -1123,6 +1331,7 @@
// and highlight the corresponding item // and highlight the corresponding item
playListFromIndex(startIndex); playListFromIndex(startIndex);
highlightPlaying(startIndex + 1); // Assuming the list items are 1-indexed highlightPlaying(startIndex + 1); // Assuming the list items are 1-indexed
updateCurrentPage(startIndex + 1); // Update the current page based on the playing item
} else { } else {
// If list is set to pause, pause the current item // If list is set to pause, pause the current item
// and remove highlighting // and remove highlighting
@@ -1155,6 +1364,26 @@
if (currentItem) { if (currentItem) {
currentItem.classList.add('highlight'); currentItem.classList.add('highlight');
} }
updateCurrentPage(id);
}
function updateCurrentPage(itemIndex) {
// Calculate the page number based on the item index
// Note: Ensure that the itemIndex is 1-based; if it's 0-based, add 1.
const newPage = Math.ceil(itemIndex / itemsPerPage);
// Update the current page and UI if the new page is different from the current page
if (currentPage !== newPage) {
currentPage = newPage; // Set the new current page
updateUIList(); // Refresh the list display to show the correct page
}
// Optionally, update the 'Jump to Page' input to reflect the current page
const jumpToPageInput = document.getElementById('jumpToPage');
if (jumpToPageInput) {
jumpToPageInput.value = currentPage;
}
} }
@@ -1192,6 +1421,7 @@
console.log('Index is out of bounds, stopping playback.'); console.log('Index is out of bounds, stopping playback.');
// Clear any highlights if out of bounds // Clear any highlights if out of bounds
highlightPlaying(null); highlightPlaying(null);
updateUIList();
} }
} }
@@ -1213,6 +1443,14 @@
if (startFromIdElement) { if (startFromIdElement) {
startFromIdElement.value = '1'; startFromIdElement.value = '1';
} }
const pageIndicator = document.getElementById('pageIndicator');
if (pageIndicator) {
pageIndicator.textContent = 'Page 1 of 1';
}
const pageIndicator1 = document.getElementById('pageIndicator1');
if (pageIndicator1) {
pageIndicator1.textContent = 'Page 1 of 1';
}
} }
function editText(id) { function editText(id) {
@@ -1300,7 +1538,7 @@
input.type = 'file'; input.type = 'file';
input.accept = '.json'; input.accept = '.json';
input.onchange = (e) => { input.onchange = async (e) => {
const file = e.target.files[0]; const file = e.target.files[0];
if (file) { if (file) {
const reader = new FileReader(); const reader = new FileReader();
@@ -1308,13 +1546,11 @@
reader.onload = (e) => { reader.onload = (e) => {
try { try {
const jsonData = JSON.parse(e.target.result); const jsonData = JSON.parse(e.target.result);
console.log('JSON data imported:', jsonData);
// Update the ttsList with the imported data
ttsList = jsonData; ttsList = jsonData;
currentPage = 1; // Reset to the first page
// Refresh the on-screen list updateUIList();
updateUIList(); // This function updates the UI with the contents of ttsList updatePaginationControls(); // Update pagination controls
} catch (error) { } catch (error) {
console.error('Error parsing JSON:', error); console.error('Error parsing JSON:', error);
} }
@@ -1325,6 +1561,32 @@
input.click(); input.click();
} }
function updatePaginationControls() {
const lastPage = Math.ceil(ttsList.length / itemsPerPage);
const pageIndicator = document.getElementById('pageIndicator');
if (pageIndicator) {
pageIndicator.textContent = `Page ${currentPage} of ${lastPage}`;
}
const prevPageButton = document.getElementById('prevPage');
if (prevPageButton) {
prevPageButton.disabled = (currentPage === 1);
}
const nextPageButton = document.getElementById('nextPage');
if (nextPageButton) {
nextPageButton.disabled = (currentPage === lastPage);
}
// Similar updates for any additional pagination controls if you have them
// ...
}
////////////////////////////// //////////////////////////////
//////// Other Things //////// //////// Other Things ////////
////////////////////////////// //////////////////////////////
@@ -1374,7 +1636,7 @@
async function fetchVoices() { async function fetchVoices() {
try { try {
const response = await fetch("http://127.0.0.1:7851/api/voices"); const response = await fetch(baseUrl + "/api/voices");
const result = await response.json(); const result = await response.json();
const characterVoiceSelect = document.getElementById("character_voice_gen"); const characterVoiceSelect = document.getElementById("character_voice_gen");
@@ -1425,6 +1687,70 @@
//////// General Dcoument Listeners //////// //////// General Dcoument Listeners ////////
//////////////////////////////////////////// ////////////////////////////////////////////
// Event listeners for pagination controls
document.getElementById('prevPage').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
updateUIList();
}
});
document.getElementById('nextPage').addEventListener('click', () => {
const lastPage = Math.ceil(ttsList.length / itemsPerPage);
if (currentPage < lastPage) {
currentPage++;
updateUIList();
}
});
// Initialize the list on page load
document.addEventListener('DOMContentLoaded', updateUIList);
// For the 'Previous' button at the bottom
document.getElementById('prevPage1').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
updateUIList();
}
});
// For the 'Next' button at the bottom
document.getElementById('nextPage1').addEventListener('click', () => {
let lastPage = Math.ceil(ttsList.length / itemsPerPage);
if (currentPage < lastPage) {
currentPage++;
updateUIList();
}
});
function handleJumpButtonClick(event) {
// Determine which set of controls to use based on the button that was clicked
const suffix = event.target.id === 'jumpButton' ? '' : '1';
const jumpToInput = document.getElementById(`jumpToPage${suffix}`);
const jumpToValue = jumpToInput.value.trim(); // Get the trimmed value
const jumpTo = parseInt(jumpToValue, 10); // Parse the value as an integer
if (!isNaN(jumpTo)) {
let lastPage = Math.ceil(ttsList.length / itemsPerPage);
if (jumpTo >= 1 && jumpTo <= lastPage) {
currentPage = jumpTo;
updateUIList();
} else {
alert(`Please enter a valid page number between 1 and ${lastPage}`);
}
} else {
alert("Please enter a number to jump to.");
}
}
// Set up the event listener for both jump buttons
document.getElementById('jumpButton').addEventListener('click', handleJumpButtonClick);
document.getElementById('jumpButton1').addEventListener('click', handleJumpButtonClick);
// Event listener for changing play type // Event listener for changing play type
document.getElementById('playType').addEventListener('change', function () { document.getElementById('playType').addEventListener('change', function () {
isStreamingMode = this.value === 'stream'; isStreamingMode = this.value === 'stream';
@@ -1546,11 +1872,13 @@
adjustPlaybackAndChunkSize(savedPlayType); // Adjust selectability on page load adjustPlaybackAndChunkSize(savedPlayType); // Adjust selectability on page load
} }
// Initialize playback based on preference document.addEventListener('DOMContentLoaded', function () {
const savedPlayMode = localStorage.getItem('playMode'); const savedPlayMode = localStorage.getItem('playMode');
if (savedPlayMode) { if (savedPlayMode) {
document.getElementById('playMode').value = savedPlayMode; document.getElementById('playMode').value = savedPlayMode;
} }
playModeValue = savedPlayMode || 'local'; // Default to 'local' if nothing is saved
});
// Initialize chunk size based on preference // Initialize chunk size based on preference
const savedChunkSize = localStorage.getItem('chunkSize'); const savedChunkSize = localStorage.getItem('chunkSize');
@@ -1660,9 +1988,11 @@
window.onload = function () { window.onload = function () {
setupPage(); setupPage();
hideProgress(); // Ensure the progress indicator is hidden on page load hideProgress(); // Ensure the progress indicator is hidden on page load
if (window.location.protocol !== 'http:' && window.location.protocol !== 'https:') {
alert('AllTalk TTS Generator is not designed to be run from your disk folder. Please run it from the correct URL e.g. http://127.0.0.1:7851/static/tts_chunk_player/tts_chunk_player.html');
}
}; };
</script> </script>
</body> </body>
+121 -33
View File
@@ -57,6 +57,10 @@ params = load_config(configfile_path)
# check someone hasnt enabled lowvram on a system thats not cuda enabled # check someone hasnt enabled lowvram on a system thats not cuda enabled
params["low_vram"] = "false" if not torch.cuda.is_available() else params["low_vram"] params["low_vram"] = "false" if not torch.cuda.is_available() else params["low_vram"]
# Load values for temperature and repetition_penalty
temperature = params["local_temperature"]
repetition_penalty = params["local_repetition_penalty"]
# Define the path to the JSON file # Define the path to the JSON file
config_file_path = this_dir / "modeldownload.json" config_file_path = this_dir / "modeldownload.json"
@@ -81,6 +85,17 @@ else:
f"[{params['branding']}Startup] \033[91mWarning\033[0m modeldownload.config is missing so please re-download it and save it in the alltalk_tts main folder." f"[{params['branding']}Startup] \033[91mWarning\033[0m modeldownload.config is missing so please re-download it and save it in the alltalk_tts main folder."
) )
##################################################
#### 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 finetuned_model:
required_files = ["model.pth", "config.json", "vocab.json"]
finetuned_model = all((trained_model_directory / file).exists() for file in required_files)
######################## ########################
#### STARTUP CHECKS #### #### STARTUP CHECKS ####
@@ -98,19 +113,17 @@ except ModuleNotFoundError:
raise raise
# DEEPSPEED Import - Check for DeepSpeed and import it if it exists # DEEPSPEED Import - Check for DeepSpeed and import it if it exists
deepspeed_available = False
try: try:
import deepspeed import deepspeed
deepspeed_available = True
deepspeed_installed = True
print(f"[{params['branding']}Startup] DeepSpeed \033[93mDetected\033[0m")
print(
f"[{params['branding']}Startup] Activate DeepSpeed in {params['branding']} settings"
)
except ImportError: except ImportError:
deepspeed_installed = False pass
print( if deepspeed_available:
f"[{params['branding']}Startup] DeepSpeed \033[93mNot Detected\033[0m. See https://github.com/microsoft/DeepSpeed" print(f"[{params['branding']}Startup] DeepSpeed \033[93mDetected\033[0m")
) print(f"[{params['branding']}Startup] Activate DeepSpeed in {params['branding']}settings")
else:
print(f"[{params['branding']}Startup] DeepSpeed \033[93mNot Detected\033[0m. See https://github.com/microsoft/DeepSpeed")
@asynccontextmanager @asynccontextmanager
@@ -464,16 +477,16 @@ async def deepspeed(request: Request, new_deepspeed_value: bool):
######################## ########################
# TTS VOICE GENERATION METHODS (called from voice_preview and output_modifer) # TTS VOICE GENERATION METHODS (called from voice_preview and output_modifer)
async def generate_audio(text, voice, language, output_file, streaming=False): async def generate_audio(text, voice, language, temperature, repetition_penalty, output_file, streaming=False):
# Get the async generator from the internal function # Get the async generator from the internal function
response = generate_audio_internal(text, voice, language, output_file, streaming) response = generate_audio_internal(text, voice, language, temperature, repetition_penalty, output_file, streaming)
# If streaming, then return the generator as-is, otherwise just exhaust it and return # If streaming, then return the generator as-is, otherwise just exhaust it and return
if streaming: if streaming:
return response return response
async for _ in response: async for _ in response:
pass pass
async def generate_audio_internal(text, voice, language, output_file, streaming): async def generate_audio_internal(text, voice, language, temperature, repetition_penalty, output_file, streaming):
global model global model
if params["low_vram"] and device == "cpu": if params["low_vram"] and device == "cpu":
await switch_device() await switch_device()
@@ -495,9 +508,9 @@ async def generate_audio_internal(text, voice, language, output_file, streaming)
"language": language, "language": language,
"gpt_cond_latent": gpt_cond_latent, "gpt_cond_latent": gpt_cond_latent,
"speaker_embedding": speaker_embedding, "speaker_embedding": speaker_embedding,
"temperature": float(params["local_temperature"]), "temperature": float(temperature),
"length_penalty": float(model.config.length_penalty), "length_penalty": float(model.config.length_penalty),
"repetition_penalty": float(params["local_repetition_penalty"]), "repetition_penalty": float(repetition_penalty),
"top_k": int(model.config.top_k), "top_k": int(model.config.top_k),
"top_p": float(model.config.top_p), "top_p": float(model.config.top_p),
"enable_text_splitting": True "enable_text_splitting": True
@@ -551,9 +564,9 @@ async def generate_audio_internal(text, voice, language, output_file, streaming)
file_path=output_file, file_path=output_file,
speaker_wav=[f"{this_dir}/voices/{voice}"], speaker_wav=[f"{this_dir}/voices/{voice}"],
language=language, language=language,
temperature=float(params["local_temperature"]), temperature=temperature,
length_penalty=model.config.length_penalty, length_penalty=model.config.length_penalty,
repetition_penalty=float(params["local_repetition_penalty"]), repetition_penalty=repetition_penalty,
top_k=model.config.top_k, top_k=model.config.top_k,
top_p=model.config.top_p, top_p=model.config.top_p,
) )
@@ -593,10 +606,12 @@ async def generate(request: Request):
text = data["text"] text = data["text"]
voice = data["voice"] voice = data["voice"]
language = data["language"] language = data["language"]
temperature = data["temperature"]
repetition_penalty = data["repetition_penalty"]
output_file = data["output_file"] output_file = data["output_file"]
streaming = False streaming = False
# Generation logic # Generation logic
response = await generate_audio(text, voice, language, output_file, streaming) response = await generate_audio(text, voice, language, temperature, repetition_penalty, output_file, streaming)
if streaming: if streaming:
return StreamingResponse(response, media_type="audio/wav") return StreamingResponse(response, media_type="audio/wav")
return JSONResponse( return JSONResponse(
@@ -713,7 +728,7 @@ async def update_settings(
async def tts_demo_request_streaming(text: str, voice: str, language: str, output_file: str): async def tts_demo_request_streaming(text: str, voice: str, language: str, output_file: str):
try: try:
output_file_path = this_dir / "outputs" / output_file output_file_path = this_dir / "outputs" / output_file
stream = await generate_audio(text, voice, language, output_file_path, streaming=True) stream = await generate_audio(text, voice, language, temperature, repetition_penalty, output_file_path, streaming=True)
return StreamingResponse(stream, media_type="audio/wav") return StreamingResponse(stream, media_type="audio/wav")
except Exception as e: except Exception as e:
print(f"An error occurred: {e}") print(f"An error occurred: {e}")
@@ -723,12 +738,17 @@ async def tts_demo_request_streaming(text: str, voice: str, language: str, outpu
async def tts_demo_request(request: Request, text: str = Form(...), voice: str = Form(...), language: str = Form(...), output_file: str = Form(...)): async def tts_demo_request(request: Request, text: str = Form(...), voice: str = Form(...), language: str = Form(...), output_file: str = Form(...)):
try: try:
output_file_path = this_dir / "outputs" / output_file output_file_path = this_dir / "outputs" / output_file
await generate_audio(text, voice, language, output_file_path, streaming=False) await generate_audio(text, voice, language, temperature, repetition_penalty, output_file_path, streaming=False)
return JSONResponse(content={"output_file_path": str(output_file)}, status_code=200) return JSONResponse(content={"output_file_path": str(output_file)}, status_code=200)
except Exception as e: except Exception as e:
print(f"An error occurred: {e}") print(f"An error occurred: {e}")
return JSONResponse(content={"error": "An error occurred"}, status_code=500) return JSONResponse(content={"error": "An error occurred"}, status_code=500)
#####################
#### Audio feeds ####
#####################
# Gives web access to the output files # Gives web access to the output files
@app.get("/audio/{filename}") @app.get("/audio/{filename}")
async def get_audio(filename: str): async def get_audio(filename: str):
@@ -780,7 +800,7 @@ async def preview_voice(request: Request, voice: str = Form(...)):
# Generate the audio # Generate the audio
output_file_path = this_dir / "outputs" / f"{output_file_name}.wav" output_file_path = this_dir / "outputs" / f"{output_file_name}.wav"
await generate_audio(text, voice, language, output_file_path, streaming=False) await generate_audio(text, voice, language, temperature, repetition_penalty, output_file_path, streaming=False)
# Generate the URL # Generate the URL
output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav' output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav'
@@ -807,6 +827,35 @@ import uuid
import numpy as np import numpy as np
import soundfile as sf import soundfile as sf
import sys import sys
import hashlib
##############################
#### Streaming Generation ####
##############################
@app.get("/api/tts-generate-streaming", response_class=StreamingResponse)
async def tts_generate_streaming(text: str, voice: str, language: str, output_file: str):
try:
output_file_path = this_dir / "outputs" / output_file
stream = await generate_audio(text, voice, language, temperature, repetition_penalty, output_file_path, streaming=True)
return StreamingResponse(stream, media_type="audio/wav")
except Exception as e:
print(f"An error occurred: {e}")
return JSONResponse(content={"error": "An error occurred"}, status_code=500)
@app.post("/api/tts-generate-streaming", response_class=JSONResponse)
async def tts_generate_streaming(request: Request, text: str = Form(...), voice: str = Form(...), language: str = Form(...), output_file: str = Form(...)):
try:
output_file_path = this_dir / "outputs" / output_file
await generate_audio(text, voice, language, temperature, repetition_penalty, output_file_path, streaming=False)
return JSONResponse(content={"output_file_path": str(output_file)}, status_code=200)
except Exception as e:
print(f"An error occurred: {e}")
return JSONResponse(content={"error": "An error occurred"}, status_code=500)
##############################
#### Standard Generation ####
##############################
# Check for PortAudio library on Linux # Check for PortAudio library on Linux
try: try:
@@ -834,7 +883,7 @@ class Request(BaseModel):
pass pass
class JSONInput(BaseModel): class JSONInput(BaseModel):
text_input: str = Field(..., max_length=1000, description="text_input needs to be 1000 characters or less.") text_input: str = Field(..., max_length=2000, description="text_input needs to be 2000 characters or less.")
text_filtering: str = Field(..., pattern="^(none|standard|html)$", description="text_filtering needs to be 'none', 'standard' or 'html'.") 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.") 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_enabled: bool = Field(..., description="narrator_enabled needs to be true or false.")
@@ -936,8 +985,8 @@ def combine(output_file_timestamp, output_file_name, audio_files):
output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}_combined.wav' output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}_combined.wav'
else: else:
output_file_path = os.path.join(this_dir / "outputs" / f'{output_file_name}_combined.wav') 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' output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}_combined.wav'
output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}.wav' output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_combined.wav'
try: try:
sf.write(output_file_path, audio, samplerate=sample_rate) sf.write(output_file_path, audio, samplerate=sample_rate)
# Clean up unnecessary files # Clean up unnecessary files
@@ -1006,12 +1055,12 @@ async def tts_generate(
# Replace multiple exclamation marks, question marks, or other punctuation with a single instance # Replace multiple exclamation marks, question marks, or other punctuation with a single instance
cleaned_part = re.sub(r'([!?.])\1+', r'\1', part) cleaned_part = re.sub(r'([!?.])\1+', r'\1', part)
# Further clean to remove any other unwanted characters # Further clean to remove any other unwanted characters
cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\$]', '', cleaned_part) cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171]\$', '', cleaned_part)
# Remove all newline characters (single or multiple) # Remove all newline characters (single or multiple)
cleaned_part = re.sub(r'\n+', ' ', cleaned_part) cleaned_part = re.sub(r'\n+', ' ', cleaned_part)
output_file = this_dir / "outputs" / f"{output_file_name}_{uuid.uuid4()}_{int(time.time())}.wav" output_file = this_dir / "outputs" / f"{output_file_name}_{uuid.uuid4()}_{int(time.time())}.wav"
output_file_str = output_file.as_posix() output_file_str = output_file.as_posix()
response = await generate_audio(cleaned_part, voice_to_use, language, output_file_str, streaming) response = await generate_audio(cleaned_part, voice_to_use, language,temperature, repetition_penalty, output_file_str, streaming)
audio_path = output_file_str audio_path = output_file_str
audio_files_all_paragraphs.append(audio_path) audio_files_all_paragraphs.append(audio_path)
# Combine audio files across paragraphs # Combine audio files across paragraphs
@@ -1019,29 +1068,36 @@ async def tts_generate(
else: else:
if output_file_timestamp: if output_file_timestamp:
timestamp = int(time.time()) timestamp = int(time.time())
output_file_path = this_dir / "outputs" / f"{output_file_name}_{timestamp}.wav" # Generate a standard UUID
output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}_{timestamp}.wav' original_uuid = uuid.uuid4()
output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}.wav' # Hash the UUID using SHA-256
hash_object = hashlib.sha256(str(original_uuid).encode())
hashed_uuid = hash_object.hexdigest()
# Truncate to the desired length, for example, 16 characters
short_uuid = hashed_uuid[:5]
output_file_path = this_dir / "outputs" / f"{output_file_name}_{timestamp}{short_uuid}.wav"
output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}_{timestamp}{short_uuid}.wav'
output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}{short_uuid}.wav'
else: else:
output_file_path = this_dir / "outputs" / f"{output_file_name}.wav" output_file_path = this_dir / "outputs" / f"{output_file_name}.wav"
output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav' output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav'
output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}.wav' output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}.wav'
if text_filtering == "html": if text_filtering == "html":
cleaned_string = html.unescape(standard_filtering(text_input)) cleaned_string = html.unescape(standard_filtering(text_input))
cleaned_string = re.sub(r'([!?.])\1+', r'\1', text_input) cleaned_string = re.sub(r'([!?.])\1+', r'\1', text_input)
# Further clean to remove any other unwanted characters # Further clean to remove any other unwanted characters
cleaned_string = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\$]', '', cleaned_string) cleaned_string = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171]\$', '', cleaned_string)
# Remove all newline characters (single or multiple) # Remove all newline characters (single or multiple)
cleaned_string = re.sub(r'\n+', ' ', cleaned_string) cleaned_string = re.sub(r'\n+', ' ', cleaned_string)
elif text_filtering == "standard": elif text_filtering == "standard":
cleaned_string = re.sub(r'([!?.])\1+', r'\1', text_input) cleaned_string = re.sub(r'([!?.])\1+', r'\1', text_input)
# Further clean to remove any other unwanted characters # Further clean to remove any other unwanted characters
cleaned_string = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171\$]', '', cleaned_string) cleaned_string = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"\u0400-\u04FFÀ-ÿ\u0150\u0151\u0170\u0171]\$', '', cleaned_string)
# Remove all newline characters (single or multiple) # Remove all newline characters (single or multiple)
cleaned_string = re.sub(r'\n+', ' ', cleaned_string) cleaned_string = re.sub(r'\n+', ' ', cleaned_string)
else: else:
cleaned_string = text_input cleaned_string = text_input
response = await generate_audio(cleaned_string, character_voice_gen, language, output_file_path, streaming) response = await generate_audio(cleaned_string, character_voice_gen, language, temperature, repetition_penalty, output_file_path, streaming)
if sounddevice_installed == False or streaming == True: if sounddevice_installed == False or streaming == True:
autoplay = False autoplay = False
if autoplay: if autoplay:
@@ -1053,6 +1109,38 @@ async def tts_generate(
return JSONResponse(content={"status": "generate-failure", "error": "An error occurred"}, status_code=500) return JSONResponse(content={"status": "generate-failure", "error": "An error occurred"}, status_code=500)
##########################
#### Current Settings ####
##########################
# Define the available models
models_available = [
{"name": "Coqui", "model_name": "API TTS"},
{"name": "Coqui", "model_name": "API Local"},
{"name": "Coqui", "model_name": "XTTSv2 Local"}
]
@app.get('/api/currentsettings')
def get_current_settings():
# Determine the current model loaded
if params["tts_method_api_tts"]:
current_model_loaded = "API TTS"
elif params["tts_method_api_local"]:
current_model_loaded = "API Local"
elif params["tts_method_xtts_local"]:
current_model_loaded = "XTTSv2 Local"
else:
current_model_loaded = None # or a default value if no method is active
settings = {
"models_available": models_available,
"current_model_loaded": current_model_loaded,
"deepspeed_available": deepspeed_available,
"deepspeed_status": params["deepspeed_activate"],
"low_vram_status": params["low_vram"],
"finetuned_model": finetuned_model
}
return settings # Automatically converted to JSON by Fas
############################# #############################
#### Word Add-in Sharing #### #### Word Add-in Sharing ####
############################# #############################