├── .gitignore ├── LICENSE ├── README.md ├── scripts └── tortoise_tts.py └── tortoise ├── gradioui.py ├── merger.py ├── readEntireBook.py └── tortoise_api.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .idea/* 132 | .models/* 133 | .custom/* 134 | results/* 135 | debug_states/* 136 | CITATION.cff 137 | LICENSE 138 | MANIFEST.in 139 | README.md 140 | requirements.txt 141 | setup.py 142 | tortoise_tts.ipynb 143 | tortoise_v2_examples.html 144 | wanker.txt 145 | desired_outputs/* 146 | examples/* 147 | tortoise/data/* 148 | tortoise/models/* 149 | tortoise/utils/* 150 | tortoise/voices/* 151 | .gitignore 152 | tortoise/__init__.py 153 | tortoise/api.py 154 | tortoise/bulk.cmd 155 | tortoise/do_tts.py 156 | tortoise/eval.py 157 | tortoise/get_conditioning_latents.py 158 | tortoise/is_this_from_tortoise.py 159 | tortoise/read.py 160 | tortoise/test.py 161 | flagged/* 162 | tortoise/scripts/* 163 | ffprobe.exe 164 | .gitignore 165 | LICENSE 166 | temporary_text.txt 167 | combined.wav 168 | ffmpeg.exe 169 | temporary_text.txt 170 | -------------------------------------------------------------------------------- /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 | # TortoiseTTS GUI 2 | 3 | ## New: Ability to encode entire books automatically 4 | Check out readEntireBook.py it allows you to paste enormously large text files and splits them into clusters. It will then split those clusters into individual sentences using tortoise built in tools. This allows you to read more files than the read.py limit which is around 20000 characters on my machine. 5 | ## What is this? 6 | This is a gradio GUI to make it easier to use [Tortoise TTS](https://github.com/neonbjb/tortoise-tts) **Check it out for more information such as cloning your own voice or others** 7 | 8 | You can find guides and demo colab link in there. I've yet to make a colab to include the gui but it should be fairly easy. 9 | 10 | ## What does this repo include? 11 | The gradioUI I've written in python and a simple middleman script I've created to make it easier to interact with the api. 12 | 13 | ## Installation 14 | Follow the installation guide here [Tortoise Local Installation](https://github.com/neonbjb/tortoise-tts#local-installation) then simply put the files in the root directors, create a shell there and run gradeui.py. 15 | If you wanna use merger.py ensure that ffprobe is in the path or working directory, otherwise you might get file not found error. 16 | 17 | ## Sentence vs Longform 18 | Sentence should be used when synthesizing one or two sentences whereas longform should be used for longer content. Sentence works like [do_tts.py](https://github.com/neonbjb/tortoise-tts#do_ttspy) whereas longform works like [read.py](https://github.com/neonbjb/tortoise-tts#readpy). Keep in mind that longform will only return a single clip regardless of selected numOfOutputs. 19 | 20 | ## WARNING - Update 21 | I'm not a 100% sure if arbitary code can be executed because I'm using cmd while generating longform audio. All requests are checked against a dictionary except the text so the text is the only thing that could be a possible attack vector. However the text is written to a txt file then the read.py reads it from there so unless there is an exploit that can execute code using the read.py it should be safe. 22 | 23 | ## What's up with the voice selections? 24 | Those are just the voices I've made myself, unfortunately I don't want to be hold liable publishing anyone elses voice on GitHub so you need to find recordings of the voices of the people you want to use yourself. More info in the Tortoise TTS repo. 25 | -------------------------------------------------------------------------------- /scripts/tortoise_tts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import os 5 | import sys 6 | import tempfile 7 | import time 8 | 9 | import torch 10 | import torchaudio 11 | 12 | from tortoise.api import MODELS_DIR, TextToSpeech 13 | from tortoise.utils.audio import get_voices, load_voices, load_audio 14 | from tortoise.utils.text import split_and_recombine_text 15 | 16 | parser = argparse.ArgumentParser( 17 | description='TorToiSe is a text-to-speech program that is capable of synthesizing speech ' 18 | 'in multiple voices with realistic prosody and intonation.') 19 | 20 | parser.add_argument( 21 | 'text', type=str, nargs='*', 22 | help='Text to speak. If omitted, text is read from stdin.') 23 | parser.add_argument( 24 | '-v, --voice', type=str, default='random', metavar='VOICE', dest='voice', 25 | help='Selects the voice to use for generation. Use the & character to join two voices together. ' 26 | 'Use a comma to perform inference on multiple voices. Set to "all" to use all available voices. ' 27 | 'Note that multiple voices require the --output-dir option to be set.') 28 | parser.add_argument( 29 | '-V, --voices-dir', metavar='VOICES_DIR', type=str, dest='voices_dir', 30 | help='Path to directory containing extra voices to be loaded. Use a comma to specify multiple directories.') 31 | parser.add_argument( 32 | '-p, --preset', type=str, default='fast', choices=['ultra_fast', 'fast', 'standard', 'high_quality'], dest='preset', 33 | help='Which voice quality preset to use.') 34 | parser.add_argument( 35 | '-q, --quiet', default=False, action='store_true', dest='quiet', 36 | help='Suppress all output.') 37 | 38 | output_group = parser.add_mutually_exclusive_group(required=True) 39 | output_group.add_argument( 40 | '-l, --list-voices', default=False, action='store_true', dest='list_voices', 41 | help='List available voices and exit.') 42 | output_group.add_argument( 43 | '-P, --play', action='store_true', dest='play', 44 | help='Play the audio (requires pydub).') 45 | output_group.add_argument( 46 | '-o, --output', type=str, metavar='OUTPUT', dest='output', 47 | help='Save the audio to a file.') 48 | output_group.add_argument( 49 | '-O, --output-dir', type=str, metavar='OUTPUT_DIR', dest='output_dir', 50 | help='Save the audio to a directory as individual segments.') 51 | 52 | multi_output_group = parser.add_argument_group('multi-output options (requires --output-dir)') 53 | multi_output_group.add_argument( 54 | '--candidates', type=int, default=1, 55 | help='How many output candidates to produce per-voice. Note that only the first candidate is used in the combined output.') 56 | multi_output_group.add_argument( 57 | '--regenerate', type=str, default=None, 58 | help='Comma-separated list of clip numbers to re-generate.') 59 | multi_output_group.add_argument( 60 | '--skip-existing', action='store_true', 61 | help='Set to skip re-generating existing clips.') 62 | 63 | advanced_group = parser.add_argument_group('advanced options') 64 | advanced_group.add_argument( 65 | '--produce-debug-state', default=False, action='store_true', 66 | help='Whether or not to produce debug_states in current directory, which can aid in reproducing problems.') 67 | advanced_group.add_argument( 68 | '--seed', type=int, default=None, 69 | help='Random seed which can be used to reproduce results.') 70 | advanced_group.add_argument( 71 | '--models-dir', type=str, default=MODELS_DIR, 72 | help='Where to find pretrained model checkpoints. Tortoise automatically downloads these to ' 73 | '~/.cache/tortoise/.models, so this should only be specified if you have custom checkpoints.') 74 | advanced_group.add_argument( 75 | '--text-split', type=str, default=None, 76 | help='How big chunks to split the text into, in the format ,.') 77 | advanced_group.add_argument( 78 | '--disable-redaction', default=False, action='store_true', 79 | help='Normally text enclosed in brackets are automatically redacted from the spoken output ' 80 | '(but are still rendered by the model), this can be used for prompt engineering. ' 81 | 'Set this to disable this behavior.') 82 | advanced_group.add_argument( 83 | '--device', type=str, default=None, 84 | help='Device to use for inference.') 85 | advanced_group.add_argument( 86 | '--batch-size', type=int, default=None, 87 | help='Batch size to use for inference. If omitted, the batch size is set based on available GPU memory.') 88 | 89 | tuning_group = parser.add_argument_group('tuning options (overrides preset settings)') 90 | tuning_group.add_argument( 91 | '--num-autoregressive-samples', type=int, default=None, 92 | help='Number of samples taken from the autoregressive model, all of which are filtered using CLVP. ' 93 | 'As TorToiSe is a probabilistic model, more samples means a higher probability of creating something "great".') 94 | tuning_group.add_argument( 95 | '--temperature', type=float, default=None, 96 | help='The softmax temperature of the autoregressive model.') 97 | tuning_group.add_argument( 98 | '--length-penalty', type=float, default=None, 99 | help='A length penalty applied to the autoregressive decoder. Higher settings causes the model to produce more terse outputs.') 100 | tuning_group.add_argument( 101 | '--repetition-penalty', type=float, default=None, 102 | help='A penalty that prevents the autoregressive decoder from repeating itself during decoding. ' 103 | 'Can be used to reduce the incidence of long silences or "uhhhhhhs", etc.') 104 | tuning_group.add_argument( 105 | '--top-p', type=float, default=None, 106 | help='P value used in nucleus sampling. 0 to 1. Lower values mean the decoder produces more "likely" (aka boring) outputs.') 107 | tuning_group.add_argument( 108 | '--max-mel-tokens', type=int, default=None, 109 | help='Restricts the output length. 1 to 600. Each unit is 1/20 of a second.') 110 | tuning_group.add_argument( 111 | '--cvvp-amount', type=float, default=None, 112 | help='How much the CVVP model should influence the output.' 113 | 'Increasing this can in some cases reduce the likelyhood of multiple speakers.') 114 | tuning_group.add_argument( 115 | '--diffusion-iterations', type=int, default=None, 116 | help='Number of diffusion steps to perform. More steps means the network has more chances to iteratively' 117 | 'refine the output, which should theoretically mean a higher quality output. ' 118 | 'Generally a value above 250 is not noticeably better, however.') 119 | tuning_group.add_argument( 120 | '--cond-free', type=bool, default=None, 121 | help='Whether or not to perform conditioning-free diffusion. Conditioning-free diffusion performs two forward passes for ' 122 | 'each diffusion step: one with the outputs of the autoregressive model and one with no conditioning priors. The output ' 123 | 'of the two is blended according to the cond_free_k value below. Conditioning-free diffusion is the real deal, and ' 124 | 'dramatically improves realism.') 125 | tuning_group.add_argument( 126 | '--cond-free-k', type=float, default=None, 127 | help='Knob that determines how to balance the conditioning free signal with the conditioning-present signal. [0,inf]. ' 128 | 'As cond_free_k increases, the output becomes dominated by the conditioning-free signal. ' 129 | 'Formula is: output=cond_present_output*(cond_free_k+1)-cond_absenct_output*cond_free_k') 130 | tuning_group.add_argument( 131 | '--diffusion-temperature', type=float, default=None, 132 | help='Controls the variance of the noise fed into the diffusion model. [0,1]. Values at 0 ' 133 | 'are the "mean" prediction of the diffusion network and will sound bland and smeared. ') 134 | 135 | usage_examples = f''' 136 | Examples: 137 | 138 | Read text using random voice and place it in a file: 139 | 140 | {parser.prog} -o hello.wav "Hello, how are you?" 141 | 142 | Read text from stdin and play it using the tom voice: 143 | 144 | echo "Say it like you mean it!" | {parser.prog} -P -v tom 145 | 146 | Read a text file using multiple voices and save the audio clips to a directory: 147 | 148 | {parser.prog} -O /tmp/tts-results -v tom,emma max_length: 183 | parser.error(f'--text-split: desired_length ({desired_length}) must be <= max_length ({max_length})') 184 | texts = split_and_recombine_text(text, desired_length, max_length) 185 | else: 186 | texts = split_and_recombine_text(text) 187 | if len(texts) == 0: 188 | parser.error('no text provided') 189 | 190 | if args.output_dir: 191 | os.makedirs(args.output_dir, exist_ok=True) 192 | else: 193 | if len(selected_voices) > 1: 194 | parser.error('cannot have multiple voices without --output-dir"') 195 | if args.candidates > 1: 196 | parser.error('cannot have multiple candidates without --output-dir"') 197 | 198 | # error out early if pydub isn't installed 199 | if args.play: 200 | try: 201 | import pydub 202 | import pydub.playback 203 | except ImportError: 204 | parser.error('--play requires pydub to be installed, which can be done with "pip install pydub"') 205 | 206 | seed = int(time.time()) if args.seed is None else args.seed 207 | if not args.quiet: 208 | print('Loading tts...') 209 | tts = TextToSpeech(models_dir=args.models_dir, enable_redaction=not args.disable_redaction, 210 | device=args.device, autoregressive_batch_size=args.batch_size) 211 | gen_settings = { 212 | 'use_deterministic_seed': seed, 213 | 'verbose': not args.quiet, 214 | 'k': args.candidates, 215 | 'preset': args.preset, 216 | } 217 | tuning_options = [ 218 | 'num_autoregressive_samples', 'temperature', 'length_penalty', 'repetition_penalty', 'top_p', 219 | 'max_mel_tokens', 'cvvp_amount', 'diffusion_iterations', 'cond_free', 'cond_free_k', 'diffusion_temperature'] 220 | for option in tuning_options: 221 | if getattr(args, option) is not None: 222 | gen_settings[option] = getattr(args, option) 223 | total_clips = len(texts) * len(selected_voices) 224 | regenerate_clips = [int(x) for x in args.regenerate.split(',')] if args.regenerate else None 225 | for voice_idx, voice in enumerate(selected_voices): 226 | audio_parts = [] 227 | voice_samples, conditioning_latents = load_voices(voice, extra_voice_dirs) 228 | for text_idx, text in enumerate(texts): 229 | clip_name = f'{"-".join(voice)}_{text_idx:02d}' 230 | if args.output_dir: 231 | first_clip = os.path.join(args.output_dir, f'{clip_name}_00.wav') 232 | if (args.skip_existing or (regenerate_clips and text_idx not in regenerate_clips)) and os.path.exists(first_clip): 233 | audio_parts.append(load_audio(first_clip, 24000)) 234 | if not args.quiet: 235 | print(f'Skipping {clip_name}') 236 | continue 237 | if not args.quiet: 238 | print(f'Rendering {clip_name} ({(voice_idx * len(texts) + text_idx + 1)} of {total_clips})...') 239 | print(' ' + text) 240 | gen = tts.tts_with_preset( 241 | text, voice_samples=voice_samples, conditioning_latents=conditioning_latents, **gen_settings) 242 | gen = gen if args.candidates > 1 else [gen] 243 | for candidate_idx, audio in enumerate(gen): 244 | audio = audio.squeeze(0).cpu() 245 | if candidate_idx == 0: 246 | audio_parts.append(audio) 247 | if args.output_dir: 248 | filename = f'{clip_name}_{candidate_idx:02d}.wav' 249 | torchaudio.save(os.path.join(args.output_dir, filename), audio, 24000) 250 | 251 | audio = torch.cat(audio_parts, dim=-1) 252 | if args.output_dir: 253 | filename = f'{"-".join(voice)}_combined.wav' 254 | torchaudio.save(os.path.join(args.output_dir, filename), audio, 24000) 255 | elif args.output: 256 | filename = args.output if args.output else os.tmp 257 | torchaudio.save(args.output, audio, 24000) 258 | elif args.play: 259 | f = tempfile.NamedTemporaryFile(suffix='.wav', delete=True) 260 | torchaudio.save(f.name, audio, 24000) 261 | pydub.playback.play(pydub.AudioSegment.from_wav(f.name)) 262 | 263 | if args.produce_debug_state: 264 | os.makedirs('debug_states', exist_ok=True) 265 | dbg_state = (seed, texts, voice_samples, conditioning_latents, args) 266 | torch.save(dbg_state, os.path.join('debug_states', f'debug_{"-".join(voice)}.pth')) 267 | -------------------------------------------------------------------------------- /tortoise/gradioui.py: -------------------------------------------------------------------------------- 1 | import os 2 | import gradio as gr 3 | # import utils 4 | # import api 5 | import scipy 6 | # import tortoise_api 7 | from tortoise_api import convert_text_to_speech 8 | from tortoise_api import updateVoicesList 9 | import torch 10 | 11 | #Migrate API to a seperate script and use cls to access it for easy unloading 12 | 13 | if not os.path.exists("desired_outputs/longform"): 14 | os.makedirs("desired_outputs/longform") 15 | 16 | presetSymbols = {'ultra fast':'ultra_fast', 'fast':'fast', 'standard':'standard', 'high quality': 'high_quality'} 17 | 18 | characterSymbols = updateVoicesList() 19 | 20 | def fileFormatter(files): 21 | #Read each file and format to work with gradioUI 22 | for filen in range(len(files)): #Read all data's from the files 23 | files[filen] = scipy.io.wavfile.read(files[filen]) 24 | 25 | if len(files) < 3: #Fill empty files to ensure fixed output size 26 | while len(files) < 3: 27 | files.append("desired_outputs\\empty.wav") #Add empty file to avoid list out of index error 28 | 29 | return files 30 | 31 | def text_to_speech(text, voice, preset, readMode, numOfOutputs): 32 | #Use dictionary to convert strings into symbols readable by the api 33 | voiceSymbol = characterSymbols[voice] 34 | presetSymbol = presetSymbols[preset] 35 | 36 | if readMode == "longform": 37 | torch.cuda.empty_cache() 38 | with open("temporary_text.txt", "w", encoding="utf-8") as f: 39 | f.write(text) 40 | 41 | arguments = f"--voice {voiceSymbol} --preset {presetSymbol} --textfile temporary_text.txt --output_path desired_outputs\\longform --preset {presetSymbol}" 42 | 43 | files = [f"desired_outputs\\longform\\{voiceSymbol}\\combined.wav"] 44 | 45 | os.system(f"python tortoise\\read.py {arguments}") 46 | 47 | #format files 48 | files = fileFormatter(files) 49 | 50 | return files 51 | 52 | #Create and get files 53 | files = convert_text_to_speech(text, voiceSymbol, presetSymbol, numOfOutputs) 54 | 55 | #format files 56 | files = fileFormatter(files) 57 | 58 | return files 59 | 60 | tripleOutput = gr.Interface( 61 | 62 | fn = text_to_speech, #Function 63 | inputs = [ #Inputs 64 | gr.Textbox( 65 | label="Text to speak", 66 | lines=3, 67 | value="Haha that's crazy bro", 68 | ), 69 | 70 | gr.Dropdown(list(characterSymbols.keys()), value=list(characterSymbols.keys())[0], label="Voice"), 71 | 72 | gr.Radio(["ultra fast", "fast", "standard", "high quality"], value="fast", label="Speed"), 73 | 74 | gr.Radio(["sentence", "longform"], value="sentence", label="Reading Mode"), 75 | 76 | gr.Slider(1, 3, value=3, step=1, label="How many generations do you want?"), 77 | ], 78 | outputs = ["audio", "audio", "audio"], #Outputs 79 | examples=[ 80 | ["I tell them hell yeah! America is great", list(characterSymbols.keys())[0], "fast", "sentence", 3], 81 | ["The universe's third eye is visible when you really look for it", list(characterSymbols.keys())[1], "fast","sentence", 2], 82 | ["The woke liberals are overrunning our university campuses", list(characterSymbols.keys())[2],"fast", "sentence", 3], 83 | ["Liz Truss, absolute wanker", list(characterSymbols.keys())[3], "fast", "sentence", 3], 84 | ["Hello dear scholars, Today I'm showing the new sentient AI", list(characterSymbols.keys())[4], "fast", "longform", 1] 85 | ], 86 | ) 87 | 88 | demo = tripleOutput 89 | 90 | if __name__ == "__main__": 91 | #Remove server_name="0.0.0.0" if you don't want to share with your entire wifi network 92 | demo.launch(server_name="0.0.0.0", share=False) #Share is set to false by default 93 | -------------------------------------------------------------------------------- /tortoise/merger.py: -------------------------------------------------------------------------------- 1 | # Combine all wav files under the folder "voice_files" into a single file "combined.wav" 2 | 3 | import os 4 | import pydub 5 | from tqdm import tqdm 6 | 7 | def mergeFiles(files, name): 8 | # Get the list of all files in directory tree at given path 9 | listOfFiles = files 10 | # for (dirpath, dirnames, filenames) in os.walk(r"C:\Users\User\tortoise-tts\desired_outputs\longform\train_atkins"): 11 | # listOfFiles += [os.path.join(dirpath, file) for file in filenames] 12 | 13 | # Print the files 14 | for elem in listOfFiles: 15 | print(elem) 16 | 17 | # Create a single file "combined.wav" 18 | combined = pydub.AudioSegment.empty() 19 | for file in tqdm(listOfFiles): 20 | sound = pydub.AudioSegment.from_wav(file) 21 | combined += sound 22 | 23 | combined.export(f"{name}.wav", format="wav") 24 | -------------------------------------------------------------------------------- /tortoise/readEntireBook.py: -------------------------------------------------------------------------------- 1 | # This file was created because: 2 | # read.py gives up after around 90ish voice clips but many books are much longer than that. 3 | # This file will allow client to paste an entire book or chapter and it will automatically split it into sections 4 | # And automatically encode every 90 clip using read.py then use merger.py to merge them into a single audio book 5 | # chapter 6 | 7 | # We will conservatively assume that the limit is 10000 characters (in actuality its more like 20000) 8 | from utils.text import split_and_recombine_text 9 | from tortoise_api import convert_text_to_speech 10 | from merger import mergeFiles 11 | from tqdm import tqdm 12 | import os 13 | 14 | with open("temporary_text.txt", "r", encoding="utf-8") as f: 15 | text = f.read() 16 | 17 | voice = "train_dotrice" 18 | 19 | characterLimit = 10000 20 | sentences = split_and_recombine_text(text) 21 | 22 | # Split sentences into 10000 character clusters 23 | clusters = [] 24 | cluster = [] 25 | 26 | elapsedCharCount = 0 27 | for sentenceIndex in range(len(sentences)): 28 | sentence = sentences[sentenceIndex] 29 | elapsedCharCount += len(sentence) 30 | cluster.append(sentence) 31 | 32 | if elapsedCharCount > 10000: 33 | clusters.append(cluster) 34 | cluster = [] 35 | elapsedCharCount = 0 36 | 37 | arguments = f"--voice {voice} --preset fast --textfile temporary_text.txt --output_path desired_outputs\\longform" 38 | 39 | tqdm(leave=False) 40 | 41 | files = [] 42 | clusterFiles = [] 43 | readnum = 0 44 | cluster = 0 45 | 46 | for cluster in tqdm(clusters, desc="Clusers"): #Todo: add tqdm progress bar 47 | for sentence in tqdm(cluster, desc="Sentences"): 48 | generations = convert_text_to_speech(sentence, voice, "fast", 1, f"{voice}_{str(readnum)}") # Returns paths to generated files 49 | files.extend(generations) 50 | clusterFiles.extend(generations) 51 | readnum += 1 52 | 53 | mergeFiles(clusterFiles, f"cluster_{cluster}") 54 | clusterFiles = [] 55 | cluster = cluster + 1 56 | 57 | print("Almost done, merging files") 58 | mergeFiles(files, "all_chapters_merged") 59 | -------------------------------------------------------------------------------- /tortoise/tortoise_api.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import api 3 | import tortoise 4 | import torchaudio 5 | import os 6 | import random 7 | 8 | if not os.path.exists("desired_outputs"): 9 | os.makedirs("desired_outputs") 10 | 11 | #Cache things for faster access 12 | 13 | def updateVoicesList(): 14 | voices = {} 15 | for root_dir , sub_dir , sub_dir_files in os.walk('tortoise/voices'): 16 | for sub_dir_file in sub_dir_files: 17 | if sub_dir_file.endswith('.wav'): 18 | voice = os.path.basename( root_dir ) 19 | voices[ voice ] = voice 20 | voices = dict( sorted( voices.items() ) ) 21 | return voices 22 | 23 | characterSymbols = updateVoicesList() 24 | 25 | characters = dict.values(characterSymbols) 26 | 27 | characterCachedVoices = {} 28 | 29 | #Load each listed characters voice into memory 30 | for character in characters: 31 | clips_paths = Path(f"tortoise/voices/{character}").glob("**/*.wav") 32 | reference_clips = [tortoise.utils.audio.load_audio(p.absolute().__str__(), 22050) for p in clips_paths] 33 | characterCachedVoices[character] = reference_clips 34 | 35 | print("Done caching voices") 36 | 37 | def convert_text_to_speech(text, voice, preset, numOfOutputs, randomNum = str(random.randint(1,1000000))): 38 | reference_clips = characterCachedVoices[voice] #Immediately load voice samples from RAM 39 | 40 | #Initialise tts api 41 | tts = api.TextToSpeech() 42 | gen = tts.tts_with_preset(text, voice_samples=reference_clips, preset=preset, k=numOfOutputs, verbose=True) #Generate speech 43 | 44 | files = [] 45 | 46 | if isinstance(gen, list): #If multiple outputs save each 47 | for j, g in enumerate(gen): 48 | filename = os.path.join("desired_outputs", f'{randomNum}{j}.wav') 49 | torchaudio.save(filename, g.squeeze(0).cpu(), 24000) 50 | files.append(filename) 51 | else: #Or just save the single output 52 | filename = os.path.join("desired_outputs", f'{randomNum}.wav') 53 | torchaudio.save(filename, gen.squeeze(0).cpu(), 24000) 54 | files.append(filename) 55 | 56 | del gen 57 | 58 | return files 59 | 60 | print("Loaded middleman") 61 | --------------------------------------------------------------------------------