Mahiruoshi commited on
Commit
996feab
1 Parent(s): fe63b85

Upload 31 files

Browse files
.gitattributes CHANGED
@@ -2,13 +2,11 @@
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
  *.npy filter=lfs diff=lfs merge=lfs -text
@@ -16,13 +14,12 @@
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
  *.pickle filter=lfs diff=lfs merge=lfs -text
21
  *.pkl filter=lfs diff=lfs merge=lfs -text
 
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
  *.tflite filter=lfs diff=lfs merge=lfs -text
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
5
  *.ftz filter=lfs diff=lfs merge=lfs -text
6
  *.gz filter=lfs diff=lfs merge=lfs -text
7
  *.h5 filter=lfs diff=lfs merge=lfs -text
8
  *.joblib filter=lfs diff=lfs merge=lfs -text
9
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
10
  *.model filter=lfs diff=lfs merge=lfs -text
11
  *.msgpack filter=lfs diff=lfs merge=lfs -text
12
  *.npy filter=lfs diff=lfs merge=lfs -text
 
14
  *.onnx filter=lfs diff=lfs merge=lfs -text
15
  *.ot filter=lfs diff=lfs merge=lfs -text
16
  *.parquet filter=lfs diff=lfs merge=lfs -text
 
17
  *.pickle filter=lfs diff=lfs merge=lfs -text
18
  *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
  *.pt filter=lfs diff=lfs merge=lfs -text
21
  *.pth filter=lfs diff=lfs merge=lfs -text
22
  *.rar filter=lfs diff=lfs merge=lfs -text
 
23
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
  *.tar.* filter=lfs diff=lfs merge=lfs -text
25
  *.tflite filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Lovelive ShojoKageki Vits
3
- emoji: 📚
4
- colorFrom: yellow
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 3.27.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Lovelive VITS JPZH
3
+ emoji: 📈
4
+ colorFrom: purple
5
+ colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 3.4.1
8
  app_file: app.py
9
  pinned: false
10
+ license: cc-by-nc-3.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ logging.getLogger('numba').setLevel(logging.WARNING)
3
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
4
+ logging.getLogger('urllib3').setLevel(logging.WARNING)
5
+ import romajitable
6
+ import re
7
+ import numpy as np
8
+ import IPython.display as ipd
9
+ import torch
10
+ import commons
11
+ import utils
12
+ from models import SynthesizerTrn
13
+ from text import text_to_sequence
14
+ import gradio as gr
15
+ import time
16
+ import datetime
17
+ import os
18
+ import librosa
19
+ class VitsGradio:
20
+ def __init__(self):
21
+ self.dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
22
+ self.lan = ["中文","日文","自动","手动"]
23
+ self.idols = ["c1","c2","高咲侑","歩夢","かすみ","しずく","果林","愛","彼方","せつ菜","璃奈","栞子","エマ","ランジュ","ミア","華恋","まひる","なな","クロディーヌ","ひかり",'純那',"香子","真矢","双葉","ミチル","メイファン","やちよ","晶","いちえ","ゆゆ子","塁","珠緒","あるる","ララフィン","美空","静羽","あるる"]
24
+ self.modelPaths = []
25
+ for root,dirs,files in os.walk("checkpoints"):
26
+ for dir in dirs:
27
+ self.modelPaths.append(dir)
28
+ with gr.Blocks() as self.Vits:
29
+ gr.Markdown(
30
+ "## <center> Lovelive虹团中日双语VITS\n"
31
+ "### <center> 请不要生成会对个人以及企划造成侵害的内容\n"
32
+ "<div align='center'>目前有标贝普通话版,去标贝版,少歌模型还是大饼状态</div>"
33
+ '<div align="center"><a>参数说明:由于爱抖露们过于有感情,合成日语时建议将噪声比例调节至0.2-0.3区间,噪声偏差对应着每个字之间的间隔,对普通话影响较大,duration代表整体语速</div>'
34
+ '<div align="center"><a>合成前请先选择模型,否则第一次合成不一定成功。长段落/小说合成建议colab或本地运行</div>')
35
+ with gr.Tab("TTS合成"):
36
+ with gr.Row():
37
+ with gr.Column():
38
+ with gr.Row():
39
+ with gr.Column():
40
+ input1 = gr.TextArea(label="Text", value="为什么你会那么熟练啊?你和雪菜亲过多少次了")
41
+ input2 = gr.Dropdown(label="Language", choices=self.lan, value="自动", interactive=True)
42
+ input3 = gr.Dropdown(label="Speaker", choices=self.idols, value="歩夢", interactive=True)
43
+ btnVC = gr.Button("Submit")
44
+ with gr.Column():
45
+ input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.267)
46
+ input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.7)
47
+ input6 = gr.Slider(minimum=0.1, maximum=10, label="duration", value=1)
48
+ output1 = gr.Audio(label="采样率22050")
49
+ btnVC.click(self.infer, inputs=[input1, input2, input3, input4, input5, input6], outputs=[output1])
50
+ with gr.Tab("选择模型"):
51
+ with gr.Column():
52
+ modelstrs = gr.Dropdown(label = "模型", choices = self.modelPaths, value = self.modelPaths[0], type = "value")
53
+ btnMod = gr.Button("载入模型")
54
+ statusa = gr.TextArea()
55
+ btnMod.click(self.loadCk, inputs=[modelstrs], outputs = [statusa])
56
+ with gr.Tab("Voice Conversion"):
57
+ gr.Markdown("""
58
+ 录制或上传声音,并选择要转换的音色。
59
+ """)
60
+ with gr.Column():
61
+ record_audio = gr.Audio(label="record your voice", source="microphone")
62
+ upload_audio = gr.Audio(label="or upload audio here", source="upload")
63
+ source_speaker = gr.Dropdown(choices=self.idols, value="歩夢", label="source speaker")
64
+ target_speaker = gr.Dropdown(choices=self.idols, value="歩夢", label="target speaker")
65
+ with gr.Column():
66
+ message_box = gr.Textbox(label="Message")
67
+ converted_audio = gr.Audio(label='converted audio')
68
+ btn = gr.Button("Convert!")
69
+ btn.click(self.vc_fn, inputs=[source_speaker, target_speaker, record_audio, upload_audio],
70
+ outputs=[message_box, converted_audio])
71
+ with gr.Tab("小说合成(带字幕)"):
72
+ with gr.Row():
73
+ with gr.Column():
74
+ with gr.Row():
75
+ with gr.Column():
76
+ input1 = gr.TextArea(label="建议colab或本地克隆后运行本仓库", value="为什么你会那么熟练啊?你和雪菜亲过多少次了")
77
+ input2 = gr.Dropdown(label="Language", choices=self.lan, value="自动", interactive=True)
78
+ input3 = gr.Dropdown(label="Speaker", choices=self.idols, value="歩夢", interactive=True)
79
+ btnVC = gr.Button("Submit")
80
+ with gr.Column():
81
+ input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.267)
82
+ input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.7)
83
+ input6 = gr.Slider(minimum=0.1, maximum=10, label="Duration", value=1)
84
+ output1 = gr.Audio(label="采样率22050")
85
+ subtitle = gr.outputs.File(label="字幕文件:subtitles.srt")
86
+ btnVC.click(self.infer2, inputs=[input1, input2, input3, input4, input5, input6], outputs=[output1,subtitle])
87
+
88
+ def loadCk(self,path):
89
+ self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
90
+ n_symbols = len(self.hps.symbols) if 'symbols' in self.hps.keys() else 0
91
+ self.net_g = SynthesizerTrn(
92
+ n_symbols,
93
+ self.hps.data.filter_length // 2 + 1,
94
+ self.hps.train.segment_size // self.hps.data.hop_length,
95
+ n_speakers=self.hps.data.n_speakers,
96
+ **self.hps.model).to(self.dev)
97
+ _ = self.net_g.eval()
98
+ _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", self.net_g)
99
+ return "success"
100
+
101
+ def get_text(self,text):
102
+ text_norm = text_to_sequence(text,self.hps.symbols,self.hps.data.text_cleaners)
103
+ if self.hps.data.add_blank:
104
+ text_norm = commons.intersperse(text_norm, 0)
105
+ text_norm = torch.LongTensor(text_norm)
106
+ return text_norm
107
+
108
+ def is_japanese(self,string):
109
+ for ch in string:
110
+ if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
111
+ return True
112
+ return False
113
+
114
+ def is_english(self,string):
115
+ import re
116
+ pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
117
+ if pattern.fullmatch(string):
118
+ return True
119
+ else:
120
+ return False
121
+
122
+ def selection(self,speaker):
123
+ if speaker == "高咲侑":
124
+ spk = 0
125
+ return spk
126
+
127
+ elif speaker == "歩夢":
128
+ spk = 1
129
+ return spk
130
+
131
+ elif speaker == "かすみ":
132
+ spk = 2
133
+ return spk
134
+
135
+ elif speaker == "しずく":
136
+ spk = 3
137
+ return spk
138
+
139
+ elif speaker == "果林":
140
+ spk = 4
141
+ return spk
142
+
143
+ elif speaker == "愛":
144
+ spk = 5
145
+ return spk
146
+
147
+ elif speaker == "彼方":
148
+ spk = 6
149
+ return spk
150
+
151
+ elif speaker == "せつ菜":
152
+ spk = 7
153
+ return spk
154
+ elif speaker == "エマ":
155
+ spk = 8
156
+ return spk
157
+ elif speaker == "璃奈":
158
+ spk = 9
159
+ return spk
160
+ elif speaker == "栞子":
161
+ spk = 10
162
+ return spk
163
+ elif speaker == "ランジュ":
164
+ spk = 11
165
+ return spk
166
+ elif speaker == "ミア":
167
+ spk = 12
168
+ return spk
169
+
170
+ elif speaker == "派蒙":
171
+ spk = 16
172
+ return spk
173
+
174
+ elif speaker == "c1":
175
+ spk = 18
176
+ return spk
177
+
178
+ elif speaker == "c2":
179
+ spk = 19
180
+ return spk
181
+
182
+ elif speaker == "華恋":
183
+ spk = 21
184
+ return spk
185
+
186
+ elif speaker == "まひる":
187
+ spk = 22
188
+ return spk
189
+
190
+ elif speaker == "なな":
191
+ spk = 23
192
+ return spk
193
+
194
+ elif speaker == "クロディーヌ":
195
+ spk = 24
196
+ return spk
197
+
198
+ elif speaker == "ひかり":
199
+ spk = 25
200
+ return spk
201
+
202
+ elif speaker == "純那":
203
+ spk = 26
204
+ return spk
205
+
206
+ elif speaker == "香子":
207
+ spk = 27
208
+ return spk
209
+
210
+ elif speaker == "真矢":
211
+ spk = 28
212
+ return spk
213
+ elif speaker == "双葉":
214
+ spk = 29
215
+ return spk
216
+ elif speaker == "ミチル":
217
+ spk = 30
218
+ return spk
219
+ elif speaker == "メイファン":
220
+ spk = 31
221
+ return spk
222
+ elif speaker == "やちよ":
223
+ spk = 32
224
+ return spk
225
+ elif speaker == "晶":
226
+ spk = 33
227
+ return spk
228
+ elif speaker == "いちえ":
229
+ spk = 34
230
+ return spk
231
+ elif speaker == "ゆゆ子":
232
+ spk = 35
233
+ return spk
234
+ elif speaker == "塁":
235
+ spk = 36
236
+ return spk
237
+ elif speaker == "珠緒":
238
+ spk = 37
239
+ return spk
240
+ elif speaker == "あるる":
241
+ spk = 38
242
+ return spk
243
+ elif speaker == "ララフィン":
244
+ spk = 39
245
+ return spk
246
+ elif speaker == "美空":
247
+ spk = 40
248
+ return spk
249
+ elif speaker == "静羽":
250
+ spk = 41
251
+ return spk
252
+ else:
253
+ return 0
254
+
255
+
256
+ def sle(self,language,text):
257
+ text = text.replace('\n','。').replace(' ',',')
258
+ if language == "中文":
259
+ tts_input1 = "[ZH]" + text + "[ZH]"
260
+ return tts_input1
261
+ elif language == "自动":
262
+ tts_input1 = f"[JA]{text}[JA]" if self.is_japanese(text) else f"[ZH]{text}[ZH]"
263
+ return tts_input1
264
+ elif language == "日文":
265
+ tts_input1 = "[JA]" + text + "[JA]"
266
+ return tts_input1
267
+ elif language == "英文":
268
+ tts_input1 = "[EN]" + text + "[EN]"
269
+ return tts_input1
270
+ elif language == "手动":
271
+ return text
272
+
273
+ def extrac(self,text):
274
+ text = re.sub("<[^>]*>","",text)
275
+ result_list = re.split(r'\n', text)
276
+ final_list = []
277
+ for i in result_list:
278
+ if self.is_english(i):
279
+ i = romajitable.to_kana(i).katakana
280
+ i = i.replace('\n','').replace(' ','')
281
+ #Current length of single sentence: 20
282
+ if len(i)>1:
283
+ if len(i) > 20:
284
+ try:
285
+ cur_list = re.split(r'。|!', i)
286
+ for i in cur_list:
287
+ if len(i)>1:
288
+ final_list.append(i+'。')
289
+ except:
290
+ pass
291
+ else:
292
+ final_list.append(i)
293
+ final_list = [x for x in final_list if x != '']
294
+ print(final_list)
295
+ return final_list
296
+
297
+ def vc_fn(self,original_speaker, target_speaker, record_audio, upload_audio):
298
+ input_audio = record_audio if record_audio is not None else upload_audio
299
+ if input_audio is None:
300
+ return "You need to record or upload an audio", None
301
+ sampling_rate, audio = input_audio
302
+ original_speaker_id = self.selection(original_speaker)
303
+ target_speaker_id = self.selection(target_speaker)
304
+
305
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
306
+ if len(audio.shape) > 1:
307
+ audio = librosa.to_mono(audio.transpose(1, 0))
308
+ if sampling_rate != self.hps.data.sampling_rate:
309
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=self.hps.data.sampling_rate)
310
+ with torch.no_grad():
311
+ y = torch.FloatTensor(audio)
312
+ y = y / max(-y.min(), y.max()) / 0.99
313
+ y = y.to(self.dev)
314
+ y = y.unsqueeze(0)
315
+ spec = spectrogram_torch(y, self.hps.data.filter_length,
316
+ self.hps.data.sampling_rate, self.hps.data.hop_length, self.hps.data.win_length,
317
+ center=False).to(self.dev)
318
+ spec_lengths = torch.LongTensor([spec.size(-1)]).to(self.dev)
319
+ sid_src = torch.LongTensor([original_speaker_id]).to(self.dev)
320
+ sid_tgt = torch.LongTensor([target_speaker_id]).to(self.dev)
321
+ audio = self.net_g.voice_conversion(spec, spec_lengths, sid_src=sid_src, sid_tgt=sid_tgt)[0][
322
+ 0, 0].data.cpu().float().numpy()
323
+ del y, spec, spec_lengths, sid_src, sid_tgt
324
+ return "Success", (self.hps.data.sampling_rate, audio)
325
+
326
+ def infer(self, text ,language, speaker_id,n_scale= 0.667,n_scale_w = 0.8, l_scale = 1):
327
+ try:
328
+ speaker_id = int(self.selection(speaker_id))
329
+ t1 = time.time()
330
+ stn_tst = self.get_text(self.sle(language,text))
331
+ with torch.no_grad():
332
+ x_tst = stn_tst.unsqueeze(0).to(self.dev)
333
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(self.dev)
334
+ sid = torch.LongTensor([speaker_id]).to(self.dev)
335
+ audio = self.net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=n_scale, noise_scale_w=n_scale_w, length_scale=l_scale)[0][0,0].data.cpu().float().numpy()
336
+ t2 = time.time()
337
+ spending_time = "推理时间为:"+str(t2-t1)+"s"
338
+ print(spending_time)
339
+ return (self.hps.data.sampling_rate, audio)
340
+ except:
341
+ self.hps = utils.get_hparams_from_file(f"checkpoints/biaobei/config.json")
342
+ self.net_g = SynthesizerTrn(
343
+ len(symbols),
344
+ self.hps.data.filter_length // 2 + 1,
345
+ self.hps.train.segment_size // self.hps.data.hop_length,
346
+ n_speakers=self.hps.data.n_speakers,
347
+ **self.hps.model).to(self.dev)
348
+ _ = self.net_g.eval()
349
+ _ = utils.load_checkpoint(f"checkpoints/biaobei/model.pth", self.net_g)
350
+
351
+ def infer2(self, text ,language, speaker_id,n_scale= 0.667,n_scale_w = 0.8, l_scale = 1):
352
+ speaker_id = int(self.selection(speaker_id))
353
+ a = ['【','[','(','(']
354
+ b = ['】',']',')',')']
355
+ for i in a:
356
+ text = text.replace(i,'<')
357
+ for i in b:
358
+ text = text.replace(i,'>')
359
+ final_list = self.extrac(text.replace('“','').replace('”',''))
360
+ audio_fin = []
361
+ c = 0
362
+ t = datetime.timedelta(seconds=0)
363
+ f1 = open("subtitles.srt",'w',encoding='utf-8')
364
+ for sentence in final_list:
365
+ c +=1
366
+ stn_tst = self.get_text(self.sle(language,sentence))
367
+ with torch.no_grad():
368
+ x_tst = stn_tst.unsqueeze(0).to(self.dev)
369
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(self.dev)
370
+ sid = torch.LongTensor([speaker_id]).to(self.dev)
371
+ t1 = time.time()
372
+ audio = self.net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=n_scale, noise_scale_w=n_scale_w, length_scale=l_scale)[0][0,0].data.cpu().float().numpy()
373
+ t2 = time.time()
374
+ spending_time = "第"+str(c)+"句的推理时间为:"+str(t2-t1)+"s"
375
+ print(spending_time)
376
+ time_start = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
377
+ last_time = datetime.timedelta(seconds=len(audio)/float(22050))
378
+ t+=last_time
379
+ time_end = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
380
+ print(time_end)
381
+ f1.write(str(c-1)+'\n'+time_start+' --> '+time_end+'\n'+sentence+'\n\n')
382
+ audio_fin.append(audio)
383
+ file_path = "subtitles.srt"
384
+ return (self.hps.data.sampling_rate, np.concatenate(audio_fin)),file_path
385
+ print("开始部署")
386
+ grVits = VitsGradio()
387
+ grVits.Vits.launch()
attentions.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ from modules import LayerNorm
8
+
9
+
10
+ class Encoder(nn.Module):
11
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
12
+ super().__init__()
13
+ self.hidden_channels = hidden_channels
14
+ self.filter_channels = filter_channels
15
+ self.n_heads = n_heads
16
+ self.n_layers = n_layers
17
+ self.kernel_size = kernel_size
18
+ self.p_dropout = p_dropout
19
+ self.window_size = window_size
20
+
21
+ self.drop = nn.Dropout(p_dropout)
22
+ self.attn_layers = nn.ModuleList()
23
+ self.norm_layers_1 = nn.ModuleList()
24
+ self.ffn_layers = nn.ModuleList()
25
+ self.norm_layers_2 = nn.ModuleList()
26
+ for i in range(self.n_layers):
27
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
28
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
29
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
30
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
31
+
32
+ def forward(self, x, x_mask):
33
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
34
+ x = x * x_mask
35
+ for i in range(self.n_layers):
36
+ y = self.attn_layers[i](x, x, attn_mask)
37
+ y = self.drop(y)
38
+ x = self.norm_layers_1[i](x + y)
39
+
40
+ y = self.ffn_layers[i](x, x_mask)
41
+ y = self.drop(y)
42
+ x = self.norm_layers_2[i](x + y)
43
+ x = x * x_mask
44
+ return x
45
+
46
+
47
+ class Decoder(nn.Module):
48
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
49
+ super().__init__()
50
+ self.hidden_channels = hidden_channels
51
+ self.filter_channels = filter_channels
52
+ self.n_heads = n_heads
53
+ self.n_layers = n_layers
54
+ self.kernel_size = kernel_size
55
+ self.p_dropout = p_dropout
56
+ self.proximal_bias = proximal_bias
57
+ self.proximal_init = proximal_init
58
+
59
+ self.drop = nn.Dropout(p_dropout)
60
+ self.self_attn_layers = nn.ModuleList()
61
+ self.norm_layers_0 = nn.ModuleList()
62
+ self.encdec_attn_layers = nn.ModuleList()
63
+ self.norm_layers_1 = nn.ModuleList()
64
+ self.ffn_layers = nn.ModuleList()
65
+ self.norm_layers_2 = nn.ModuleList()
66
+ for i in range(self.n_layers):
67
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
68
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
69
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
70
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
71
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
72
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
73
+
74
+ def forward(self, x, x_mask, h, h_mask):
75
+ """
76
+ x: decoder input
77
+ h: encoder output
78
+ """
79
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
80
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
81
+ x = x * x_mask
82
+ for i in range(self.n_layers):
83
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
84
+ y = self.drop(y)
85
+ x = self.norm_layers_0[i](x + y)
86
+
87
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
88
+ y = self.drop(y)
89
+ x = self.norm_layers_1[i](x + y)
90
+
91
+ y = self.ffn_layers[i](x, x_mask)
92
+ y = self.drop(y)
93
+ x = self.norm_layers_2[i](x + y)
94
+ x = x * x_mask
95
+ return x
96
+
97
+
98
+ class MultiHeadAttention(nn.Module):
99
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
100
+ super().__init__()
101
+ assert channels % n_heads == 0
102
+
103
+ self.channels = channels
104
+ self.out_channels = out_channels
105
+ self.n_heads = n_heads
106
+ self.p_dropout = p_dropout
107
+ self.window_size = window_size
108
+ self.heads_share = heads_share
109
+ self.block_length = block_length
110
+ self.proximal_bias = proximal_bias
111
+ self.proximal_init = proximal_init
112
+ self.attn = None
113
+
114
+ self.k_channels = channels // n_heads
115
+ self.conv_q = nn.Conv1d(channels, channels, 1)
116
+ self.conv_k = nn.Conv1d(channels, channels, 1)
117
+ self.conv_v = nn.Conv1d(channels, channels, 1)
118
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
119
+ self.drop = nn.Dropout(p_dropout)
120
+
121
+ if window_size is not None:
122
+ n_heads_rel = 1 if heads_share else n_heads
123
+ rel_stddev = self.k_channels**-0.5
124
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
125
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
126
+
127
+ nn.init.xavier_uniform_(self.conv_q.weight)
128
+ nn.init.xavier_uniform_(self.conv_k.weight)
129
+ nn.init.xavier_uniform_(self.conv_v.weight)
130
+ if proximal_init:
131
+ with torch.no_grad():
132
+ self.conv_k.weight.copy_(self.conv_q.weight)
133
+ self.conv_k.bias.copy_(self.conv_q.bias)
134
+
135
+ def forward(self, x, c, attn_mask=None):
136
+ q = self.conv_q(x)
137
+ k = self.conv_k(c)
138
+ v = self.conv_v(c)
139
+
140
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
141
+
142
+ x = self.conv_o(x)
143
+ return x
144
+
145
+ def attention(self, query, key, value, mask=None):
146
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
147
+ b, d, t_s, t_t = (*key.size(), query.size(2))
148
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
149
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
150
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
151
+
152
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
153
+ if self.window_size is not None:
154
+ assert t_s == t_t, "Relative attention is only available for self-attention."
155
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
156
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
157
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
158
+ scores = scores + scores_local
159
+ if self.proximal_bias:
160
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
161
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
162
+ if mask is not None:
163
+ scores = scores.masked_fill(mask == 0, -1e4)
164
+ if self.block_length is not None:
165
+ assert t_s == t_t, "Local attention is only available for self-attention."
166
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
167
+ scores = scores.masked_fill(block_mask == 0, -1e4)
168
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
169
+ p_attn = self.drop(p_attn)
170
+ output = torch.matmul(p_attn, value)
171
+ if self.window_size is not None:
172
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
173
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
174
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
175
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
176
+ return output, p_attn
177
+
178
+ def _matmul_with_relative_values(self, x, y):
179
+ """
180
+ x: [b, h, l, m]
181
+ y: [h or 1, m, d]
182
+ ret: [b, h, l, d]
183
+ """
184
+ ret = torch.matmul(x, y.unsqueeze(0))
185
+ return ret
186
+
187
+ def _matmul_with_relative_keys(self, x, y):
188
+ """
189
+ x: [b, h, l, d]
190
+ y: [h or 1, m, d]
191
+ ret: [b, h, l, m]
192
+ """
193
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
194
+ return ret
195
+
196
+ def _get_relative_embeddings(self, relative_embeddings, length):
197
+ max_relative_position = 2 * self.window_size + 1
198
+ # Pad first before slice to avoid using cond ops.
199
+ pad_length = max(length - (self.window_size + 1), 0)
200
+ slice_start_position = max((self.window_size + 1) - length, 0)
201
+ slice_end_position = slice_start_position + 2 * length - 1
202
+ if pad_length > 0:
203
+ padded_relative_embeddings = F.pad(
204
+ relative_embeddings,
205
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
206
+ else:
207
+ padded_relative_embeddings = relative_embeddings
208
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
209
+ return used_relative_embeddings
210
+
211
+ def _relative_position_to_absolute_position(self, x):
212
+ """
213
+ x: [b, h, l, 2*l-1]
214
+ ret: [b, h, l, l]
215
+ """
216
+ batch, heads, length, _ = x.size()
217
+ # Concat columns of pad to shift from relative to absolute indexing.
218
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
219
+
220
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
221
+ x_flat = x.view([batch, heads, length * 2 * length])
222
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
223
+
224
+ # Reshape and slice out the padded elements.
225
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
226
+ return x_final
227
+
228
+ def _absolute_position_to_relative_position(self, x):
229
+ """
230
+ x: [b, h, l, l]
231
+ ret: [b, h, l, 2*l-1]
232
+ """
233
+ batch, heads, length, _ = x.size()
234
+ # padd along column
235
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
236
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
237
+ # add 0's in the beginning that will skew the elements after reshape
238
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
239
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
240
+ return x_final
241
+
242
+ def _attention_bias_proximal(self, length):
243
+ """Bias for self-attention to encourage attention to close positions.
244
+ Args:
245
+ length: an integer scalar.
246
+ Returns:
247
+ a Tensor with shape [1, 1, length, length]
248
+ """
249
+ r = torch.arange(length, dtype=torch.float32)
250
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
251
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
252
+
253
+
254
+ class FFN(nn.Module):
255
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
256
+ super().__init__()
257
+ self.in_channels = in_channels
258
+ self.out_channels = out_channels
259
+ self.filter_channels = filter_channels
260
+ self.kernel_size = kernel_size
261
+ self.p_dropout = p_dropout
262
+ self.activation = activation
263
+ self.causal = causal
264
+
265
+ if causal:
266
+ self.padding = self._causal_padding
267
+ else:
268
+ self.padding = self._same_padding
269
+
270
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
271
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
272
+ self.drop = nn.Dropout(p_dropout)
273
+
274
+ def forward(self, x, x_mask):
275
+ x = self.conv_1(self.padding(x * x_mask))
276
+ if self.activation == "gelu":
277
+ x = x * torch.sigmoid(1.702 * x)
278
+ else:
279
+ x = torch.relu(x)
280
+ x = self.drop(x)
281
+ x = self.conv_2(self.padding(x * x_mask))
282
+ return x * x_mask
283
+
284
+ def _causal_padding(self, x):
285
+ if self.kernel_size == 1:
286
+ return x
287
+ pad_l = self.kernel_size - 1
288
+ pad_r = 0
289
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
290
+ x = F.pad(x, commons.convert_pad_shape(padding))
291
+ return x
292
+
293
+ def _same_padding(self, x):
294
+ if self.kernel_size == 1:
295
+ return x
296
+ pad_l = (self.kernel_size - 1) // 2
297
+ pad_r = self.kernel_size // 2
298
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
299
+ x = F.pad(x, commons.convert_pad_shape(padding))
300
+ return x
checkpoints/ShojoKageki/config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 32,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"/www/training/dataset/train_with_paimeng2.txt",
21
+ "validation_files":"/www/training/dataset/val_filelist.txt",
22
+ "text_cleaners":["cjke_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 50,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "A", "E", "I", "N", "O", "Q", "U", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "v", "w", "y", "z", "\u0283", "\u02a7", "\u02a6", "\u026f", "\u0279", "\u0259", "\u0265", "\u207c", "\u02b0", "`", "\u2192", "\u2193", "\u2191", " "]
54
+ }
checkpoints/ShojoKageki/model-0ld.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aacf2ab87f213ef06fde55066569c1b947761c5bab8e2f389db330097fb4b425
3
+ size 476964251
checkpoints/ShojoKageki/model-1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60939942eb23ba8b12583ffb3402da8ef5442740efeef4b05a315b068ad87451
3
+ size 476964251
checkpoints/ShojoKageki/model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9feb190c113f26d1a273c7fd5047beedacc064528668c3d1715da163c63efef
3
+ size 476964251
checkpoints/biaobei/config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 32,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"/www/training/dataset/train_with_paimeng2.txt",
21
+ "validation_files":"/www/training/dataset/val_filelist.txt",
22
+ "text_cleaners":["cjke_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 50,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "N", "Q", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "s", "t", "u", "v", "w", "x", "y", "z", "\u0251", "\u00e6", "\u0283", "\u0291", "\u00e7", "\u026f", "\u026a", "\u0254", "\u025b", "\u0279", "\u00f0", "\u0259", "\u026b", "\u0265", "\u0278", "\u028a", "\u027e", "\u0292", "\u03b8", "\u03b2", "\u014b", "\u0266", "\u207c", "\u02b0", "`", "^", "#", "*", "=", "\u02c8", "\u02cc", "\u2192", "\u2193", "\u2191", " "]
54
+ }
checkpoints/biaobei/model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:715cb3e0c35b288b465c24040817b0b75379b16f3e9ad9a191a5dbcd7c2143b2
3
+ size 476967685
checkpoints/default/config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 32,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"/www/training/dataset/train_with_paimeng2.txt",
21
+ "validation_files":"/www/training/dataset/val_filelist.txt",
22
+ "text_cleaners":["cjke_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 50,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "N", "Q", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "s", "t", "u", "v", "w", "x", "y", "z", "\u0251", "\u00e6", "\u0283", "\u0291", "\u00e7", "\u026f", "\u026a", "\u0254", "\u025b", "\u0279", "\u00f0", "\u0259", "\u026b", "\u0265", "\u0278", "\u028a", "\u027e", "\u0292", "\u03b8", "\u03b2", "\u014b", "\u0266", "\u207c", "\u02b0", "`", "^", "#", "*", "=", "\u02c8", "\u02cc", "\u2192", "\u2193", "\u2191", " "]
54
+ }
checkpoints/default/model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9114848f7b7f854a030064600a4703ee7d22f76bdf6a12b2335874faf4f93c52
3
+ size 476964251
checkpoints/info.json ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Seisho-Nijigasaki":{
3
+ "speakers":{
4
+ "華恋":{
5
+ "sid": 21,
6
+ "speech": "私たちはもう舞台の上。",
7
+ "name": "華恋"
8
+ },
9
+ "まひる":{
10
+ "sid": 22,
11
+ "speech": "夢咲く舞台に、輝け、私!",
12
+ "name": "まひる"
13
+ },
14
+ "なな":{
15
+ "sid": 23,
16
+ "speech": "燃える宝石のようなキラめき、やっと届いた。ありがとう、純那ちゃん。",
17
+ "name": "なな"
18
+ },
19
+ "クロディーヌ":{
20
+ "sid": 24,
21
+ "speech": "ライバルのレヴューは終わらない、永遠に。",
22
+ "name": "クロディーヌ"
23
+ },
24
+ "ひかり":{
25
+ "sid": 25,
26
+ "speech": "じゃあ、探しに行きなさいよ。次の舞台、次の役を。",
27
+ "name": "ひかり"
28
+ },
29
+ "純那":{
30
+ "sid": 26,
31
+ "speech": "でもいつか、いつかまた新しい舞台で、一緒に。",
32
+ "name": "純那"
33
+ },
34
+ "香子":{
35
+ "sid": 27,
36
+ "speech": "ガキのわがままには勝てんわ。",
37
+ "name": "香子"
38
+ },
39
+ "真矢":{
40
+ "sid": 28,
41
+ "speech": "私たちは、燃えながら、ともに落ちていく炎。",
42
+ "name": "真矢"
43
+ },
44
+ "双葉":{
45
+ "sid": 29,
46
+ "speech": "ほんと、しょうもないな、あたしたち。",
47
+ "name": "双葉"
48
+ },
49
+ "珠緒":{
50
+ "sid": 37,
51
+ "speech": "お持ちなさい あなたの望んだその星を。",
52
+ "name": "珠緒"
53
+ },
54
+ "塁":{
55
+ "sid": 36,
56
+ "speech": "凛明館女学校演劇科,秋風塁。命の在処 この舞台に見つけたり。",
57
+ "name": "塁"
58
+ },
59
+ "ゆゆ子":{
60
+ "sid": 35,
61
+ "speech": "凛明館女学校演劇科 田中ゆゆ子!命かけたる正念場 いざご覧あれ!",
62
+ "name": "ゆゆ子"
63
+ },
64
+ "いちえ":{
65
+ "sid": 34,
66
+ "speech": "凛明館女学校演劇科,音無いちえ。聞かせて魅せます,命の響!",
67
+ "name": "いちえ"
68
+ },
69
+ "あるる":{
70
+ "sid": 38,
71
+ "speech": "舞台少女,大月あるる。いどめ向かい風 すすめフロンティア!",
72
+ "name": "あるる"
73
+ },
74
+ "ララフィン":{
75
+ "sid": 39,
76
+ "speech": "舞台少女,野々宮ララフィン。愛と勇気で すすめフロンティア。",
77
+ "name": "ララフィン"
78
+ },
79
+ "美空":{
80
+ "sid": 40,
81
+ "speech": "私の舞台は,この胸、この奥。",
82
+ "name": "美空"
83
+ },
84
+ "静羽":{
85
+ "sid": 41,
86
+ "speech": "舞台少女,胡蝶静羽。あの空目指して すすめフロンティア。",
87
+ "name": "静羽"
88
+ },
89
+ "ミチル":{
90
+ "sid": 30,
91
+ "speech": "わが宿命は、王と共に。",
92
+ "name": "ミチル"
93
+ },
94
+ "メイファン":{
95
+ "sid": 31,
96
+ "speech": "重力转动九十九万匹力量,海虎爆破拳!",
97
+ "name": "メイファン"
98
+ },
99
+ "やちよ":{
100
+ "sid": 32,
101
+ "speech": "この世は舞台王すらも役者——ですよ?",
102
+ "name": "やちよ"
103
+ },
104
+ "晶":{
105
+ "sid": 33,
106
+ "speech": "アタシ――再契約,神無き舞台に王者の光を。",
107
+ "name": "晶"
108
+ },
109
+ "歩夢":{
110
+ "sid": 1,
111
+ "speech": "みなさん、はじめまして。上原歩夢です。",
112
+ "name": "歩夢"
113
+ },
114
+ "かすみ":{
115
+ "sid": 2,
116
+ "speech": "みんなのアイドルかすみんだよー。",
117
+ "name": "かすみ"
118
+ },
119
+ "しずく":{
120
+ "sid": 3,
121
+ "speech": "みなさん、こんにちは。しずくです。",
122
+ "name": "しずく"
123
+ },
124
+ "果林":{
125
+ "sid": 4,
126
+ "speech": "ハーイ。 朝香果林よ。よろしくね",
127
+ "name": "果林"
128
+ },
129
+ "愛":{
130
+ "sid": 5,
131
+ "speech": "ちっすー。アタシは愛。",
132
+ "name": "愛"
133
+ },
134
+ "せつ菜":{
135
+ "sid": 7,
136
+ "speech": "絶えぬ命は,常世に在らず。終わらぬ芝居も,夢幻のごとく。儚く燃えゆく,さだめであれば。舞台に刻まん,刹那の瞬き。",
137
+ "name": "せつ菜"
138
+ },
139
+ "エマ":{
140
+ "sid": 8,
141
+ "speech": "こんにちは、エマです。自然溢れるスイスからやってきましたっ。",
142
+ "name": "エマ"
143
+ },
144
+ "璃奈":{
145
+ "sid": 9,
146
+ "speech": "私、天王寺璃奈。とってもきゅーとな女の子。ホントだよ?",
147
+ "name": "璃奈"
148
+ },
149
+ "栞子":{
150
+ "sid": 10,
151
+ "speech": "みなさん、初めまして。三船栞子と申します。",
152
+ "name": "栞子"
153
+ },
154
+ "ランジュ":{
155
+ "sid": 11,
156
+ "speech": "你好啊,我是钟岚珠。",
157
+ "name": "ランジュ"
158
+ },
159
+ "ミア":{
160
+ "sid": 12,
161
+ "speech": "ボクはミア・テイラー。",
162
+ "name": "ミア"
163
+ },
164
+ "高咲侑":{
165
+ "sid": 0,
166
+ "speech": "只选一个做不到啊",
167
+ "name": "高咲侑"
168
+ }
169
+ },
170
+ "checkpoint": "checkpoints/tmp/model.pth"
171
+
172
+ },
173
+ "Seisho-betterchinese":{
174
+ "speakers":{
175
+ "華恋":{
176
+ "sid": 21,
177
+ "speech": "何为农业世界,毕竟人是铁饭是钢,吃这东西一直都是刚需。而农业世界专职从事于生产,也就成为了帝国字面意思上的粮仓。",
178
+ "name": "華恋"
179
+ },
180
+ "まひる":{
181
+ "sid": 22,
182
+ "speech": "倘若没有农业世界那持续的产出,可能周围的星系乃至整个次星区都有可能陷入饥荒和饿肚子。",
183
+ "name": "まひる"
184
+ },
185
+ "なな":{
186
+ "sid": 23,
187
+ "speech": "虽说许多文明世界和巢都世界都有着一定自给自足的能力,比如瓦尔哈拉的众多居民必须在黑暗的洞穴中劳作来培育维持民众生活的营养泥 ;涅克蒙洛达上的尸体行会也会不断回收死者并将其回收制成尸体淀粉以喂饱更多的生者。",
188
+ "name": "なな"
189
+ },
190
+ "クロディーヌ":{
191
+ "sid": 24,
192
+ "speech": "而德索莱姆的巢都中也会进口大量来自其他世界海洋中的有机物,并被制成浓稠、富含蛋白质的稀粥,随后被用来喂养伊洛克胆蝇幼虫,接着这些幼虫会在合适的时机被打浆、压缩并成型为臭名昭著的油腻且普遍厌恶的口粮棒,这些口粮棒也被用来喂饱规模庞大的工厂工人和士兵。",
193
+ "name": "クロディーヌ"
194
+ },
195
+ "ひかり":{
196
+ "sid": 25,
197
+ "speech": "但作为帝国人力资源的最大提供者,并为帝国生产提供了大量工业产品和什一税的巢都世界,在失去外部资源的供给时无疑也是毁灭性的打击,被隔离的阿戈斯已经生动的为各个巢都世界上了一节名为“隔绝灭亡”的课了。",
198
+ "name": "ひかり"
199
+ },
200
+ "純那":{
201
+ "sid": 26,
202
+ "speech": "而这些补给资源的来源很大一部分则是来自于农业世界。",
203
+ "name": "純那"
204
+ },
205
+ "香子":{
206
+ "sid": 27,
207
+ "speech": "农业世界完全致力于农业产品的生产,并将这些产出用于喂饱巢都世界和铸造世界上嗷嗷待哺的饥饿人口,当然了,还有的便是为那星界军的庞大部队提供食粮。",
208
+ "name": "香子"
209
+ },
210
+ "真矢":{
211
+ "sid": 28,
212
+ "speech": "农业世界有时甚至会直接被内政部管理而不是当地行星政府,这一切都只是为了确保这些农业世界能以最大效率种植和收获作物。",
213
+ "name": "真矢"
214
+ },
215
+ "双葉":{
216
+ "sid": 29,
217
+ "speech": "作为农业世界,整个世界上的大部分区域都被用于种植、水培、动物饲料或畜牧业生产。其中许多行星已经完全变成了巨型农场,其中大多数人口不足1亿,并在星球上仅有数个主要城市。",
218
+ "name": "双葉"
219
+ },
220
+ "珠緒":{
221
+ "sid": 37,
222
+ "speech": "以农业世界纳扬为例,这个世界上种植这7种富含营养的作物,这里的超级农业工厂种共有超过300万名机仆,但只有20万人在这��控制着半自动车辆并监督者气象网络控制节点。",
223
+ "name": "珠緒"
224
+ },
225
+ "塁":{
226
+ "sid": 36,
227
+ "speech": "这里的军事人员和其他机构也并不多,可以说在许多混沌战帮的眼中不亚于一个唾手可得的战利品。",
228
+ "name": "塁"
229
+ },
230
+ "ゆゆ子":{
231
+ "sid": 35,
232
+ "speech": "农业世界的组成部分也相当不同,内政部也会根据当地环境、气候或是特殊情况而创造出不同的农业世界。",
233
+ "name": "ゆゆ子"
234
+ },
235
+ "いちえ":{
236
+ "sid": 34,
237
+ "speech": "比如世界上可能是受人监管的水培湖;悬浮在空心行星上的漂浮田野;或是深埋在辐射山脉中的藻类大桶。",
238
+ "name": "いちえ"
239
+ },
240
+ "あるる":{
241
+ "sid": 38,
242
+ "speech": "但无论如何,这些农业世界都致力于一个目标:喂饱帝国的亿万人口。有时即使是最轻微的作物歉收或牲畜瘟疫,都可能会让其他世界陷入可怕的饥荒,或使帝国的战线崩溃,因此在帝国日常的运行中,农业世界虽不起眼但至关重要。",
243
+ "name": "あるる"
244
+ },
245
+ "ララフィン":{
246
+ "sid": 39,
247
+ "speech": "毕竟只有依靠农业世界的产出,帝国的战争机器才能良好运转。",
248
+ "name": "ララフィン"
249
+ },
250
+ "美空":{
251
+ "sid": 40,
252
+ "speech": "得益于产出的食物,工厂里的工人才不会饿着肚子制造战争引擎,战线上士兵饥饿的肚子才能被填饱。",
253
+ "name": "美空"
254
+ },
255
+ "静羽":{
256
+ "sid": 41,
257
+ "speech": "对于一些独立于帝国之外的叛乱势力而言农业世界也是相当重要的。",
258
+ "name": "静羽"
259
+ },
260
+ "ミチル":{
261
+ "sid": 30,
262
+ "speech": "比如让卡里西斯星区相当苦恼的赛弗鲁公爵领来说,农业世界富特希登便至关重要,因为这里提供了赛弗鲁公爵领的大部分食物供应,这群分离主义势力的绝大多数战略储备均来自这个星球上的什一税。",
263
+ "name": "ミチル"
264
+ },
265
+ "メイファン":{
266
+ "sid": 31,
267
+ "speech": "当然如果赛弗鲁公爵领失去了对这个世界的控制权,那么整个脱离于帝国之外的独立国度将会在几个星期内土崩瓦解。",
268
+ "name": "メイファン"
269
+ },
270
+ "やちよ":{
271
+ "sid": 32,
272
+ "speech": "一些农业世界会专注于种植一些主食作物,因为这些食物相对简单,易于种植、储存,并加工成各种形式,供人类在银河系消费。",
273
+ "name": "やちよ"
274
+ },
275
+ "晶":{
276
+ "sid": 33,
277
+ "speech": "他妈的,怎么到处都是锤佬。",
278
+ "name": "晶"
279
+ },
280
+ "梁芷柔":{
281
+ "sid": 18,
282
+ "speech": "而画风正常一点的农业世界也有,在奥特拉玛,农业世界新星弗利恩便是为马库拉格星系的其他地区提供食物的主要来源。",
283
+ "name": "梁芷柔"
284
+ },
285
+ "墨小菊":{
286
+ "sid": 0,
287
+ "speech": "虽然这里盛产粮食,但这里营养不良依然是折磨当地居民的问题之一,同时因工作原因也让当地人饱受地方性肺病的折磨。",
288
+ "name": "墨小菊"
289
+ }
290
+ },
291
+ "checkpoint": "checkpoints/ShojoKageki/model.pth"
292
+ },
293
+ "Nijigasaki":{
294
+ "speakers":{
295
+ "歩夢":{
296
+ "sid": 1,
297
+ "speech": "みなさん、はじめまして。上原歩夢です。",
298
+ "name": "歩夢"
299
+ },
300
+ "かすみ":{
301
+ "sid": 2,
302
+ "speech": "みんなのアイドルかすみんだよー。",
303
+ "name": "かすみ"
304
+ },
305
+ "しずく":{
306
+ "sid": 3,
307
+ "speech": "みなさん、こんにちは。しずくです。",
308
+ "name": "しずく"
309
+ },
310
+ "果林":{
311
+ "sid": 4,
312
+ "speech": "ハーイ。 朝香果林よ。よろしくね",
313
+ "name": "果林"
314
+ },
315
+ "愛":{
316
+ "sid": 5,
317
+ "speech": "ちっすー。アタシは愛。",
318
+ "name": "愛"
319
+ },
320
+ "せつ菜":{
321
+ "sid": 7,
322
+ "speech": "絶えぬ命は,常世に在らず。終わらぬ芝居も,夢幻のごとく。儚く燃えゆく,さだめであれば。舞台に刻まん,刹那の瞬き。",
323
+ "name": "せつ菜"
324
+ },
325
+ "エマ":{
326
+ "sid": 8,
327
+ "speech": "こんにちは、エマです。自然溢れるスイスからやってきましたっ。",
328
+ "name": "エマ"
329
+ },
330
+ "璃奈":{
331
+ "sid": 9,
332
+ "speech": "私、天王寺璃奈。とってもきゅーとな女の子。ホントだよ?",
333
+ "name": "璃奈"
334
+ },
335
+ "栞子":{
336
+ "sid": 10,
337
+ "speech": "みなさん、初めまして。三船栞子と申します。",
338
+ "name": "栞子"
339
+ },
340
+ "ランジュ":{
341
+ "sid": 11,
342
+ "speech": "你好啊,我是钟岚珠。",
343
+ "name": "ランジュ"
344
+ },
345
+ "ミア":{
346
+ "sid": 12,
347
+ "speech": "ボクはミア・テイラー。",
348
+ "name": "ミア"
349
+ },
350
+ "高咲侑":{
351
+ "sid": 0,
352
+ "speech": "只选一个做不到啊",
353
+ "name": "高咲侑"
354
+ }
355
+ },
356
+ "checkpoint": "checkpoints/paimeng/model.pth"
357
+ },
358
+ "Nijigasaki-biaobei":{
359
+ "speakers":{
360
+ "歩夢":{
361
+ "sid": 1,
362
+ "speech": "みなさん、はじめまして。上原歩夢です。",
363
+ "name": "歩夢"
364
+ },
365
+ "かすみ":{
366
+ "sid": 2,
367
+ "speech": "みんなのアイドルかすみんだよー。",
368
+ "name": "かすみ"
369
+ },
370
+ "しずく":{
371
+ "sid": 3,
372
+ "speech": "みなさん、こんにちは。しずくです。",
373
+ "name": "しずく"
374
+ },
375
+ "果林":{
376
+ "sid": 4,
377
+ "speech": "ハーイ。 朝香果林よ。よろしくね",
378
+ "name": "果林"
379
+ },
380
+ "愛":{
381
+ "sid": 5,
382
+ "speech": "ちっすー。アタシは愛。",
383
+ "name": "愛"
384
+ },
385
+ "せつ菜":{
386
+ "sid": 7,
387
+ "speech": "絶えぬ命は,常世に在らず。終わらぬ芝居も,夢幻のごとく。儚く燃えゆく,さだめであれば。舞台に刻まん,刹那の瞬き。",
388
+ "name": "せつ菜"
389
+ },
390
+ "エマ":{
391
+ "sid": 8,
392
+ "speech": "こんにちは、エマです。自然溢れるスイスからやってきましたっ。",
393
+ "name": "エマ"
394
+ },
395
+ "璃奈":{
396
+ "sid": 9,
397
+ "speech": "私、天王寺璃奈。とってもきゅーとな女の子。ホントだよ?",
398
+ "name": "璃奈"
399
+ },
400
+ "栞子":{
401
+ "sid": 10,
402
+ "speech": "みなさん、初めまして。三船栞子と申します。",
403
+ "name": "栞子"
404
+ },
405
+ "ランジュ":{
406
+ "sid": 11,
407
+ "speech": "你好啊,我是钟岚珠。",
408
+ "name": "ランジュ"
409
+ },
410
+ "ミア":{
411
+ "sid": 12,
412
+ "speech": "ボクはミア・テイラー。",
413
+ "name": "ミア"
414
+ },
415
+ "高咲侑":{
416
+ "sid": 0,
417
+ "speech": "只选一个做不到啊",
418
+ "name": "高咲侑"
419
+ }
420
+ },
421
+ "checkpoint": "checkpoints/biaobei/model.pth"
422
+ }
423
+
424
+ }
checkpoints/paimeng/config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 32,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"/www/training/dataset/train_with_paimeng2.txt",
21
+ "validation_files":"/www/training/dataset/val_filelist.txt",
22
+ "text_cleaners":["cjke_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 50,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "A", "E", "I", "N", "O", "Q", "U", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "v", "w", "y", "z", "\u0283", "\u02a7", "\u02a6", "\u026f", "\u0279", "\u0259", "\u0265", "\u207c", "\u02b0", "`", "\u2192", "\u2193", "\u2191", " "]
54
+ }
checkpoints/paimeng/model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c26f3ab4835c46f91abcf5f5069e20b822657be15a58d818cc6fd2d21abe39a
3
+ size 476967685
checkpoints/tmp/config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 32,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"/www/training/dataset/train_with_paimeng2.txt",
21
+ "validation_files":"/www/training/dataset/val_filelist.txt",
22
+ "text_cleaners":["cjke_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 50,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "A", "E", "I", "N", "O", "Q", "U", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "v", "w", "y", "z", "\u0283", "\u02a7", "\u02a6", "\u026f", "\u0279", "\u0259", "\u0265", "\u207c", "\u02b0", "`", "\u2192", "\u2193", "\u2191", " "]
54
+ }
checkpoints/tmp/model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8b14630c79a536cd9bb32daf850ae24ffe7955608c66cdb799421fb5a4f1309
3
+ size 476964251
commons.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+ import torch.jit
5
+
6
+
7
+ def script_method(fn, _rcb=None):
8
+ return fn
9
+
10
+
11
+ def script(obj, optimize=True, _frames_up=0, _rcb=None):
12
+ return obj
13
+
14
+
15
+ torch.jit.script_method = script_method
16
+ torch.jit.script = script
17
+
18
+
19
+ def init_weights(m, mean=0.0, std=0.01):
20
+ classname = m.__class__.__name__
21
+ if classname.find("Conv") != -1:
22
+ m.weight.data.normal_(mean, std)
23
+
24
+
25
+ def get_padding(kernel_size, dilation=1):
26
+ return int((kernel_size*dilation - dilation)/2)
27
+
28
+
29
+ def intersperse(lst, item):
30
+ result = [item] * (len(lst) * 2 + 1)
31
+ result[1::2] = lst
32
+ return result
33
+
34
+
35
+ def slice_segments(x, ids_str, segment_size=4):
36
+ ret = torch.zeros_like(x[:, :, :segment_size])
37
+ for i in range(x.size(0)):
38
+ idx_str = ids_str[i]
39
+ idx_end = idx_str + segment_size
40
+ ret[i] = x[i, :, idx_str:idx_end]
41
+ return ret
42
+
43
+
44
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
45
+ b, d, t = x.size()
46
+ if x_lengths is None:
47
+ x_lengths = t
48
+ ids_str_max = x_lengths - segment_size + 1
49
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
50
+ ret = slice_segments(x, ids_str, segment_size)
51
+ return ret, ids_str
52
+
53
+
54
+ def subsequent_mask(length):
55
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
56
+ return mask
57
+
58
+
59
+ @torch.jit.script
60
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
61
+ n_channels_int = n_channels[0]
62
+ in_act = input_a + input_b
63
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
64
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
65
+ acts = t_act * s_act
66
+ return acts
67
+
68
+
69
+ def convert_pad_shape(pad_shape):
70
+ l = pad_shape[::-1]
71
+ pad_shape = [item for sublist in l for item in sublist]
72
+ return pad_shape
73
+
74
+
75
+ def sequence_mask(length, max_length=None):
76
+ if max_length is None:
77
+ max_length = length.max()
78
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
79
+ return x.unsqueeze(0) < length.unsqueeze(1)
80
+
81
+
82
+ def generate_path(duration, mask):
83
+ """
84
+ duration: [b, 1, t_x]
85
+ mask: [b, 1, t_y, t_x]
86
+ """
87
+ device = duration.device
88
+
89
+ b, _, t_y, t_x = mask.shape
90
+ cum_duration = torch.cumsum(duration, -1)
91
+
92
+ cum_duration_flat = cum_duration.view(b * t_x)
93
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
94
+ path = path.view(b, t_x, t_y)
95
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
96
+ path = path.unsqueeze(1).transpose(2,3) * mask
97
+ return path
jieba/dict.txt ADDED
The diff for this file is too large to render. See raw diff
 
models.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
6
+ from torch.nn import functional as F
7
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
8
+
9
+ import attentions
10
+ import commons
11
+ import modules
12
+ from commons import init_weights, get_padding
13
+
14
+
15
+ class StochasticDurationPredictor(nn.Module):
16
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
17
+ super().__init__()
18
+ filter_channels = in_channels # it needs to be removed from future version.
19
+ self.in_channels = in_channels
20
+ self.filter_channels = filter_channels
21
+ self.kernel_size = kernel_size
22
+ self.p_dropout = p_dropout
23
+ self.n_flows = n_flows
24
+ self.gin_channels = gin_channels
25
+
26
+ self.log_flow = modules.Log()
27
+ self.flows = nn.ModuleList()
28
+ self.flows.append(modules.ElementwiseAffine(2))
29
+ for i in range(n_flows):
30
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
31
+ self.flows.append(modules.Flip())
32
+
33
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
34
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
35
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
36
+ self.post_flows = nn.ModuleList()
37
+ self.post_flows.append(modules.ElementwiseAffine(2))
38
+ for i in range(4):
39
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
40
+ self.post_flows.append(modules.Flip())
41
+
42
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
43
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
44
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
45
+ if gin_channels != 0:
46
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
47
+
48
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
49
+ x = torch.detach(x)
50
+ x = self.pre(x)
51
+ if g is not None:
52
+ g = torch.detach(g)
53
+ x = x + self.cond(g)
54
+ x = self.convs(x, x_mask)
55
+ x = self.proj(x) * x_mask
56
+
57
+ if not reverse:
58
+ flows = self.flows
59
+ assert w is not None
60
+
61
+ logdet_tot_q = 0
62
+ h_w = self.post_pre(w)
63
+ h_w = self.post_convs(h_w, x_mask)
64
+ h_w = self.post_proj(h_w) * x_mask
65
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
66
+ z_q = e_q
67
+ for flow in self.post_flows:
68
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
69
+ logdet_tot_q += logdet_q
70
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
71
+ u = torch.sigmoid(z_u) * x_mask
72
+ z0 = (w - u) * x_mask
73
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
74
+ logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q
75
+
76
+ logdet_tot = 0
77
+ z0, logdet = self.log_flow(z0, x_mask)
78
+ logdet_tot += logdet
79
+ z = torch.cat([z0, z1], 1)
80
+ for flow in flows:
81
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
82
+ logdet_tot = logdet_tot + logdet
83
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot
84
+ return nll + logq # [b]
85
+ else:
86
+ flows = list(reversed(self.flows))
87
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
88
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
89
+ for flow in flows:
90
+ z = flow(z, x_mask, g=x, reverse=reverse)
91
+ z0, z1 = torch.split(z, [1, 1], 1)
92
+ logw = z0
93
+ return logw
94
+
95
+
96
+ class DurationPredictor(nn.Module):
97
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
98
+ super().__init__()
99
+
100
+ self.in_channels = in_channels
101
+ self.filter_channels = filter_channels
102
+ self.kernel_size = kernel_size
103
+ self.p_dropout = p_dropout
104
+ self.gin_channels = gin_channels
105
+
106
+ self.drop = nn.Dropout(p_dropout)
107
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
108
+ self.norm_1 = modules.LayerNorm(filter_channels)
109
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
110
+ self.norm_2 = modules.LayerNorm(filter_channels)
111
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
112
+
113
+ if gin_channels != 0:
114
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
115
+
116
+ def forward(self, x, x_mask, g=None):
117
+ x = torch.detach(x)
118
+ if g is not None:
119
+ g = torch.detach(g)
120
+ x = x + self.cond(g)
121
+ x = self.conv_1(x * x_mask)
122
+ x = torch.relu(x)
123
+ x = self.norm_1(x)
124
+ x = self.drop(x)
125
+ x = self.conv_2(x * x_mask)
126
+ x = torch.relu(x)
127
+ x = self.norm_2(x)
128
+ x = self.drop(x)
129
+ x = self.proj(x * x_mask)
130
+ return x * x_mask
131
+
132
+
133
+ class TextEncoder(nn.Module):
134
+ def __init__(self,
135
+ n_vocab,
136
+ out_channels,
137
+ hidden_channels,
138
+ filter_channels,
139
+ n_heads,
140
+ n_layers,
141
+ kernel_size,
142
+ p_dropout):
143
+ super().__init__()
144
+ self.n_vocab = n_vocab
145
+ self.out_channels = out_channels
146
+ self.hidden_channels = hidden_channels
147
+ self.filter_channels = filter_channels
148
+ self.n_heads = n_heads
149
+ self.n_layers = n_layers
150
+ self.kernel_size = kernel_size
151
+ self.p_dropout = p_dropout
152
+
153
+ if self.n_vocab != 0:
154
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
155
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
156
+
157
+ self.encoder = attentions.Encoder(
158
+ hidden_channels,
159
+ filter_channels,
160
+ n_heads,
161
+ n_layers,
162
+ kernel_size,
163
+ p_dropout)
164
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
165
+
166
+ def forward(self, x, x_lengths):
167
+ if self.n_vocab != 0:
168
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
169
+ x = torch.transpose(x, 1, -1) # [b, h, t]
170
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
171
+
172
+ x = self.encoder(x * x_mask, x_mask)
173
+ stats = self.proj(x) * x_mask
174
+
175
+ m, logs = torch.split(stats, self.out_channels, dim=1)
176
+ return x, m, logs, x_mask
177
+
178
+
179
+ class ResidualCouplingBlock(nn.Module):
180
+ def __init__(self,
181
+ channels,
182
+ hidden_channels,
183
+ kernel_size,
184
+ dilation_rate,
185
+ n_layers,
186
+ n_flows=4,
187
+ gin_channels=0):
188
+ super().__init__()
189
+ self.channels = channels
190
+ self.hidden_channels = hidden_channels
191
+ self.kernel_size = kernel_size
192
+ self.dilation_rate = dilation_rate
193
+ self.n_layers = n_layers
194
+ self.n_flows = n_flows
195
+ self.gin_channels = gin_channels
196
+
197
+ self.flows = nn.ModuleList()
198
+ for i in range(n_flows):
199
+ self.flows.append(
200
+ modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
201
+ gin_channels=gin_channels, mean_only=True))
202
+ self.flows.append(modules.Flip())
203
+
204
+ def forward(self, x, x_mask, g=None, reverse=False):
205
+ if not reverse:
206
+ for flow in self.flows:
207
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
208
+ else:
209
+ for flow in reversed(self.flows):
210
+ x = flow(x, x_mask, g=g, reverse=reverse)
211
+ return x
212
+
213
+
214
+ class PosteriorEncoder(nn.Module):
215
+ def __init__(self,
216
+ in_channels,
217
+ out_channels,
218
+ hidden_channels,
219
+ kernel_size,
220
+ dilation_rate,
221
+ n_layers,
222
+ gin_channels=0):
223
+ super().__init__()
224
+ self.in_channels = in_channels
225
+ self.out_channels = out_channels
226
+ self.hidden_channels = hidden_channels
227
+ self.kernel_size = kernel_size
228
+ self.dilation_rate = dilation_rate
229
+ self.n_layers = n_layers
230
+ self.gin_channels = gin_channels
231
+
232
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
233
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
234
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
235
+
236
+ def forward(self, x, x_lengths, g=None):
237
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
238
+ x = self.pre(x) * x_mask
239
+ x = self.enc(x, x_mask, g=g)
240
+ stats = self.proj(x) * x_mask
241
+ m, logs = torch.split(stats, self.out_channels, dim=1)
242
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
243
+ return z, m, logs, x_mask
244
+
245
+
246
+ class Generator(torch.nn.Module):
247
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
248
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
249
+ super(Generator, self).__init__()
250
+ self.num_kernels = len(resblock_kernel_sizes)
251
+ self.num_upsamples = len(upsample_rates)
252
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
253
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
254
+
255
+ self.ups = nn.ModuleList()
256
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
257
+ self.ups.append(weight_norm(
258
+ ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
259
+ k, u, padding=(k - u) // 2)))
260
+
261
+ self.resblocks = nn.ModuleList()
262
+ for i in range(len(self.ups)):
263
+ ch = upsample_initial_channel // (2 ** (i + 1))
264
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
265
+ self.resblocks.append(resblock(ch, k, d))
266
+
267
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
268
+ self.ups.apply(init_weights)
269
+
270
+ if gin_channels != 0:
271
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
272
+
273
+ def forward(self, x, g=None):
274
+ x = self.conv_pre(x)
275
+ if g is not None:
276
+ x = x + self.cond(g)
277
+
278
+ for i in range(self.num_upsamples):
279
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
280
+ x = self.ups[i](x)
281
+ xs = None
282
+ for j in range(self.num_kernels):
283
+ if xs is None:
284
+ xs = self.resblocks[i * self.num_kernels + j](x)
285
+ else:
286
+ xs += self.resblocks[i * self.num_kernels + j](x)
287
+ x = xs / self.num_kernels
288
+ x = F.leaky_relu(x)
289
+ x = self.conv_post(x)
290
+ x = torch.tanh(x)
291
+
292
+ return x
293
+
294
+ def remove_weight_norm(self):
295
+ print('Removing weight norm...')
296
+ for l in self.ups:
297
+ remove_weight_norm(l)
298
+ for l in self.resblocks:
299
+ l.remove_weight_norm()
300
+
301
+
302
+ class DiscriminatorP(torch.nn.Module):
303
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
304
+ super(DiscriminatorP, self).__init__()
305
+ self.period = period
306
+ self.use_spectral_norm = use_spectral_norm
307
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
308
+ self.convs = nn.ModuleList([
309
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
310
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
311
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
312
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
313
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
314
+ ])
315
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
316
+
317
+ def forward(self, x):
318
+ fmap = []
319
+
320
+ # 1d to 2d
321
+ b, c, t = x.shape
322
+ if t % self.period != 0: # pad first
323
+ n_pad = self.period - (t % self.period)
324
+ x = F.pad(x, (0, n_pad), "reflect")
325
+ t = t + n_pad
326
+ x = x.view(b, c, t // self.period, self.period)
327
+
328
+ for l in self.convs:
329
+ x = l(x)
330
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
331
+ fmap.append(x)
332
+ x = self.conv_post(x)
333
+ fmap.append(x)
334
+ x = torch.flatten(x, 1, -1)
335
+
336
+ return x, fmap
337
+
338
+
339
+ class DiscriminatorS(torch.nn.Module):
340
+ def __init__(self, use_spectral_norm=False):
341
+ super(DiscriminatorS, self).__init__()
342
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
343
+ self.convs = nn.ModuleList([
344
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
345
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
346
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
347
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
348
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
349
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
350
+ ])
351
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
352
+
353
+ def forward(self, x):
354
+ fmap = []
355
+
356
+ for l in self.convs:
357
+ x = l(x)
358
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
359
+ fmap.append(x)
360
+ x = self.conv_post(x)
361
+ fmap.append(x)
362
+ x = torch.flatten(x, 1, -1)
363
+
364
+ return x, fmap
365
+
366
+
367
+ class MultiPeriodDiscriminator(torch.nn.Module):
368
+ def __init__(self, use_spectral_norm=False):
369
+ super(MultiPeriodDiscriminator, self).__init__()
370
+ periods = [2, 3, 5, 7, 11]
371
+
372
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
373
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
374
+ self.discriminators = nn.ModuleList(discs)
375
+
376
+ def forward(self, y, y_hat):
377
+ y_d_rs = []
378
+ y_d_gs = []
379
+ fmap_rs = []
380
+ fmap_gs = []
381
+ for i, d in enumerate(self.discriminators):
382
+ y_d_r, fmap_r = d(y)
383
+ y_d_g, fmap_g = d(y_hat)
384
+ y_d_rs.append(y_d_r)
385
+ y_d_gs.append(y_d_g)
386
+ fmap_rs.append(fmap_r)
387
+ fmap_gs.append(fmap_g)
388
+
389
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
390
+
391
+
392
+ class SynthesizerTrn(nn.Module):
393
+ """
394
+ Synthesizer for Training
395
+ """
396
+
397
+ def __init__(self,
398
+ n_vocab,
399
+ spec_channels,
400
+ segment_size,
401
+ inter_channels,
402
+ hidden_channels,
403
+ filter_channels,
404
+ n_heads,
405
+ n_layers,
406
+ kernel_size,
407
+ p_dropout,
408
+ resblock,
409
+ resblock_kernel_sizes,
410
+ resblock_dilation_sizes,
411
+ upsample_rates,
412
+ upsample_initial_channel,
413
+ upsample_kernel_sizes,
414
+ n_speakers=0,
415
+ gin_channels=0,
416
+ use_sdp=True,
417
+ **kwargs):
418
+
419
+ super().__init__()
420
+ self.n_vocab = n_vocab
421
+ self.spec_channels = spec_channels
422
+ self.inter_channels = inter_channels
423
+ self.hidden_channels = hidden_channels
424
+ self.filter_channels = filter_channels
425
+ self.n_heads = n_heads
426
+ self.n_layers = n_layers
427
+ self.kernel_size = kernel_size
428
+ self.p_dropout = p_dropout
429
+ self.resblock = resblock
430
+ self.resblock_kernel_sizes = resblock_kernel_sizes
431
+ self.resblock_dilation_sizes = resblock_dilation_sizes
432
+ self.upsample_rates = upsample_rates
433
+ self.upsample_initial_channel = upsample_initial_channel
434
+ self.upsample_kernel_sizes = upsample_kernel_sizes
435
+ self.segment_size = segment_size
436
+ self.n_speakers = n_speakers
437
+ self.gin_channels = gin_channels
438
+
439
+ self.use_sdp = use_sdp
440
+
441
+ self.enc_p = TextEncoder(n_vocab,
442
+ inter_channels,
443
+ hidden_channels,
444
+ filter_channels,
445
+ n_heads,
446
+ n_layers,
447
+ kernel_size,
448
+ p_dropout)
449
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
450
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
451
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
452
+ gin_channels=gin_channels)
453
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
454
+
455
+ if use_sdp:
456
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
457
+ else:
458
+ self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
459
+
460
+ if n_speakers > 1:
461
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
462
+
463
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
464
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
465
+ if self.n_speakers > 0:
466
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
467
+ else:
468
+ g = None
469
+
470
+ if self.use_sdp:
471
+ logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
472
+ else:
473
+ logw = self.dp(x, x_mask, g=g)
474
+ w = torch.exp(logw) * x_mask * length_scale
475
+ w_ceil = torch.ceil(w)
476
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
477
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
478
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
479
+ attn = commons.generate_path(w_ceil, attn_mask)
480
+
481
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
482
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1,
483
+ 2) # [b, t', t], [b, t, d] -> [b, d, t']
484
+
485
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
486
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
487
+ o = self.dec((z * y_mask)[:, :, :max_len], g=g)
488
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
489
+
490
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
491
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
492
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
493
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
494
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
495
+ z_p = self.flow(z, y_mask, g=g_src)
496
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
497
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
498
+ return o_hat, y_mask, (z, z_p, z_hat)
modules.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from torch.nn import Conv1d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm
8
+
9
+ import commons
10
+ from commons import init_weights, get_padding
11
+ from transforms import piecewise_rational_quadratic_transform
12
+
13
+
14
+ LRELU_SLOPE = 0.1
15
+
16
+
17
+ class LayerNorm(nn.Module):
18
+ def __init__(self, channels, eps=1e-5):
19
+ super().__init__()
20
+ self.channels = channels
21
+ self.eps = eps
22
+
23
+ self.gamma = nn.Parameter(torch.ones(channels))
24
+ self.beta = nn.Parameter(torch.zeros(channels))
25
+
26
+ def forward(self, x):
27
+ x = x.transpose(1, -1)
28
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
29
+ return x.transpose(1, -1)
30
+
31
+
32
+ class ConvReluNorm(nn.Module):
33
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
34
+ super().__init__()
35
+ self.in_channels = in_channels
36
+ self.hidden_channels = hidden_channels
37
+ self.out_channels = out_channels
38
+ self.kernel_size = kernel_size
39
+ self.n_layers = n_layers
40
+ self.p_dropout = p_dropout
41
+ assert n_layers > 1, "Number of layers should be larger than 0."
42
+
43
+ self.conv_layers = nn.ModuleList()
44
+ self.norm_layers = nn.ModuleList()
45
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
46
+ self.norm_layers.append(LayerNorm(hidden_channels))
47
+ self.relu_drop = nn.Sequential(
48
+ nn.ReLU(),
49
+ nn.Dropout(p_dropout))
50
+ for _ in range(n_layers-1):
51
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
52
+ self.norm_layers.append(LayerNorm(hidden_channels))
53
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
54
+ self.proj.weight.data.zero_()
55
+ self.proj.bias.data.zero_()
56
+
57
+ def forward(self, x, x_mask):
58
+ x_org = x
59
+ for i in range(self.n_layers):
60
+ x = self.conv_layers[i](x * x_mask)
61
+ x = self.norm_layers[i](x)
62
+ x = self.relu_drop(x)
63
+ x = x_org + self.proj(x)
64
+ return x * x_mask
65
+
66
+
67
+ class DDSConv(nn.Module):
68
+ """
69
+ Dialted and Depth-Separable Convolution
70
+ """
71
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
72
+ super().__init__()
73
+ self.channels = channels
74
+ self.kernel_size = kernel_size
75
+ self.n_layers = n_layers
76
+ self.p_dropout = p_dropout
77
+
78
+ self.drop = nn.Dropout(p_dropout)
79
+ self.convs_sep = nn.ModuleList()
80
+ self.convs_1x1 = nn.ModuleList()
81
+ self.norms_1 = nn.ModuleList()
82
+ self.norms_2 = nn.ModuleList()
83
+ for i in range(n_layers):
84
+ dilation = kernel_size ** i
85
+ padding = (kernel_size * dilation - dilation) // 2
86
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
87
+ groups=channels, dilation=dilation, padding=padding
88
+ ))
89
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
90
+ self.norms_1.append(LayerNorm(channels))
91
+ self.norms_2.append(LayerNorm(channels))
92
+
93
+ def forward(self, x, x_mask, g=None):
94
+ if g is not None:
95
+ x = x + g
96
+ for i in range(self.n_layers):
97
+ y = self.convs_sep[i](x * x_mask)
98
+ y = self.norms_1[i](y)
99
+ y = F.gelu(y)
100
+ y = self.convs_1x1[i](y)
101
+ y = self.norms_2[i](y)
102
+ y = F.gelu(y)
103
+ y = self.drop(y)
104
+ x = x + y
105
+ return x * x_mask
106
+
107
+
108
+ class WN(torch.nn.Module):
109
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
110
+ super(WN, self).__init__()
111
+ assert(kernel_size % 2 == 1)
112
+ self.hidden_channels =hidden_channels
113
+ self.kernel_size = kernel_size,
114
+ self.dilation_rate = dilation_rate
115
+ self.n_layers = n_layers
116
+ self.gin_channels = gin_channels
117
+ self.p_dropout = p_dropout
118
+
119
+ self.in_layers = torch.nn.ModuleList()
120
+ self.res_skip_layers = torch.nn.ModuleList()
121
+ self.drop = nn.Dropout(p_dropout)
122
+
123
+ if gin_channels != 0:
124
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
125
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
126
+
127
+ for i in range(n_layers):
128
+ dilation = dilation_rate ** i
129
+ padding = int((kernel_size * dilation - dilation) / 2)
130
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
131
+ dilation=dilation, padding=padding)
132
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
133
+ self.in_layers.append(in_layer)
134
+
135
+ # last one is not necessary
136
+ if i < n_layers - 1:
137
+ res_skip_channels = 2 * hidden_channels
138
+ else:
139
+ res_skip_channels = hidden_channels
140
+
141
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
142
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
143
+ self.res_skip_layers.append(res_skip_layer)
144
+
145
+ def forward(self, x, x_mask, g=None, **kwargs):
146
+ output = torch.zeros_like(x)
147
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
148
+
149
+ if g is not None:
150
+ g = self.cond_layer(g)
151
+
152
+ for i in range(self.n_layers):
153
+ x_in = self.in_layers[i](x)
154
+ if g is not None:
155
+ cond_offset = i * 2 * self.hidden_channels
156
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
157
+ else:
158
+ g_l = torch.zeros_like(x_in)
159
+
160
+ acts = commons.fused_add_tanh_sigmoid_multiply(
161
+ x_in,
162
+ g_l,
163
+ n_channels_tensor)
164
+ acts = self.drop(acts)
165
+
166
+ res_skip_acts = self.res_skip_layers[i](acts)
167
+ if i < self.n_layers - 1:
168
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
169
+ x = (x + res_acts) * x_mask
170
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
171
+ else:
172
+ output = output + res_skip_acts
173
+ return output * x_mask
174
+
175
+ def remove_weight_norm(self):
176
+ if self.gin_channels != 0:
177
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
178
+ for l in self.in_layers:
179
+ torch.nn.utils.remove_weight_norm(l)
180
+ for l in self.res_skip_layers:
181
+ torch.nn.utils.remove_weight_norm(l)
182
+
183
+
184
+ class ResBlock1(torch.nn.Module):
185
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
186
+ super(ResBlock1, self).__init__()
187
+ self.convs1 = nn.ModuleList([
188
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
189
+ padding=get_padding(kernel_size, dilation[0]))),
190
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
191
+ padding=get_padding(kernel_size, dilation[1]))),
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
193
+ padding=get_padding(kernel_size, dilation[2])))
194
+ ])
195
+ self.convs1.apply(init_weights)
196
+
197
+ self.convs2 = nn.ModuleList([
198
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
199
+ padding=get_padding(kernel_size, 1))),
200
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
201
+ padding=get_padding(kernel_size, 1))),
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1)))
204
+ ])
205
+ self.convs2.apply(init_weights)
206
+
207
+ def forward(self, x, x_mask=None):
208
+ for c1, c2 in zip(self.convs1, self.convs2):
209
+ xt = F.leaky_relu(x, LRELU_SLOPE)
210
+ if x_mask is not None:
211
+ xt = xt * x_mask
212
+ xt = c1(xt)
213
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
214
+ if x_mask is not None:
215
+ xt = xt * x_mask
216
+ xt = c2(xt)
217
+ x = xt + x
218
+ if x_mask is not None:
219
+ x = x * x_mask
220
+ return x
221
+
222
+ def remove_weight_norm(self):
223
+ for l in self.convs1:
224
+ remove_weight_norm(l)
225
+ for l in self.convs2:
226
+ remove_weight_norm(l)
227
+
228
+
229
+ class ResBlock2(torch.nn.Module):
230
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
231
+ super(ResBlock2, self).__init__()
232
+ self.convs = nn.ModuleList([
233
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
234
+ padding=get_padding(kernel_size, dilation[0]))),
235
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
236
+ padding=get_padding(kernel_size, dilation[1])))
237
+ ])
238
+ self.convs.apply(init_weights)
239
+
240
+ def forward(self, x, x_mask=None):
241
+ for c in self.convs:
242
+ xt = F.leaky_relu(x, LRELU_SLOPE)
243
+ if x_mask is not None:
244
+ xt = xt * x_mask
245
+ xt = c(xt)
246
+ x = xt + x
247
+ if x_mask is not None:
248
+ x = x * x_mask
249
+ return x
250
+
251
+ def remove_weight_norm(self):
252
+ for l in self.convs:
253
+ remove_weight_norm(l)
254
+
255
+
256
+ class Log(nn.Module):
257
+ def forward(self, x, x_mask, reverse=False, **kwargs):
258
+ if not reverse:
259
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
260
+ logdet = torch.sum(-y, [1, 2])
261
+ return y, logdet
262
+ else:
263
+ x = torch.exp(x) * x_mask
264
+ return x
265
+
266
+
267
+ class Flip(nn.Module):
268
+ def forward(self, x, *args, reverse=False, **kwargs):
269
+ x = torch.flip(x, [1])
270
+ if not reverse:
271
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
272
+ return x, logdet
273
+ else:
274
+ return x
275
+
276
+
277
+ class ElementwiseAffine(nn.Module):
278
+ def __init__(self, channels):
279
+ super().__init__()
280
+ self.channels = channels
281
+ self.m = nn.Parameter(torch.zeros(channels,1))
282
+ self.logs = nn.Parameter(torch.zeros(channels,1))
283
+
284
+ def forward(self, x, x_mask, reverse=False, **kwargs):
285
+ if not reverse:
286
+ y = self.m + torch.exp(self.logs) * x
287
+ y = y * x_mask
288
+ logdet = torch.sum(self.logs * x_mask, [1,2])
289
+ return y, logdet
290
+ else:
291
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
292
+ return x
293
+
294
+
295
+ class ResidualCouplingLayer(nn.Module):
296
+ def __init__(self,
297
+ channels,
298
+ hidden_channels,
299
+ kernel_size,
300
+ dilation_rate,
301
+ n_layers,
302
+ p_dropout=0,
303
+ gin_channels=0,
304
+ mean_only=False):
305
+ assert channels % 2 == 0, "channels should be divisible by 2"
306
+ super().__init__()
307
+ self.channels = channels
308
+ self.hidden_channels = hidden_channels
309
+ self.kernel_size = kernel_size
310
+ self.dilation_rate = dilation_rate
311
+ self.n_layers = n_layers
312
+ self.half_channels = channels // 2
313
+ self.mean_only = mean_only
314
+
315
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
316
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
317
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
318
+ self.post.weight.data.zero_()
319
+ self.post.bias.data.zero_()
320
+
321
+ def forward(self, x, x_mask, g=None, reverse=False):
322
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
323
+ h = self.pre(x0) * x_mask
324
+ h = self.enc(h, x_mask, g=g)
325
+ stats = self.post(h) * x_mask
326
+ if not self.mean_only:
327
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
328
+ else:
329
+ m = stats
330
+ logs = torch.zeros_like(m)
331
+
332
+ if not reverse:
333
+ x1 = m + x1 * torch.exp(logs) * x_mask
334
+ x = torch.cat([x0, x1], 1)
335
+ logdet = torch.sum(logs, [1,2])
336
+ return x, logdet
337
+ else:
338
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
339
+ x = torch.cat([x0, x1], 1)
340
+ return x
341
+
342
+
343
+ class ConvFlow(nn.Module):
344
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
345
+ super().__init__()
346
+ self.in_channels = in_channels
347
+ self.filter_channels = filter_channels
348
+ self.kernel_size = kernel_size
349
+ self.n_layers = n_layers
350
+ self.num_bins = num_bins
351
+ self.tail_bound = tail_bound
352
+ self.half_channels = in_channels // 2
353
+
354
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
355
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
356
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
357
+ self.proj.weight.data.zero_()
358
+ self.proj.bias.data.zero_()
359
+
360
+ def forward(self, x, x_mask, g=None, reverse=False):
361
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
362
+ h = self.pre(x0)
363
+ h = self.convs(h, x_mask, g=g)
364
+ h = self.proj(h) * x_mask
365
+
366
+ b, c, t = x0.shape
367
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
368
+
369
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
370
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
371
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
372
+
373
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
374
+ unnormalized_widths,
375
+ unnormalized_heights,
376
+ unnormalized_derivatives,
377
+ inverse=reverse,
378
+ tails='linear',
379
+ tail_bound=self.tail_bound
380
+ )
381
+
382
+ x = torch.cat([x0, x1], 1) * x_mask
383
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
384
+ if not reverse:
385
+ return x, logdet
386
+ else:
387
+ return x
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Cython==0.29.21
2
+ librosa==0.8.0
3
+ matplotlib==3.3.1
4
+ numpy==1.21.6
5
+ phonemizer==2.2.1
6
+ scipy==1.5.2
7
+ tensorboard==2.3.0
8
+ torch
9
+ torchvision
10
+ Unidecode==1.1.1
11
+ pyopenjtalk==0.2.0
12
+ jamo==0.4.1
13
+ pypinyin==0.44.0
14
+ jieba==0.42.1
15
+ cn2an==0.5.17
16
+ jieba==0.42.1
17
+ ipython==7.34.0
18
+ gradio==3.4.1
text/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2017 Keith Ito
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
text/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+ from text import cleaners
3
+
4
+
5
+ def text_to_sequence(text, symbols, cleaner_names):
6
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
7
+ Args:
8
+ text: string to convert to a sequence
9
+ cleaner_names: names of the cleaner functions to run the text through
10
+ Returns:
11
+ List of integers corresponding to the symbols in the text
12
+ '''
13
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
14
+
15
+ sequence = []
16
+
17
+ clean_text = _clean_text(text, cleaner_names)
18
+ for symbol in clean_text:
19
+ if symbol not in _symbol_to_id.keys():
20
+ continue
21
+ symbol_id = _symbol_to_id[symbol]
22
+ sequence += [symbol_id]
23
+ return sequence
24
+
25
+
26
+ def _clean_text(text, cleaner_names):
27
+ for name in cleaner_names:
28
+ cleaner = getattr(cleaners, name)
29
+ if not cleaner:
30
+ raise Exception('Unknown cleaner: %s' % name)
31
+ text = cleaner(text)
32
+ return text
text/cleaners.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from text.japanese import japanese_to_romaji_with_accent, japanese_to_ipa, japanese_to_ipa2, japanese_to_ipa3
3
+ from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo, chinese_to_romaji, chinese_to_lazy_ipa, chinese_to_ipa, chinese_to_ipa2
4
+
5
+ def japanese_cleaners(text):
6
+ from text.japanese import japanese_to_romaji_with_accent
7
+ text = japanese_to_romaji_with_accent(text)
8
+ if re.match('[A-Za-z]', text[-1]):
9
+ text += '.'
10
+ return text
11
+
12
+
13
+ def japanese_cleaners2(text):
14
+ return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…')
15
+
16
+
17
+ def korean_cleaners(text):
18
+ '''Pipeline for Korean text'''
19
+ from text.korean import latin_to_hangul, number_to_hangul, divide_hangul
20
+ text = latin_to_hangul(text)
21
+ text = number_to_hangul(text)
22
+ text = divide_hangul(text)
23
+ if re.match('[\u3131-\u3163]', text[-1]):
24
+ text += '.'
25
+ return text
26
+
27
+
28
+ def chinese_cleaners(text):
29
+ '''Pipeline for Chinese text'''
30
+ from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo
31
+ text = number_to_chinese(text)
32
+ text = chinese_to_bopomofo(text)
33
+ text = latin_to_bopomofo(text)
34
+ if re.match('[ˉˊˇˋ˙]', text[-1]):
35
+ text += '。'
36
+ return text
37
+
38
+
39
+ def zh_ja_mixture_cleaners(text):
40
+ from text.mandarin import chinese_to_romaji
41
+ from text.japanese import japanese_to_romaji_with_accent
42
+ chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text)
43
+ japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text)
44
+ for chinese_text in chinese_texts:
45
+ cleaned_text = chinese_to_romaji(chinese_text[4:-4])
46
+ text = text.replace(chinese_text, cleaned_text+' ', 1)
47
+ for japanese_text in japanese_texts:
48
+ cleaned_text = japanese_to_romaji_with_accent(
49
+ japanese_text[4:-4]).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…')
50
+ text = text.replace(japanese_text, cleaned_text+' ', 1)
51
+ text = text[:-1]
52
+ if re.match('[A-Za-zɯɹəɥ→↓↑]', text[-1]):
53
+ text += '.'
54
+ return text
55
+
56
+
57
+ def sanskrit_cleaners(text):
58
+ text = text.replace('॥', '।').replace('ॐ', 'ओम्')
59
+ if text[-1] != '।':
60
+ text += ' ।'
61
+ return text
62
+
63
+
64
+ def cjks_cleaners(text):
65
+ from text.mandarin import chinese_to_lazy_ipa
66
+ from text.japanese import japanese_to_ipa
67
+ from text.korean import korean_to_lazy_ipa
68
+ from text.sanskrit import devanagari_to_ipa
69
+ chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text)
70
+ japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text)
71
+ korean_texts = re.findall(r'\[KO\].*?\[KO\]', text)
72
+ sanskrit_texts = re.findall(r'\[SA\].*?\[SA\]', text)
73
+ for chinese_text in chinese_texts:
74
+ cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4])
75
+ text = text.replace(chinese_text, cleaned_text+' ', 1)
76
+ for japanese_text in japanese_texts:
77
+ cleaned_text = japanese_to_ipa(japanese_text[4:-4])
78
+ text = text.replace(japanese_text, cleaned_text+' ', 1)
79
+ for korean_text in korean_texts:
80
+ cleaned_text = korean_to_lazy_ipa(korean_text[4:-4])
81
+ text = text.replace(korean_text, cleaned_text+' ', 1)
82
+ for sanskrit_text in sanskrit_texts:
83
+ cleaned_text = devanagari_to_ipa(sanskrit_text[4:-4])
84
+ text = text.replace(sanskrit_text, cleaned_text+' ', 1)
85
+ text = text[:-1]
86
+ if re.match(r'[^\.,!\?\-…~]', text[-1]):
87
+ text += '.'
88
+ return text
89
+
90
+ def cjke_cleaners(text):
91
+ chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text)
92
+ japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text)
93
+ for chinese_text in chinese_texts:
94
+ cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4])
95
+ cleaned_text = cleaned_text.replace(
96
+ 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn')
97
+ text = text.replace(chinese_text, cleaned_text+' ', 1)
98
+ for japanese_text in japanese_texts:
99
+ cleaned_text = japanese_to_ipa(japanese_text[4:-4])
100
+ cleaned_text = cleaned_text.replace('ʧ', 'tʃ').replace(
101
+ 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz')
102
+ text = text.replace(japanese_text, cleaned_text+' ', 1)
103
+ text = text[:-1]
104
+ if re.match(r'[^\.,!\?\-…~]', text[-1]):
105
+ text += '.'
106
+ return text
text/japanese.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from unidecode import unidecode
3
+ import pyopenjtalk
4
+
5
+
6
+ # Regular expression matching Japanese without punctuation marks:
7
+ _japanese_characters = re.compile(
8
+ r'[A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]')
9
+
10
+ # Regular expression matching non-Japanese characters or punctuation marks:
11
+ _japanese_marks = re.compile(
12
+ r'[^A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]')
13
+
14
+ # List of (symbol, Japanese) pairs for marks:
15
+ _symbols_to_japanese = [(re.compile('%s' % x[0]), x[1]) for x in [
16
+ ('%', 'パーセント')
17
+ ]]
18
+
19
+ # List of (romaji, ipa) pairs for marks:
20
+ _romaji_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
21
+ ('ts', 'ʦ'),
22
+ ('u', 'ɯ'),
23
+ ('j', 'ʥ'),
24
+ ('y', 'j'),
25
+ ('ni', 'n^i'),
26
+ ('nj', 'n^'),
27
+ ('hi', 'çi'),
28
+ ('hj', 'ç'),
29
+ ('f', 'ɸ'),
30
+ ('I', 'i*'),
31
+ ('U', 'ɯ*'),
32
+ ('r', 'ɾ')
33
+ ]]
34
+
35
+ # List of (romaji, ipa2) pairs for marks:
36
+ _romaji_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [
37
+ ('u', 'ɯ'),
38
+ ('ʧ', 'tʃ'),
39
+ ('j', 'dʑ'),
40
+ ('y', 'j'),
41
+ ('ni', 'n^i'),
42
+ ('nj', 'n^'),
43
+ ('hi', 'çi'),
44
+ ('hj', 'ç'),
45
+ ('f', 'ɸ'),
46
+ ('I', 'i*'),
47
+ ('U', 'ɯ*'),
48
+ ('r', 'ɾ')
49
+ ]]
50
+
51
+ # List of (consonant, sokuon) pairs:
52
+ _real_sokuon = [(re.compile('%s' % x[0]), x[1]) for x in [
53
+ (r'Q([↑↓]*[kg])', r'k#\1'),
54
+ (r'Q([↑↓]*[tdjʧ])', r't#\1'),
55
+ (r'Q([↑↓]*[sʃ])', r's\1'),
56
+ (r'Q([↑↓]*[pb])', r'p#\1')
57
+ ]]
58
+
59
+ # List of (consonant, hatsuon) pairs:
60
+ _real_hatsuon = [(re.compile('%s' % x[0]), x[1]) for x in [
61
+ (r'N([↑↓]*[pbm])', r'm\1'),
62
+ (r'N([↑↓]*[ʧʥj])', r'n^\1'),
63
+ (r'N([↑↓]*[tdn])', r'n\1'),
64
+ (r'N([↑↓]*[kg])', r'ŋ\1')
65
+ ]]
66
+
67
+
68
+ def symbols_to_japanese(text):
69
+ for regex, replacement in _symbols_to_japanese:
70
+ text = re.sub(regex, replacement, text)
71
+ return text
72
+
73
+
74
+ def japanese_to_romaji_with_accent(text):
75
+ '''Reference https://r9y9.github.io/ttslearn/latest/notebooks/ch10_Recipe-Tacotron.html'''
76
+ text = symbols_to_japanese(text)
77
+ sentences = re.split(_japanese_marks, text)
78
+ marks = re.findall(_japanese_marks, text)
79
+ text = ''
80
+ for i, sentence in enumerate(sentences):
81
+ if re.match(_japanese_characters, sentence):
82
+ if text != '':
83
+ text += ' '
84
+ labels = pyopenjtalk.extract_fullcontext(sentence)
85
+ for n, label in enumerate(labels):
86
+ phoneme = re.search(r'\-([^\+]*)\+', label).group(1)
87
+ if phoneme not in ['sil', 'pau']:
88
+ text += phoneme.replace('ch', 'ʧ').replace('sh',
89
+ 'ʃ').replace('cl', 'Q')
90
+ else:
91
+ continue
92
+ # n_moras = int(re.search(r'/F:(\d+)_', label).group(1))
93
+ a1 = int(re.search(r"/A:(\-?[0-9]+)\+", label).group(1))
94
+ a2 = int(re.search(r"\+(\d+)\+", label).group(1))
95
+ a3 = int(re.search(r"\+(\d+)/", label).group(1))
96
+ if re.search(r'\-([^\+]*)\+', labels[n + 1]).group(1) in ['sil', 'pau']:
97
+ a2_next = -1
98
+ else:
99
+ a2_next = int(
100
+ re.search(r"\+(\d+)\+", labels[n + 1]).group(1))
101
+ # Accent phrase boundary
102
+ if a3 == 1 and a2_next == 1:
103
+ text += ' '
104
+ # Falling
105
+ elif a1 == 0 and a2_next == a2 + 1:
106
+ text += '↓'
107
+ # Rising
108
+ elif a2 == 1 and a2_next == 2:
109
+ text += '↑'
110
+ if i < len(marks):
111
+ text += unidecode(marks[i]).replace(' ', '')
112
+ return text
113
+
114
+
115
+ def get_real_sokuon(text):
116
+ for regex, replacement in _real_sokuon:
117
+ text = re.sub(regex, replacement, text)
118
+ return text
119
+
120
+
121
+ def get_real_hatsuon(text):
122
+ for regex, replacement in _real_hatsuon:
123
+ text = re.sub(regex, replacement, text)
124
+ return text
125
+
126
+
127
+ def japanese_to_ipa(text):
128
+ text = japanese_to_romaji_with_accent(text).replace('...', '…')
129
+ text = re.sub(
130
+ r'([aiueo])\1+', lambda x: x.group(0)[0]+'ː'*(len(x.group(0))-1), text)
131
+ text = get_real_sokuon(text)
132
+ text = get_real_hatsuon(text)
133
+ for regex, replacement in _romaji_to_ipa:
134
+ text = re.sub(regex, replacement, text)
135
+ return text
136
+
137
+
138
+ def japanese_to_ipa2(text):
139
+ text = japanese_to_romaji_with_accent(text).replace('...', '…')
140
+ text = get_real_sokuon(text)
141
+ text = get_real_hatsuon(text)
142
+ for regex, replacement in _romaji_to_ipa2:
143
+ text = re.sub(regex, replacement, text)
144
+ return text
145
+
146
+
147
+ def japanese_to_ipa3(text):
148
+ text = japanese_to_ipa2(text).replace('n^', 'ȵ').replace(
149
+ 'ʃ', 'ɕ').replace('*', '\u0325').replace('#', '\u031a')
150
+ text = re.sub(
151
+ r'([aiɯeo])\1+', lambda x: x.group(0)[0]+'ː'*(len(x.group(0))-1), text)
152
+ text = re.sub(r'((?:^|\s)(?:ts|tɕ|[kpt]))', r'\1ʰ', text)
153
+ return text
text/korean.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from jamo import h2j, j2hcj
3
+ import ko_pron
4
+
5
+
6
+ # This is a list of Korean classifiers preceded by pure Korean numerals.
7
+ _korean_classifiers = '군데 권 개 그루 닢 대 두 마리 모 모금 뭇 발 발짝 방 번 벌 보루 살 수 술 시 쌈 움큼 정 짝 채 척 첩 축 켤레 톨 통'
8
+
9
+ # List of (hangul, hangul divided) pairs:
10
+ _hangul_divided = [(re.compile('%s' % x[0]), x[1]) for x in [
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
+ # List of (Latin alphabet, hangul) pairs:
38
+ _latin_to_hangul = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
39
+ ('a', '에이'),
40
+ ('b', '비'),
41
+ ('c', '시'),
42
+ ('d', '디'),
43
+ ('e', '이'),
44
+ ('f', '에프'),
45
+ ('g', '지'),
46
+ ('h', '에이치'),
47
+ ('i', '아이'),
48
+ ('j', '제이'),
49
+ ('k', '케이'),
50
+ ('l', '엘'),
51
+ ('m', '엠'),
52
+ ('n', '엔'),
53
+ ('o', '오'),
54
+ ('p', '피'),
55
+ ('q', '큐'),
56
+ ('r', '아르'),
57
+ ('s', '에스'),
58
+ ('t', '티'),
59
+ ('u', '유'),
60
+ ('v', '브이'),
61
+ ('w', '더블유'),
62
+ ('x', '엑스'),
63
+ ('y', '와이'),
64
+ ('z', '제트')
65
+ ]]
66
+
67
+ # List of (ipa, lazy ipa) pairs:
68
+ _ipa_to_lazy_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
69
+ ('t͡ɕ','ʧ'),
70
+ ('d͡ʑ','ʥ'),
71
+ ('ɲ','n^'),
72
+ ('ɕ','ʃ'),
73
+ ('ʷ','w'),
74
+ ('ɭ','l`'),
75
+ ('ʎ','ɾ'),
76
+ ('ɣ','ŋ'),
77
+ ('ɰ','ɯ'),
78
+ ('ʝ','j'),
79
+ ('ʌ','ə'),
80
+ ('ɡ','g'),
81
+ ('\u031a','#'),
82
+ ('\u0348','='),
83
+ ('\u031e',''),
84
+ ('\u0320',''),
85
+ ('\u0339','')
86
+ ]]
87
+
88
+
89
+ def latin_to_hangul(text):
90
+ for regex, replacement in _latin_to_hangul:
91
+ text = re.sub(regex, replacement, text)
92
+ return text
93
+
94
+
95
+ def divide_hangul(text):
96
+ text = j2hcj(h2j(text))
97
+ for regex, replacement in _hangul_divided:
98
+ text = re.sub(regex, replacement, text)
99
+ return text
100
+
101
+
102
+ def hangul_number(num, sino=True):
103
+ '''Reference https://github.com/Kyubyong/g2pK'''
104
+ num = re.sub(',', '', num)
105
+
106
+ if num == '0':
107
+ return '영'
108
+ if not sino and num == '20':
109
+ return '스무'
110
+
111
+ digits = '123456789'
112
+ names = '일이삼사오육칠팔구'
113
+ digit2name = {d: n for d, n in zip(digits, names)}
114
+
115
+ modifiers = '한 두 세 네 다섯 여섯 일곱 여덟 아홉'
116
+ decimals = '열 스물 서른 마흔 쉰 예순 일흔 여든 아흔'
117
+ digit2mod = {d: mod for d, mod in zip(digits, modifiers.split())}
118
+ digit2dec = {d: dec for d, dec in zip(digits, decimals.split())}
119
+
120
+ spelledout = []
121
+ for i, digit in enumerate(num):
122
+ i = len(num) - i - 1
123
+ if sino:
124
+ if i == 0:
125
+ name = digit2name.get(digit, '')
126
+ elif i == 1:
127
+ name = digit2name.get(digit, '') + '십'
128
+ name = name.replace('일십', '십')
129
+ else:
130
+ if i == 0:
131
+ name = digit2mod.get(digit, '')
132
+ elif i == 1:
133
+ name = digit2dec.get(digit, '')
134
+ if digit == '0':
135
+ if i % 4 == 0:
136
+ last_three = spelledout[-min(3, len(spelledout)):]
137
+ if ''.join(last_three) == '':
138
+ spelledout.append('')
139
+ continue
140
+ else:
141
+ spelledout.append('')
142
+ continue
143
+ if i == 2:
144
+ name = digit2name.get(digit, '') + '백'
145
+ name = name.replace('일백', '백')
146
+ elif i == 3:
147
+ name = digit2name.get(digit, '') + '천'
148
+ name = name.replace('일천', '천')
149
+ elif i == 4:
150
+ name = digit2name.get(digit, '') + '만'
151
+ name = name.replace('일만', '만')
152
+ elif i == 5:
153
+ name = digit2name.get(digit, '') + '십'
154
+ name = name.replace('일십', '십')
155
+ elif i == 6:
156
+ name = digit2name.get(digit, '') + '백'
157
+ name = name.replace('일백', '백')
158
+ elif i == 7:
159
+ name = digit2name.get(digit, '') + '천'
160
+ name = name.replace('일천', '천')
161
+ elif i == 8:
162
+ name = digit2name.get(digit, '') + '억'
163
+ elif i == 9:
164
+ name = digit2name.get(digit, '') + '십'
165
+ elif i == 10:
166
+ name = digit2name.get(digit, '') + '백'
167
+ elif i == 11:
168
+ name = digit2name.get(digit, '') + '천'
169
+ elif i == 12:
170
+ name = digit2name.get(digit, '') + '조'
171
+ elif i == 13:
172
+ name = digit2name.get(digit, '') + '십'
173
+ elif i == 14:
174
+ name = digit2name.get(digit, '') + '백'
175
+ elif i == 15:
176
+ name = digit2name.get(digit, '') + '천'
177
+ spelledout.append(name)
178
+ return ''.join(elem for elem in spelledout)
179
+
180
+
181
+ def number_to_hangul(text):
182
+ '''Reference https://github.com/Kyubyong/g2pK'''
183
+ tokens = set(re.findall(r'(\d[\d,]*)([\uac00-\ud71f]+)', text))
184
+ for token in tokens:
185
+ num, classifier = token
186
+ if classifier[:2] in _korean_classifiers or classifier[0] in _korean_classifiers:
187
+ spelledout = hangul_number(num, sino=False)
188
+ else:
189
+ spelledout = hangul_number(num, sino=True)
190
+ text = text.replace(f'{num}{classifier}', f'{spelledout}{classifier}')
191
+ # digit by digit for remaining digits
192
+ digits = '0123456789'
193
+ names = '영일이삼사오육칠팔구'
194
+ for d, n in zip(digits, names):
195
+ text = text.replace(d, n)
196
+ return text
197
+
198
+
199
+ def korean_to_lazy_ipa(text):
200
+ text = latin_to_hangul(text)
201
+ text = number_to_hangul(text)
202
+ text=re.sub('[\uac00-\ud7af]+',lambda x:ko_pron.romanise(x.group(0),'ipa'),text).split('] ~ [')[0]
203
+ for regex, replacement in _ipa_to_lazy_ipa:
204
+ text = re.sub(regex, replacement, text)
205
+ return text
text/mandarin.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import re
4
+ from pypinyin import lazy_pinyin, BOPOMOFO
5
+ import jieba
6
+ import cn2an
7
+
8
+
9
+ # List of (Latin alphabet, bopomofo) pairs:
10
+ _latin_to_bopomofo = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
11
+ ('a', 'ㄟˉ'),
12
+ ('b', 'ㄅㄧˋ'),
13
+ ('c', 'ㄙㄧˉ'),
14
+ ('d', 'ㄉㄧˋ'),
15
+ ('e', 'ㄧˋ'),
16
+ ('f', 'ㄝˊㄈㄨˋ'),
17
+ ('g', 'ㄐㄧˋ'),
18
+ ('h', 'ㄝˇㄑㄩˋ'),
19
+ ('i', 'ㄞˋ'),
20
+ ('j', 'ㄐㄟˋ'),
21
+ ('k', 'ㄎㄟˋ'),
22
+ ('l', 'ㄝˊㄛˋ'),
23
+ ('m', 'ㄝˊㄇㄨˋ'),
24
+ ('n', 'ㄣˉ'),
25
+ ('o', 'ㄡˉ'),
26
+ ('p', 'ㄆㄧˉ'),
27
+ ('q', 'ㄎㄧㄡˉ'),
28
+ ('r', 'ㄚˋ'),
29
+ ('s', 'ㄝˊㄙˋ'),
30
+ ('t', 'ㄊㄧˋ'),
31
+ ('u', 'ㄧㄡˉ'),
32
+ ('v', 'ㄨㄧˉ'),
33
+ ('w', 'ㄉㄚˋㄅㄨˋㄌㄧㄡˋ'),
34
+ ('x', 'ㄝˉㄎㄨˋㄙˋ'),
35
+ ('y', 'ㄨㄞˋ'),
36
+ ('z', 'ㄗㄟˋ')
37
+ ]]
38
+
39
+ # List of (bopomofo, romaji) pairs:
40
+ _bopomofo_to_romaji = [(re.compile('%s' % x[0]), x[1]) for x in [
41
+ ('ㄅㄛ', 'p⁼wo'),
42
+ ('ㄆㄛ', 'pʰwo'),
43
+ ('ㄇㄛ', 'mwo'),
44
+ ('ㄈㄛ', 'fwo'),
45
+ ('ㄅ', 'p⁼'),
46
+ ('ㄆ', 'pʰ'),
47
+ ('ㄇ', 'm'),
48
+ ('ㄈ', 'f'),
49
+ ('ㄉ', 't⁼'),
50
+ ('ㄊ', 'tʰ'),
51
+ ('ㄋ', 'n'),
52
+ ('ㄌ', 'l'),
53
+ ('ㄍ', 'k⁼'),
54
+ ('ㄎ', 'kʰ'),
55
+ ('ㄏ', 'h'),
56
+ ('ㄐ', 'ʧ⁼'),
57
+ ('ㄑ', 'ʧʰ'),
58
+ ('ㄒ', 'ʃ'),
59
+ ('ㄓ', 'ʦ`⁼'),
60
+ ('ㄔ', 'ʦ`ʰ'),
61
+ ('ㄕ', 's`'),
62
+ ('ㄖ', 'ɹ`'),
63
+ ('ㄗ', 'ʦ⁼'),
64
+ ('ㄘ', 'ʦʰ'),
65
+ ('ㄙ', 's'),
66
+ ('ㄚ', 'a'),
67
+ ('ㄛ', 'o'),
68
+ ('ㄜ', 'ə'),
69
+ ('ㄝ', 'e'),
70
+ ('ㄞ', 'ai'),
71
+ ('ㄟ', 'ei'),
72
+ ('ㄠ', 'au'),
73
+ ('ㄡ', 'ou'),
74
+ ('ㄧㄢ', 'yeNN'),
75
+ ('ㄢ', 'aNN'),
76
+ ('ㄧㄣ', 'iNN'),
77
+ ('ㄣ', 'əNN'),
78
+ ('ㄤ', 'aNg'),
79
+ ('ㄧㄥ', 'iNg'),
80
+ ('ㄨㄥ', 'uNg'),
81
+ ('ㄩㄥ', 'yuNg'),
82
+ ('ㄥ', 'əNg'),
83
+ ('ㄦ', 'əɻ'),
84
+ ('ㄧ', 'i'),
85
+ ('ㄨ', 'u'),
86
+ ('ㄩ', 'ɥ'),
87
+ ('ˉ', '→'),
88
+ ('ˊ', '↑'),
89
+ ('ˇ', '↓↑'),
90
+ ('ˋ', '↓'),
91
+ ('˙', ''),
92
+ (',', ','),
93
+ ('。', '.'),
94
+ ('!', '!'),
95
+ ('?', '?'),
96
+ ('—', '-')
97
+ ]]
98
+
99
+ # List of (romaji, ipa) pairs:
100
+ _romaji_to_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
101
+ ('ʃy', 'ʃ'),
102
+ ('ʧʰy', 'ʧʰ'),
103
+ ('ʧ⁼y', 'ʧ⁼'),
104
+ ('NN', 'n'),
105
+ ('Ng', 'ŋ'),
106
+ ('y', 'j'),
107
+ ('h', 'x')
108
+ ]]
109
+
110
+ # List of (bopomofo, ipa) pairs:
111
+ _bopomofo_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
112
+ ('ㄅㄛ', 'p⁼wo'),
113
+ ('ㄆㄛ', 'pʰwo'),
114
+ ('ㄇㄛ', 'mwo'),
115
+ ('ㄈㄛ', 'fwo'),
116
+ ('ㄅ', 'p⁼'),
117
+ ('ㄆ', 'pʰ'),
118
+ ('ㄇ', 'm'),
119
+ ('ㄈ', 'f'),
120
+ ('ㄉ', 't⁼'),
121
+ ('ㄊ', 'tʰ'),
122
+ ('ㄋ', 'n'),
123
+ ('ㄌ', 'l'),
124
+ ('ㄍ', 'k⁼'),
125
+ ('ㄎ', 'kʰ'),
126
+ ('ㄏ', 'x'),
127
+ ('ㄐ', 'tʃ⁼'),
128
+ ('ㄑ', 'tʃʰ'),
129
+ ('ㄒ', 'ʃ'),
130
+ ('ㄓ', 'ts`⁼'),
131
+ ('ㄔ', 'ts`ʰ'),
132
+ ('ㄕ', 's`'),
133
+ ('ㄖ', 'ɹ`'),
134
+ ('ㄗ', 'ts⁼'),
135
+ ('ㄘ', 'tsʰ'),
136
+ ('ㄙ', 's'),
137
+ ('ㄚ', 'a'),
138
+ ('ㄛ', 'o'),
139
+ ('ㄜ', 'ə'),
140
+ ('ㄝ', 'ɛ'),
141
+ ('ㄞ', 'aɪ'),
142
+ ('ㄟ', 'eɪ'),
143
+ ('ㄠ', 'ɑʊ'),
144
+ ('ㄡ', 'oʊ'),
145
+ ('ㄧㄢ', 'jɛn'),
146
+ ('ㄩㄢ', 'ɥæn'),
147
+ ('ㄢ', 'an'),
148
+ ('ㄧㄣ', 'in'),
149
+ ('ㄩㄣ', 'ɥn'),
150
+ ('ㄣ', 'ən'),
151
+ ('ㄤ', 'ɑŋ'),
152
+ ('ㄧㄥ', 'iŋ'),
153
+ ('ㄨㄥ', 'ʊŋ'),
154
+ ('ㄩㄥ', 'jʊŋ'),
155
+ ('ㄥ', 'əŋ'),
156
+ ('ㄦ', 'əɻ'),
157
+ ('ㄧ', 'i'),
158
+ ('ㄨ', 'u'),
159
+ ('ㄩ', 'ɥ'),
160
+ ('ˉ', '→'),
161
+ ('ˊ', '↑'),
162
+ ('ˇ', '↓↑'),
163
+ ('ˋ', '↓'),
164
+ ('˙', ''),
165
+ (',', ','),
166
+ ('。', '.'),
167
+ ('!', '!'),
168
+ ('?', '?'),
169
+ ('—', '-')
170
+ ]]
171
+
172
+ # List of (bopomofo, ipa2) pairs:
173
+ _bopomofo_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [
174
+ ('ㄅㄛ', 'pwo'),
175
+ ('ㄆㄛ', 'pʰwo'),
176
+ ('ㄇㄛ', 'mwo'),
177
+ ('ㄈㄛ', 'fwo'),
178
+ ('ㄅ', 'p'),
179
+ ('ㄆ', 'pʰ'),
180
+ ('ㄇ', 'm'),
181
+ ('ㄈ', 'f'),
182
+ ('ㄉ', 't'),
183
+ ('ㄊ', 'tʰ'),
184
+ ('ㄋ', 'n'),
185
+ ('ㄌ', 'l'),
186
+ ('ㄍ', 'k'),
187
+ ('ㄎ', 'kʰ'),
188
+ ('ㄏ', 'h'),
189
+ ('ㄐ', 'tɕ'),
190
+ ('ㄑ', 'tɕʰ'),
191
+ ('ㄒ', 'ɕ'),
192
+ ('ㄓ', 'tʂ'),
193
+ ('ㄔ', 'tʂʰ'),
194
+ ('ㄕ', 'ʂ'),
195
+ ('ㄖ', 'ɻ'),
196
+ ('ㄗ', 'ts'),
197
+ ('ㄘ', 'tsʰ'),
198
+ ('ㄙ', 's'),
199
+ ('ㄚ', 'a'),
200
+ ('ㄛ', 'o'),
201
+ ('ㄜ', 'ɤ'),
202
+ ('ㄝ', 'ɛ'),
203
+ ('ㄞ', 'aɪ'),
204
+ ('ㄟ', 'eɪ'),
205
+ ('ㄠ', 'ɑʊ'),
206
+ ('ㄡ', 'oʊ'),
207
+ ('ㄧㄢ', 'jɛn'),
208
+ ('ㄩㄢ', 'yæn'),
209
+ ('ㄢ', 'an'),
210
+ ('ㄧㄣ', 'in'),
211
+ ('ㄩㄣ', 'yn'),
212
+ ('ㄣ', 'ən'),
213
+ ('ㄤ', 'ɑŋ'),
214
+ ('ㄧㄥ', 'iŋ'),
215
+ ('ㄨㄥ', 'ʊŋ'),
216
+ ('ㄩㄥ', 'jʊŋ'),
217
+ ('ㄥ', 'ɤŋ'),
218
+ ('ㄦ', 'əɻ'),
219
+ ('ㄧ', 'i'),
220
+ ('ㄨ', 'u'),
221
+ ('ㄩ', 'y'),
222
+ ('ˉ', '˥'),
223
+ ('ˊ', '˧˥'),
224
+ ('ˇ', '˨˩˦'),
225
+ ('ˋ', '˥˩'),
226
+ ('˙', ''),
227
+ (',', ','),
228
+ ('。', '.'),
229
+ ('!', '!'),
230
+ ('?', '?'),
231
+ ('—', '-')
232
+ ]]
233
+
234
+
235
+ def number_to_chinese(text):
236
+ numbers = re.findall(r'\d+(?:\.?\d+)?', text)
237
+ for number in numbers:
238
+ text = text.replace(number, cn2an.an2cn(number), 1)
239
+ return text
240
+
241
+
242
+ def chinese_to_bopomofo(text, taiwanese=False):
243
+ text = text.replace('、', ',').replace(';', ',').replace(':', ',')
244
+ words = jieba.lcut(text, cut_all=False)
245
+ text = ''
246
+ for word in words:
247
+ bopomofos = lazy_pinyin(word, BOPOMOFO)
248
+ if not re.search('[\u4e00-\u9fff]', word):
249
+ text += word
250
+ continue
251
+ for i in range(len(bopomofos)):
252
+ bopomofos[i] = re.sub(r'([\u3105-\u3129])$', r'\1ˉ', bopomofos[i])
253
+ if text != '':
254
+ text += ' '
255
+ if taiwanese:
256
+ text += '#'+'#'.join(bopomofos)
257
+ else:
258
+ text += ''.join(bopomofos)
259
+ return text
260
+
261
+
262
+ def latin_to_bopomofo(text):
263
+ for regex, replacement in _latin_to_bopomofo:
264
+ text = re.sub(regex, replacement, text)
265
+ return text
266
+
267
+
268
+ def bopomofo_to_romaji(text):
269
+ for regex, replacement in _bopomofo_to_romaji:
270
+ text = re.sub(regex, replacement, text)
271
+ return text
272
+
273
+
274
+ def bopomofo_to_ipa(text):
275
+ for regex, replacement in _bopomofo_to_ipa:
276
+ text = re.sub(regex, replacement, text)
277
+ return text
278
+
279
+
280
+ def bopomofo_to_ipa2(text):
281
+ for regex, replacement in _bopomofo_to_ipa2:
282
+ text = re.sub(regex, replacement, text)
283
+ return text
284
+
285
+
286
+ def chinese_to_romaji(text):
287
+ text = number_to_chinese(text)
288
+ text = chinese_to_bopomofo(text)
289
+ text = latin_to_bopomofo(text)
290
+ text = bopomofo_to_romaji(text)
291
+ text = re.sub('i([aoe])', r'y\1', text)
292
+ text = re.sub('u([aoəe])', r'w\1', text)
293
+ text = re.sub('([ʦsɹ]`[⁼ʰ]?)([→↓↑ ]+|$)',
294
+ r'\1ɹ`\2', text).replace('ɻ', 'ɹ`')
295
+ text = re.sub('([ʦs][⁼ʰ]?)([→↓↑ ]+|$)', r'\1ɹ\2', text)
296
+ return text
297
+
298
+
299
+ def chinese_to_lazy_ipa(text):
300
+ text = chinese_to_romaji(text)
301
+ for regex, replacement in _romaji_to_ipa:
302
+ text = re.sub(regex, replacement, text)
303
+ return text
304
+
305
+
306
+ def chinese_to_ipa(text):
307
+ text = number_to_chinese(text)
308
+ text = chinese_to_bopomofo(text)
309
+ text = latin_to_bopomofo(text)
310
+ text = bopomofo_to_ipa(text)
311
+ text = re.sub('i([aoe])', r'j\1', text)
312
+ text = re.sub('u([aoəe])', r'w\1', text)
313
+ text = re.sub('([sɹ]`[⁼ʰ]?)([→↓↑ ]+|$)',
314
+ r'\1ɹ`\2', text).replace('ɻ', 'ɹ`')
315
+ text = re.sub('([s][⁼ʰ]?)([→↓↑ ]+|$)', r'\1ɹ\2', text)
316
+ return text
317
+
318
+
319
+ def chinese_to_ipa2(text, taiwanese=False):
320
+ text = number_to_chinese(text)
321
+ text = chinese_to_bopomofo(text, taiwanese)
322
+ text = latin_to_bopomofo(text)
323
+ text = bopomofo_to_ipa2(text)
324
+ text = re.sub(r'i([aoe])', r'j\1', text)
325
+ text = re.sub(r'u([aoəe])', r'w\1', text)
326
+ text = re.sub(r'([ʂɹ]ʰ?)([˩˨˧˦˥ ]+|$)', r'\1ʅ\2', text)
327
+ text = re.sub(r'(sʰ?)([˩˨˧˦˥ ]+|$)', r'\1ɿ\2', text)
328
+ return text
text/sanskrit.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from indic_transliteration import sanscript
3
+
4
+
5
+ # List of (iast, ipa) pairs:
6
+ _iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
7
+ ('a', 'ə'),
8
+ ('ā', 'aː'),
9
+ ('ī', 'iː'),
10
+ ('ū', 'uː'),
11
+ ('ṛ', 'ɹ`'),
12
+ ('ṝ', 'ɹ`ː'),
13
+ ('ḷ', 'l`'),
14
+ ('ḹ', 'l`ː'),
15
+ ('e', 'eː'),
16
+ ('o', 'oː'),
17
+ ('k', 'k⁼'),
18
+ ('k⁼h', 'kʰ'),
19
+ ('g', 'g⁼'),
20
+ ('g⁼h', 'gʰ'),
21
+ ('ṅ', 'ŋ'),
22
+ ('c', 'ʧ⁼'),
23
+ ('ʧ⁼h', 'ʧʰ'),
24
+ ('j', 'ʥ⁼'),
25
+ ('ʥ⁼h', 'ʥʰ'),
26
+ ('ñ', 'n^'),
27
+ ('ṭ', 't`⁼'),
28
+ ('t`⁼h', 't`ʰ'),
29
+ ('ḍ', 'd`⁼'),
30
+ ('d`⁼h', 'd`ʰ'),
31
+ ('ṇ', 'n`'),
32
+ ('t', 't⁼'),
33
+ ('t⁼h', 'tʰ'),
34
+ ('d', 'd⁼'),
35
+ ('d⁼h', 'dʰ'),
36
+ ('p', 'p⁼'),
37
+ ('p⁼h', 'pʰ'),
38
+ ('b', 'b⁼'),
39
+ ('b⁼h', 'bʰ'),
40
+ ('y', 'j'),
41
+ ('ś', 'ʃ'),
42
+ ('ṣ', 's`'),
43
+ ('r', 'ɾ'),
44
+ ('l̤', 'l`'),
45
+ ('h', 'ɦ'),
46
+ ("'", ''),
47
+ ('~', '^'),
48
+ ('ṃ', '^')
49
+ ]]
50
+
51
+
52
+ def devanagari_to_ipa(text):
53
+ text = text.replace('ॐ', 'ओम्')
54
+ text = re.sub(r'\s*।\s*$', '.', text)
55
+ text = re.sub(r'\s*।\s*', ', ', text)
56
+ text = re.sub(r'\s*॥', '.', text)
57
+ text = sanscript.transliterate(text, sanscript.DEVANAGARI, sanscript.IAST)
58
+ for regex, replacement in _iast_to_ipa:
59
+ text = re.sub(regex, replacement, text)
60
+ text = re.sub('(.)[`ː]*ḥ', lambda x: x.group(0)
61
+ [:-1]+'h'+x.group(1)+'*', text)
62
+ return text
transforms.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import numpy as np
5
+
6
+
7
+ DEFAULT_MIN_BIN_WIDTH = 1e-3
8
+ DEFAULT_MIN_BIN_HEIGHT = 1e-3
9
+ DEFAULT_MIN_DERIVATIVE = 1e-3
10
+
11
+
12
+ def piecewise_rational_quadratic_transform(inputs,
13
+ unnormalized_widths,
14
+ unnormalized_heights,
15
+ unnormalized_derivatives,
16
+ inverse=False,
17
+ tails=None,
18
+ tail_bound=1.,
19
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
20
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
21
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
22
+
23
+ if tails is None:
24
+ spline_fn = rational_quadratic_spline
25
+ spline_kwargs = {}
26
+ else:
27
+ spline_fn = unconstrained_rational_quadratic_spline
28
+ spline_kwargs = {
29
+ 'tails': tails,
30
+ 'tail_bound': tail_bound
31
+ }
32
+
33
+ outputs, logabsdet = spline_fn(
34
+ inputs=inputs,
35
+ unnormalized_widths=unnormalized_widths,
36
+ unnormalized_heights=unnormalized_heights,
37
+ unnormalized_derivatives=unnormalized_derivatives,
38
+ inverse=inverse,
39
+ min_bin_width=min_bin_width,
40
+ min_bin_height=min_bin_height,
41
+ min_derivative=min_derivative,
42
+ **spline_kwargs
43
+ )
44
+ return outputs, logabsdet
45
+
46
+
47
+ def searchsorted(bin_locations, inputs, eps=1e-6):
48
+ bin_locations[..., -1] += eps
49
+ return torch.sum(
50
+ inputs[..., None] >= bin_locations,
51
+ dim=-1
52
+ ) - 1
53
+
54
+
55
+ def unconstrained_rational_quadratic_spline(inputs,
56
+ unnormalized_widths,
57
+ unnormalized_heights,
58
+ unnormalized_derivatives,
59
+ inverse=False,
60
+ tails='linear',
61
+ tail_bound=1.,
62
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
63
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
64
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
65
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
66
+ outside_interval_mask = ~inside_interval_mask
67
+
68
+ outputs = torch.zeros_like(inputs)
69
+ logabsdet = torch.zeros_like(inputs)
70
+
71
+ if tails == 'linear':
72
+ unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
73
+ constant = np.log(np.exp(1 - min_derivative) - 1)
74
+ unnormalized_derivatives[..., 0] = constant
75
+ unnormalized_derivatives[..., -1] = constant
76
+
77
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
78
+ logabsdet[outside_interval_mask] = 0
79
+ else:
80
+ raise RuntimeError('{} tails are not implemented.'.format(tails))
81
+
82
+ outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
83
+ inputs=inputs[inside_interval_mask],
84
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
85
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
86
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
87
+ inverse=inverse,
88
+ left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
89
+ min_bin_width=min_bin_width,
90
+ min_bin_height=min_bin_height,
91
+ min_derivative=min_derivative
92
+ )
93
+
94
+ return outputs, logabsdet
95
+
96
+ def rational_quadratic_spline(inputs,
97
+ unnormalized_widths,
98
+ unnormalized_heights,
99
+ unnormalized_derivatives,
100
+ inverse=False,
101
+ left=0., right=1., bottom=0., top=1.,
102
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
103
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
104
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
105
+ if torch.min(inputs) < left or torch.max(inputs) > right:
106
+ raise ValueError('Input to a transform is not within its domain')
107
+
108
+ num_bins = unnormalized_widths.shape[-1]
109
+
110
+ if min_bin_width * num_bins > 1.0:
111
+ raise ValueError('Minimal bin width too large for the number of bins')
112
+ if min_bin_height * num_bins > 1.0:
113
+ raise ValueError('Minimal bin height too large for the number of bins')
114
+
115
+ widths = F.softmax(unnormalized_widths, dim=-1)
116
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
117
+ cumwidths = torch.cumsum(widths, dim=-1)
118
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
119
+ cumwidths = (right - left) * cumwidths + left
120
+ cumwidths[..., 0] = left
121
+ cumwidths[..., -1] = right
122
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
123
+
124
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
125
+
126
+ heights = F.softmax(unnormalized_heights, dim=-1)
127
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
128
+ cumheights = torch.cumsum(heights, dim=-1)
129
+ cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
130
+ cumheights = (top - bottom) * cumheights + bottom
131
+ cumheights[..., 0] = bottom
132
+ cumheights[..., -1] = top
133
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
134
+
135
+ if inverse:
136
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
137
+ else:
138
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
139
+
140
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
141
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
142
+
143
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
144
+ delta = heights / widths
145
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
146
+
147
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
148
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
149
+
150
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
151
+
152
+ if inverse:
153
+ a = (((inputs - input_cumheights) * (input_derivatives
154
+ + input_derivatives_plus_one
155
+ - 2 * input_delta)
156
+ + input_heights * (input_delta - input_derivatives)))
157
+ b = (input_heights * input_derivatives
158
+ - (inputs - input_cumheights) * (input_derivatives
159
+ + input_derivatives_plus_one
160
+ - 2 * input_delta))
161
+ c = - input_delta * (inputs - input_cumheights)
162
+
163
+ discriminant = b.pow(2) - 4 * a * c
164
+ assert (discriminant >= 0).all()
165
+
166
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
167
+ outputs = root * input_bin_widths + input_cumwidths
168
+
169
+ theta_one_minus_theta = root * (1 - root)
170
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
171
+ * theta_one_minus_theta)
172
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
173
+ + 2 * input_delta * theta_one_minus_theta
174
+ + input_derivatives * (1 - root).pow(2))
175
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
176
+
177
+ return outputs, -logabsdet
178
+ else:
179
+ theta = (inputs - input_cumwidths) / input_bin_widths
180
+ theta_one_minus_theta = theta * (1 - theta)
181
+
182
+ numerator = input_heights * (input_delta * theta.pow(2)
183
+ + input_derivatives * theta_one_minus_theta)
184
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
185
+ * theta_one_minus_theta)
186
+ outputs = input_cumheights + numerator / denominator
187
+
188
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
189
+ + 2 * input_delta * theta_one_minus_theta
190
+ + input_derivatives * (1 - theta).pow(2))
191
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
192
+
193
+ return outputs, logabsdet
utils.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from json import loads
3
+ from torch import load, FloatTensor
4
+ from numpy import float32
5
+ import librosa
6
+
7
+
8
+ class HParams():
9
+ def __init__(self, **kwargs):
10
+ for k, v in kwargs.items():
11
+ if type(v) == dict:
12
+ v = HParams(**v)
13
+ self[k] = v
14
+
15
+ def keys(self):
16
+ return self.__dict__.keys()
17
+
18
+ def items(self):
19
+ return self.__dict__.items()
20
+
21
+ def values(self):
22
+ return self.__dict__.values()
23
+
24
+ def __len__(self):
25
+ return len(self.__dict__)
26
+
27
+ def __getitem__(self, key):
28
+ return getattr(self, key)
29
+
30
+ def __setitem__(self, key, value):
31
+ return setattr(self, key, value)
32
+
33
+ def __contains__(self, key):
34
+ return key in self.__dict__
35
+
36
+ def __repr__(self):
37
+ return self.__dict__.__repr__()
38
+
39
+
40
+ def load_checkpoint(checkpoint_path, model):
41
+ checkpoint_dict = load(checkpoint_path, map_location='cpu')
42
+ iteration = checkpoint_dict['iteration']
43
+ saved_state_dict = checkpoint_dict['model']
44
+ if hasattr(model, 'module'):
45
+ state_dict = model.module.state_dict()
46
+ else:
47
+ state_dict = model.state_dict()
48
+ new_state_dict = {}
49
+ for k, v in state_dict.items():
50
+ try:
51
+ new_state_dict[k] = saved_state_dict[k]
52
+ except:
53
+ logging.info("%s is not in the checkpoint" % k)
54
+ new_state_dict[k] = v
55
+ pass
56
+ if hasattr(model, 'module'):
57
+ model.module.load_state_dict(new_state_dict)
58
+ else:
59
+ model.load_state_dict(new_state_dict)
60
+ logging.info("Loaded checkpoint '{}' (iteration {})".format(
61
+ checkpoint_path, iteration))
62
+ return
63
+
64
+
65
+ def get_hparams_from_file(config_path):
66
+ with open(config_path, "r") as f:
67
+ data = f.read()
68
+ config = loads(data)
69
+
70
+ hparams = HParams(**config)
71
+ return hparams
72
+
73
+
74
+ def load_audio_to_torch(full_path, target_sampling_rate):
75
+ audio, sampling_rate = librosa.load(full_path, sr=target_sampling_rate, mono=True)
76
+ return FloatTensor(audio.astype(float32))