forked from as-ideas/ForwardTacotron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen_forward.py
136 lines (111 loc) · 5.79 KB
/
gen_forward.py
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
import argparse
from pathlib import Path
from typing import Tuple, Dict, Any, Union
import numpy as np
import torch
from models.fast_pitch import FastPitch
from models.fatchord_version import WaveRNN
from models.forward_tacotron import ForwardTacotron
from utils.checkpoints import init_tts_model
from utils.display import simple_table
from utils.dsp import DSP
from utils.files import read_config
from utils.paths import Paths
from utils.text.cleaners import Cleaner
from utils.text.tokenizer import Tokenizer
def load_tts_model(checkpoint_path: str) -> Tuple[Union[ForwardTacotron, FastPitch], Dict[str, Any]]:
print(f'Loading tts checkpoint {checkpoint_path}')
checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
config = checkpoint['config']
tts_model = init_tts_model(config)
tts_model.load_state_dict(checkpoint['model'])
print(f'Initialized tts model: {tts_model}')
print(f'Restored model with step {tts_model.get_step()}')
return tts_model, config
def load_wavernn(checkpoint_path: str) -> Tuple[WaveRNN, Dict[str, Any]]:
print(f'Loading voc checkpoint {checkpoint_path}')
checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
config = checkpoint['config']
voc_model = WaveRNN.from_config(config)
voc_model.load_state_dict(checkpoint['model'])
print(f'Loaded model with step {voc_model.get_step()}')
return voc_model, config
if __name__ == '__main__':
# Parse Arguments
parser = argparse.ArgumentParser(description='TTS Generator')
parser.add_argument('--input_text', '-i', default=None, type=str, help='[string] Type in something here and TTS will generate it!')
parser.add_argument('--checkpoint', type=str, default=None, help='[string/path] path to .pt model file.')
parser.add_argument('--config', metavar='FILE', default='config.yaml', help='The config containing all hyperparams. Only'
'used if no checkpoint is set.')
parser.add_argument('--alpha', type=float, default=1., help='Parameter for controlling length regulator for speedup '
'or slow-down of generated speech, e.g. alpha=2.0 is double-time')
parser.add_argument('--amp', type=float, default=1., help='Parameter for controlling pitch amplification')
# name of subcommand goes to args.vocoder
subparsers = parser.add_subparsers(dest='vocoder')
wr_parser = subparsers.add_parser('wavernn')
wr_parser.add_argument('--overlap', '-o', default=550, type=int, help='[int] number of crossover samples')
wr_parser.add_argument('--target', '-t', default=11_000, type=int, help='[int] number of samples in each batch index')
wr_parser.add_argument('--voc_checkpoint', type=str, help='[string/path] Load in different WaveRNN weights')
gl_parser = subparsers.add_parser('griffinlim')
mg_parser = subparsers.add_parser('melgan')
hg_parser = subparsers.add_parser('hifigan')
args = parser.parse_args()
assert args.vocoder in {'griffinlim', 'wavernn', 'melgan', 'hifigan'}, \
'Please provide a valid vocoder! Choices: [\'griffinlim\', \'wavernn\', \'melgan\', \'hifigan\']'
checkpoint_path = args.checkpoint
if checkpoint_path is None:
config = read_config(args.config)
paths = Paths(config['data_path'], config['voc_model_id'], config['tts_model_id'])
checkpoint_path = paths.forward_checkpoints / 'latest_model.pt'
tts_model, config = load_tts_model(checkpoint_path)
dsp = DSP.from_config(config)
voc_model, voc_dsp = None, None
if args.vocoder == 'wavernn':
voc_model, voc_config = load_wavernn(args.voc_checkpoint)
voc_dsp = DSP.from_config(voc_config)
out_path = Path('model_outputs')
out_path.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
tts_model.to(device)
cleaner = Cleaner.from_config(config)
tokenizer = Tokenizer()
print(f'Using device: {device}\n')
if args.input_text:
texts = [args.input_text]
else:
with open('sentences.txt', 'r', encoding='utf-8') as f:
texts = f.readlines()
tts_k = tts_model.get_step() // 1000
tts_model.eval()
simple_table([('Forward Tacotron', str(tts_k) + 'k'),
('Vocoder Type', args.vocoder)])
# simple amplification of pitch
pitch_function = lambda x: x * args.amp
energy_function = lambda x: x
for i, x in enumerate(texts, 1):
print(f'\n| Generating {i}/{len(texts)}')
text = x
x = cleaner(x)
x = tokenizer(x)
x = torch.as_tensor(x, dtype=torch.long, device=device).unsqueeze(0)
wav_name = f'{i}_forward_{tts_k}k_alpha{args.alpha}_amp{args.amp}_{args.vocoder}'
gen = tts_model.generate(x=x,
alpha=args.alpha,
pitch_function=pitch_function,
energy_function=energy_function)
m = gen['mel_post'].cpu()
if args.vocoder == 'melgan':
torch.save(m, out_path / f'{wav_name}.mel')
if args.vocoder == 'hifigan':
np.save(out_path / f'{wav_name}.npy', m.numpy(), allow_pickle=False)
if args.vocoder == 'wavernn':
wav = voc_model.generate(mels=m,
batched=True,
target=args.target,
overlap=args.overlap,
mu_law=voc_dsp.mu_law)
dsp.save_wav(wav, out_path / f'{wav_name}.wav')
elif args.vocoder == 'griffinlim':
wav = dsp.griffinlim(m.squeeze().numpy())
dsp.save_wav(wav, out_path / f'{wav_name}.wav')
print('\n\nDone.\n')