stephenhoang commited on
Commit
cd71d82
·
1 Parent(s): 55b1857

Deploy Space app and model code

Browse files
Files changed (3) hide show
  1. app.py +159 -0
  2. meldataset.py +307 -0
  3. models.py +532 -0
app.py CHANGED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import os
4
+ import json
5
+ import tempfile
6
+ import traceback
7
+
8
+ import gradio as gr
9
+ import numpy as np
10
+ import soundfile as sf
11
+ import torch
12
+
13
+ from inference import StyleTTS2
14
+
15
+ # =========================
16
+ # CONFIG: CHINH 2 DUONG DAN NAY
17
+ # =========================
18
+ DATA_ROOT = "./demo_data"
19
+ SPEAKER2REFS_PATH = os.path.join(DATA_ROOT, "speaker2refs.json")
20
+
21
+ # Repo StyleTTS2-lite-vi (neu app.py nam trong repo thi de "./")
22
+ repo_dir = "./"
23
+ config_path = os.path.join(repo_dir, "Models", "config.yaml")
24
+ models_path = os.path.join(repo_dir, "Models", "inference", "model.pth")
25
+
26
+ device = "cuda" if torch.cuda.is_available() else "cpu"
27
+
28
+ # =========================
29
+ # LOAD speaker2refs.json
30
+ # =========================
31
+ if not os.path.isfile(SPEAKER2REFS_PATH):
32
+ raise FileNotFoundError(f"speaker2refs.json not found: {SPEAKER2REFS_PATH}")
33
+
34
+ with open(SPEAKER2REFS_PATH, "r", encoding="utf-8") as f:
35
+ SPEAKER2REFS = json.load(f)
36
+
37
+ SPEAKER_CHOICES = sorted(SPEAKER2REFS.keys())
38
+ if not SPEAKER_CHOICES:
39
+ raise RuntimeError("speaker2refs.json is empty (no speakers found).")
40
+
41
+ def _abs_audio(p: str) -> str:
42
+ return p if os.path.isabs(p) else os.path.join(DATA_ROOT, p)
43
+
44
+ # =========================
45
+ # LOAD MODEL
46
+ # =========================
47
+ model = StyleTTS2(config_path, models_path).eval().to(device)
48
+
49
+ # =========================
50
+ # STYLE CACHE (giam lag khi gen nhieu lan cung speaker)
51
+ # key = (speaker, denoise, avg_style)
52
+ # =========================
53
+ STYLE_CACHE = {}
54
+ STYLE_CACHE_MAX = 64
55
+
56
+ def _cache_get(key):
57
+ return STYLE_CACHE.get(key, None)
58
+
59
+ def _cache_set(key, val):
60
+ if key in STYLE_CACHE:
61
+ STYLE_CACHE[key] = val
62
+ return
63
+ if len(STYLE_CACHE) >= STYLE_CACHE_MAX:
64
+ STYLE_CACHE.pop(next(iter(STYLE_CACHE)))
65
+ STYLE_CACHE[key] = val
66
+
67
+ @torch.inference_mode()
68
+ def synth_one_speaker(speaker_name: str, text_prompt: str,
69
+ denoise: float, avg_style: bool, stabilize: bool):
70
+ try:
71
+ if not speaker_name:
72
+ return None, "Bạn chưa chọn speaker."
73
+
74
+ refs = SPEAKER2REFS.get(speaker_name, [])
75
+ if not refs:
76
+ return None, f"Speaker '{speaker_name}' không có ref trong speaker2refs.json."
77
+
78
+ ref_path = _abs_audio(refs[0])
79
+ if not os.path.isfile(ref_path):
80
+ return None, f"Ref audio not found: {ref_path}"
81
+
82
+ if not text_prompt or not text_prompt.strip():
83
+ return None, "Bạn chưa nhập text."
84
+
85
+ speakers = {
86
+ "id_1": {"path": ref_path, "lang": "vi", "speed": 1.0}
87
+ }
88
+
89
+ cache_key = (speaker_name, float(denoise), bool(avg_style))
90
+ styles = _cache_get(cache_key)
91
+ if styles is None:
92
+ styles = model.get_styles(speakers, denoise, avg_style)
93
+ _cache_set(cache_key, styles)
94
+
95
+ # Neu user khong them tag [id_1] thi tu them
96
+ text_prompt = text_prompt.strip()
97
+ if "[id_" not in text_prompt:
98
+ text_prompt = "[id_1] " + text_prompt
99
+
100
+ r = model.generate(text_prompt, styles, stabilize, 18, "[id_1]")
101
+
102
+ r = np.asarray(r, dtype=np.float32)
103
+ m = float(np.max(np.abs(r))) if r.size else 0.0
104
+ if m > 1e-9:
105
+ r = r / m
106
+
107
+ out_f = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
108
+ out_path = out_f.name
109
+ out_f.close()
110
+ sf.write(out_path, r, samplerate=24000)
111
+
112
+ status = (
113
+ "OK\n"
114
+ f"speaker: {speaker_name}\n"
115
+ f"device: {device}"
116
+ )
117
+ return out_path, status
118
+
119
+ except Exception:
120
+ return None, traceback.format_exc()
121
+
122
+ # =========================
123
+ # GRADIO UI
124
+ # =========================
125
+ with gr.Blocks() as demo:
126
+ gr.HTML("<h2 style='text-align:center;'>TTS</h2>")
127
+
128
+ speaker_name = gr.Dropdown(
129
+ choices=SPEAKER_CHOICES,
130
+ label="Speaker Name (closed-set)",
131
+ value=SPEAKER_CHOICES[0],
132
+ interactive=True
133
+ )
134
+
135
+ text_prompt = gr.Textbox(
136
+ label="Text Prompt",
137
+ placeholder="Nhập câu tiếng Việt cần đọc...",
138
+ lines=4
139
+ )
140
+
141
+ with gr.Row():
142
+ denoise = gr.Slider(0.0, 1.0, step=0.1, value=0.6, label="Denoise Strength")
143
+ avg_style = gr.Checkbox(label="Use Average Styles", value=True)
144
+ stabilize = gr.Checkbox(label="Stabilize Speaking Speed", value=True)
145
+
146
+ gen_button = gr.Button("Generate")
147
+ synthesized_audio = gr.Audio(label="Generated Audio", type="filepath")
148
+ status = gr.Textbox(label="Status", lines=4, interactive=False)
149
+
150
+ gen_button.click(
151
+ fn=synth_one_speaker,
152
+ inputs=[speaker_name, text_prompt, denoise, avg_style, stabilize],
153
+ outputs=[synthesized_audio, status]
154
+ )
155
+
156
+ try:
157
+ demo.queue().launch()
158
+ except TypeError:
159
+ demo.launch()
meldataset.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ coding: utf-8
2
+ import os.path as osp
3
+ import random
4
+ import numpy as np
5
+ import random
6
+ import soundfile as sf
7
+ import librosa
8
+
9
+ import torch
10
+ import torchaudio
11
+ import torch.utils.data
12
+ import torch.distributed as dist
13
+ from multiprocessing import Pool
14
+
15
+ import logging
16
+ logger = logging.getLogger(__name__)
17
+ logger.setLevel(logging.DEBUG)
18
+
19
+ import pandas as pd
20
+
21
+ class TextCleaner:
22
+ def __init__(self, symbol_dict, debug=True):
23
+ self.word_index_dictionary = symbol_dict
24
+ self.debug = debug
25
+ def __call__(self, text):
26
+ indexes = []
27
+ for char in text:
28
+ try:
29
+ indexes.append(self.word_index_dictionary[char])
30
+ except KeyError as e:
31
+ if self.debug:
32
+ print("\nWARNING UNKNOWN IPA CHARACTERS/LETTERS: ", char)
33
+ print("To ignore set 'debug' to false in the config")
34
+ continue
35
+ return indexes
36
+
37
+ np.random.seed(1)
38
+ random.seed(1)
39
+ SPECT_PARAMS = {
40
+ "n_fft": 2048,
41
+ "win_length": 1200,
42
+ "hop_length": 300
43
+ }
44
+ MEL_PARAMS = {
45
+ "n_mels": 80,
46
+ }
47
+
48
+ to_mel = torchaudio.transforms.MelSpectrogram(
49
+ n_mels=80, n_fft=2048, win_length=1200, hop_length=300)
50
+ mean, std = -4, 4
51
+
52
+ def preprocess(wave):
53
+ wave_tensor = torch.from_numpy(wave).float()
54
+ mel_tensor = to_mel(wave_tensor)
55
+ mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std
56
+ return mel_tensor
57
+
58
+ class FilePathDataset(torch.utils.data.Dataset):
59
+ def __init__(self,
60
+ data_list,
61
+ root_path,
62
+ symbol_dict,
63
+ sr=24000,
64
+ data_augmentation=False,
65
+ validation=False,
66
+ debug=True
67
+ ):
68
+
69
+ _data_list = [l.strip().split('|') for l in data_list]
70
+ self.data_list = _data_list #[data if len(data) == 3 else (*data, 0) for data in _data_list] #append speakerid=0 for all
71
+ self.text_cleaner = TextCleaner(symbol_dict, debug)
72
+ self.sr = sr
73
+
74
+ self.df = pd.DataFrame(self.data_list)
75
+
76
+ self.to_melspec = torchaudio.transforms.MelSpectrogram(**MEL_PARAMS)
77
+
78
+ self.mean, self.std = -4, 4
79
+ self.data_augmentation = data_augmentation and (not validation)
80
+ self.max_mel_length = 192
81
+
82
+ self.root_path = root_path
83
+
84
+ def __len__(self):
85
+ return len(self.data_list)
86
+
87
+ def __getitem__(self, idx):
88
+ data = self.data_list[idx]
89
+ path = data[0]
90
+
91
+ wave, text_tensor = self._load_tensor(data)
92
+
93
+ mel_tensor = preprocess(wave).squeeze()
94
+
95
+ acoustic_feature = mel_tensor.squeeze()
96
+ length_feature = acoustic_feature.size(1)
97
+ acoustic_feature = acoustic_feature[:, :(length_feature - length_feature % 2)]
98
+
99
+ return acoustic_feature, text_tensor, path, wave
100
+
101
+ def _load_tensor(self, data):
102
+ wave_path, text = data
103
+ wave, sr = sf.read(osp.join(self.root_path, wave_path))
104
+ if wave.shape[-1] == 2:
105
+ wave = wave[:, 0].squeeze()
106
+ if sr != 24000:
107
+ wave = librosa.resample(wave, orig_sr=sr, target_sr=24000)
108
+ print(wave_path, sr)
109
+
110
+ # Adding half a second padding.
111
+ wave = np.concatenate([np.zeros([12000]), wave, np.zeros([12000])], axis=0)
112
+
113
+ text = self.text_cleaner(text)
114
+
115
+ text.insert(0, 0)
116
+ text.append(0)
117
+
118
+ text = torch.LongTensor(text)
119
+
120
+ return wave, text
121
+
122
+ def _load_data(self, data):
123
+ wave, text_tensor = self._load_tensor(data)
124
+ mel_tensor = preprocess(wave).squeeze()
125
+
126
+ mel_length = mel_tensor.size(1)
127
+ if mel_length > self.max_mel_length:
128
+ random_start = np.random.randint(0, mel_length - self.max_mel_length)
129
+ mel_tensor = mel_tensor[:, random_start:random_start + self.max_mel_length]
130
+
131
+ return mel_tensor
132
+
133
+
134
+ class Collater(object):
135
+ """
136
+ Args:
137
+ adaptive_batch_size (bool): if true, decrease batch size when long data comes.
138
+ """
139
+
140
+ def __init__(self, return_wave=False):
141
+ self.text_pad_index = 0
142
+ self.min_mel_length = 192
143
+ self.max_mel_length = 192
144
+ self.return_wave = return_wave
145
+
146
+
147
+ def __call__(self, batch):
148
+ batch_size = len(batch)
149
+
150
+ # sort by mel length
151
+ lengths = [b[0].shape[1] for b in batch]
152
+ batch_indexes = np.argsort(lengths)[::-1]
153
+ batch = [batch[bid] for bid in batch_indexes]
154
+
155
+ nmels = batch[0][0].size(0)
156
+ max_mel_length = max([b[0].shape[1] for b in batch])
157
+ max_text_length = max([b[1].shape[0] for b in batch])
158
+
159
+ mels = torch.zeros((batch_size, nmels, max_mel_length)).float()
160
+ texts = torch.zeros((batch_size, max_text_length)).long()
161
+
162
+ input_lengths = torch.zeros(batch_size).long()
163
+ output_lengths = torch.zeros(batch_size).long()
164
+ paths = ['' for _ in range(batch_size)]
165
+ waves = [None for _ in range(batch_size)]
166
+
167
+ for bid, (mel, text, path, wave) in enumerate(batch):
168
+ mel_size = mel.size(1)
169
+ text_size = text.size(0)
170
+ mels[bid, :, :mel_size] = mel
171
+ texts[bid, :text_size] = text
172
+ input_lengths[bid] = text_size
173
+ output_lengths[bid] = mel_size
174
+ paths[bid] = path
175
+
176
+ waves[bid] = wave
177
+
178
+ return waves, texts, input_lengths, mels, output_lengths
179
+
180
+
181
+ def get_length(wave_path, root_path):
182
+ info = sf.info(osp.join(root_path, wave_path))
183
+ return info.frames * (24000 / info.samplerate)
184
+
185
+ def build_dataloader(path_list,
186
+ root_path,
187
+ symbol_dict,
188
+ validation=False,
189
+ batch_size=4,
190
+ num_workers=1,
191
+ device='cpu',
192
+ collate_config={},
193
+ dataset_config={}):
194
+
195
+ dataset = FilePathDataset(path_list, root_path, symbol_dict, validation=validation, **dataset_config)
196
+ collate_fn = Collater(**collate_config)
197
+
198
+ print("Getting sample lengths...")
199
+
200
+ num_processes = num_workers * 2
201
+ if num_processes != 0:
202
+ list_of_tuples = [(d[0], root_path) for d in dataset.data_list]
203
+ with Pool(processes=num_processes) as pool:
204
+ sample_lengths = pool.starmap(get_length, list_of_tuples, chunksize=16)
205
+ else:
206
+ sample_lengths = []
207
+ for d in dataset.data_list:
208
+ sample_lengths.append(get_length(d[0], root_path))
209
+
210
+ data_loader = torch.utils.data.DataLoader(
211
+ dataset,
212
+ num_workers=num_workers,
213
+ batch_sampler=BatchSampler(
214
+ sample_lengths,
215
+ batch_size,
216
+ shuffle=(not validation),
217
+ drop_last=(not validation),
218
+ num_replicas=1,
219
+ rank=0,
220
+ ),
221
+ collate_fn=collate_fn,
222
+ pin_memory=(device != "cpu"),
223
+ )
224
+
225
+ return data_loader
226
+
227
+ #https://github.com/duerig/StyleTTS2/
228
+ class BatchSampler(torch.utils.data.Sampler):
229
+ def __init__(
230
+ self,
231
+ sample_lengths,
232
+ batch_sizes,
233
+ num_replicas=None,
234
+ rank=None,
235
+ shuffle=True,
236
+ drop_last=False,
237
+ ):
238
+ self.batch_sizes = batch_sizes
239
+ if num_replicas is None:
240
+ self.num_replicas = dist.get_world_size()
241
+ else:
242
+ self.num_replicas = num_replicas
243
+ if rank is None:
244
+ self.rank = dist.get_rank()
245
+ else:
246
+ self.rank = rank
247
+ self.shuffle = shuffle
248
+ self.drop_last = drop_last
249
+
250
+ self.time_bins = {}
251
+ self.epoch = 0
252
+ self.total_len = 0
253
+ self.last_bin = None
254
+
255
+ for i in range(len(sample_lengths)):
256
+ bin_num = self.get_time_bin(sample_lengths[i])
257
+ if bin_num != -1:
258
+ if bin_num not in self.time_bins:
259
+ self.time_bins[bin_num] = []
260
+ self.time_bins[bin_num].append(i)
261
+
262
+ for key in self.time_bins.keys():
263
+ val = self.time_bins[key]
264
+ total_batch = self.batch_sizes * num_replicas
265
+ self.total_len += len(val) // total_batch
266
+ if not self.drop_last and len(val) % total_batch != 0:
267
+ self.total_len += 1
268
+
269
+ def __iter__(self):
270
+ sampler_order = list(self.time_bins.keys())
271
+ sampler_indices = []
272
+
273
+ if self.shuffle:
274
+ sampler_indices = torch.randperm(len(sampler_order)).tolist()
275
+ else:
276
+ sampler_indices = list(range(len(sampler_order)))
277
+
278
+ for index in sampler_indices:
279
+ key = sampler_order[index]
280
+ current_bin = self.time_bins[key]
281
+ dist = torch.utils.data.distributed.DistributedSampler(
282
+ current_bin,
283
+ num_replicas=self.num_replicas,
284
+ rank=self.rank,
285
+ shuffle=self.shuffle,
286
+ drop_last=self.drop_last,
287
+ )
288
+ dist.set_epoch(self.epoch)
289
+ sampler = torch.utils.data.sampler.BatchSampler(
290
+ dist, self.batch_sizes, self.drop_last
291
+ )
292
+ for item_list in sampler:
293
+ self.last_bin = key
294
+ yield [current_bin[i] for i in item_list]
295
+
296
+ def __len__(self):
297
+ return self.total_len
298
+
299
+ def set_epoch(self, epoch):
300
+ self.epoch = epoch
301
+
302
+ def get_time_bin(self, sample_count):
303
+ result = -1
304
+ frames = sample_count // 300
305
+ if frames >= 20:
306
+ result = (frames - 20) // 20
307
+ return result
models.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torch.nn.utils import weight_norm
6
+
7
+ from munch import Munch
8
+
9
+ class LearnedDownSample(nn.Module):
10
+ def __init__(self, layer_type, dim_in):
11
+ super().__init__()
12
+ self.layer_type = layer_type
13
+
14
+ if self.layer_type == 'none':
15
+ self.conv = nn.Identity()
16
+ elif self.layer_type == 'timepreserve':
17
+ self.conv = nn.Conv2d(dim_in, dim_in, kernel_size=(3, 1), stride=(2, 1), groups=dim_in, padding=(1, 0))
18
+ elif self.layer_type == 'half':
19
+ self.conv = nn.Conv2d(dim_in, dim_in, kernel_size=(3, 3), stride=(2, 2), groups=dim_in, padding=1)
20
+ else:
21
+ raise RuntimeError('Got unexpected donwsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
22
+
23
+ def forward(self, x):
24
+ return self.conv(x)
25
+
26
+ class LearnedUpSample(nn.Module):
27
+ def __init__(self, layer_type, dim_in):
28
+ super().__init__()
29
+ self.layer_type = layer_type
30
+
31
+ if self.layer_type == 'none':
32
+ self.conv = nn.Identity()
33
+ elif self.layer_type == 'timepreserve':
34
+ self.conv = nn.ConvTranspose2d(dim_in, dim_in, kernel_size=(3, 1), stride=(2, 1), groups=dim_in, output_padding=(1, 0), padding=(1, 0))
35
+ elif self.layer_type == 'half':
36
+ self.conv = nn.ConvTranspose2d(dim_in, dim_in, kernel_size=(3, 3), stride=(2, 2), groups=dim_in, output_padding=1, padding=1)
37
+ else:
38
+ raise RuntimeError('Got unexpected upsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
39
+
40
+
41
+ def forward(self, x):
42
+ return self.conv(x)
43
+
44
+ class DownSample(nn.Module):
45
+ def __init__(self, layer_type):
46
+ super().__init__()
47
+ self.layer_type = layer_type
48
+
49
+ def forward(self, x):
50
+ if self.layer_type == 'none':
51
+ return x
52
+ elif self.layer_type == 'timepreserve':
53
+ return F.avg_pool2d(x, (2, 1))
54
+ elif self.layer_type == 'half':
55
+ if x.shape[-1] % 2 != 0:
56
+ x = torch.cat([x, x[..., -1].unsqueeze(-1)], dim=-1)
57
+ return F.avg_pool2d(x, 2)
58
+ else:
59
+ raise RuntimeError('Got unexpected donwsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
60
+
61
+
62
+ class UpSample(nn.Module):
63
+ def __init__(self, layer_type):
64
+ super().__init__()
65
+ self.layer_type = layer_type
66
+
67
+ def forward(self, x):
68
+ if self.layer_type == 'none':
69
+ return x
70
+ elif self.layer_type == 'timepreserve':
71
+ return F.interpolate(x, scale_factor=(2, 1), mode='nearest')
72
+ elif self.layer_type == 'half':
73
+ return F.interpolate(x, scale_factor=2, mode='nearest')
74
+ else:
75
+ raise RuntimeError('Got unexpected upsampletype %s, expected is [none, timepreserve, half]' % self.layer_type)
76
+
77
+
78
+ class ResBlk(nn.Module):
79
+ def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2),
80
+ normalize=False, downsample='none'):
81
+ super().__init__()
82
+ self.actv = actv
83
+ self.normalize = normalize
84
+ self.downsample = DownSample(downsample)
85
+ self.downsample_res = LearnedDownSample(downsample, dim_in)
86
+ self.learned_sc = dim_in != dim_out
87
+ self._build_weights(dim_in, dim_out)
88
+
89
+ def _build_weights(self, dim_in, dim_out):
90
+ self.conv1 = nn.Conv2d(dim_in, dim_in, 3, 1, 1)
91
+ self.conv2 = nn.Conv2d(dim_in, dim_out, 3, 1, 1)
92
+ if self.normalize:
93
+ self.norm1 = nn.InstanceNorm2d(dim_in, affine=True)
94
+ self.norm2 = nn.InstanceNorm2d(dim_in, affine=True)
95
+ if self.learned_sc:
96
+ self.conv1x1 = nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=False)
97
+
98
+ def _shortcut(self, x):
99
+ if self.learned_sc:
100
+ x = self.conv1x1(x)
101
+ if self.downsample:
102
+ x = self.downsample(x)
103
+ return x
104
+
105
+ def _residual(self, x):
106
+ if self.normalize:
107
+ x = self.norm1(x)
108
+ x = self.actv(x)
109
+ x = self.conv1(x)
110
+ x = self.downsample_res(x)
111
+ if self.normalize:
112
+ x = self.norm2(x)
113
+ x = self.actv(x)
114
+ x = self.conv2(x)
115
+ return x
116
+
117
+ def forward(self, x):
118
+ x = self._shortcut(x) + self._residual(x)
119
+ return x / math.sqrt(2) # unit variance
120
+
121
+ class StyleEncoder(nn.Module):
122
+ def __init__(self, dim_in=48, style_dim=48, max_conv_dim=384):
123
+ super().__init__()
124
+ blocks = []
125
+ blocks += [nn.Conv2d(1, dim_in, 3, 1, 1)]
126
+
127
+ repeat_num = 4
128
+ for _ in range(repeat_num):
129
+ dim_out = min(dim_in*2, max_conv_dim)
130
+ blocks += [ResBlk(dim_in, dim_out, downsample='half')]
131
+ dim_in = dim_out
132
+
133
+ blocks += [nn.LeakyReLU(0.2)]
134
+ blocks += [nn.Conv2d(dim_out, dim_out, 5, 1, 0)]
135
+ blocks += [nn.AdaptiveAvgPool2d(1)]
136
+ blocks += [nn.LeakyReLU(0.2)]
137
+ self.shared = nn.Sequential(*blocks)
138
+
139
+ self.unshared = nn.Linear(dim_out, style_dim)
140
+
141
+ def forward(self, x):
142
+ h = self.shared(x)
143
+ h = h.view(h.size(0), -1)
144
+ s = self.unshared(h)
145
+
146
+ return s
147
+
148
+ class LinearNorm(torch.nn.Module):
149
+ def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
150
+ super(LinearNorm, self).__init__()
151
+ self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
152
+
153
+ torch.nn.init.xavier_uniform_(
154
+ self.linear_layer.weight,
155
+ gain=torch.nn.init.calculate_gain(w_init_gain))
156
+
157
+ def forward(self, x):
158
+ return self.linear_layer(x)
159
+
160
+ class ResBlk1d(nn.Module):
161
+ def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2),
162
+ normalize=False, downsample='none', dropout_p=0.2):
163
+ super().__init__()
164
+ self.actv = actv
165
+ self.normalize = normalize
166
+ self.downsample_type = downsample
167
+ self.learned_sc = dim_in != dim_out
168
+ self._build_weights(dim_in, dim_out)
169
+ self.dropout_p = dropout_p
170
+
171
+ if self.downsample_type == 'none':
172
+ self.pool = nn.Identity()
173
+ else:
174
+ self.pool = weight_norm(nn.Conv1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1))
175
+
176
+ def _build_weights(self, dim_in, dim_out):
177
+ self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_in, 3, 1, 1))
178
+ self.conv2 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
179
+ if self.normalize:
180
+ self.norm1 = nn.InstanceNorm1d(dim_in, affine=True)
181
+ self.norm2 = nn.InstanceNorm1d(dim_in, affine=True)
182
+ if self.learned_sc:
183
+ self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
184
+
185
+ def downsample(self, x):
186
+ if self.downsample_type == 'none':
187
+ return x
188
+ else:
189
+ if x.shape[-1] % 2 != 0:
190
+ x = torch.cat([x, x[..., -1].unsqueeze(-1)], dim=-1)
191
+ return F.avg_pool1d(x, 2)
192
+
193
+ def _shortcut(self, x):
194
+ if self.learned_sc:
195
+ x = self.conv1x1(x)
196
+ x = self.downsample(x)
197
+ return x
198
+
199
+ def _residual(self, x):
200
+ if self.normalize:
201
+ x = self.norm1(x)
202
+ x = self.actv(x)
203
+ x = F.dropout(x, p=self.dropout_p, training=self.training)
204
+
205
+ x = self.conv1(x)
206
+ x = self.pool(x)
207
+ if self.normalize:
208
+ x = self.norm2(x)
209
+
210
+ x = self.actv(x)
211
+ x = F.dropout(x, p=self.dropout_p, training=self.training)
212
+
213
+ x = self.conv2(x)
214
+ return x
215
+
216
+ def forward(self, x):
217
+ x = self._shortcut(x) + self._residual(x)
218
+ return x / math.sqrt(2) # unit variance
219
+
220
+ class LayerNorm(nn.Module):
221
+ def __init__(self, channels, eps=1e-5):
222
+ super().__init__()
223
+ self.channels = channels
224
+ self.eps = eps
225
+
226
+ self.gamma = nn.Parameter(torch.ones(channels))
227
+ self.beta = nn.Parameter(torch.zeros(channels))
228
+
229
+ def forward(self, x):
230
+ x = x.transpose(1, -1)
231
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
232
+ return x.transpose(1, -1)
233
+
234
+ class TextEncoder(nn.Module):
235
+ def __init__(self, channels, kernel_size, depth, n_symbols, actv=nn.LeakyReLU(0.2)):
236
+ super().__init__()
237
+ self.embedding = nn.Embedding(n_symbols, channels)
238
+
239
+ padding = (kernel_size - 1) // 2
240
+ self.cnn = nn.ModuleList()
241
+ for _ in range(depth):
242
+ self.cnn.append(nn.Sequential(
243
+ weight_norm(nn.Conv1d(channels, channels, kernel_size=kernel_size, padding=padding)),
244
+ LayerNorm(channels),
245
+ actv,
246
+ nn.Dropout(0.2),
247
+ ))
248
+ # self.cnn = nn.Sequential(*self.cnn)
249
+
250
+ self.lstm = nn.LSTM(channels, channels//2, 1, batch_first=True, bidirectional=True)
251
+
252
+ def forward(self, x, input_lengths, m):
253
+ x = self.embedding(x) # [B, T, emb]
254
+ x = x.transpose(1, 2) # [B, emb, T]
255
+ m = m.to(input_lengths.device).unsqueeze(1)
256
+ x.masked_fill_(m, 0.0)
257
+
258
+ for c in self.cnn:
259
+ x = c(x)
260
+ x.masked_fill_(m, 0.0)
261
+
262
+ x = x.transpose(1, 2) # [B, T, chn]
263
+
264
+ input_lengths = input_lengths.cpu().numpy()
265
+ x = nn.utils.rnn.pack_padded_sequence(
266
+ x, input_lengths, batch_first=True, enforce_sorted=False)
267
+
268
+ self.lstm.flatten_parameters()
269
+ x, _ = self.lstm(x)
270
+ x, _ = nn.utils.rnn.pad_packed_sequence(
271
+ x, batch_first=True)
272
+
273
+ x = x.transpose(-1, -2)
274
+ x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]])
275
+
276
+ x_pad[:, :, :x.shape[-1]] = x
277
+ x = x_pad.to(x.device)
278
+
279
+ x.masked_fill_(m, 0.0)
280
+
281
+ return x
282
+
283
+ def inference(self, x):
284
+ x = self.embedding(x)
285
+ x = x.transpose(1, 2)
286
+ x = self.cnn(x)
287
+ x = x.transpose(1, 2)
288
+ self.lstm.flatten_parameters()
289
+ x, _ = self.lstm(x)
290
+ return x
291
+
292
+ def length_to_mask(self, lengths):
293
+ mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
294
+ mask = torch.gt(mask+1, lengths.unsqueeze(1))
295
+ return mask
296
+
297
+
298
+
299
+ class AdaIN1d(nn.Module):
300
+ def __init__(self, style_dim, num_features):
301
+ super().__init__()
302
+ self.norm = nn.InstanceNorm1d(num_features, affine=False)
303
+ self.fc = nn.Linear(style_dim, num_features*2)
304
+
305
+ def forward(self, x, s):
306
+ h = self.fc(s)
307
+ h = h.view(h.size(0), h.size(1), 1)
308
+ gamma, beta = torch.chunk(h, chunks=2, dim=1)
309
+ return (1 + gamma) * self.norm(x) + beta
310
+
311
+ class UpSample1d(nn.Module):
312
+ def __init__(self, layer_type):
313
+ super().__init__()
314
+ self.layer_type = layer_type
315
+
316
+ def forward(self, x):
317
+ if self.layer_type == 'none':
318
+ return x
319
+ else:
320
+ return F.interpolate(x, scale_factor=2, mode='nearest')
321
+
322
+ class AdainResBlk1d(nn.Module):
323
+ def __init__(self, dim_in, dim_out, style_dim=64, actv=nn.LeakyReLU(0.2),
324
+ upsample='none', dropout_p=0.0):
325
+ super().__init__()
326
+ self.actv = actv
327
+ self.upsample_type = upsample
328
+ self.upsample = UpSample1d(upsample)
329
+ self.learned_sc = dim_in != dim_out
330
+ self._build_weights(dim_in, dim_out, style_dim)
331
+ self.dropout = nn.Dropout(dropout_p)
332
+
333
+ if upsample == 'none':
334
+ self.pool = nn.Identity()
335
+ else:
336
+ self.pool = weight_norm(nn.ConvTranspose1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1, output_padding=1))
337
+
338
+
339
+ def _build_weights(self, dim_in, dim_out, style_dim):
340
+ self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
341
+ self.conv2 = weight_norm(nn.Conv1d(dim_out, dim_out, 3, 1, 1))
342
+ self.norm1 = AdaIN1d(style_dim, dim_in)
343
+ self.norm2 = AdaIN1d(style_dim, dim_out)
344
+ if self.learned_sc:
345
+ self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
346
+
347
+ def _shortcut(self, x):
348
+ x = self.upsample(x)
349
+ if self.learned_sc:
350
+ x = self.conv1x1(x)
351
+ return x
352
+
353
+ def _residual(self, x, s):
354
+ x = self.norm1(x, s)
355
+ x = self.actv(x)
356
+ x = self.pool(x)
357
+ x = self.conv1(self.dropout(x))
358
+ x = self.norm2(x, s)
359
+ x = self.actv(x)
360
+ x = self.conv2(self.dropout(x))
361
+ return x
362
+
363
+ def forward(self, x, s):
364
+ out = self._residual(x, s)
365
+ out = (out + self._shortcut(x)) / math.sqrt(2)
366
+ return out
367
+
368
+ class AdaLayerNorm(nn.Module):
369
+ def __init__(self, style_dim, channels, eps=1e-5):
370
+ super().__init__()
371
+ self.channels = channels
372
+ self.eps = eps
373
+
374
+ self.fc = nn.Linear(style_dim, channels*2)
375
+
376
+ def forward(self, x, s):
377
+ x = x.transpose(-1, -2)
378
+ x = x.transpose(1, -1)
379
+
380
+ h = self.fc(s)
381
+ h = h.view(h.size(0), h.size(1), 1)
382
+ gamma, beta = torch.chunk(h, chunks=2, dim=1)
383
+ gamma, beta = gamma.transpose(1, -1), beta.transpose(1, -1)
384
+
385
+
386
+ x = F.layer_norm(x, (self.channels,), eps=self.eps)
387
+ x = (1 + gamma) * x + beta
388
+ return x.transpose(1, -1).transpose(-1, -2)
389
+
390
+ class ProsodyPredictor(nn.Module):
391
+
392
+ def __init__(self, style_dim, d_hid, nlayers, max_dur=50, dropout=0.1):
393
+ super().__init__()
394
+
395
+ self.text_encoder = DurationEncoder(sty_dim=style_dim,
396
+ d_model=d_hid,
397
+ nlayers=nlayers,
398
+ dropout=dropout)
399
+
400
+ self.lstm = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True)
401
+ self.duration_proj = LinearNorm(d_hid, max_dur)
402
+
403
+ self.shared = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True)
404
+ self.F0 = nn.ModuleList()
405
+ self.F0.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout))
406
+ self.F0.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout))
407
+ self.F0.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout))
408
+
409
+ self.N = nn.ModuleList()
410
+ self.N.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout))
411
+ self.N.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout))
412
+ self.N.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout))
413
+
414
+ self.F0_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
415
+ self.N_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
416
+
417
+
418
+ def forward(self, texts, style, text_lengths, alignment, m):
419
+ d = self.text_encoder(texts, style, text_lengths, m)
420
+
421
+ batch_size = d.shape[0]
422
+ text_size = d.shape[1]
423
+
424
+ # predict duration
425
+ input_lengths = text_lengths.cpu().numpy()
426
+ x = nn.utils.rnn.pack_padded_sequence(
427
+ d, input_lengths, batch_first=True, enforce_sorted=False)
428
+
429
+ m = m.to(text_lengths.device).unsqueeze(1)
430
+
431
+ self.lstm.flatten_parameters()
432
+ x, _ = self.lstm(x)
433
+ x, _ = nn.utils.rnn.pad_packed_sequence(
434
+ x, batch_first=True)
435
+
436
+ x_pad = torch.zeros([x.shape[0], m.shape[-1], x.shape[-1]])
437
+
438
+ x_pad[:, :x.shape[1], :] = x
439
+ x = x_pad.to(x.device)
440
+
441
+ duration = self.duration_proj(nn.functional.dropout(x, 0.5, training=self.training))
442
+
443
+ en = (d.transpose(-1, -2) @ alignment)
444
+
445
+ return duration.squeeze(-1), en
446
+
447
+ def F0Ntrain(self, x, s):
448
+ x, _ = self.shared(x.transpose(-1, -2))
449
+
450
+ F0 = x.transpose(-1, -2)
451
+ for block in self.F0:
452
+ F0 = block(F0, s)
453
+ F0 = self.F0_proj(F0)
454
+
455
+ N = x.transpose(-1, -2)
456
+ for block in self.N:
457
+ N = block(N, s)
458
+ N = self.N_proj(N)
459
+
460
+ return F0.squeeze(1), N.squeeze(1)
461
+
462
+ def length_to_mask(self, lengths):
463
+ mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
464
+ mask = torch.gt(mask+1, lengths.unsqueeze(1))
465
+ return mask
466
+
467
+ class DurationEncoder(nn.Module):
468
+
469
+ def __init__(self, sty_dim, d_model, nlayers, dropout=0.1):
470
+ super().__init__()
471
+ self.lstms = nn.ModuleList()
472
+ for _ in range(nlayers):
473
+ self.lstms.append(nn.LSTM(d_model + sty_dim,
474
+ d_model // 2,
475
+ num_layers=1,
476
+ batch_first=True,
477
+ bidirectional=True,
478
+ dropout=dropout))
479
+ self.lstms.append(AdaLayerNorm(sty_dim, d_model))
480
+
481
+
482
+ self.dropout = dropout
483
+ self.d_model = d_model
484
+ self.sty_dim = sty_dim
485
+
486
+ def forward(self, x, style, text_lengths, m):
487
+ masks = m.to(text_lengths.device)
488
+
489
+ x = x.permute(2, 0, 1)
490
+ s = style.expand(x.shape[0], x.shape[1], -1)
491
+ x = torch.cat([x, s], axis=-1)
492
+ x.masked_fill_(masks.unsqueeze(-1).transpose(0, 1), 0.0)
493
+
494
+ x = x.transpose(0, 1)
495
+ input_lengths = text_lengths.cpu().numpy()
496
+ x = x.transpose(-1, -2)
497
+
498
+ for block in self.lstms:
499
+ if isinstance(block, AdaLayerNorm):
500
+ x = block(x.transpose(-1, -2), style).transpose(-1, -2)
501
+ x = torch.cat([x, s.permute(1, -1, 0)], axis=1)
502
+ x.masked_fill_(masks.unsqueeze(-1).transpose(-1, -2), 0.0)
503
+ else:
504
+ x = x.transpose(-1, -2)
505
+ x = nn.utils.rnn.pack_padded_sequence(
506
+ x, input_lengths, batch_first=True, enforce_sorted=False)
507
+ block.flatten_parameters()
508
+ x, _ = block(x)
509
+ x, _ = nn.utils.rnn.pad_packed_sequence(
510
+ x, batch_first=True)
511
+ x = F.dropout(x, p=self.dropout, training=self.training)
512
+ x = x.transpose(-1, -2)
513
+
514
+ x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]])
515
+
516
+ x_pad[:, :, :x.shape[-1]] = x
517
+ x = x_pad.to(x.device)
518
+
519
+ return x.transpose(-1, -2)
520
+
521
+ def inference(self, x, style):
522
+ x = self.embedding(x.transpose(-1, -2)) * math.sqrt(self.d_model)
523
+ style = style.expand(x.shape[0], x.shape[1], -1)
524
+ x = torch.cat([x, style], axis=-1)
525
+ src = self.pos_encoder(x)
526
+ output = self.transformer_encoder(src).transpose(0, 1)
527
+ return output
528
+
529
+ def length_to_mask(self, lengths):
530
+ mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
531
+ mask = torch.gt(mask+1, lengths.unsqueeze(1))
532
+ return mask