Mahiruoshi commited on
Commit
f222b7d
1 Parent(s): 500b816

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +336 -236
app.py CHANGED
@@ -2,7 +2,7 @@ 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 json
6
  import re
7
  import numpy as np
8
  import IPython.display as ipd
@@ -16,97 +16,251 @@ import gradio as gr
16
  import time
17
  import datetime
18
  import os
19
- import pickle
20
- import openai
21
- from scipy.io.wavfile import write
22
- def is_japanese(string):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  for ch in string:
24
  if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
25
  return True
26
  return False
27
-
28
- def is_english(string):
29
  import re
30
  pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
31
  if pattern.fullmatch(string):
32
  return True
33
  else:
34
  return False
 
 
 
 
 
35
 
36
- def extrac(text):
37
- text = re.sub("<[^>]*>","",text)
38
- result_list = re.split(r'\n', text)
39
- final_list = []
40
- for i in result_list:
41
- if is_english(i):
42
- i = romajitable.to_kana(i).katakana
43
- i = i.replace('\n','').replace(' ','')
44
- #Current length of single sentence: 20
45
- '''
46
- if len(i)>1:
47
- if len(i) > 20:
48
- try:
49
- cur_list = re.split(r'。|!', i)
50
- for i in cur_list:
51
- if len(i)>1:
52
- final_list.append(i+'。')
53
- except:
54
- pass
55
- else:
56
- final_list.append(i)
57
- '''
58
- final_list.append(i)
59
- final_list = [x for x in final_list if x != '']
60
- print(final_list)
61
- return final_list
62
 
63
- def to_numpy(tensor: torch.Tensor):
64
- return tensor.detach().cpu().numpy() if tensor.requires_grad \
65
- else tensor.detach().numpy()
66
 
67
- def chatgpt(text):
68
- messages = []
69
- try:
70
- if text != 'exist':
71
- with open('log.pickle', 'rb') as f:
72
- messages = pickle.load(f)
73
- messages.append({"role": "user", "content": text},)
74
- chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
75
- reply = chat.choices[0].message.content
76
- messages.append({"role": "assistant", "content": reply})
77
- print(messages[-1])
78
- if len(messages) == 12:
79
- messages[6:10] = messages[8:]
80
- del messages[-2:]
81
- with open('log.pickle', 'wb') as f:
82
- pickle.dump(messages, f)
83
- return reply
84
- except:
85
- messages.append({"role": "user", "content": text},)
86
- chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
87
- reply = chat.choices[0].message.content
88
- messages.append({"role": "assistant", "content": reply})
89
- print(messages[-1])
90
- if len(messages) == 12:
91
- messages[6:10] = messages[8:]
92
- del messages[-2:]
93
- with open('log.pickle', 'wb') as f:
94
- pickle.dump(messages, f)
95
- return reply
96
 
97
- def get_symbols_from_json(path):
98
- assert os.path.isfile(path)
99
- with open(path, 'r') as f:
100
- data = json.load(f)
101
- return data['symbols']
 
 
 
 
 
 
102
 
103
- def sle(language,text):
104
- text = text.replace('\n', '').replace('\r', '').replace(" ", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  if language == "中文":
106
  tts_input1 = "[ZH]" + text + "[ZH]"
107
  return tts_input1
108
  elif language == "自动":
109
- tts_input1 = f"[JA]{text}[JA]" if is_japanese(text) else f"[ZH]{text}[ZH]"
110
  return tts_input1
111
  elif language == "日文":
112
  tts_input1 = "[JA]" + text + "[JA]"
@@ -116,173 +270,119 @@ def sle(language,text):
116
  return tts_input1
117
  elif language == "手动":
118
  return text
119
- def get_text(text,hps_ms):
120
- text_norm = text_to_sequence(text,hps_ms.data.text_cleaners)
121
- if hps_ms.data.add_blank:
122
- text_norm = commons.intersperse(text_norm, 0)
123
- text_norm = torch.LongTensor(text_norm)
124
- return text_norm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- def create_tts_fn(net_g,hps,speaker_id):
127
- speaker_id = int(speaker_id)
128
- 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 ):
129
- repeat_ime = int(repeat_time)
130
- if is_gpt:
131
- openai.api_key = api_key
132
- text,messages = chatgpt(text)
133
- htm = to_html(messages)
134
- else:
135
- messages = []
136
- messages.append({"role": "assistant", "content": text},)
137
- htm = to_html(messages)
138
- if not extract:
 
 
 
 
 
 
 
 
 
 
 
139
  t1 = time.time()
140
- stn_tst = get_text(sle(language,text),hps)
141
  with torch.no_grad():
142
- x_tst = stn_tst.unsqueeze(0).to(dev)
143
- x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(dev)
144
- sid = torch.LongTensor([speaker_id]).to(dev)
145
- 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()
146
  t2 = time.time()
147
  spending_time = "推理时间为:"+str(t2-t1)+"s"
148
  print(spending_time)
149
- file_path = "subtitles.srt"
150
- try:
151
- write(audiopath + '.wav',22050,audio)
152
- if is_audio:
153
- for i in range(repeat_time):
154
- cmd = 'ffmpeg -y -i ' + audiopath + '.wav' + ' -ar 44100 '+ audiopath.replace('temp','temp'+str(i))
155
- os.system(cmd)
156
- except:
157
- pass
158
- return (hps.data.sampling_rate, audio),file_path,htm
159
- else:
160
- a = ['【','[','(','(']
161
- b = ['】',']',')',')']
162
- for i in a:
163
- text = text.replace(i,'<')
164
- for i in b:
165
- text = text.replace(i,'>')
166
- final_list = extrac(text.replace('���','').replace('”',''))
167
- audio_fin = []
168
- c = 0
169
- t = datetime.timedelta(seconds=0)
170
- for sentence in final_list:
171
- try:
172
- f1 = open("subtitles.srt",'w',encoding='utf-8')
173
- c +=1
174
- stn_tst = get_text(sle(language,sentence),hps)
175
- with torch.no_grad():
176
- x_tst = stn_tst.unsqueeze(0).to(dev)
177
- x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(dev)
178
- sid = torch.LongTensor([speaker_id]).to(dev)
179
- t1 = time.time()
180
- 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()
181
- t2 = time.time()
182
- spending_time = "第"+str(c)+"句的推理时间为:"+str(t2-t1)+"s"
183
- print(spending_time)
184
- time_start = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
185
- last_time = datetime.timedelta(seconds=len(audio)/float(22050))
186
- t+=last_time
187
- time_end = str(t).split(".")[0] + "," + str(t.microseconds)[:3]
188
- print(time_end)
189
- f1.write(str(c-1)+'\n'+time_start+' --> '+time_end+'\n'+sentence+'\n\n')
190
- audio_fin.append(audio)
191
- except:
192
- pass
193
- try:
194
- write(audiopath + '.wav',22050,np.concatenate(audio_fin))
195
- if is_audio:
196
- for i in range(repeat_time):
197
- cmd = 'ffmpeg -y -i ' + audiopath + '.wav' + ' -ar 44100 '+ audiopath.replace('temp','temp'+str(i))
198
- os.system(cmd)
199
-
200
- except:
201
- pass
202
-
203
- file_path = "subtitles.srt"
204
- return (hps.data.sampling_rate, np.concatenate(audio_fin)),file_path,htm
205
- return tts_fn
206
 
207
- if __name__ == '__main__':
208
- hps = utils.get_hparams_from_file('checkpoints/tmp/config.json')
209
- dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
210
- models = []
211
- schools = ["Seisho-Nijigasaki","Seisho-betterchinese","Nijigasaki","Nijigasaki-biaobei"]
212
- lan = ["中文","日文","自动","手动"]
213
- with open("checkpoints/info.json", "r", encoding="utf-8") as f:
214
- models_info = json.load(f)
215
- for i in models_info:
216
- checkpoint = models_info[i]["checkpoint"]
217
- phone_dict = {
218
- symbol: i for i, symbol in enumerate(symbols)
219
- }
220
- net_g = SynthesizerTrn(
221
- len(symbols),
222
- hps.data.filter_length // 2 + 1,
223
- hps.train.segment_size // hps.data.hop_length,
224
- n_speakers=hps.data.n_speakers,
225
- **hps.model).to(dev)
226
- _ = net_g.eval()
227
- _ = utils.load_checkpoint(checkpoint, net_g)
228
- school = models_info[i]
229
- speakers = school["speakers"]
230
- phone_dict = {
231
- symbol: i for i, symbol in enumerate(symbols)
232
- }
233
- content = []
234
- for j in speakers:
235
- sid = int(speakers[j]['sid'])
236
- title = school
237
- example = speakers[j]['speech']
238
- name = speakers[j]["name"]
239
- content.append((sid, name, title, example, create_tts_fn(net_g,hps,sid)))
240
- models.append(content)
241
-
242
- with gr.Blocks() as app:
243
- with gr.Accordion(label="Note", open=True):
244
- gr.Markdown(
245
- "# <center>Seisho-Nijigasaki vits-models with chatgpt support\n"
246
- "# <center>少歌&&虹团vits\n"
247
- "## <center> Please do not generate content that could infringe upon the rights or cause harm to individuals or organizations.\n"
248
- "## <center> 四个模型包含了少歌及虹团的大部分角色,第二个正在训练的模型加入了梁芷柔和墨小菊,目前已可以进行质量较高的中文合成。数据集版权归官方所有,严禁商用及恶意使用\n"
249
- "## <center> 请不要生成会对个人以及企划造成侵害,带有侮辱性的言论,自觉遵守相关法律 >>> http://www.cac.gov.cn/2023-04/11/c_1682854275475410.htm \n"
250
- "## <center> 效果不佳时可将噪音和噪音偏差调为0.自带chatgpt支持,长句分割支持,srt字幕生成,可修改音频生成路径至live2d语音路径,建议本地使用。\n"
251
-
252
- )
253
- with gr.Tabs():
254
- for i in schools:
255
- with gr.TabItem(i):
256
- for (sid, name, title, example, tts_fn) in models[schools.index(i)]:
257
- with gr.TabItem(name):
258
- with gr.Column():
259
- with gr.Row():
260
- with gr.Row():
261
- gr.Markdown(
262
- '<div align="center">'
263
- f'<img style="width:auto;height:400px;" src="file/image/{name}.png">'
264
- '</div>'
265
- )
266
- output_UI = gr.outputs.HTML()
267
- with gr.Row():
268
- with gr.Column(scale=0.85):
269
- input1 = gr.TextArea(label="Text", value=example,lines = 1)
270
- with gr.Column(scale=0.15, min_width=0):
271
- btnVC = gr.Button("Send")
272
- output1 = gr.Audio(label="采样率22050")
273
- with gr.Accordion(label="Setting(TTS)", open=False):
274
- input2 = gr.Dropdown(label="Language", choices=lan, value="自动", interactive=True)
275
- input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.6)
276
- input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.668)
277
- input6 = gr.Slider(minimum=0.1, maximum=10, label="duration", value=1)
278
- with gr.Accordion(label="Advanced Setting(GPT3.5接口+长句子合成,建议克隆本仓库后运行main.py)", open=False):
279
- input3 = gr.Checkbox(value=False, label="长句切割(小说合成)")
280
- output2 = gr.outputs.File(label="字幕文件:subtitles.srt")
281
- api_input1 = gr.Checkbox(value=False, label="接入chatgpt")
282
- api_input2 = gr.TextArea(label="api-key",lines=1,value = '见 https://openai.com/blog/openai-api')
283
- audio_input1 = gr.Checkbox(value=False, label="修改音频路径(live2d)")
284
- audio_input2 = gr.TextArea(label="音频路径",lines=1,value = '#参考 D:/app_develop/live2d_whole/2010002/sounds/temp.wav')
285
- audio_input3 = gr.Dropdown(label="重复生成次数", choices=list(range(101)), value='0', interactive=True)
286
- 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])
287
-
288
- app.launch()
 
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
 
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 = ["c1","c2","高咲侑","歩夢","かすみ","しずく","果林","愛","彼方","せつ菜","璃奈","栞子","エマ","ランジュ","ミア","華恋","まひる","なな","クロディーヌ","ひかり",'純那',"香子","真矢","双葉","ミチル","メイファン","やちよ","晶","いちえ","ゆゆ子","塁","珠緒","あるる","ララフィン","美空","静羽","あるる"]
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> Lovelive虹团中日双语VITS\n"
33
+ "### <center> 请不要生成会对个人以及企划造成侵害的内容\n"
34
+ "<div align='center'>目前有标贝普通话版,去标贝版,少歌模型还是大饼状态</div>"
35
+ '<div align="center"><a>参数说明:由于爱抖露们过于有感情,合成日语时建议将噪声比例调节至0.2-0.3区间,噪声偏差对应着每个字之间的间隔,对普通话影响较大,duration代表整体语速</div>'
36
+ '<div align="center"><a>合成前请先选择模型,否则第一次合成不一定成功。长段落/小说合成建议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.267)
48
+ input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.7)
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="建议colab或本地克隆后运行本仓库", 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 == "c1":
176
+ spk = 18
177
+ return spk
178
+
179
+ elif speaker == "c2":
180
+ spk = 19
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]"
 
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()