How do I get started training a custom voice model with Mozilla TTS on Ubuntu 20.04? - audio

I'd like to create a custom voice in Mozilla TTS using audio samples I have recorded but am not sure how to get started. The Mozilla TTS project has documentation and tutorials, but I'm having trouble putting the pieces together -- it seems like there's some basic information missing that someone starting out needs to know to get going.
Some questions I have:
I see that there is a Docker image for Mozilla TTS, but that the documentation for it covers creating speech and doesn't mention training. Can I use the Docker image for training?
If I can't use the Docker image for training, how do I get a functional copy of Mozilla TTS running on my system with Python 3? I've tried following the commands that the project provides, but I get dependency errors, version conflicts, or errors about not having sufficient permission to install packages.
What information do I need in order to train the model? What audio formats do I need? I see that I need a metadata.csv file -- what do I need to put in that file? What do I customize in the config file?
Most of the configs reference a scale_stats.npy file -- how do I generate this?
How do I run the training?

After a lot of research and experimentation, I can share my learnings to answer my own questions.
Can the Mozilla TTS Docker image be used for training (TL;DR: "No")
The Mozilla TTS docker image is really geared for playback and doesn't seem equipped to be used for training. At least, even when running a shell inside the container, I could not get training to work. But after figuring out what was causing PIP to be unhappy, the process of getting Mozilla TTS up and running in Ubuntu turns out to be pretty straightforward.
Installing Mozilla TTS using Python 3, PIP, and a Virtual Environment
The documentation for Mozilla TTS doesn't mention anything about virtual environments, but IMHO it really should. Virtual environments ensure that dependencies for different Python-based applications on your machine don't conflict.
I'm running Ubuntu 20.04 on WSL, so Python 3 is already installed. Given that, from within my home folder, here are the commands I used to get a working copy of Mozilla TTS:
sudo apt-get install espeak
git clone https://github.com/mozilla/TTS mozilla-tts
python3 -m venv mozilla-tts
cd mozilla-tts
./bin/pip install -e .
This created a folder called ~/mozilla-tts in my home folder that contains the Mozilla TTS code. The folder is setup as a virtual environment, which means that as long as I execute python commands via ~/mozilla-tts/bin/python and PIP via ~/mozilla-tts/bin/pip, Python will use only the packages that exist in that virtual environment. That eliminates the need to be root when running pip (since we're not affecting system-wide packages), and it ensures no package conflicts. Score!
Prerequisites for Training a Model
For the best results when training a model, you will need:
Short audio recordings (at least 100) that are:
In 16-bit, mono PCM WAV format.
Between 1 and 10 seconds each.
Have a sample rate of 22050 Hz.
Have a minimum of background noise and distortion.
Have no long pauses of silence at the beginning, throughout the middle, and at the end.
A metadata.csv file that references each WAV file and indicates what text is spoken in the WAV file.
A configuration file tailored to your data set and chosen vocoder (e.g. Tacotron, WavGrad, etc).
A machine with a fast CPU (ideally an nVidia GPU with CUDA support and at least 12 GB of GPU RAM; you cannot effectively use CUDA if you have less than 8 GB OF GPU RAM).
Lots of RAM (at least 16 GB of RAM is preferable).
Preparing the Audio Files
If your source of audio is in a different format than WAV, you will need to use a program like Audacity or SoX to convert the files into WAV format. You should also trim out portions of audio that are just noise, umms, ahs, and other sounds from the speaker that aren't really words you're training on.
If your source of audio isn't perfect (i.e. has some background noise), is in a different format, or happens to be a higher sample rate or different resolution (e.g. 24-bit, 32-bit, etc.), you can perform some clean-up and conversion. Here's a script that is based on an earlier script from the Mozilla TTS Discourse forums:
from pathlib import Path
import os
import subprocess
import soundfile as sf
import pyloudnorm as pyln
import sys
src = sys.argv[1]
rnn = "/PATH/TO/rnnoise_demo"
paths = Path(src).glob("**/*.wav")
for filepath in paths:
target_filepath=Path(str(filepath).replace("original", "converted"))
target_dir=os.path.dirname(target_filepath)
if (str(filepath) == str(target_filepath)):
raise ValueError("Source and target path are identical: " + str(target_filepath))
print("From: " + str(filepath))
print("To: " + str(target_filepath))
# Stereo to Mono; upsample to 48000Hz
subprocess.run(["sox", filepath, "48k.wav", "remix", "-", "rate", "48000"])
subprocess.run(["sox", "48k.wav", "-c", "1", "-r", "48000", "-b", "16", "-e", "signed-integer", "-t", "raw", "temp.raw"]) # convert wav to raw
subprocess.run([rnn, "temp.raw", "rnn.raw"]) # apply rnnoise
subprocess.run(["sox", "-r", "48k", "-b", "16", "-e", "signed-integer", "rnn.raw", "-t", "wav", "rnn.wav"]) # convert raw back to wav
subprocess.run(["mkdir", "-p", str(target_dir)])
subprocess.run(["sox", "rnn.wav", str(target_filepath), "remix", "-", "highpass", "100", "lowpass", "7000", "rate", "22050"]) # apply high/low pass filter and change sr to 22050Hz
data, rate = sf.read(target_filepath)
# peak normalize audio to -1 dB
peak_normalized_audio = pyln.normalize.peak(data, -1.0)
# measure the loudness first
meter = pyln.Meter(rate) # create BS.1770 meter
loudness = meter.integrated_loudness(data)
# loudness normalize audio to -25 dB LUFS
loudness_normalized_audio = pyln.normalize.loudness(data, loudness, -25.0)
sf.write(target_filepath, data=loudness_normalized_audio, samplerate=22050)
print("")
To use the script above, you will need to check out and build the RNNoise project:
sudo apt update
sudo apt-get install build-essential autoconf automake gdb git libffi-dev zlib1g-dev libssl-dev
git clone https://github.com/xiph/rnnoise.git
cd rnnoise
./autogen.sh
./configure
make
You will also need SoX installed:
sudo apt install sox
And, you will need to install pyloudnorm via ./bin/pip.
Then, just customize the script so that rnn points to the path of the rnnoise_demo command (after building RNNoise, you can find it in the examples folder). Then, run the script, passing the source path -- the folder where you have your WAV files -- as the first command line argument. Make sure that the word "original" appears somewhere in the path. The script will automatically place the converted files in a corresponding path, with original changed to converted; for example, if your source path is /path/to/files/original, the script will automatically place the converted results in /path/to/files/converted.
Preparing the Metadata
Mozilla TTS supports several different data loaders, but one of the most common is LJSpeech. To use it, we can organize our data set to follow LJSpeech conventions.
First, organize your files so that you have a structure like this:
- metadata.csv
- wavs/
- audio1.wav
- audio2.wav
...
- last_audio.wav
The naming of the audio files doesn't appear to be significant. But, the files must be in a folder called wavs. You can use sub-folders inside wavs though, if so desired.
The metadata.csv file should be in the following format:
audio1|line that's spoken in the first file
audio2|line that's spoken in the second file
last_audio|line that's spoken in the last file
Note that:
There is no header line.
The columns are joined together with a pipe symbol (|).
There should be one row per WAV file.
The WAV filename is in the first column, without the wavs/ folder prefix, and without the .wav suffix.
The textual description of what's spoken in the WAV is written out in the second column, with all numbers and abbreviations spelled-out.
(I did observe that steps in the documentation for Mozilla TTS have you then shuffle the metadata file and then split it into a "training" set (metadata_train.csv) and "validation" set (metadata_val.csv), but none of the sample configs provided in the repo are actually configured to use these files. I've filed an issue about that because it's confusing/counter-intuitive to a beginner.)
Preparing the config.json File
You need to prepare a configuration file that describes how your custom TTS will be configured. This file is used by multiple parts of Mozilla TTS when preparing for training, performing training, and generating audio from your custom TTS. Unfortunately, though this file is very important, the documentation for Mozilla TTS largely glosses over how to customize this file.
To start, create a copy of the default Tacotron config.json file from the Mozilla repo. Then, be sure to customize at least the audio.stats_path, output_path, phoneme_cache_path, and datasets.path file.
You can customize other parameters if you so choose, but the defaults are a good place to start. For example, you can change the run_name to control the naming of folders containing your datasets.
Do not change the datasets.name parameter (leave it set to "ljspeech"); otherwise you'll get strange errors related to an undefined dataset type. It appears that the dataset name refers to the type of data loader used, rather than what you call your data set. Similarly, I haven't risked changing the model setting, since I don't yet know how that value gets used by the system.
Preparing scale_stats.npy
Most of the training configurations rely on a statistics file called scale_stats.npy that's generated based on the training set. You can use the ./TTS/bin/compute_statistics.py script inside the Mozilla TTS repo to generate this file. This script requires your config.json file as an input, and is a good step to sanity check that everything looks good up to this point.
Here's an example of a command you can run if you are inside the Mozilla TTS folder you created at the start of this tutorial (adjust paths to fit your project):
./bin/python ./TTS/bin/compute_statistics.py --config_path /path/to/your/project/config.json --out_path /path/to/your/project/scale_stats.npy
If successful, this will generate a scale_stats.npy file under /path/to/your/project/scale_stats.npy. Be sure that the path in the audio.stats_path setting of your config.json file matches this path.
Training the Model
It's now time for the moment of truth -- it's time to start training your model!
Here's an example of a command you can run to train a Tacotron model if you are inside the Mozilla TTS folder you created at the start of this tutorial (adjust paths to fit your project):
./bin/python ./TTS/bin/train_tacotron.py --config_path /path/to/your/project/config.json
This process will take several hours, if not days. If your machine supports CUDA and has it properly configured, the process will run more quickly than if you are just relying on CPU alone.
If you get any errors related to a "signal error" or "signal received", this typically indicates that your machine does not have enough memory for the operation. You can run the training with less parallelism but it will run much more slowly.

Note, on windows, following GuyPaddock's advice from prior, I had to use pip install -e. instead of leading with ./bin/pip, and I had to use python instead of python3
Might be obvious to someone else but I am not so familiar with python or path shortcuts in shell being customized etc.

Related

Inspecting tensorflow's .data, .meta, and .index

I have been trying, for a couple of weeks now, to use multiple neural networks that I've found on GitHub. Most of the time these repos contain a folder with .meta, .index, and .data files. I first want to inspect these neural networks using TensorBoard(or any other tool), and then use them propertly.
So far I have tried converting these files to .pb, and then use this file in tensor board. But ofcourse this approach has not worked.
I have made some assumptions in this process:
1) I'm running the latest TensorFlow (py3) docker container on macOS.
2) I'm assuming that for just inspecting a file I do not require the necessary hardware that a network might need.
For converting these files to .pb, I've used the following code:
import tensorflow as tf
meta_path = '/Users/emiliovazquez/Documents/Fall2019/cs594/Final/models/triviaqa-unfiltered-shared-norm/best-weights/best-202000.meta' # Your .meta file
output_node_names = [n.name for n in tf.get_default_graph().as_graph_def().node] # Output nodes
with tf.Session() as sess:
# Restore the graph
saver = tf.train.import_meta_graph(meta_path)
# Load weights
saver.restore(sess,tf.train.latest_checkpoint('/Users/emiliovazquez/Documents/Fall2019/cs594/Final/models/triviaqa-unfiltered-shared-norm/best-weights/best-202000'))
# Freeze the graph
frozen_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
sess.graph_def,
output_node_names)
# Save the frozen graph
with open('./output_graph.pb', 'wb') as f:
f.write(frozen_graph_def.SerializeToString())
To inspect the generated .pb file I've used this repo and made the appropriate changes to run on the latest TensorFlow version.
However, after running this second python file propertly, the process exits with and error. OS did not find the file specified. However, I tried with both relative and absolute paths inside the container .
Please let me know what information I'm missing, what tool I should use, or whether the given approach is correct
It'd be better if you showed your Docker files, but from what your question shows, you haven't sent the Python files to the Docker machine. If the Python file has been sent, then you haven't specified the path to the output file correctly. Since this is running in Docker, you can't use an absolute path for your computer, you'll have to use a relative path so that it works on both your machine and in Docker.

Read temperature, humdity, etc from grib2 files with EECodes in python3

I am trying to use EECodes in python to get various weather information, such as temperature, humidity, etc out of grib2 files. I am using the GFS files. I would like to be able to extract the data as (lat,lon,alt,$data_point), and as a 2d array for each altitude.
I have tried the example programs located here: https://confluence.ecmwf.int/display/ECC/grib_iterator_bitmap
I can't figure out what I am looking in the output of that program. When I load the messages using their keys, it is not obvious how to make a grid. When I load the grid, the data doesn't have labels I understand.
#craeft have a look to https://github.com/ecmwf/cfgrib. cfgrib is the new standard for python and grib file handling. It is easy to install and easy to access files. Please install the latest version because it supports GFS files.

How to build python class structure for matplotlib to export ot .exe with cx_freeze?

I built a code to generate and play random musical notes. It is working great within python, but I would like to make it into an .exe stand alone program, so people without python can use it. I show an image below of the output. It creates a matplotlib figure with a 'TkAgg' backend. There are 5 buttons and an user entry box that all work.
I used cx_freeze to try to package it, and I worked through all of the errors. I also got some of the examples to work. I can see the the build folder is getting the 4 Images and many .wav files I need to draw the musical staff and play the notes. One error showed that the .exe tried to run my code, because it couldn't find the .wav files). I changed how I specified where they were for the .exe. But now when I run the .exe nothing happens.
Unfortunately my code is a monstrosity. It's messy, and somewhat long (750 lines if you count white space). The .py file I am trying to write to the .exe is Interval_Trainer_v1_1.py. It can be found here.
Because it works in python, but not in the .exe, I thought it might have to do with my ignorance of how to use classes in conjunction with plotting well. Basically I call the class, and then initialize a bunch of things so I can refer to them later. That allows me to delete notes I've plotted before, old answers, etc.
How can I practice building up 'TkAgg' backended figures that will execute properly after cf_freeze? I feel like I need to start with some basic ideas and build up to my application, which is fairly complex.
One note, I do use pygame for the sounds.
Here is my setup file:
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY']=r'C:\Users\Bart\Anaconda3\tcl\tcl8.6'
os.environ['TK_LIBRARY']=r'C:\Users\Bart\Anaconda3\tcl\tk8.6'
import sys
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
additional_mods = ['numpy.core._methods', 'numpy.lib.format',"matplotlib.backends.backend_tkagg", 'matplotlib.pyplot', 'matplotlib.image', 'matplotlib.widgets']
setup(
name = "Interval Trainer",
version = "1.0.0",
author = "Bart",
author_email = "bcubrich#gmail.com",
options = {"build_exe": {'includes': additional_mods,"packages":["pygame","tkinter",'random'],
"include_files": [
'Images/F cleff 8vb.png', 'Images/F cleff.png',
'Images/G cleff 8vb.png', 'Images/G cleff.png',
'Pitches/A#1.wav', 'Pitches/A#2.wav', 'Pitches/A#3.wav',
'Pitches/A#4.wav', 'Pitches/A#5.wav', 'Pitches/A1.wav',
'Pitches/A2.wav', 'Pitches/A3.wav', 'Pitches/A4.wav',
'Pitches/A5.wav', 'Pitches/Ab1.wav', 'Pitches/Ab2.wav',
'Pitches/Ab3.wav', 'Pitches/Ab4.wav', 'Pitches/B#2.wav',
'Pitches/B#3.wav', 'Pitches/B#4.wav', 'Pitches/B1.wav',
'Pitches/B2.wav', 'Pitches/B3.wav', 'Pitches/B4.wav',
'Pitches/B5.wav', 'Pitches/Bb1.wav', 'Pitches/Bb2.wav',
'Pitches/Bb3.wav', 'Pitches/Bb4.wav', 'Pitches/C#2.wav',
'Pitches/C#3.wav', 'Pitches/C#4.wav', 'Pitches/C#5.wav',
'Pitches/C2.wav', 'Pitches/C3.wav', 'Pitches/C4.wav',
'Pitches/C5.wav', 'Pitches/C6.wav', 'Pitches/D#2.wav',
'Pitches/D#3.wav', 'Pitches/D#4.wav', 'Pitches/D#5.wav',
'Pitches/D2.wav', 'Pitches/D3.wav', 'Pitches/D4.wav',
'Pitches/D5.wav', 'Pitches/Db1.wav', 'Pitches/Db2.wav',
'Pitches/Db3.wav', 'Pitches/Db4.wav', 'Pitches/E#2.wav',
'Pitches/E#3.wav', 'Pitches/E#4.wav', 'Pitches/E1.wav',
'Pitches/E2.wav', 'Pitches/E3.wav', 'Pitches/E4.wav',
'Pitches/E5.wav', 'Pitches/Eb2.wav', 'Pitches/Eb3.wav',
'Pitches/Eb4.wav', 'Pitches/F#1.wav', 'Pitches/F#2.wav',
'Pitches/F#3.wav', 'Pitches/F#4.wav', 'Pitches/F#5.wav',
'Pitches/F1.wav', 'Pitches/F2.wav', 'Pitches/F3.wav',
'Pitches/F4.wav', 'Pitches/F5.wav', 'Pitches/G#1.wav',
'Pitches/G#2.wav', 'Pitches/G#3.wav', 'Pitches/G#4.wav',
'Pitches/G#5.wav', 'Pitches/G1.wav', 'Pitches/G2.wav',
'Pitches/G3.wav', 'Pitches/G4.wav', 'Pitches/G5.wav',
'Pitches/Gb1.wav', 'Pitches/Gb2.wav', 'Pitches/Gb3.wav',
'Pitches/Gb4.wav']}},
executables = [Executable("Interval_trainer_v1_1.py", base=base)],
)
Output Image
Any help is appreciate.
See the matplotlib user interfaces examples embedding_in_tk and embedding_in_tk2 to practice building up TkAgg backended figures.

About Tkinter python 2.76 on Linux Mint 17.2

I have 2 functions as below:
def select_audio():
os.chdir("/home/norman/songbook")
top1.lower(root)
name=tkFileDialog.askopenfilename()
doit="play " + name
top1.lift(root)
os.system(doit)
def select_video():
os.chdir("/home/norman/Videos")
top2.lower(root)
name=tkFileDialog.askopenfilename()
doit="mpv --fs " + name
top2.lift(root)
os.system(doit)
They are selected from buttons to allow choosing and playing audio files or video files.
They work to some extent.
Videos are in a different directory and at the same level as the audio files.
It doesn't matter which I choose first I see the correct directory so I can play say a video, if after it's finished I choose audio it still shows the video directory.
Similarly if I first choose audio it still shows the audio directory if I select videos.
I have no idea why it does this. I am not an experienced programmer as you can probably tell from the code.
Some suggestions:
Use a raw string to make sure that Python doesn't try to interpret anything following a \ as an escape sequence:
Change os.chdir("/home/norman/whatever") to os.chdir(r"/home/norman/whatever")
It won't solve this problem, but it will avoid you future problems.
For tkFileDialog use the initialdir option:
Change name=tkFileDialog.askopenfilename() to
name=tkFileDialog.askopenfilename(initialdir=r"home/norman/whatever", parent=root)

pcap file viewing library in python 3

I'm looking at trying to read pcap files from various CTF events.
Ideally, I would like something that can do the breakdown of information such as wireshark, but just being able to read the timestamp and return the packet as a bytestring of some kind would be welcome.
The problem is that there is little or no python 3 support with all the commonly cited libraries: dpkt, pylibpcap, pcapy, etc.
Does anyone know of a pcap library that works with python 3?
to my knowledge, there are at least 2 packages that seems to work with Python 3: pure-pcapfile and dpkt:
pure-pcapfile is easy to install in python 3 using pip. It's very easy to use but still limited to decoding Ethernet and IP data. The rest is left to you. But it works right out of the box.
dpkt doesn't work right out of the box and needs some manipulation before. They are porting it to Python 3 and plan to have a Python 2 and 3 compatible version for version 2.0. Unfortunately, it's not there yet. However, it is way more complete than pure-pcapfile and can decode many protocols. If your packet embeds several layers of protocols, it will decode them automatically for you. The only problem is that you need to make a few corrections here and there to make it work (as the time of writing this comment).
pure-pcapfile
the only one that I found working for Python 3 so far is pcapfile. You can find it at https://pypi.python.org/pypi/pypcapfile/ or install it by doing pip3 install pypcapfile.
There are just basic functionalities but it works very well for me and has been updated quite recently (at the time of writing this message):
from pcapfile import savefile
file = open('mypcapfile.pcp' , 'rb')
pcapfile = savefile.load_savefile(file,verbose=True)
If everything goes well, you should see something like this:
[+] attempting to load mypcapfile.pcap
[+] found valid header
[+] loaded 1234 packets
[+] finished loading savefile.
A few remarks now. I'm using Python 3.4.3. And doing import pcapfile will not import anything from it (I'm still a beginner with Python) but the only basic information and functions from the package. Next, you have to explicitly open your file in read binary mode by passing 'rb' as the mode in the open() function. In the documentation they don't say it explicitly.
The rest is like in the documentation:
packet = pcapfile.packets[12]
to access the packet number 12 (the 13th packet then, the first one being at 0). And you have basic functionalities like
packet.timestamp
to get a timestamp or
packet.raw()
to get raw data.
The documentation mentions functions to do packet decoding of some standard formats like Ethernet and IP.
dpkt
dpkt is not available for Python 3 so you need to do the following, assuming you have access to a command line. The code is available on https://github.com/kbandla/dpkt.git and you must download it before:
git clone https://github.com/kbandla/dpkt.git
cd dpkt
git checkout --track origin/migrate_py3
git pull
This 4 commands do the following:
clone (download) the code from its git repository on github
go into the newly created directory named dpkt
switch to the branch name migrate_py3 which contains the Python 3 code. As you can see from the name of this branch, it's still experimental. So far it works for me.
(just in case) download again the code
then copy the directory named dpkt in your project or wherever Python 3 can find it.
Later on, in Python 3 here is what you have to do to get started:
import dpkt
file = open('mypcapfile.pcap','rb')
will open your file. Don't forget the 'rb' binary mode in Python 3 (same thing as in pure-pcapfile).
pcap = dpkt.pcap.Reader(file)
will read and decode your file
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
print(eth)
will, for example, decode Ethernet packet and print them. Then read the documentation on how to use dpkt. If your packets contain IP or TCP layer, then dpkt.ethernet.Ethernet(buf) will decode them as well. Also note that in the for loop, we have access to the timestamps in ts.
You may want to iterate it in a less constrained form and doing as follows will help:
(ts,buf) = next(pcap)
eth = dpkt.ethernet.Ethernet(buf)
where the first line get the next tuple from the pcap file. If pcap is False then you read everything.

Resources