├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── VoiceCraftAPI.py ├── install.sh ├── install_voicecraftapi.sh ├── requirements.txt ├── run_api.sh ├── uninstall.sh └── voicecraft-api.service /.gitignore: -------------------------------------------------------------------------------- 1 | VoiceCraft/ 2 | conda/ 3 | voices/ 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | cover/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | .pybuilder/ 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | # For a library or package, you might want to ignore these files since the code is 91 | # intended to run in multiple environments; otherwise, check them in: 92 | # .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # poetry 102 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 103 | # This is especially recommended for binary packages to ensure reproducibility, and is more 104 | # commonly ignored for libraries. 105 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 106 | #poetry.lock 107 | 108 | # pdm 109 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 110 | #pdm.lock 111 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 112 | # in version control. 113 | # https://pdm.fming.dev/#use-with-ide 114 | .pdm.toml 115 | 116 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 117 | __pypackages__/ 118 | 119 | # Celery stuff 120 | celerybeat-schedule 121 | celerybeat.pid 122 | 123 | # SageMath parsed files 124 | *.sage.py 125 | 126 | # Environments 127 | .env 128 | .venv 129 | env/ 130 | venv/ 131 | ENV/ 132 | env.bak/ 133 | venv.bak/ 134 | 135 | # Spyder project settings 136 | .spyderproject 137 | .spyproject 138 | 139 | # Rope project settings 140 | .ropeproject 141 | 142 | # mkdocs documentation 143 | /site 144 | 145 | # mypy 146 | .mypy_cache/ 147 | .dmypy.json 148 | dmypy.json 149 | 150 | # Pyre type checker 151 | .pyre/ 152 | 153 | # pytype static type analyzer 154 | .pytype/ 155 | 156 | # Cython debug symbols 157 | cython_debug/ 158 | 159 | # PyCharm 160 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 161 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 162 | # and can be added to the global gitignore or merged into this file. For a more nuclear 163 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 164 | #.idea/ 165 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use an official Ubuntu runtime as the base image 2 | FROM ubuntu:latest 3 | 4 | # Set the working directory in the container 5 | WORKDIR /app 6 | 7 | # Install necessary apt packages, including sudo 8 | RUN apt-get update && apt-get install -y \ 9 | git \ 10 | wget \ 11 | sudo 12 | 13 | # Create a new user called "docker" and add it to the sudo group 14 | RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo 15 | 16 | # Copy the VoiceCraftAPI files to the working directory 17 | COPY . . 18 | 19 | # Make the install_voicecraftapi.sh and run_api.sh scripts executable 20 | RUN chmod +x install_voicecraftapi.sh run_api.sh 21 | 22 | # Allow the "docker" user to run sudo commands without a password prompt 23 | RUN echo "docker ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers 24 | 25 | # Switch to the "docker" user 26 | USER docker 27 | 28 | # Execute the install_voicecraftapi.sh script as the "docker" user 29 | RUN sudo bash ./install_voicecraftapi.sh 30 | 31 | # Expose the port on which the API will run (adjust if needed) 32 | EXPOSE 8245 33 | 34 | # Set the command to run the run_api.sh script as the "docker" user 35 | CMD ["sudo", "bash", "./run_api.sh"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VoiceCraft API 2 | 3 | This is a API for the extremely awesome [VoiceCraft](https://github.com/jasonppy/VoiceCraft) repository. The API allows you to generate voices from a single example .wav file and generate text using those voices. 4 | 5 | ## Installing 6 | 7 | Currently, the API is only natively supported on Ubuntu/Debian systems, but that may change in the future if enough people want other distributions. Alternatively, the API can be run on Windows / macOS using Docker. 8 | 9 | ### Automatic 10 | 11 | The VoiceCraft API can easily be installed (on ubuntu/debian) by running the following command: 12 | 13 | ```bash 14 | curl -fsSL https://raw.github.com/CalvesGEH/VoiceCraftAPI/main/install.sh | sh 15 | ``` 16 | 17 | This will download and run the installation script which will create a new user `voicecraftapi` and configure the API, VoiceCraft and a systemd service that will run on startup. You need `SUDO` access to run this as it needs to install packages and create the systemd service. 18 | 19 | ### Manual/Development 20 | 21 | The VoiceCraft API can also be built manually for either development or whatever other reason. 22 | 23 | ```bash 24 | git clone https://github.com/CalvesGEH/VoiceCraftAPI.git 25 | cd VoiceCraftAPI 26 | ./install_voicecraftapi.sh 27 | # you can then run the api if desired 28 | ./run_api.sh 29 | ``` 30 | 31 | Once installed, you can also manually edit and install the systemd service. 32 | 33 | ### Docker 34 | VoiceCraft API is compatible with Windows / macOS via Docker. Run the commands below to start the server: 35 | ```bash 36 | docker build -t voicecraft-api . 37 | docker run -p 8245:8245 --name voicecraft-api voicecraft-api 38 | ``` 39 | 40 | The API will be accessible on http://localhost:8245. 41 | 42 | Note for Windows users: You may need to change `install_voicecraftapi.sh` and `run_api.sh` from a CRLF to an LF End of Line Sequence format to allow the Dockerfile to read these files correctly. 43 | 44 | ## Uninstalling 45 | 46 | I have also provided a script which will uninstall VoiceCraftAPI except for the APT packages required, those can be manually uninstalled if you'd like. 47 | 48 | ```bash 49 | curl -fsSL https://raw.github.com/CalvesGEH/VoiceCraftAPI/main/uninstall.sh | sh 50 | ``` 51 | 52 | ## API Calls 53 | 54 | The API only exposes a couple of endpoints and all of these endpoints can be tested/accessed from `http://:8245/docs`. This `/docs` endpoint also includes information about each endpoint and is usually a good place to start if you are confused. 55 | 56 | ### /newvoice 57 | 58 | This endpoint creates a new voice from a given .wav audio file and optional configuration parameters. The .wav file should be following be ~6-12s and be 16000Hz. The name of the new voice will be exactly matched the name of the .wav file (`frank.wav` will create voice `frank`). 59 | 60 | You can include a transcript but if one is not given, the API will automatically transcribe it for you. I've never not had it be correct but you can check the logs if you think it's wrong. 61 | 62 | ### /voicelist 63 | 64 | This endpoint simply returns a list of all available voices for inference. 65 | 66 | ### /editvoice/{voice} 67 | 68 | This endpoint will edit the saved inference parameters of a voice. Check out your server's `/docs` endpoint for available parameters. 69 | 70 | ### /generateaudio/{voice} 71 | 72 | This endpoint will generate audio as the given voice using the `target_text` given. It will return a .wav audio file streaming response. 73 | 74 | ## Examples 75 | 76 | It is extremely simple to use once the API is up and running. I start by finding a suitable voice clip for the character I want to clone and then edit the file to ensure it is a .wav at 16000Hz. Then, I navigate to `http://:8245/docs` and test the `/newvoice` endpoint directly in the browser, giving it my .wav file and then executing the request. Now that the voice is generated, I can make a request to the server to generate text. 77 | 78 | ```bash 79 | curl --output generated.wav -d "target_text=It is crazy how easy it is to use VoiceCraft api!" http://:8245/generateaudio/ 80 | ``` -------------------------------------------------------------------------------- /VoiceCraftAPI.py: -------------------------------------------------------------------------------- 1 | # Generic imports 2 | import sys 3 | sys.path.append("./VoiceCraft") # Append VoiceCraft folder to fix python import 4 | import os 5 | import logging as logger 6 | 7 | # VoiceCraft imports 8 | import torch 9 | import torchaudio 10 | from data.tokenizer import ( 11 | AudioTokenizer, 12 | TextTokenizer, 13 | ) 14 | from models import voicecraft 15 | import io 16 | import numpy as np 17 | import random 18 | import re 19 | import uuid 20 | 21 | # API imports 22 | from fastapi import FastAPI, File, UploadFile, Form 23 | from starlette.responses import StreamingResponse 24 | import subprocess 25 | import json 26 | import shutil 27 | 28 | # Configure logging 29 | logger.basicConfig(level=logger.DEBUG, 30 | format='%(asctime)s - %(levelname)s - %(message)s', 31 | handlers=[ 32 | logger.FileHandler('api.log'), 33 | logger.StreamHandler() 34 | ]) 35 | 36 | ############################ 37 | # API Variables # 38 | ############################ 39 | 40 | app = FastAPI() 41 | 42 | VOICES_PATH = os.getenv("VOICES_PATH", "./voices") 43 | 44 | ############################ 45 | # VoiceCraft Variables # 46 | ############################ 47 | 48 | DEMO_PATH = os.getenv("DEMO_PATH", "./VoiceCraft/demo") 49 | TMP_PATH = os.getenv("TMP_PATH", "./VoiceCraft/demo/temp") 50 | MODELS_PATH = os.getenv("MODELS_PATH", "./VoiceCraft/pretrained_models") 51 | device = "cuda" if torch.cuda.is_available() else "cpu" 52 | whisper_model, align_model, voicecraft_model = None, None, None 53 | 54 | ############################ 55 | # VoiceCraft Functions # 56 | ############################ 57 | 58 | def get_random_string(): 59 | return "".join(str(uuid.uuid4()).split("-")) 60 | 61 | 62 | def seed_everything(seed): 63 | if seed != -1: 64 | os.environ['PYTHONHASHSEED'] = str(seed) 65 | random.seed(seed) 66 | np.random.seed(seed) 67 | torch.manual_seed(seed) 68 | torch.cuda.manual_seed(seed) 69 | torch.backends.cudnn.benchmark = False 70 | torch.backends.cudnn.deterministic = True 71 | 72 | 73 | class WhisperxAlignModel: 74 | def __init__(self): 75 | from whisperx import load_align_model 76 | self.model, self.metadata = load_align_model(language_code="en", device=device) 77 | 78 | def align(self, segments, audio_path): 79 | from whisperx import align, load_audio 80 | audio = load_audio(audio_path) 81 | return align(segments, self.model, self.metadata, audio, device, return_char_alignments=False)["segments"] 82 | 83 | 84 | class WhisperModel: 85 | def __init__(self, model_name): 86 | from whisper import load_model 87 | self.model = load_model(model_name, device) 88 | 89 | from whisper.tokenizer import get_tokenizer 90 | tokenizer = get_tokenizer(multilingual=False) 91 | self.supress_tokens = [-1] + [ 92 | i 93 | for i in range(tokenizer.eot) 94 | if all(c in "0123456789" for c in tokenizer.decode([i]).removeprefix(" ")) 95 | ] 96 | 97 | def transcribe(self, audio_path): 98 | return self.model.transcribe(audio_path, suppress_tokens=self.supress_tokens, word_timestamps=True)["segments"] 99 | 100 | 101 | class WhisperxModel: 102 | def __init__(self, model_name, align_model: WhisperxAlignModel): 103 | from whisperx import load_model 104 | possible_compute_types = ["float16", "float32", "int8"] 105 | for type in possible_compute_types: 106 | try: 107 | logger.debug(f"Trying to create a whisperx model using {type}.") 108 | self.model = load_model(model_name, device, compute_type=type, asr_options={"suppress_numerals": True, "max_new_tokens": None, "clip_timestamps": None, "hallucination_silence_threshold": None}) 109 | logger.debug(f"Created whisperx model using {type}.") 110 | break 111 | except ValueError as err: 112 | logger.warning(f"Caught Exception while creating WhisperxModel: {err.args[0]}") 113 | if type == possible_compute_types[-1]: 114 | # If we went through all types, forward error. 115 | raise ValueError(err.args[0]) 116 | self.align_model = align_model 117 | 118 | def transcribe(self, audio_path): 119 | segments = self.model.transcribe(audio_path, batch_size=8)["segments"] 120 | return self.align_model.align(segments, audio_path) 121 | 122 | # Parameters: 123 | # whisper_backend_name: 'whisper' or 'whisperX'. 'whisperX' is default. 124 | # whisper_mode_name: 'None', 'base.en', 'small.en', 'medium.en', 'large'. 'base.en' is default. 125 | # alignment_mode_name: 'None'or 'whisperX'. 'whisperX' is default. 126 | # voicecraft_model: 127 | # - 'giga330M' 128 | # - 'giga830M' 129 | # - 'giga330M_TTSEnhanced' 130 | # - '830M_TTSEnhanced.pth' (default) 131 | def load_models(whisper_backend_name, whisper_model_name, alignment_model_name, voicecraft_model_name): 132 | global transcribe_model, align_model, voicecraft_model 133 | 134 | if voicecraft_model_name == "giga330M_TTSEnhanced": 135 | voicecraft_model_name = "gigaHalfLibri330M_TTSEnhanced_max16s" 136 | 137 | if alignment_model_name is not None: 138 | align_model = WhisperxAlignModel() 139 | 140 | if whisper_model_name is not None: 141 | if whisper_backend_name == "whisper": 142 | transcribe_model = WhisperModel(whisper_model_name) 143 | else: 144 | if align_model is None: 145 | logger.error("Align model required for whisperx backend.") 146 | return False 147 | transcribe_model = WhisperxModel(whisper_model_name, align_model) 148 | 149 | model = voicecraft.VoiceCraft.from_pretrained(f'pyp1/VoiceCraft_{voicecraft_model_name}') 150 | phn2num = model.args.phn2num 151 | config = model.args 152 | model.to(device) 153 | 154 | encodec_fn = f"{MODELS_PATH}/encodec_4cb2048_giga.th" 155 | if not os.path.exists(encodec_fn): 156 | os.system(f"wget https://huggingface.co/pyp1/VoiceCraft/resolve/main/encodec_4cb2048_giga.th") 157 | os.system(f"mv encodec_4cb2048_giga.th {encodec_fn}") 158 | 159 | voicecraft_model = { 160 | "config": config, 161 | "phn2num": phn2num, 162 | "model": model, 163 | "text_tokenizer": TextTokenizer(backend="espeak"), 164 | "audio_tokenizer": AudioTokenizer(signature=encodec_fn) 165 | } 166 | return True 167 | 168 | 169 | def get_transcribe_state(segments): 170 | words_info = [word_info for segment in segments for word_info in segment["words"]] 171 | return { 172 | "segments": segments, 173 | "transcript": " ".join([segment["text"] for segment in segments]), 174 | "words_info": words_info, 175 | "transcript_with_start_time": " ".join([f"{word['start']} {word['word']}" for word in words_info]), 176 | "transcript_with_end_time": " ".join([f"{word['word']} {word['end']}" for word in words_info]), 177 | "word_bounds": [f"{word['start']} {word['word']} {word['end']}" for word in words_info] 178 | } 179 | 180 | 181 | def transcribe(seed, audio_path): 182 | if transcribe_model is None: 183 | logger.error("Transcription model not loaded. Please load models first.") 184 | return False 185 | seed_everything(seed) 186 | 187 | segments = transcribe_model.transcribe(audio_path) 188 | state = get_transcribe_state(segments) 189 | 190 | return state 191 | 192 | 193 | def align_segments(transcript, audio_path, voice): 194 | from aeneas.executetask import ExecuteTask 195 | from aeneas.task import Task 196 | import json 197 | logger.debug("Aligning segments...") 198 | config_string = 'task_language=eng|os_task_file_format=json|is_text_type=plain' 199 | 200 | transcript_path = os.path.join(VOICES_PATH, f"{voice}.txt") 201 | sync_map_path = os.path.join(VOICES_PATH, f"{voice}.json") 202 | with open(transcript_path, "w") as f: 203 | f.write(transcript) 204 | 205 | task = Task(config_string=config_string) 206 | task.audio_file_path_absolute = os.path.abspath(audio_path) 207 | task.text_file_path_absolute = os.path.abspath(transcript_path) 208 | task.sync_map_file_path_absolute = os.path.abspath(sync_map_path) 209 | ExecuteTask(task).execute() 210 | task.output_sync_map_file() 211 | 212 | logger.debug(f'Saved alignment files to {transcript_path} and {sync_map_path}.') 213 | 214 | logger.debug("Finished aligning segments. Returning sync_map as json.") 215 | with open(sync_map_path, "r") as f: 216 | return json.load(f) 217 | 218 | 219 | def align(seed, transcript, audio_path, voice): 220 | if align_model is None: 221 | logger.error("Align model not loaded") 222 | return False 223 | seed_everything(seed) 224 | 225 | fragments = align_segments(transcript, audio_path, voice) 226 | segments = [{ 227 | "start": float(fragment["begin"]), 228 | "end": float(fragment["end"]), 229 | "text": " ".join(fragment["lines"]) 230 | } for fragment in fragments["fragments"]] 231 | segments = align_model.align(segments, audio_path) 232 | state = get_transcribe_state(segments) 233 | 234 | return state 235 | 236 | 237 | def get_output_audio(audio_tensors, codec_audio_sr): 238 | result = torch.cat(audio_tensors, 1) 239 | buffer = io.BytesIO() 240 | torchaudio.save(buffer, result, int(codec_audio_sr), format="wav") 241 | buffer.seek(0) 242 | return buffer 243 | 244 | 245 | # Parameters: 246 | # seed: Random seed 247 | # top_k: 248 | # top_p 249 | # temperature 250 | # stop_repetition 251 | # sample_batch_size 252 | # kvcache 253 | # audio_path 254 | # transcribe_state 255 | # transcript 256 | # smart_transcript: Whether or not to create the target transcript automatically. If disabled, you need to supply the transcript. 257 | # prompt_end_time: End time of the last message of the transcript. Float. 258 | # split_text: How to split the transcript. Only applies to 'Long TTS' mode. Options: 'Newline', 'Sentence'. 259 | def generate(seed, top_k, top_p, temperature, stop_repetition, sample_batch_size, 260 | kvcache, audio_path, transcribe_state, transcript, smart_transcript, 261 | prompt_end_time, 262 | codec_audio_sr=16000, codec_sr=50, silence_tokens=[1388, 1898, 131] # Codec specific options 263 | ): 264 | if voicecraft_model is None: 265 | logger.error("VoiceCraft model not loaded.") 266 | return False 267 | if smart_transcript and (transcribe_state is None): 268 | logger.error("Can't use smart transcript: whisper transcript not found.") 269 | return False 270 | 271 | seed_everything(seed) 272 | 273 | if type(transcript) == str: 274 | logger.debug(f'Given transcript is a string, separating by sentences into a list.') 275 | punctuation_regex = r'[!.?]+\s*' 276 | transcript = transcript.strip('"').strip('\\').strip('*') 277 | transcript = re.sub(punctuation_regex, '?\\n', transcript) 278 | transcript = re.sub(punctuation_regex, '.\\n', transcript) 279 | transcript = re.sub(punctuation_regex, '!\\n', transcript) 280 | sentences = transcript.split('\n') 281 | # Delete last item in list if empty 282 | if not sentences[-1].strip(): 283 | del sentences[-1] 284 | elif type(transcript) == list: 285 | for i in range(len(transcript)): 286 | transcript[i] = transcript[i].strip('"').strip('\\').strip('*') 287 | sentences = transcript 288 | 289 | logger.debug(f'Generated sentences: {sentences}') 290 | 291 | info = torchaudio.info(audio_path) 292 | audio_dur = info.num_frames / info.sample_rate 293 | 294 | audio_tensors = [] 295 | inference_transcript = "" 296 | for sentence in sentences: 297 | decode_config = {"top_k": top_k, "top_p": top_p, "temperature": temperature, "stop_repetition": stop_repetition, 298 | "kvcache": kvcache, "codec_audio_sr": codec_audio_sr, "codec_sr": codec_sr, 299 | "silence_tokens": silence_tokens, "sample_batch_size": sample_batch_size} 300 | 301 | from inference_tts_scale import inference_one_sample 302 | 303 | if smart_transcript: 304 | target_transcript = "" 305 | for word in transcribe_state["words_info"]: 306 | if word["end"] < prompt_end_time: 307 | target_transcript += word["word"] + (" " if word["word"][-1] != " " else "") 308 | elif (word["start"] + word["end"]) / 2 < prompt_end_time: 309 | # include part of the word it it's big, but adjust prompt_end_time 310 | target_transcript += word["word"] + (" " if word["word"][-1] != " " else "") 311 | prompt_end_time = word["end"] 312 | break 313 | else: 314 | break 315 | target_transcript += f" {sentence}" 316 | else: 317 | target_transcript = sentence 318 | 319 | logger.debug(f'Created target_transcript: {target_transcript}') 320 | 321 | inference_transcript += target_transcript + "\n" 322 | 323 | prompt_end_frame = int(min(audio_dur, prompt_end_time) * info.sample_rate) 324 | _, gen_audio = inference_one_sample(voicecraft_model["model"], 325 | voicecraft_model["config"], 326 | voicecraft_model["phn2num"], 327 | voicecraft_model["text_tokenizer"], voicecraft_model["audio_tokenizer"], 328 | audio_path, target_transcript, device, decode_config, 329 | prompt_end_frame) 330 | 331 | gen_audio = gen_audio[0].cpu() 332 | audio_tensors.append(gen_audio) 333 | 334 | output_audio = get_output_audio(audio_tensors, codec_audio_sr) 335 | return output_audio, inference_transcript, audio_tensors 336 | 337 | 338 | ############################ 339 | # API Functions # 340 | ############################ 341 | 342 | @app.post("/newvoice") 343 | async def generate__or_update_voice( 344 | audio: UploadFile = File(...), 345 | transcript: UploadFile = None, 346 | top_k: int = Form(0), 347 | top_p: float = Form(0.8), 348 | temperature: float = Form(1.0), 349 | stop_repetition: int = Form(3), 350 | kvcache: int = Form(1), 351 | sample_batch_size: int = Form(3), 352 | seed: int = Form(-1) # Random Seed 353 | ): 354 | logger.info("Received request to generate new voice.") 355 | 356 | # Convert to all lower to keep consistency 357 | voice = os.path.splitext(audio.filename)[0].lower() 358 | 359 | # Create the voice folder 360 | voice_folder = f"{VOICES_PATH}/{voice}" 361 | logger.debug(f"Creating voice folder: {voice_folder}") 362 | os.makedirs(voice_folder, exist_ok=True) 363 | 364 | audio_fn = os.path.join(voice_folder, audio.filename) 365 | logger.debug(f'Saving audio file to {audio_fn}') 366 | with open(audio_fn, "wb") as f: 367 | shutil.copyfileobj(audio.file, f) 368 | 369 | # If we were not given a transcript, we can transcribe using the whisper model. 370 | if transcript == None: 371 | logger.debug('Did not receive a transcription. Transcribing using whisper model.') 372 | transcribe_state = transcribe(seed, audio_fn) 373 | else: 374 | transcript_text = await transcript.read() 375 | transcript_text = transcript_text.decode('utf-8').replace("\r\n", " ").replace("\n", " ").replace("\r", " ") 376 | logger.debug(f"Aligning {voice} transcript.") 377 | transcribe_state = align(seed, transcript_text, audio_fn, voice) 378 | 379 | logger.debug(f"Saving {voice} alignment to {voice_folder}/{voice}_alignment.json") 380 | with open(f'{voice_folder}/{voice}_alignment.json', 'w') as alignment_file: 381 | json.dump(transcribe_state, alignment_file, indent=4) 382 | 383 | logger.info(f"Saving the voice settings to {voice}_options.json") 384 | options = { 385 | "top_k": top_k, 386 | "top_p": top_p, 387 | "temperature": temperature, 388 | "stop_repetition": stop_repetition, 389 | "kvcache": kvcache, 390 | "sample_batch_size": sample_batch_size, 391 | "seed": seed 392 | } 393 | with open(f'{VOICES_PATH}/{voice}/{voice}_options.json', 'w') as options_file: 394 | json.dump(options, options_file, indent=4) 395 | 396 | return {"message": f"{voice} voice generated successfully."} 397 | 398 | @app.get("/voicelist") 399 | async def get_voices(): 400 | # Read all of the folders from VOICES_PATH and return them in a list. 401 | retList = [] 402 | for folder in os.listdir(VOICES_PATH): 403 | if os.path.isdir(os.path.join(VOICES_PATH, folder)): 404 | retList.append(folder) 405 | return {"voices": retList} 406 | 407 | @app.post("/editvoice/{voice}") 408 | async def edit_voice_config( 409 | voice: str, 410 | time: float = None, 411 | top_k: int = None, 412 | top_p: float = None, 413 | temperature: float = None, 414 | stop_repetition: int = None, 415 | kvcache: int = None, 416 | sample_batch_size: int = None, 417 | seed: int = None 418 | ): 419 | # Check to see if the voice exists 420 | if not os.path.exists(f'{VOICES_PATH}/{voice}'): 421 | return {"message": f"Given voice '{voice}' does not exist.", "status_code": 404} 422 | 423 | # Parse json, update values that aren't 'None', then write values back to json file 424 | options_file = f'{VOICES_PATH}/{voice}/{voice}_options.json' 425 | with open(options_file, 'r') as f: 426 | new_options = json.load(f) 427 | 428 | if time is not None: 429 | new_options["time"] = time 430 | if top_k is not None: 431 | new_options["top_k"] = top_k 432 | if top_p is not None: 433 | new_options["top_p"] = top_p 434 | if temperature is not None: 435 | new_options["temperature"] = temperature 436 | if stop_repetition is not None: 437 | new_options["stop_repetition"] = stop_repetition 438 | if kvcache is not None: 439 | new_options["kvcache"] = kvcache 440 | if sample_batch_size is not None: 441 | new_options["sample_batch_size"] = sample_batch_size 442 | if seed is not None: 443 | new_options["seed"] = seed 444 | 445 | # Re-write the JSON file 446 | with open(options_file, "w") as f: 447 | json.dump(new_options, f, indent=4) 448 | 449 | 450 | @app.post("/generateaudio/{voice}") 451 | async def generate_voice_audio( 452 | voice: str, 453 | target_text: str = Form(...), 454 | device: str = Form(None), 455 | ): 456 | if not os.path.exists(f'{VOICES_PATH}/{voice}/{voice}.wav'): 457 | logger.error(f'Missing the {voice}.wav file when generating audio. Returning error message and cancelling API call to /generateaudio/{voice}.') 458 | return {"message": "Missing the {voice}.wav file! Please recreate the voice using the /newvoice endpoint.", "status_code": 500} 459 | if not os.path.exists(f'{VOICES_PATH}/{voice}/{voice}_options.json'): 460 | logger.error(f'Missing the {voice}_options.json file when generating audio. Returning error message and cancelling API call to /generateaudio/{voice}.') 461 | return {"message": "Missing the {voice}_options.json file! Please recreate the voice using the /newvoice endpoint.", "status_code": 500} 462 | if not os.path.exists(f'{VOICES_PATH}/{voice}/{voice}_alignment.json'): 463 | logger.error(f'Missing the {voice}_alignment.jsonfile when generating audio. Returning error message and cancelling API call to /generateaudio/{voice}.') 464 | return {"message": "Missing the {voice}_alignment.json file! Please recreate the voice using the /newvoice endpoint.", "status_code": 500} 465 | 466 | prompt_end_time = None 467 | if os.path.exists(f'{VOICES_PATH}/{voice}/{voice}.json'): 468 | logger.debug('sync_map_file exists, using it for the prompt end time.') 469 | with open(f'{VOICES_PATH}/{voice}/{voice}.json', 'r') as f: 470 | sync_map = json.load(f) # The sync_map only ever has a single fragment in it because we replace all newlines with spaces. 471 | prompt_end_time = sync_map['fragments'][-1]['end'] 472 | else: 473 | logger.debug('sync_map_file does not exist, grabbing prompt end time from the alignment file.') 474 | 475 | # Load in transcribe_state, voice_options and sync_map 476 | with open(f'{VOICES_PATH}/{voice}/{voice}_options.json', 'r') as f: 477 | options = json.load(f) 478 | with open(f'{VOICES_PATH}/{voice}/{voice}_alignment.json', 'r') as f: 479 | transcribe_state = json.load(f) 480 | if not prompt_end_time: 481 | prompt_end_time = transcribe_state['segments'][-1]['end'] # Grab the last segment's end time 482 | 483 | logger.debug(f'''Generating audio using the following parameters: 484 | seed: {options['seed']} 485 | top_k: {options['top_k']} 486 | top_p: {options['top_p']} 487 | temperature: {options['temperature']} 488 | stop_repetition: {options['stop_repetition']} 489 | sample_batch_size: {options['sample_batch_size']} 490 | kvcache: {options['kvcache']} 491 | target_text: {target_text} 492 | prompt_end_time: {prompt_end_time} 493 | ''') 494 | 495 | output_audio, inference_transcript, audio_tensors = generate(options['seed'], options['top_k'], 496 | options['top_p'], options['temperature'], 497 | options['stop_repetition'], options['sample_batch_size'], 498 | options['kvcache'], f'{VOICES_PATH}/{voice}/{voice}.wav', 499 | transcribe_state, target_text, True, prompt_end_time) 500 | 501 | # Serve the generated bytesIO object 502 | return StreamingResponse(output_audio, media_type="audio/wav") 503 | 504 | if __name__ == "__main__": 505 | import uvicorn 506 | logger.info("Loading models...") 507 | load_models('whisperX', 'base.en', 'whisperX', '830M_TTSEnhanced') 508 | 509 | logger.info("Starting uvicorn server...") 510 | uvicorn.run(app, host="0.0.0.0", port=8245) 511 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | info() { 4 | echo -e "[$(date '+%H:%M:%S')]\033[32m[INFO]\033[0m ${@}" 5 | } 6 | error() { 7 | echo -e "[$(date '+%H:%M:%S')]\033[31m[ERROR]\033[0m ${@}" 8 | } 9 | warning() { 10 | echo -e "[$(date '+%H:%M:%S')]\033[33m[WARNING]\033[0m ${@}" 11 | } 12 | 13 | install_apt_packages() { 14 | # Install all packages from VoiceCraft README: https://github.com/jasonppy/VoiceCraft 15 | info "Installing apt packages..." 16 | sudo apt-get update 17 | sudo apt-get install -y git 18 | sudo apt-get install -y ffmpeg 19 | sudo apt-get install -y espeak-ng 20 | sudo apt-get install -y espeak espeak-data libespeak1 libespeak-dev 21 | sudo apt-get install -y festival* 22 | sudo apt-get install -y build-essential 23 | sudo apt-get install -y flac libasound2-dev libsndfile1-dev vorbis-tools 24 | sudo apt-get install -y libxml2-dev libxslt-dev zlib1g-dev 25 | } 26 | 27 | create_voicecraftapi_user() { 28 | if ! id voicecraftapi >/dev/null 2>&1; then 29 | info "Creating voicecraftapi user." 30 | sudo useradd -r -U -m -d /usr/share/voicecraftapi voicecraftapi 31 | fi 32 | } 33 | 34 | configure_systemd() { 35 | info "Creating systemd service." 36 | sudo cp /usr/share/voicecraftapi/VoiceCraftAPI/voicecraft-api.service /etc/systemd/system/voicecraft-api.service 37 | sudo systemctl daemon-reload 38 | sudo systemctl enable --now voicecraft-api.service 39 | } 40 | 41 | info "Please input your password so that the script can use sudo to configure." 42 | sudo -v 43 | while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & 44 | 45 | install_apt_packages 46 | 47 | create_voicecraftapi_user 48 | 49 | # Login as user 50 | sudo -i -u voicecraftapi /bin/bash << EOF 51 | cd ~/ 52 | if [ -d "$(basename https://github.com/CalvesGEH/VoiceCraftAPI .git)" ]; then 53 | echo "Directory exists, pulling latest changes..." 54 | cd $(basename https://github.com/CalvesGEH/VoiceCraftAPI .git) && git pull origin master 55 | else 56 | echo "Cloning repository..." 57 | git clone https://github.com/CalvesGEH/VoiceCraftAPI && cd $(basename https://github.com/CalvesGEH/VoiceCraftAPI .git) 58 | fi 59 | ./install_voicecraftapi.sh --skip-apt 60 | EOF 61 | 62 | configure_systemd -------------------------------------------------------------------------------- /install_voicecraftapi.sh: -------------------------------------------------------------------------------- 1 | ###################### 2 | # Variables # 3 | ###################### 4 | 5 | # Folder path to script 6 | VOICECRAFTAPI_PATH="$(dirname "$(readlink -f "${0}")")" 7 | CONDA_PATH="${VOICECRAFTAPI_PATH}/conda" 8 | CONDA_BINARY="${CONDA_PATH}/bin/conda" 9 | 10 | ###################### 11 | # Functions # 12 | ###################### 13 | 14 | info() { 15 | echo -e "[$(date '+%H:%M:%S')]\033[32m[INFO]\033[0m ${@}" 16 | } 17 | error() { 18 | echo -e "[$(date '+%H:%M:%S')]\033[31m[ERROR]\033[0m ${@}" 19 | } 20 | warning() { 21 | echo -e "[$(date '+%H:%M:%S')]\033[33m[WARNING]\033[0m ${@}" 22 | } 23 | 24 | install_conda() { 25 | info "Installing Conda..." 26 | # Download the Conda installer 27 | wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh 28 | # Install Conda 29 | bash miniconda.sh -b -p "${CONDA_PATH}" 30 | # Source conda 31 | source "${CONDA_PATH}/etc/profile.d/conda.sh" 32 | # Init conda 33 | conda init 34 | # Cleanup 35 | rm miniconda.sh 36 | info "Conda installation completed." 37 | } 38 | 39 | install_apt_packages() { 40 | # Install all packages from VoiceCraft README: https://github.com/jasonppy/VoiceCraft 41 | info "Installing apt packages..." 42 | sudo apt-get update 43 | sudo apt-get install -y git 44 | sudo apt-get install -y ffmpeg 45 | sudo apt-get install -y espeak-ng 46 | sudo apt-get install -y espeak espeak-data libespeak1 libespeak-dev 47 | sudo apt-get install -y festival* 48 | sudo apt-get install -y build-essential 49 | sudo apt-get install -y flac libasound2-dev libsndfile1-dev vorbis-tools 50 | sudo apt-get install -y libxml2-dev libxslt-dev zlib1g-dev 51 | } 52 | 53 | install_api_packages() { 54 | info "Installing VoiceCraftAPI pip packages..." 55 | # Create a conda environment named voicecraftapiconda only if it doesn't exist 56 | if [ "$(conda env list | grep voicecraftapiconda)" ]; then 57 | info "VoiceCraftAPI environment already exists. Updating..." 58 | else 59 | conda create -n voicecraftapiconda python=3.9.16 -y 60 | fi 61 | # Activate the environment 62 | conda activate voicecraftapiconda 63 | 64 | info "Installing pip requirements..." 65 | pip install numpy==1.26.4 # Numpy is seperate otherwise 'aeneas' complains. 66 | pip install -r "${VOICECRAFTAPI_PATH}/requirements.txt" 67 | # Audiocraft needs to be installed seperately from requirement.txt as it seems like 'hydra' will complain about a missing 68 | # config folder when installed through requirements.txt. 69 | pip install -e git+https://github.com/facebookresearch/audiocraft.git@c5157b5bf14bf83449c17ea1eeb66c19fb4bc7f0#egg=audiocraft 70 | 71 | info "Installing mfa and mfa models..." 72 | conda install -c conda-forge montreal-forced-aligner=2.2.17 openfst=1.8.2 kaldi=5.5.1068 73 | mfa model download dictionary english_us_arpa 74 | mfa model download acoustic english_us_arpa 75 | 76 | info "Finished installing all VoiceCraftAPI packages." 77 | } 78 | 79 | for arg in "$@"; do 80 | if [ "$arg" == "--skip-apt" ]; then 81 | info "--skip-apt flag set. Skipping apt package installation." 82 | skip_apt_installation=true 83 | fi 84 | done 85 | 86 | # Call sudo once and then refresh it every 60s so that user only has to input it once. 87 | info "Please input your password so that the script can use sudo to install system packages." 88 | sudo -v 89 | while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & 90 | 91 | # Log all paths 92 | info "VOICECRAFTAPI_PATH: ${VOICECRAFTAPI_PATH}" 93 | info "CONDA_PATH: ${CONDA_PATH}" 94 | info "CONDA_BINARY: ${CONDA_BINARY}" 95 | 96 | # Enter the VoiceCraftAPI path 97 | info "Entering VoiceCraftAPI folder: ${VOICECRAFTAPI_PATH}" 98 | cd "${VOICECRAFTAPI_PATH}" 99 | 100 | # If the conda binary doesn't exist, run install_conda() 101 | if ! command -v $CONDA_BINARY &> /dev/null; then 102 | install_conda 103 | else 104 | info "Conda already installed. Activating 'voicecraftapiconda' environment..." 105 | source "${CONDA_PATH}/etc/profile.d/conda.sh" 106 | conda activate voicecraftapiconda 107 | fi 108 | source "${CONDA_PATH}/etc/profile.d/conda.sh" 109 | 110 | # Install packages 111 | if [ -z "${skip_apt_installation}" ]; then 112 | error "Installing pacakges" 113 | install_apt_packages 114 | fi 115 | install_api_packages 116 | 117 | # Clone the VoiceCraft repository. 118 | if [ ! -d "${VOICECRAFTAPI_PATH}/VoiceCraft" ]; then 119 | info "Cloning the VoiceCraft repository..." 120 | git clone https://github.com/jasonppy/VoiceCraft 121 | fi 122 | 123 | # Set the VoiceCraft repository to the correct commit 124 | info "Setting VoiceCraft HEAD to commit: 013a21c" 125 | cd "${VOICECRAFTAPI_PATH}/VoiceCraft" 126 | git reset --hard 013a21c 127 | cd "${VOICECRAFTAPI_PATH}" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | nltk>=3.8.1 2 | openai-whisper>=20231117 3 | aeneas>=1.7.3.0 4 | whisperx>=3.1.1 5 | xformers==0.0.22 6 | torchaudio==2.0.2 7 | torch==2.0.1 # this assumes your system is compatible with CUDA 11.7, otherwise checkout https://pytorch.org/get-started/previous-versions/#v201 8 | tensorboard==2.16.2 9 | phonemizer==3.2.1 10 | datasets==2.16.0 11 | torchmetrics==0.11.1 12 | huggingface_hub==0.22.2 -------------------------------------------------------------------------------- /run_api.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Starting API" 4 | source "./conda/etc/profile.d/conda.sh" 5 | conda activate voicecraftapiconda 6 | python3 VoiceCraftAPI.py -------------------------------------------------------------------------------- /uninstall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | info() { 4 | echo -e "[$(date '+%H:%M:%S')]\033[32m[INFO]\033[0m ${@}" 5 | } 6 | error() { 7 | echo -e "[$(date '+%H:%M:%S')]\033[31m[ERROR]\033[0m ${@}" 8 | } 9 | warning() { 10 | echo -e "[$(date '+%H:%M:%S')]\033[33m[WARNING]\033[0m ${@}" 11 | } 12 | 13 | delete_voicecraftapi_user() { 14 | if id voicecraftapi >/dev/null 2>&1; then 15 | info "Deleting voicecraftapi user." 16 | sudo userdel -r -f voicecraftapi 17 | else 18 | warning "voicecraftapi user does not exist. Skipping deleting user..." 19 | fi 20 | } 21 | 22 | configure_systemd() { 23 | info "Stopping and removing systemd service." 24 | sudo systemctl stop voicecraft-api.service 25 | sudo systemctl disable voicecraft-api.service 26 | sudo rm /etc/systemd/system/voicecraft-api.service 27 | sudo systemctl daemon-reload 28 | } 29 | 30 | info "Please input your password so that the script can use sudo to configure." 31 | sudo -v 32 | while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & 33 | 34 | delete_voicecraftapi_user 35 | 36 | configure_systemd -------------------------------------------------------------------------------- /voicecraft-api.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=VoiceCraft Server API 3 | After=network.target 4 | 5 | [Service] 6 | Type=simple 7 | User=voicecraftapi 8 | Group=voicecraftapi 9 | ExecStart=/bin/bash /usr/share/voicecraftapi/VoiceCraftAPI/run_api.sh 10 | WorkingDirectory=/usr/share/voicecraftapi/VoiceCraftAPI/ 11 | 12 | [Install] 13 | WantedBy=multi-user.target --------------------------------------------------------------------------------