Merge branch 'develop' of https://github.com/PaddlePaddle/Parakeet into add_frontend_egs

This commit is contained in:
TianYuan 2021-08-16 10:27:58 +00:00
commit 19631f4eab
22 changed files with 308 additions and 19 deletions

View File

@ -0,0 +1,118 @@
# Parallel WaveGAN with the Baker dataset
This example contains code used to train a [parallel wavegan](http://arxiv.org/abs/1910.11480) model with [Chinese Standard Mandarin Speech Copus](https://www.data-baker.com/open_source.html).
## Preprocess the dataset
Download the dataset from the [official website of data-baker](https://www.data-baker.com/data/index/source) and extract it to `~/datasets`. Then the dataset is in directory `~/datasets/BZNSYP`.
Run the script for preprocessing.
```bash
bash preprocess.sh
```
When it is done. A `dump` folder is created in the current directory. The structure of the dump folder is listed below.
```text
dump
├── dev
│   ├── norm
│   └── raw
├── test
│   ├── norm
│   └── raw
└── train
├── norm
├── raw
└── stats.npy
```
The dataset is split into 3 parts, namely train, dev and test, each of which contains a `norm` and `raw` subfolder. The `raw` folder contains log magnitude of mel spectrogram of each utterances, while the norm folder contains normalized spectrogram. The statistics used to normalize the spectrogram is computed from the training set, which is located in `dump/train/stats.npy`.
Also there is a `metadata.jsonl` in each subfolder. It is a table-like file which contains id and paths to spectrogam of each utterance.
## Train the model
To train the model use the `run.sh`. It is an example script to run `train.py`.
```bash
bash run.sh
```
Or you can use the `train.py` directly. Here's the complete help message to run it.
```text
usage: train.py [-h] [--config CONFIG] [--train-metadata TRAIN_METADATA]
[--dev-metadata DEV_METADATA] [--output-dir OUTPUT_DIR]
[--device DEVICE] [--nprocs NPROCS] [--verbose VERBOSE]
Train a Parallel WaveGAN model with Baker Mandrin TTS dataset.
optional arguments:
-h, --help show this help message and exit
--config CONFIG config file to overwrite default config
--train-metadata TRAIN_METADATA
training data
--dev-metadata DEV_METADATA
dev data
--output-dir OUTPUT_DIR
output dir
--device DEVICE device type to use
--nprocs NPROCS number of processes
--verbose VERBOSE verbose
```
1. `--config` is a config file in yaml format to overwrite the default config, which can be found at `conf/default.yaml`.
2. `--train-metadata` and `--dev-metadata` should be the metadata file in the normalized subfolder of `train` and `dev` in the `dump` folder.
3. `--output-dir` is the directory to save the results of the experiment. Checkpoints are save in `checkpoints/` inside this directory.
4. `--device` is the type of the device to run the experiment, 'cpu' or 'gpu' are supported.
5. `--nprocs` is the number of processes to run in parallel, note that nprocs > 1 is only supported when `--device` is 'gpu'.
## Pretrained Models
Pretrained models can be downloaded here:
1. Parallel WaveGAN checkpoint. [pwg_baker_ckpt_0.4.zip](https://paddlespeech.bj.bcebos.com/Parakeet/pwg_baker_ckpt_0.4.zip), which is used as a vocoder in the end-to-end inference script.
Parallel WaveGAN checkpoint contains files listed below.
```text
pwg_baker_ckpt_0.4
├── pwg_default.yaml # default config used to train parallel wavegan
├── pwg_snapshot_iter_400000.pdz # generator parameters of parallel wavegan
└── pwg_stats.npy # statistics used to normalize spectrogram when training parallel wavegan
```
## Synthesize
When training is done or pretrained models are downloaded. You can run `synthesize.py` to synthsize.
```text
usage: synthesize.py [-h] [--config CONFIG] [--checkpoint CHECKPOINT]
[--test-metadata TEST_METADATA] [--output-dir OUTPUT_DIR]
[--device DEVICE] [--verbose VERBOSE]
synthesize with parallel wavegan.
optional arguments:
-h, --help show this help message and exit
--config CONFIG config file to overwrite default config
--checkpoint CHECKPOINT
snapshot to load
--test-metadata TEST_METADATA
dev data
--output-dir OUTPUT_DIR
output dir
--device DEVICE device to run
--verbose VERBOSE verbose
```
1. `--config` is the extra configuration file to overwrite the default config. You should use the same config with which the model is trained.
2. `--checkpoint` is the checkpoint to load. Pick one of the checkpoints from `/checkpoints` inside the training output directory. If you use the pretrained model, use the `pwg_snapshot_iter_400000.pdz`.
3. `--test-metadata` is the metadata of the test dataset. Use the `metadata.jsonl` in the `dev/norm` subfolder from the processed directory.
4. `--output-dir` is the directory to save the synthesized audio files.
5. `--device` is the type of device to run synthesis, 'cpu' and 'gpu' are supported.
## Acknowledgement
We adapted some code from https://github.com/kan-bayashi/ParallelWaveGAN.

View File

@ -0,0 +1,141 @@
# Speedyspeech with the Baker dataset
This example contains code used to train a [Speedyspeech](http://arxiv.org/abs/2008.03802) model with [Chinese Standard Mandarin Speech Copus](https://www.data-baker.com/open_source.html). NOTE that we only implement the student part of the Speedyspeech model. The ground truth alignment used to train the model is extracted from the dataset.
## Preprocess the dataset
Download the dataset from the [official website of data-baker](https://www.data-baker.com/data/index/source) and extract it to `~/datasets`. Then the dataset is in directory `~/datasets/BZNSYP`.
Run the script for preprocessing.
```bash
bash preprocess.sh
```
When it is done. A `dump` folder is created in the current directory. The structure of the dump folder is listed below.
```text
dump
├── dev
│   ├── norm
│   └── raw
├── test
│   ├── norm
│   └── raw
└── train
├── norm
├── raw
└── stats.npy
```
The dataset is split into 3 parts, namely train, dev and test, each of which contains a `norm` and `raw` sub folder. The raw folder contains log magnitude of mel spectrogram of each utterances, while the norm folder contains normalized spectrogram. The statistics used to normalize the spectrogram is computed from the training set, which is located in `dump/train/stats.npy`.
Also there is a `metadata.jsonl` in each subfolder. It is a table-like file which contains phones, tones, durations, path of spectrogram, and id of each utterance.
## Train the model
To train the model use the `run.sh`. It is an example script to run `train.py`.
```bash
bash run.sh
```
Or you can use `train.py` directly. Here's the complete help message.
```text
usage: train.py [-h] [--config CONFIG] [--train-metadata TRAIN_METADATA]
[--dev-metadata DEV_METADATA] [--output-dir OUTPUT_DIR]
[--device DEVICE] [--nprocs NPROCS] [--verbose VERBOSE]
Train a Speedyspeech model with Baker Mandrin TTS dataset.
optional arguments:
-h, --help show this help message and exit
--config CONFIG config file to overwrite default config
--train-metadata TRAIN_METADATA
training data
--dev-metadata DEV_METADATA
dev data
--output-dir OUTPUT_DIR
output dir
--device DEVICE device type to use
--nprocs NPROCS number of processes
--verbose VERBOSE verbose
```
1. `--config` is a config file in yaml format to overwrite the default config, which can be found at `conf/default.yaml`.
2. `--train-metadata` and `--dev-metadata` should be the metadata file in the normalized subfolder of `train` and `dev` in the `dump` folder.
3. `--output-dir` is the directory to save the results of the experiment. Checkpoints are save in `checkpoints/` inside this directory.
4. `--device` is the type of the device to run the experiment, 'cpu' or 'gpu' are supported.
5. `--nprocs` is the number of processes to run in parallel, note that nprocs > 1 is only supported when `--device` is 'gpu'.
## Pretrained Models
Pretrained models can be downloaded here:
1. Speedyspeech checkpoint. [speedyspeech_baker_ckpt_0.4.zip](https://paddlespeech.bj.bcebos.com/Parakeet/speedyspeech_baker_ckpt_0.4.zip)
2. Parallel WaveGAN checkpoint. [pwg_baker_ckpt_0.4.zip](https://paddlespeech.bj.bcebos.com/Parakeet/pwg_baker_ckpt_0.4.zip), which is used as a vocoder in the end-to-end inference script.
Speedyspeech checkpoint contains files listed below.
```text
speedyspeech_baker_ckpt_0.4
├── speedyspeech_default.yaml # default config used to train speedyseech
├── speedy_speech_stats.npy # statistics used to normalize spectrogram when training speedyspeech
└── speedyspeech_snapshot_iter_91800.pdz # model parameters and optimizer states
```
Parallel WaveGAN checkpoint contains files listed below.
```text
pwg_baker_ckpt_0.4
├── pwg_default.yaml # default config used to train parallel wavegan
├── pwg_snapshot_iter_400000.pdz # model parameters and optimizer states of parallel wavegan
└── pwg_stats.npy # statistics used to normalize spectrogram when training parallel wavegan
```
## Synthesize End to End
When training is done or pretrained models are downloaded. You can run `synthesize_e2e.py` to synthsize.
```text
usage: synthesize_e2e.py [-h] [--speedyspeech-config SPEEDYSPEECH_CONFIG]
[--speedyspeech-checkpoint SPEEDYSPEECH_CHECKPOINT]
[--speedyspeech-stat SPEEDYSPEECH_STAT]
[--pwg-config PWG_CONFIG] [--pwg-params PWG_PARAMS]
[--pwg-stat PWG_STAT] [--text TEXT]
[--output-dir OUTPUT_DIR]
[--inference-dir INFERENCE_DIR] [--device DEVICE]
[--verbose VERBOSE]
Synthesize with speedyspeech & parallel wavegan.
optional arguments:
-h, --help show this help message and exit
--speedyspeech-config SPEEDYSPEECH_CONFIG
config file for speedyspeech.
--speedyspeech-checkpoint SPEEDYSPEECH_CHECKPOINT
speedyspeech checkpoint to load.
--speedyspeech-stat SPEEDYSPEECH_STAT
mean and standard deviation used to normalize
spectrogram when training speedyspeech.
--pwg-config PWG_CONFIG
config file for parallelwavegan.
--pwg-checkpoint PWG_PARAMS
parallel wavegan checkpoint to load.
--pwg-stat PWG_STAT mean and standard deviation used to normalize
spectrogram when training speedyspeech.
--text TEXT text to synthesize, a 'utt_id sentence' pair per line
--output-dir OUTPUT_DIR
output dir
--inference-dir INFERENCE_DIR
dir to save inference models
--device DEVICE device type to use
--verbose VERBOSE verbose
```
1. `--speedyspeech-config`, `--speedyspeech-checkpoint`, `--speedyspeech-stat` are arguments for speedyspeech, which correspond to the 3 files in the speedyspeech pretrained model.
2. `--pwg-config`, `--pwg-checkpoint`, `--pwg-stat` are arguments for speedyspeech, which correspond to the 3 files in the parallel wavegan pretrained model.
3. `--text` is the text file, which contains sentences to synthesize.
4. `--output-dir` is the directory to save synthesized audio files.
5. `--inference-dir` is the directory to save exported model, which can be used with paddle infernece.
6. `--device` is the type of device to run synthesis, 'cpu' and 'gpu' are supported. 'gpu' is recommended for faster synthesis.

View File

@ -89,6 +89,11 @@ def main():
with jsonlines.open(args.metadata, 'r') as reader:
metadata = list(reader)
metadata_dir = Path(args.metadata).parent
for item in metadata:
item["feats"] = str(metadata_dir / item["feats"])
dataset = DataTable(
metadata,
fields=[args.field_name],

View File

@ -14,6 +14,9 @@
import yaml
from yacs.config import CfgNode as Configuration
from pathlib import Path
config_path = (Path(__file__).parent / "conf" / "default.yaml").resolve()
with open("conf/default.yaml", 'rt') as f:
_C = yaml.safe_load(f)

View File

@ -13,6 +13,8 @@
# limitations under the License.
import re
from pathlib import Path
import numpy as np
import paddle
import pypinyin
@ -22,10 +24,11 @@ import phkit
phkit.initialize()
from parakeet.frontend.vocab import Vocab
with open("phones.txt", 'rt') as f:
file_dir = Path(__file__).parent.resolve()
with open(file_dir / "phones.txt", 'rt') as f:
phones = [line.strip() for line in f.readlines()]
with open("tones.txt", 'rt') as f:
with open(file_dir / "tones.txt", 'rt') as f:
tones = [line.strip() for line in f.readlines()]
voc_phones = Vocab(phones, start_symbol=None, end_symbol=None)
voc_tones = Vocab(tones, start_symbol=None, end_symbol=None)

View File

@ -33,7 +33,7 @@ def main():
help="text to synthesize, a 'utt_id sentence' pair per line")
parser.add_argument("--output-dir", type=str, help="output dir")
args = parser.parse_args()
args, _ = parser.parse_known_args()
speedyspeech_config = inference.Config(
str(Path(args.inference_dir) / "speedyspeech.pdmodel"),

View File

@ -96,6 +96,10 @@ def main():
# get dataset
with jsonlines.open(args.metadata, 'r') as reader:
metadata = list(reader)
metadata_dir = Path(args.metadata).parent
for item in metadata:
item["feats"] = str(metadata_dir / item["feats"])
dataset = DataTable(metadata, converters={'feats': np.load, })
logging.info(f"The number of files = {len(dataset)}.")
@ -136,7 +140,7 @@ def main():
'num_phones': item['num_phones'],
'num_frames': item['num_frames'],
'durations': item['durations'],
'feats': str(mel_path),
'feats': str(mel_path.relative_to(dumpdir)),
})
output_metadata.sort(key=itemgetter('utt_id'))
output_metadata_path = Path(args.dumpdir) / "metadata.jsonl"

View File

@ -181,7 +181,7 @@ def process_sentence(config: Dict[str, Any],
"num_phones": len(phones),
"num_frames": num_frames,
"durations": durations_frame,
"feats": str(mel_path.resolve()), # use absolute path
"feats": mel_path, # Path object
}
return record
@ -212,8 +212,12 @@ def process_sentences(config,
results.append(ft.result())
results.sort(key=itemgetter("utt_id"))
with jsonlines.open(output_dir / "metadata.jsonl", 'w') as writer:
output_dir = Path(output_dir)
metadata_path = output_dir / "metadata.jsonl"
# NOTE: use relative path to the meta jsonlines file
with jsonlines.open(metadata_path, 'w') as writer:
for item in results:
item["feats"] = str(item["feats"].relative_to(output_dir))
writer.write(item)
print("Done")

View File

@ -70,7 +70,6 @@ class SpeedySpeechUpdater(StandardUpdater):
class SpeedySpeechEvaluator(StandardEvaluator):
def evaluate_core(self, batch):
print("fire")
decoded, predicted_durations = self.model(
text=batch["phones"],
tones=batch["tones"],

View File

@ -150,7 +150,7 @@ def main():
"--device", type=str, default="gpu", help="device type to use")
parser.add_argument("--verbose", type=int, default=1, help="verbose")
args = parser.parse_args()
args, _ = parser.parse_known_args()
with open(args.speedyspeech_config) as f:
speedyspeech_config = CfgNode(yaml.safe_load(f))
with open(args.pwg_config) as f:

View File

@ -57,7 +57,8 @@ def evaluate(args, speedyspeech_config, pwg_config):
model.eval()
vocoder = PWGGenerator(**pwg_config["generator_params"])
vocoder.set_state_dict(paddle.load(args.pwg_params))
vocoder.set_state_dict(
paddle.load(args.pwg_checkpoint)["generator_params"])
vocoder.remove_weight_norm()
vocoder.eval()
print("model done!")
@ -133,9 +134,9 @@ def main():
parser.add_argument(
"--pwg-config", type=str, help="config file for parallelwavegan.")
parser.add_argument(
"--pwg-params",
"--pwg-checkpoint",
type=str,
help="parallel wavegan generator parameters to load.")
help="parallel wavegan checkpoint to load.")
parser.add_argument(
"--pwg-stat",
type=str,
@ -152,7 +153,7 @@ def main():
"--device", type=str, default="gpu", help="device type to use")
parser.add_argument("--verbose", type=int, default=1, help="verbose")
args = parser.parse_args()
args, _ = parser.parse_known_args()
with open(args.speedyspeech_config) as f:
speedyspeech_config = CfgNode(yaml.safe_load(f))
with open(args.pwg_config) as f:

View File

@ -72,6 +72,10 @@ def train_sp(args, config):
# construct dataset for training and validation
with jsonlines.open(args.train_metadata, 'r') as reader:
train_metadata = list(reader)
metadata_dir = Path(args.train_metadata).parent
for item in train_metadata:
item["feats"] = str(metadata_dir / item["feats"])
train_dataset = DataTable(
data=train_metadata,
fields=[
@ -80,6 +84,9 @@ def train_sp(args, config):
converters={"feats": np.load, }, )
with jsonlines.open(args.dev_metadata, 'r') as reader:
dev_metadata = list(reader)
metadata_dir = Path(args.dev_metadata).parent
for item in dev_metadata:
item["feats"] = str(metadata_dir / item["feats"])
dev_dataset = DataTable(
data=dev_metadata,
fields=[
@ -113,9 +120,6 @@ def train_sp(args, config):
num_workers=config.num_workers)
print("dataloaders done!")
# batch = collate_baker_examples([train_dataset[i] for i in range(10)])
# # batch = collate_baker_examples([dev_dataset[i] for i in range(10)])
# import pdb; pdb.set_trace()
model = SpeedySpeech(**config["model"])
if world_size > 1:
model = DataParallel(model) # TODO, do not use vocab size from config
@ -141,13 +145,13 @@ def train_sp(args, config):
trainer.extend(VisualDL(writer), trigger=(1, "iteration"))
trainer.extend(
Snapshot(max_size=config.num_snapshots), trigger=(1, 'epoch'))
print(trainer.extensions)
# print(trainer.extensions)
trainer.run()
def main():
# parse args and config and redirect to train_sp
parser = argparse.ArgumentParser(description="Train a ParallelWaveGAN "
parser = argparse.ArgumentParser(description="Train a Speedyspeech "
"model with Baker Mandrin TTS dataset.")
parser.add_argument(
"--config", type=str, help="config file to overwrite default config")
@ -160,12 +164,18 @@ def main():
"--nprocs", type=int, default=1, help="number of processes")
parser.add_argument("--verbose", type=int, default=1, help="verbose")
args = parser.parse_args()
args, rest = parser.parse_known_args()
if args.device == "cpu" and args.nprocs > 1:
raise RuntimeError("Multiprocess training on CPU is not supported.")
config = get_cfg_default()
if args.config:
config.merge_from_file(args.config)
if rest:
extra = []
# to support key=value format
for item in rest:
extra.extend(item.split("=", maxsplit=1))
config.merge_from_list(extra)
print("========Args========")
print(yaml.safe_dump(vars(args)))

View File

@ -64,7 +64,7 @@ setup_info = dict(
'scipy',
'pandas',
'sox',
'soundfile',
'soundfile~=0.10',
'g2p_en',
'yacs',
'visualdl',
@ -78,6 +78,7 @@ setup_info = dict(
'pyworld',
'typeguard',
'jieba',
"phkit",
],
extras_require={'doc': ["sphinx", "sphinx-rtd-theme", "numpydoc"], },