{ "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 }