forked from HGU-DLLAB/Korean-FastSpeech2-Pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
synthesize.py
120 lines (98 loc) · 4.67 KB
/
synthesize.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
import torch
import torch.nn as nn
import numpy as np
import os
import argparse
import re
from string import punctuation
from fastspeech2 import FastSpeech2
from text import text_to_sequence, sequence_to_text
import hparams as hp
import utils
import audio as Audio
import codecs
from g2pk import G2p
from jamo import h2j
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def kor_preprocess(text):
text = text.rstrip(punctuation)
g2p=G2p()
phone = g2p(text)
print('after g2p: ',phone)
phone = h2j(phone)
print('after h2j: ',phone)
phone = list(filter(lambda p: p != ' ', phone))
phone = '{' + '}{'.join(phone) + '}'
print('phone: ',phone)
phone = re.sub(r'\{[^\w\s]?\}', '{sp}', phone)
print('after re.sub: ',phone)
phone = phone.replace('}{', ' ')
print('|' + phone + '|')
sequence = np.array(text_to_sequence(phone,hp.text_cleaners))
sequence = np.stack([sequence])
return torch.from_numpy(sequence).long().to(device)
def get_FastSpeech2(num):
checkpoint_path = os.path.join(hp.checkpoint_path, "checkpoint_{}.pth.tar".format(num))
model = nn.DataParallel(FastSpeech2())
model.load_state_dict(torch.load(checkpoint_path)['model'])
model.requires_grad = False
model.eval()
return model
def synthesize(model, waveglow, melgan, text, sentence, prefix=''):
sentence = sentence[:10] # long filename will result in OS Error
src_len = torch.from_numpy(np.array([text.shape[1]])).to(device)
mel, mel_postnet, log_duration_output, f0_output, energy_output, _, _, mel_len = model(text, src_len)
mel_torch = mel.transpose(1, 2).detach()
mel_postnet_torch = mel_postnet.transpose(1, 2).detach()
mel = mel[0].cpu().transpose(0, 1).detach()
mel_postnet = mel_postnet[0].cpu().transpose(0, 1).detach()
f0_output = f0_output[0].detach().cpu().numpy()
energy_output = energy_output[0].detach().cpu().numpy()
if not os.path.exists(hp.test_path):
os.makedirs(hp.test_path)
Audio.tools.inv_mel_spec(mel_postnet, os.path.join(hp.test_path, '{}_griffin_lim_{}.wav'.format(prefix, sentence)))
if waveglow is not None:
utils.waveglow_infer(mel_postnet_torch, waveglow, os.path.join(hp.test_path, '{}_{}_{}.wav'.format(prefix, hp.vocoder, sentence)))
if melgan is not None:
utils.melgan_infer(mel_postnet_torch, melgan, os.path.join(hp.test_path, '{}_{}_{}.wav'.format(prefix, hp.vocoder, sentence)))
utils.plot_data([(mel_postnet.numpy(), f0_output, energy_output)], ['Synthesized Spectrogram'], filename=os.path.join(hp.test_path, '{}_{}.png'.format(prefix, sentence)))
if __name__ == "__main__":
# Test
parser = argparse.ArgumentParser()
parser.add_argument('--step', type=int, default=30000)
args = parser.parse_args()
model = get_FastSpeech2(args.step).to(device)
melgan = waveglow = None
if hp.vocoder == 'melgan':
melgan = utils.get_melgan()
melgan.to(device)
elif hp.vocoder == 'waveglow':
waveglow = utils.get_waveglow()
waveglow.to(device)
#kss
eval_sentence=['그는 괜찮은 척하려고 애쓰는 것 같았다','그녀의 사랑을 얻기 위해 애썼지만 헛수고였다','용돈을 아껴써라','그는 아내를 많이 아낀다','요즘 공부가 안돼요','한 여자가 내 옆에 앉았다']
train_sentence=['가까운 시일 내에 한번, 댁으로 찾아가겠습니다','우리의 승리는 기적에 가까웠다','아이들의 얼굴에는 행복한 미소가 가득했다','헬륨은 공기보다 가볍다','이것은 간단한 문제가 아니다']
test_sentence=['시간이 촉박해요','이런, 큰일 났어','좀 더 먹지 그래?','제가 뭘 잘못했죠?','더 이상 묻지마']
g2p=G2p()
print('which sentence do you want?')
print('1.eval_sentence 2.train_sentence 3.test_sentence 4.create new sentence')
mode=input()
print('you went for mode {}'.format(mode))
if mode=='4':
print('input sentence')
sentence = input()
elif mode=='1':
sentence = eval_sentence
elif mode=='2':
sentence = train_sentence
elif mode=='3':
sentence = test_sentence
print('sentence that will be synthesized: ')
print(sentence)
if mode != '4':
for s in sentence:
text = kor_preprocess(s)
synthesize(model, waveglow, melgan, text, s, prefix='step_{}'.format(args.step))
else:
text = kor_preprocess(sentence)
synthesize(model, waveglow, melgan, text, sentence, prefix='step_{}'.format(args.step))