File size: 16,666 Bytes
7934b29 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# TTS Inference Model Selection\n",
"\n",
"This notebook can be used to generate audio samples using either NeMo's pretrained models or after training NeMo TTS models. This notebook supports all TTS models and is intended to showcase different models and how their results differ."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# License\n",
"\n",
"> Copyright 2020 NVIDIA. All Rights Reserved.\n",
"> \n",
"> Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"> you may not use this file except in compliance with the License.\n",
"> You may obtain a copy of the License at\n",
"> \n",
"> http://www.apache.org/licenses/LICENSE-2.0\n",
"> \n",
"> Unless required by applicable law or agreed to in writing, software\n",
"> distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"> See the License for the specific language governing permissions and\n",
"> limitations under the License."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"\"\"\"\n",
"You can either run this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
"Instructions for setting up Colab are as follows:\n",
"1. Open a new Python 3 notebook.\n",
"2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
"3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
"4. Run this cell to set up dependencies.\n",
"\"\"\"\n",
"BRANCH = 'r1.17.0'\n",
"# # If you're using Google Colab and not running locally, uncomment and run this cell.\n",
"# !apt-get install sox libsndfile1 ffmpeg\n",
"# !pip install wget text-unidecode\n",
"# !python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Models\n",
"\n",
"First we pick the models that we want to use. Currently supported models are:\n",
"\n",
"Spectrogram Generators:\n",
"- [Tacotron 2](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_en_tacotron2)\n",
"- [FastPitch](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_en_fastpitch)\n",
"- [Mixer-TTS](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_en_lj_mixertts)\n",
"- [Mixer-TTS-X](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_en_lj_mixerttsx)\n",
"\n",
"Audio Generators\n",
"- [WaveGlow](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_waveglow_88m)\n",
"- [HiFiGAN](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_hifigan)\n",
"- [UnivNet](https://ngc.nvidia.com/catalog/models/nvidia:nemo:tts_en_lj_univnet)\n",
"- Griffin-Lim"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from ipywidgets import Select, HBox, Label\n",
"from IPython.display import display\n",
"\n",
"supported_spec_gen = [\"tacotron2\", \"fastpitch\", \"mixertts\", \"mixerttsx\", None]\n",
"supported_audio_gen = [\"waveglow\", \"hifigan\", \"univnet\", \"griffin-lim\", None]\n",
"\n",
"print(\"Select the model(s) that you want to use. Please choose 1 spectrogram generator and 1 vocoder.\")\n",
"spectrogram_generator_selector = Select(options=supported_spec_gen, value=None)\n",
"audio_generator_selector = Select(options=supported_audio_gen, value=None)\n",
"display(HBox([spectrogram_generator_selector, Label(\"+\"), audio_generator_selector]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"spectrogram_generator = spectrogram_generator_selector.value\n",
"audio_generator = audio_generator_selector.value\n",
"\n",
"if spectrogram_generator is None and audio_generator is None:\n",
" raise ValueError(\"No models were chosen. Please return to the previous step and choose either 1 end-to-end model or 1 spectrogram generator and 1 vocoder.\")\n",
"\n",
"if (spectrogram_generator and audio_generator is None) or (audio_generator and spectrogram_generator is None):\n",
" raise ValueError(\"In order to continue with the two step pipeline, both the spectrogram generator and the audio generator must be chosen, but one was `None`\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load model checkpoints\n",
"\n",
"Next we load the pretrained model provided by NeMo. All NeMo models have two functions to help with this\n",
"\n",
"- list_available_models(): This function will return a list of all pretrained checkpoints for that model\n",
"- from_pretrained(): This function will download the pretrained checkpoint, load it, and return an instance of the model\n",
"\n",
"Below we will use `from_pretrained` to load the chosen models from above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false,
"tags": []
},
"outputs": [],
"source": [
"from omegaconf import OmegaConf, open_dict\n",
"import torch\n",
"from nemo.collections.tts.models.base import SpectrogramGenerator, Vocoder\n",
"\n",
"\n",
"def load_spectrogram_model():\n",
" override_conf = None\n",
" \n",
" from_pretrained_call = SpectrogramGenerator.from_pretrained\n",
" \n",
" if spectrogram_generator == \"tacotron2\":\n",
" from nemo.collections.tts.models import Tacotron2Model\n",
" pretrained_model = \"tts_en_tacotron2\"\n",
" elif spectrogram_generator == \"fastpitch\":\n",
" from nemo.collections.tts.models import FastPitchModel\n",
" pretrained_model = \"tts_en_fastpitch\"\n",
" elif spectrogram_generator == \"mixertts\":\n",
" from nemo.collections.tts.models import MixerTTSModel\n",
" pretrained_model = \"tts_en_lj_mixertts\"\n",
" elif spectrogram_generator == \"mixerttsx\":\n",
" from nemo.collections.tts.models import MixerTTSModel\n",
" pretrained_model = \"tts_en_lj_mixerttsx\"\n",
" else:\n",
" raise NotImplementedError\n",
" \n",
" model = from_pretrained_call(pretrained_model, override_config_path=override_conf)\n",
" \n",
" return model\n",
"\n",
"\n",
"def load_vocoder_model():\n",
" TwoStagesModel = False\n",
" strict=True\n",
" \n",
" if audio_generator == \"waveglow\":\n",
" from nemo.collections.tts.models import WaveGlowModel\n",
" pretrained_model = \"tts_waveglow\"\n",
" strict=False\n",
" elif audio_generator == \"hifigan\":\n",
" from nemo.collections.tts.models import HifiGanModel\n",
" spectrogram_generator2ft_hifigan = {\n",
" \"mixertts\": \"tts_en_lj_hifigan_ft_mixertts\",\n",
" \"mixerttsx\": \"tts_en_lj_hifigan_ft_mixerttsx\"\n",
" }\n",
" pretrained_model = spectrogram_generator2ft_hifigan.get(spectrogram_generator, \"tts_en_hifigan\")\n",
" elif audio_generator == \"univnet\":\n",
" from nemo.collections.tts.models import UnivNetModel\n",
" pretrained_model = \"tts_en_lj_univnet\"\n",
" elif audio_generator == \"griffin-lim\":\n",
" from nemo.collections.tts.models import TwoStagesModel\n",
" cfg = {'linvocoder': {'_target_': 'nemo.collections.tts.models.two_stages.GriffinLimModel',\n",
" 'cfg': {'n_iters': 64, 'n_fft': 1024, 'l_hop': 256}},\n",
" 'mel2spec': {'_target_': 'nemo.collections.tts.models.two_stages.MelPsuedoInverseModel',\n",
" 'cfg': {'sampling_rate': 22050, 'n_fft': 1024, \n",
" 'mel_fmin': 0, 'mel_fmax': 8000, 'mel_freq': 80}}}\n",
" model = TwoStagesModel(cfg) \n",
" TwoStagesModel = True\n",
" else:\n",
" raise NotImplementedError\n",
"\n",
" if not TwoStagesModel:\n",
" model = Vocoder.from_pretrained(pretrained_model, strict=strict)\n",
" \n",
" return model\n",
"\n",
"spec_gen = load_spectrogram_model().eval().cuda()\n",
"vocoder = load_vocoder_model().eval().cuda()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference\n",
"\n",
"Now that we have downloaded the model checkpoints and loaded them into memory. Let's define a short infer helper function that takes a string, and our models to produce speech.\n",
"\n",
"Notice that the NeMo TTS model interface is fairly simple and standardized across all models.\n",
"\n",
"End-to-end models have two helper functions:\n",
"- parse(): Accepts raw python strings and returns a torch.tensor that represents tokenized text\n",
"- convert_text_to_waveform(): Accepts a batch of tokenized text and returns a torch.tensor that represents a batch of raw audio\n",
"\n",
"Mel Spectrogram generators have two helper functions:\n",
"\n",
"- parse(): Accepts raw python strings and returns a torch.tensor that represents tokenized text\n",
"- generate_spectrogram(): Accepts a batch of tokenized text and returns a torch.tensor that represents a batch of spectrograms\n",
"\n",
"Vocoder have just one helper function:\n",
"\n",
"- convert_spectrogram_to_audio(): Accepts a batch of spectrograms and returns a torch.tensor that represents a batch of raw audio"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def infer(spec_gen_model, vocoder_model, str_input):\n",
" parser_model = spec_gen_model\n",
" with torch.no_grad():\n",
" parsed = parser_model.parse(str_input)\n",
" gen_spec_kwargs = {}\n",
" \n",
" if spectrogram_generator == \"mixerttsx\":\n",
" gen_spec_kwargs[\"raw_texts\"] = [str_input]\n",
" \n",
" spectrogram = spec_gen_model.generate_spectrogram(tokens=parsed, **gen_spec_kwargs)\n",
" audio = vocoder_model.convert_spectrogram_to_audio(spec=spectrogram)\n",
" \n",
" if audio_generator == \"hifigan\":\n",
" audio = vocoder_model._bias_denoise(audio, spectrogram).squeeze(1)\n",
" if spectrogram is not None:\n",
" if isinstance(spectrogram, torch.Tensor):\n",
" spectrogram = spectrogram.to('cpu').numpy()\n",
" if len(spectrogram.shape) == 3:\n",
" spectrogram = spectrogram[0]\n",
" if isinstance(audio, torch.Tensor):\n",
" audio = audio.to('cpu').numpy()\n",
" return spectrogram, audio"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that everything is set up, let's give an input that we want our models to speak"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"text_to_generate = input(\"Input what you want the model to say: \")\n",
"spec, audio = infer(spec_gen, vocoder, text_to_generate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Results\n",
"\n",
"After our model generates the audio, let's go ahead and play it. We can also visualize the spectrogram that was produced from the first stage model if a spectrogram generator was used."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import IPython.display as ipd\n",
"import numpy as np\n",
"from PIL import Image\n",
"from matplotlib.pyplot import imshow\n",
"from matplotlib import pyplot as plt\n",
"\n",
"ipd.Audio(audio, rate=22050)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"if spec is not None:\n",
" imshow(spec, origin=\"lower\")\n",
" plt.show()"
]
}
],
"metadata": {
"interpreter": {
"hash": "9750c3195c8cb9412c65c8ba8b36c6ba2b82b23ddd61f39d29e01b403b049680"
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|