Mahiruoshi commited on
Commit
3e7715d
1 Parent(s): 221a661

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +497 -350
app.py CHANGED
@@ -1,388 +1,535 @@
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.symbols import symbols
14
- from text import text_to_sequence
15
- import gradio as gr
16
  import time
17
  import datetime
18
  import os
19
- import librosa
20
- from mel_processing import spectrogram_torch
21
- class VitsGradio:
22
- def __init__(self):
23
- self.dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
24
- self.lan = ["中文","日文","自动","手动"]
25
- self.idols = ["高咲侑","歩夢","かすみ","しずく","果林","愛","彼方","せつ菜","璃奈","栞子","エマ","ランジュ","ミア","華恋","まひる","なな","クロディーヌ","ひかり",'純那',"香子","真矢","双葉","ミチル","メイファン","やちよ","晶","いちえ","ゆゆ子","塁","珠緒","あるる","ララフィン","美空","静羽","あるる","梁芷柔","墨小菊"]
26
- self.modelPaths = []
27
- for root,dirs,files in os.walk("checkpoints"):
28
- for dir in dirs:
29
- self.modelPaths.append(dir)
30
- with gr.Blocks() as self.Vits:
31
- gr.Markdown(
32
- "## <center> 虹团-少歌vits\n"
33
- "### <center> 请不要生成会对个人以及企划造成侵害的内容\n"
34
- "<div align='center'>目前有混合模型(tmp)、少歌中文特化版(ShojoKageki),虹团默认(default)、标贝版(biaobei)</div>"
35
- '<div align="center"><a>参数说明:目前的默认参数不一定理想,可以直接将噪声比例和噪声偏差调为0,也可以噪声比例调节至0.2-0.3区间,噪声偏差对应着每个字之间的间隔,可单独调为0,duration代表整体语速</div>'
36
- '<div align="center"><a>合成前请先选择模型,否则第一次合成不一定成功。添加了vits自带的svc功能,可以图一乐。长段落/小说合成建议colab或本地运行</div>')
37
- with gr.Tab("TTS合成"):
38
- with gr.Row():
39
- with gr.Column():
40
- with gr.Row():
41
- with gr.Column():
42
- input1 = gr.TextArea(label="Text", value="夢咲く舞台に、輝け、私!")
43
- input2 = gr.Dropdown(label="Language", choices=self.lan, value="自动", interactive=True)
44
- input3 = gr.Dropdown(label="Speaker", choices=self.idols, value="華恋", interactive=True)
45
- btnVC = gr.Button("Submit")
46
- with gr.Column():
47
- input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.6)
48
- input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.668)
49
- input6 = gr.Slider(minimum=0.1, maximum=10, label="duration", value=1)
50
- output1 = gr.Audio(label="采样率22050")
51
- btnVC.click(self.infer, inputs=[input1, input2, input3, input4, input5, input6], outputs=[output1])
52
- with gr.Tab("选择模型"):
53
- with gr.Column():
54
- modelstrs = gr.Dropdown(label = "模型", choices = self.modelPaths, value = self.modelPaths[0], type = "value")
55
- btnMod = gr.Button("载入模型")
56
- statusa = gr.TextArea()
57
- btnMod.click(self.loadCk, inputs=[modelstrs], outputs = [statusa])
58
- with gr.Tab("Voice Conversion"):
59
- gr.Markdown("""
60
- 录制或上传声音,并选择要转换的音色。
61
- """)
62
- with gr.Column():
63
- record_audio = gr.Audio(label="record your voice", source="microphone")
64
- upload_audio = gr.Audio(label="or upload audio here", source="upload")
65
- source_speaker = gr.Dropdown(choices=self.idols, value="歩夢", label="source speaker")
66
- target_speaker = gr.Dropdown(choices=self.idols, value="歩夢", label="target speaker")
67
- with gr.Column():
68
- message_box = gr.Textbox(label="Message")
69
- converted_audio = gr.Audio(label='converted audio')
70
- btn = gr.Button("Convert!")
71
- btn.click(self.vc_fn, inputs=[source_speaker, target_speaker, record_audio, upload_audio],
72
- outputs=[message_box, converted_audio])
73
- with gr.Tab("小说合成(带字幕)"):
74
- with gr.Row():
75
- with gr.Column():
76
- with gr.Row():
77
- with gr.Column():
78
- input1 = gr.TextArea(label="Text", value="为什么你会那么熟练啊?你和雪菜亲过多少次了")
79
- input2 = gr.Dropdown(label="Language", choices=self.lan, value="自动", interactive=True)
80
- input3 = gr.Dropdown(label="Speaker", choices=self.idols, value="歩夢", interactive=True)
81
- btnVC = gr.Button("Submit")
82
- with gr.Column():
83
- input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.267)
84
- input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.7)
85
- input6 = gr.Slider(minimum=0.1, maximum=10, label="Duration", value=1)
86
- output1 = gr.Audio(label="采样率22050")
87
- subtitle = gr.outputs.File(label="字幕文件:subtitles.srt")
88
- btnVC.click(self.infer2, inputs=[input1, input2, input3, input4, input5, input6], outputs=[output1,subtitle])
89
-
90
- def loadCk(self,path):
91
- self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
92
- self.net_g = SynthesizerTrn(
93
- len(symbols),
94
- self.hps.data.filter_length // 2 + 1,
95
- self.hps.train.segment_size // self.hps.data.hop_length,
96
- n_speakers=self.hps.data.n_speakers,
97
- **self.hps.model).to(self.dev)
98
- _ = self.net_g.eval()
99
- _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", self.net_g)
100
- return "success"
101
-
102
- def get_text(self,text):
103
- text_norm = text_to_sequence(text,self.hps.data.text_cleaners)
104
- if self.hps.data.add_blank:
105
- text_norm = commons.intersperse(text_norm, 0)
106
- text_norm = torch.LongTensor(text_norm)
107
- return text_norm
108
-
109
- def is_japanese(self,string):
110
  for ch in string:
111
  if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
112
  return True
113
  return False
114
-
115
- def is_english(self,string):
116
  import re
117
  pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
118
  if pattern.fullmatch(string):
119
  return True
120
  else:
121
  return False
122
-
123
- def selection(self,speaker):
124
- if speaker == "高咲侑":
125
- spk = 0
126
- return spk
127
-
128
- elif speaker == "歩夢":
129
- spk = 1
130
- return spk
131
-
132
- elif speaker == "かすみ":
133
- spk = 2
134
- return spk
135
-
136
- elif speaker == "しずく":
137
- spk = 3
138
- return spk
139
-
140
- elif speaker == "果林":
141
- spk = 4
142
- return spk
143
-
144
- elif speaker == "愛":
145
- spk = 5
146
- return spk
147
-
148
- elif speaker == "彼方":
149
- spk = 6
150
- return spk
151
-
152
- elif speaker == "せつ菜":
153
- spk = 7
154
- return spk
155
- elif speaker == "エマ":
156
- spk = 8
157
- return spk
158
- elif speaker == "璃奈":
159
- spk = 9
160
- return spk
161
- elif speaker == "栞子":
162
- spk = 10
163
- return spk
164
- elif speaker == "ランジュ":
165
- spk = 11
166
- return spk
167
- elif speaker == "ミア":
168
- spk = 12
169
- return spk
170
-
171
- elif speaker == "派蒙":
172
- spk = 16
173
- return spk
174
-
175
- elif speaker == "梁芷柔":
176
- spk = 18
177
- return spk
178
 
179
- elif speaker == "墨小菊":
180
- spk = 0
181
- return spk
182
 
183
- elif speaker == "華恋":
184
- spk = 21
185
- return spk
186
 
187
- elif speaker == "まひる":
188
- spk = 22
189
- return spk
190
-
191
- elif speaker == "なな":
192
- spk = 23
193
- return spk
194
-
195
- elif speaker == "クロディーヌ":
196
- spk = 24
197
- return spk
198
-
199
- elif speaker == "ひかり":
200
- spk = 25
201
- return spk
202
-
203
- elif speaker == "純那":
204
- spk = 26
205
- return spk
206
-
207
- elif speaker == "香子":
208
- spk = 27
209
- return spk
210
-
211
- elif speaker == "真矢":
212
- spk = 28
213
- return spk
214
- elif speaker == "双葉":
215
- spk = 29
216
- return spk
217
- elif speaker == "ミチル":
218
- spk = 30
219
- return spk
220
- elif speaker == "メイファン":
221
- spk = 31
222
- return spk
223
- elif speaker == "やちよ":
224
- spk = 32
225
- return spk
226
- elif speaker == "晶":
227
- spk = 33
228
- return spk
229
- elif speaker == "いちえ":
230
- spk = 34
231
- return spk
232
- elif speaker == "ゆゆ子":
233
- spk = 35
234
- return spk
235
- elif speaker == "塁":
236
- spk = 36
237
- return spk
238
- elif speaker == "珠緒":
239
- spk = 37
240
- return spk
241
- elif speaker == "あるる":
242
- spk = 38
243
- return spk
244
- elif speaker == "ララフィン":
245
- spk = 39
246
- return spk
247
- elif speaker == "美空":
248
- spk = 40
249
- return spk
250
- elif speaker == "静羽":
251
- spk = 41
252
- return spk
253
  else:
254
- return 0
255
-
256
-
257
- def sle(self,language,text):
258
- text = text.replace('\n','。').replace(' ',',')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  if language == "中文":
260
  tts_input1 = "[ZH]" + text + "[ZH]"
261
  return tts_input1
262
  elif language == "自动":
263
- tts_input1 = f"[JA]{text}[JA]" if self.is_japanese(text) else f"[ZH]{text}[ZH]"
264
  return tts_input1
265
  elif language == "日文":
266
  tts_input1 = "[JA]" + text + "[JA]"
267
  return tts_input1
268
- elif language == "英文":
269
- tts_input1 = "[EN]" + text + "[EN]"
270
- return tts_input1
271
  elif language == "手动":
272
  return text
273
-
274
- def extrac(self,text):
275
- text = re.sub("<[^>]*>","",text)
276
- result_list = re.split(r'\n', text)
277
- final_list = []
278
- for i in result_list:
279
- if self.is_english(i):
280
- i = romajitable.to_kana(i).katakana
281
- i = i.replace('\n','').replace(' ','')
282
- #Current length of single sentence: 20
283
- if len(i)>1:
284
- if len(i) > 20:
285
- try:
286
- cur_list = re.split(r'。|!', i)
287
- for i in cur_list:
288
- if len(i)>1:
289
- final_list.append(i+'。')
290
- except:
291
- pass
292
- else:
293
- final_list.append(i)
294
- final_list = [x for x in final_list if x != '']
295
- print(final_list)
296
- return final_list
297
-
298
- def vc_fn(self,original_speaker, target_speaker, record_audio, upload_audio):
299
- input_audio = record_audio if record_audio is not None else upload_audio
300
- if input_audio is None:
301
- return "You need to record or upload an audio", None
302
- sampling_rate, audio = input_audio
303
- original_speaker_id = self.selection(original_speaker)
304
- target_speaker_id = self.selection(target_speaker)
305
-
306
- audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
307
- if len(audio.shape) > 1:
308
- audio = librosa.to_mono(audio.transpose(1, 0))
309
- if sampling_rate != self.hps.data.sampling_rate:
310
- audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=self.hps.data.sampling_rate)
311
- with torch.no_grad():
312
- y = torch.FloatTensor(audio)
313
- y = y / max(-y.min(), y.max()) / 0.99
314
- y = y.to(self.dev)
315
- y = y.unsqueeze(0)
316
- spec = spectrogram_torch(y, self.hps.data.filter_length,
317
- self.hps.data.sampling_rate, self.hps.data.hop_length, self.hps.data.win_length,
318
- center=False).to(self.dev)
319
- spec_lengths = torch.LongTensor([spec.size(-1)]).to(self.dev)
320
- sid_src = torch.LongTensor([original_speaker_id]).to(self.dev)
321
- sid_tgt = torch.LongTensor([target_speaker_id]).to(self.dev)
322
- audio = self.net_g.voice_conversion(spec, spec_lengths, sid_src=sid_src, sid_tgt=sid_tgt)[0][
323
- 0, 0].data.cpu().float().numpy()
324
- del y, spec, spec_lengths, sid_src, sid_tgt
325
- return "Success", (self.hps.data.sampling_rate, audio)
326
-
327
- def infer(self, text ,language, speaker_id,n_scale= 0.667,n_scale_w = 0.8, l_scale = 1):
328
- try:
329
- speaker_id = int(self.selection(speaker_id))
330
  t1 = time.time()
331
- stn_tst = self.get_text(self.sle(language,text))
332
  with torch.no_grad():
333
- x_tst = stn_tst.unsqueeze(0).to(self.dev)
334
- x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(self.dev)
335
- sid = torch.LongTensor([speaker_id]).to(self.dev)
336
- 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()
337
  t2 = time.time()
338
  spending_time = "推理时间为:"+str(t2-t1)+"s"
339
  print(spending_time)
340
- return (self.hps.data.sampling_rate, audio)
341
- except:
342
- self.hps = utils.get_hparams_from_file(f"checkpoints/biaobei/config.json")
343
- self.net_g = SynthesizerTrn(
344
- len(symbols),
345
- self.hps.data.filter_length // 2 + 1,
346
- self.hps.train.segment_size // self.hps.data.hop_length,
347
- n_speakers=self.hps.data.n_speakers,
348
- **self.hps.model).to(self.dev)
349
- _ = self.net_g.eval()
350
- _ = utils.load_checkpoint(f"checkpoints/biaobei/model.pth", self.net_g)
351
-
352
- def infer2(self, text ,language, speaker_id,n_scale= 0.667,n_scale_w = 0.8, l_scale = 1):
353
- speaker_id = int(self.selection(speaker_id))
354
- a = ['【','[','(','']
355
- b = ['】',']',')',')']
356
- for i in a:
357
- text = text.replace(i,'<')
358
- for i in b:
359
- text = text.replace(i,'>')
360
- final_list = self.extrac(text.replace('“','').replace('”',''))
361
- audio_fin = []
362
- c = 0
363
- t = datetime.timedelta(seconds=0)
364
- f1 = open("subtitles.srt",'w',encoding='utf-8')
365
- for sentence in final_list:
366
- c +=1
367
- stn_tst = self.get_text(self.sle(language,sentence))
368
- with torch.no_grad():
369
- x_tst = stn_tst.unsqueeze(0).to(self.dev)
370
- x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(self.dev)
371
- sid = torch.LongTensor([speaker_id]).to(self.dev)
372
- t1 = time.time()
373
- 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()
374
- t2 = time.time()
375
- spending_time = "第"+str(c)+"句的推理时间为:"+str(t2-t1)+"s"
376
- print(spending_time)
377
- time_start = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
378
- last_time = datetime.timedelta(seconds=len(audio)/float(22050))
379
- t+=last_time
380
- time_end = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
381
- print(time_end)
382
- f1.write(str(c-1)+'\n'+time_start+' --> '+time_end+'\n'+sentence+'\n\n')
383
- audio_fin.append(audio)
384
- file_path = "subtitles.srt"
385
- return (self.hps.data.sampling_rate, np.concatenate(audio_fin)),file_path
386
- print("开始部署")
387
- grVits = VitsGradio()
388
- grVits.Vits.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  logging.getLogger('numba').setLevel(logging.WARNING)
2
  logging.getLogger('matplotlib').setLevel(logging.WARNING)
3
  logging.getLogger('urllib3').setLevel(logging.WARNING)
4
+ import json
5
  import re
6
  import numpy as np
7
  import IPython.display as ipd
 
 
 
 
 
 
 
8
  import time
9
  import datetime
10
  import os
11
+ import pickle
12
+ import openai
13
+ from scipy.io.wavfile import write
14
+ def is_japanese(string):
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
  for ch in string:
103
  if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
104
  return True
105
  return False
106
+
107
+ def is_english(string):
108
  import re
109
  pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
110
  if pattern.fullmatch(string):
111
  return True
112
  else:
113
  return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
 
 
 
115
 
 
 
 
116
 
117
+
118
+
119
+
120
+ def to_html(chat_history):
121
+ chat_html = ""
122
+ for item in chat_history:
123
+ if item['role'] == 'user':
124
+ chat_html += f"""
125
+ <div style="margin-bottom: 20px;">
126
+ <div style="text-align: right; margin-right: 20px;">
127
+ <span style="background-color: #4CAF50; color: black; padding: 10px; border-radius: 10px; display: inline-block; max-width: 80%; word-wrap: break-word;">
128
+ {item['content']}
129
+ </span>
130
+ </div>
131
+ </div>
132
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  else:
134
+ chat_html += f"""
135
+ <div style="margin-bottom: 20px;">
136
+ <div style="text-align: left; margin-left: 20px;">
137
+ <span style="background-color: white; color: black; padding: 10px; border-radius: 10px; display: inline-block; max-width: 80%; word-wrap: break-word;">
138
+ {item['content']}
139
+ </span>
140
+ </div>
141
+ </div>
142
+ """
143
+ output_html = f"""
144
+ <div style="height: 400px; overflow-y: scroll; padding: 10px;">
145
+ {chat_html}
146
+ </div>
147
+ """
148
+ return output_html
149
+
150
+ def extrac(text):
151
+ text = re.sub("<[^>]*>","",text)
152
+ result_list = re.split(r'\n', text)
153
+ final_list = []
154
+ for i in result_list:
155
+ if is_english(i):
156
+ i = romajitable.to_kana(i).katakana
157
+ i = i.replace('\n','').replace(' ','')
158
+ #Current length of single sentence: 20
159
+ if len(i)>1:
160
+ if len(i) > 20:
161
+ try:
162
+ cur_list = re.split(r'。|!', i)
163
+ for i in cur_list:
164
+ if len(i)>1:
165
+ final_list.append(i+'。')
166
+ except:
167
+ pass
168
+ else:
169
+ final_list.append(i)
170
+ final_list = [x for x in final_list if x != '']
171
+ print(final_list)
172
+ return final_list
173
+
174
+ def to_numpy(tensor: torch.Tensor):
175
+ return tensor.detach().cpu().numpy() if tensor.requires_grad \
176
+ else tensor.detach().numpy()
177
+
178
+ def chatgpt(text):
179
+ messages = []
180
+ try:
181
+ with open('log.pickle', 'rb') as f:
182
+ messages = pickle.load(f)
183
+ messages.append({"role": "user", "content": text},)
184
+ chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
185
+ reply = chat.choices[0].message.content
186
+ messages.append({"role": "assistant", "content": reply})
187
+ print(messages[-1])
188
+ if len(messages) == 12:
189
+ messages[6:10] = messages[8:]
190
+ del messages[-2:]
191
+ with open('log.pickle', 'wb') as f:
192
+ messages2 = []
193
+ pickle.dump(messages2, f)
194
+ return reply,messages
195
+ except:
196
+ messages.append({"role": "user", "content": text},)
197
+ chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
198
+ reply = chat.choices[0].message.content
199
+ messages.append({"role": "assistant", "content": reply})
200
+ print(messages[-1])
201
+ if len(messages) == 12:
202
+ messages[6:10] = messages[8:]
203
+ del messages[-2:]
204
+ with open('log.pickle', 'wb') as f:
205
+ pickle.dump(messages, f)
206
+ return reply,messages
207
+
208
+ def get_symbols_from_json(path):
209
+ assert os.path.isfile(path)
210
+ with open(path, 'r') as f:
211
+ data = json.load(f)
212
+ return data['symbols']
213
+
214
+ def sle(language,text):
215
+ text = text.replace('\n', ' ').replace('\r', '').replace(" ", "")
216
+
217
+
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+
273
+
274
+
275
+
276
+
277
+
278
+
279
+
280
+
281
+
282
+
283
+
284
+
285
+
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
+
295
+
296
+
297
+
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+
319
+
320
+
321
  if language == "中文":
322
  tts_input1 = "[ZH]" + text + "[ZH]"
323
  return tts_input1
324
  elif language == "自动":
325
+ tts_input1 = f"[JA]{text}[JA]" if is_japanese(text) else f"[ZH]{text}[ZH]"
326
  return tts_input1
327
  elif language == "日文":
328
  tts_input1 = "[JA]" + text + "[JA]"
329
  return tts_input1
 
 
 
330
  elif language == "手动":
331
  return text
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+
346
+
347
+
348
+
349
+
350
+
351
+
352
+
353
+
354
+
355
+
356
+
357
+
358
+
359
+
360
+
361
+
362
+
363
+
364
+
365
+ def get_text(text,hps_ms):
366
+ text_norm = text_to_sequence(text,hps_ms.data.text_cleaners)
367
+ if hps_ms.data.add_blank:
368
+ text_norm = commons.intersperse(text_norm, 0)
369
+ text_norm = torch.LongTensor(text_norm)
370
+ return text_norm
371
+
372
+ def create_tts_fn(net_g,hps,speaker_id):
373
+ speaker_id = int(speaker_id)
374
+ def tts_fn(is_gpt,api_key,is_audio,audiopath,repeat_time,text, language, extract, n_scale= 0.667,n_scale_w = 0.8, l_scale = 1 ):
375
+ repeat_ime = int(repeat_time)
376
+ if is_gpt:
377
+ openai.api_key = api_key
378
+ text,messages = chatgpt(text)
379
+ htm = to_html(messages)
380
+ else:
381
+ messages = []
382
+ messages.append({"role": "assistant", "content": text},)
383
+ htm = to_html(messages)
384
+ if not extract:
385
+
386
+
387
+
388
+
389
  t1 = time.time()
390
+ stn_tst = get_text(sle(language,text),hps)
391
  with torch.no_grad():
392
+ x_tst = stn_tst.unsqueeze(0).to(dev)
393
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(dev)
394
+ sid = torch.LongTensor([speaker_id]).to(dev)
395
+ audio = 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()
396
  t2 = time.time()
397
  spending_time = "推理时间为:"+str(t2-t1)+"s"
398
  print(spending_time)
399
+ file_path = "subtitles.srt"
400
+ try:
401
+ write(audiopath + '.wav',22050,audio)
402
+ if is_audio:
403
+ for i in range(repeat_time):
404
+ cmd = 'ffmpeg -y -i ' + audiopath + '.wav' + ' -ar 44100 '+ audiopath.replace('temp','temp'+str(i))
405
+ os.system(cmd)
406
+ except:
407
+ pass
408
+ return (hps.data.sampling_rate, audio),file_path,htm
409
+ else:
410
+ a = ['【','[','(','(']
411
+ b = ['】',']',')',')']
412
+ for i in a:
413
+ text = text.replace(i,'<')
414
+ for i in b:
415
+ text = text.replace(i,'>')
416
+ final_list = extrac(text.replace('“','').replace('”',''))
417
+ audio_fin = []
418
+ c = 0
419
+ t = datetime.timedelta(seconds=0)
420
+ for sentence in final_list:
421
+ try:
422
+ f1 = open("subtitles.srt",'w',encoding='utf-8')
423
+ c +=1
424
+ stn_tst = get_text(sle(language,sentence),hps)
425
+ with torch.no_grad():
426
+ x_tst = stn_tst.unsqueeze(0).to(dev)
427
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(dev)
428
+ sid = torch.LongTensor([speaker_id]).to(dev)
429
+ t1 = time.time()
430
+ audio = 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()
431
+ t2 = time.time()
432
+ spending_time = "第"+str(c)+"句的推理时间为:"+str(t2-t1)+"s"
433
+ print(spending_time)
434
+ time_start = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
435
+ last_time = datetime.timedelta(seconds=len(audio)/float(22050))
436
+ t+=last_time
437
+ time_end = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
438
+ print(time_end)
439
+ f1.write(str(c-1)+'\n'+time_start+' --> '+time_end+'\n'+sentence+'\n\n')
440
+ audio_fin.append(audio)
441
+ except:
442
+ pass
443
+ try:
444
+ write(audiopath + '.wav',22050,np.concatenate(audio_fin))
445
+ if is_audio:
446
+ for i in range(repeat_time):
447
+ cmd = 'ffmpeg -y -i ' + audiopath + '.wav' + ' -ar 44100 '+ audiopath.replace('temp','temp'+str(i))
448
+ os.system(cmd)
449
+
450
+ except:
451
+ pass
452
+
453
+ file_path = "subtitles.srt"
454
+ return (hps.data.sampling_rate, np.concatenate(audio_fin)),file_path,htm
455
+ return tts_fn
456
+
457
+ if __name__ == '__main__':
458
+ hps = utils.get_hparams_from_file('checkpoints/tmp/config.json')
459
+ dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
460
+ models = []
461
+ schools = ["Nijigasaki High School","Seisho Music Academy","Rinmeikan Girls School","Frontier School of Arts","Siegfeld Institute of Music"]
462
+ lan = ["中文","日文","自动","手动"]
463
+ with open("checkpoints/info.json", "r", encoding="utf-8") as f:
464
+ models_info = json.load(f)
465
+ for i in models_info:
466
+ school = models_info[i]
467
+ speakers = school["speakers"]
468
+ phone_dict = {
469
+ symbol: i for i, symbol in enumerate(symbols)
470
+ }
471
+ checkpoint = models_info[i]["checkpoint"]
472
+ net_g = SynthesizerTrn(
473
+ len(symbols),
474
+ hps.data.filter_length // 2 + 1,
475
+ hps.train.segment_size // hps.data.hop_length,
476
+ n_speakers=hps.data.n_speakers,
477
+ **hps.model).to(dev)
478
+ _ = net_g.eval()
479
+ _ = utils.load_checkpoint(checkpoint, net_g)
480
+ content = []
481
+ for j in speakers:
482
+ sid = int(speakers[j]['sid'])
483
+ title = school
484
+ example = speakers[j]['speech']
485
+ name = speakers[j]["name"]
486
+ content.append((sid, name, title, example, create_tts_fn(net_g,hps,sid)))
487
+ models.append(content)
488
+
489
+ with gr.Blocks() as app:
490
+ with gr.Accordion(label="Note", open=True):
491
+ gr.Markdown(
492
+ "# <center>Seisho-Nijigasaki vits-models with chatgpt support\n"
493
+ "# <center>少歌&&虹团vits\n"
494
+ "## <center> Please do not generate content that could infringe upon the rights or cause harm to individuals or organizations.\n"
495
+ "## <center> 四个模型包含了少歌及虹团的大部分角色,第二个正在训练的模型加入了梁芷柔和墨小菊,目前已可以进行质量较高的中文合成。数据集版权归官方所有,严禁商用及恶意使用\n"
496
+ "## <center> 请不要生成会对个人以及企划造成侵害,带有侮辱性的言论,自觉遵守相关法律 >>> http://www.cac.gov.cn/2023-04/11/c_1682854275475410.htm \n"
497
+ "## <center> 效果不佳时可将噪音和噪音偏差调为0.自带chatgpt支持,长句分割支持,srt字幕生成,可修改音频生成路径至live2d语音路径,建议本地使用。\n"
498
+
499
+ )
500
+ with gr.Tabs():
501
+ for i in schools:
502
+ with gr.TabItem(i):
503
+ for (sid, name, title, example, tts_fn) in models[schools.index(i)]:
504
+ with gr.TabItem(name):
505
+ with gr.Column():
506
+ with gr.Row():
507
+ with gr.Row():
508
+ gr.Markdown(
509
+ '<div align="center">'
510
+ f'<img style="width:auto;height:400px;" src="file/image/{name}.png">'
511
+ '</div>'
512
+ )
513
+ output_UI = gr.outputs.HTML()
514
+ with gr.Row():
515
+ with gr.Column(scale=0.85):
516
+ input1 = gr.TextArea(label="Text", value=example,lines = 1)
517
+ with gr.Column(scale=0.15, min_width=0):
518
+ btnVC = gr.Button("Send")
519
+ output1 = gr.Audio(label="采样率22050")
520
+ with gr.Accordion(label="Setting(TTS)", open=False):
521
+ input2 = gr.Dropdown(label="Language", choices=lan, value="自动", interactive=True)
522
+ input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.6)
523
+ input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.668)
524
+ input6 = gr.Slider(minimum=0.1, maximum=10, label="duration", value=1)
525
+ with gr.Accordion(label="Advanced Setting(GPT3.5接口+长句子合成,建议克隆本仓库后运行main.py)", open=False):
526
+ input3 = gr.Checkbox(value=False, label="长句切割(小说合成)")
527
+ output2 = gr.outputs.File(label="字幕文件:subtitles.srt")
528
+ api_input1 = gr.Checkbox(value=False, label="接入chatgpt")
529
+ api_input2 = gr.TextArea(label="api-key",lines=1,value = '见 https://openai.com/blog/openai-api')
530
+ audio_input1 = gr.Checkbox(value=False, label="修改音频路径(live2d)")
531
+ audio_input2 = gr.TextArea(label="音频路径",lines=1,value = '#参考 D:/app_develop/live2d_whole/2010002/sounds/temp.wav')
532
+ audio_input3 = gr.Dropdown(label="重复生成次数", choices=list(range(101)), value='0', interactive=True)
533
+ btnVC.click(tts_fn, inputs=[api_input1,api_input2,audio_input1,audio_input2,audio_input3,input1,input2,input3,input4,input5,input6], outputs=[output1,output2,output_UI])
534
+
535
+ app.launch()