Spaces:
Build error
Build error
File size: 11,101 Bytes
6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 cbbc229 6bab300 |
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 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"\n",
"# Audiobook Generator - Proof of Concept Notebook\n",
"\n",
"This notebook is intended to be a proof of concept for the end-to-end work of generating an audiobook file from an ebook. This includes converting the .epub book files into raw python text strings, splitting into items and sentences, then tokenizing and batching them to run through the Silero text-to-speech (TTS) implementation.\n",
"\n",
"*Updated: September 2, 2022*\n",
"\n",
"---\n",
"\n",
"### Overview\n",
"\n",
"1. Setup\n",
" - Needed libraries and packages\n",
" - Variables\n",
" - Silero model selection\n",
"2. Ebook Import\n",
" - Target file selection\n",
" - File (.epub) import\n",
" - String parsing\n",
" - String length wrapping\n",
"3. Text-to-Speech\n",
" - Silero implementation\n",
" - Results\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 1 - Setup\n",
"\n",
"This proof-of-concept relies on PyTorch and TorchAudio for its implementation. OmegaConf is used to support providing the latest model from Silero in a consistent manner. A seed is created, and used for all random function that are needed.\n",
"\n",
"We will also use the TQDM package to provide progress bars while running the proof-of-concept within this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import torch\n",
"import torchaudio\n",
"from omegaconf import OmegaConf\n",
"from tqdm.notebook import tqdm\n",
"\n",
"torch.hub.download_url_to_file('https://raw.githubusercontent.com/snakers4/silero-models/master/models.yml',\n",
" 'latest_silero_models.yml',\n",
" progress=False)\n",
"models = OmegaConf.load('latest_silero_models.yml')\n",
"\n",
"seed = 1337\n",
"torch.manual_seed(seed)\n",
"torch.cuda.manual_seed(seed)\n",
"\n",
"device = 'cuda' if torch.cuda.is_available() else 'cpu'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We also need to set some variables for later use during the text processing steps, and the audio output in the TTS step.\n",
"\n",
"- `max_char_len` is set based on the results of performance testing done by the Silero devs. Larger values enable sentence structure to be better preserved, but negatively affect performance.\n",
"- `sample_rate` is also set based on recommendations from the Silero team for performance vs. quality. Using 16k or 8k audio will improve performance, but result in lower quality audio. Silero estimates a decrease of ~0.5 MOS (from 3.7 to 3.2)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"max_char_len = 140\n",
"sample_rate = 24000"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Silero implementation comes with models trained on various languages, the most common being Russian, but we will use the latest English model for this proof of concept. There are also a number of English speaker choices available."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"language = 'en'\n",
"model_id = 'v3_en'\n",
"speaker = 'en_0'\n",
"\n",
"model, example_text = torch.hub.load(repo_or_dir='snakers4/silero-models',\n",
" model='silero_tts',\n",
" language=language,\n",
" speaker=model_id)\n",
"model.to(device) # gpu or cpu"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 2 - Ebook Import\n",
"\n",
"Below is a representative ebook (`Protrait of Dorian Gray`), taken from Project Gutenberg - a free directory of public-domain works."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ebook_path = 'test.epub'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function below - `read_ebook()` - performs the following steps:\n",
"- Takes in the ebook, located at `ebook_path`\n",
"- Strips out any html tags\n",
"- Uses the nltk packages to download and use the `punkt` sentence-level tokenizer\n",
"- Calls the TextWrapper package to wrap sentences to the `max_char_len`, with care to fix sentence endings\n",
"- I.e. sentences are not split in the middle of a word, but rather words are preserved\n",
"- Finally sentences are appended to a chapter, and the chapters to a complete list: `corpus`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def read_ebook(ebook_path):\n",
"\n",
" import ebooklib\n",
" from ebooklib import epub\n",
" from bs4 import BeautifulSoup\n",
" from tqdm.notebook import tqdm\n",
" from nltk import tokenize, download\n",
" from textwrap import TextWrapper\n",
"\n",
" download('punkt')\n",
" wrapper = TextWrapper(max_char_len, fix_sentence_endings=True)\n",
"\n",
" book = epub.read_epub(ebook_path)\n",
"\n",
" ebook_title = book.get_metadata('DC', 'title')[0][0]\n",
" ebook_title = ebook_title.lower().replace(' ', '_')\n",
"\n",
" corpus = []\n",
" for item in tqdm(list(book.get_items())):\n",
" if item.get_type() == ebooklib.ITEM_DOCUMENT:\n",
" input_text = BeautifulSoup(item.get_content(), \"html.parser\").text\n",
" text_list = []\n",
" for paragraph in input_text.split('\\n'):\n",
" paragraph = paragraph.replace('—', '-')\n",
" sentences = tokenize.sent_tokenize(paragraph)\n",
"\n",
" # Truncate sentences to maximum character limit\n",
" sentence_list = []\n",
" for sentence in sentences:\n",
" wrapped_sentences = wrapper.wrap(sentence)\n",
" sentence_list.append(wrapped_sentences)\n",
" # Flatten list of list of sentences\n",
" trunc_sentences = [phrase for sublist in sentence_list for phrase in sublist]\n",
"\n",
" text_list.append(trunc_sentences)\n",
" text_list = [text for sentences in text_list for text in sentences]\n",
" corpus.append(text_list)\n",
"\n",
" return corpus, ebook_title"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we use the above function to read in the chosen ebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ebook, title = read_ebook(ebook_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And here, let us take a peak at the contents of the ebook:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(f'Title of ebook (path name):{title}\\n')\n",
"print(f'First line of the ebook:{ebook[0][0]}\\n')\n",
"print(f'First paragraph (truncated for display): \\n {ebook[2][0:5]}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ebook[0][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 3 - Text-to-Speech\n",
"\n",
"The ebook is fed through the Silero TTS implementation sentence by sentence. We will also check that each tensor being created is valid (i.e. non-zero).\n",
"\n",
"Finally, the output tensors are exported as `.wav` files on a chapter by chapter basis - consistent with the file structure of common audiobooks."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#os.mkdir(f'outputs/{title}')\n",
"\n",
"for chapter in tqdm(ebook[0:3]):\n",
" chapter_index = f'chapter{ebook.index(chapter):03}'\n",
" audio_list = []\n",
" for sentence in tqdm(chapter):\n",
" audio = model.apply_tts(text=sentence,\n",
" speaker=speaker,\n",
" sample_rate=sample_rate)\n",
" if len(audio) > 0 and isinstance(audio, torch.Tensor):\n",
" audio_list.append(audio)\n",
" else:\n",
" print(f'Tensor for sentence is not valid: \\n {sentence}')\n",
"\n",
" sample_path = f'outputs/{title}/{chapter_index}.wav'\n",
"\n",
" if len(audio_list) > 0:\n",
" audio_file = torch.cat(audio_list).reshape(1, -1)\n",
"# torchaudio.save(sample_path, audio_file, sample_rate)\n",
" else:\n",
" print(f'Chapter {chapter_index} is empty.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Results\n",
"\n",
"##### CPU (i7-4790k)\n",
"\n",
"Running \"Pride and Prejudice\" through the Silero model took **34m42s** to convert. This book is a good representation of the average book length: the average audiobook length on Audible is between 10 & 12 hours, while Pride and Prejudice is 11h20m.\n",
"\n",
"This is approximately a 20:1 ratio of audio length to processing time.\n",
"\n",
"Pride and Prejudice: **34m42s** - 1h39m33s on i7-4650u\n",
"\n",
"Portrait of Dorian Gray: **18m18s** - 18m50s w/output - 1h06hm04s on i7-4650u\n",
"\n",
"Crime and Punishment: **Unknown** - error converting ebook at 7/50, 19/368\n",
"\n",
"##### GPU (P4000)\n",
"\n",
"Running the same book through the Silero model on GPU took **5m39s** to convert.\n",
"\n",
"This is approximately a 122:1 ratio of audio length to processing time.\n",
"\n",
"Pride and Prejudice: **5m39s**\n",
"\n",
"Portrait of Dorian Gray: **4m26s**\n",
"\n",
"Crime and Punishment: **Unknown** - error converting ebook"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|