kevinwang676 commited on
Commit
9fa8ebf
·
verified ·
1 Parent(s): fdb9f5b

Create inference_webui.py

Browse files
Files changed (1) hide show
  1. GPT_SoVITS/inference_webui.py +762 -0
GPT_SoVITS/inference_webui.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ 按中英混合识别
3
+ 按日英混合识别
4
+ 多语种启动切分识别语种
5
+ 全部按中文识别
6
+ 全部按英文识别
7
+ 全部按日文识别
8
+ '''
9
+ import logging
10
+ import traceback
11
+
12
+ logging.getLogger("markdown_it").setLevel(logging.ERROR)
13
+ logging.getLogger("urllib3").setLevel(logging.ERROR)
14
+ logging.getLogger("httpcore").setLevel(logging.ERROR)
15
+ logging.getLogger("httpx").setLevel(logging.ERROR)
16
+ logging.getLogger("asyncio").setLevel(logging.ERROR)
17
+ logging.getLogger("charset_normalizer").setLevel(logging.ERROR)
18
+ logging.getLogger("torchaudio._extension").setLevel(logging.ERROR)
19
+ logging.getLogger("multipart.multipart").setLevel(logging.ERROR)
20
+ import LangSegment, os, re, sys, json
21
+ import pdb
22
+ import torch
23
+
24
+ version=os.environ.get("version","v2")
25
+ pretrained_sovits_name=["GPT_SoVITS/pretrained_models/gsv-v2final-pretrained/s2G2333k.pth", "GPT_SoVITS/pretrained_models/s2G488k.pth"]
26
+ pretrained_gpt_name=["GPT_SoVITS/pretrained_models/gsv-v2final-pretrained/s1bert25hz-5kh-longer-epoch=12-step=369668.ckpt", "GPT_SoVITS/pretrained_models/s1bert25hz-2kh-longer-epoch=68e-step=50232.ckpt"]
27
+
28
+ _ =[[],[]]
29
+ for i in range(2):
30
+ if os.path.exists(pretrained_gpt_name[i]):
31
+ _[0].append(pretrained_gpt_name[i])
32
+ if os.path.exists(pretrained_sovits_name[i]):
33
+ _[-1].append(pretrained_sovits_name[i])
34
+ pretrained_gpt_name,pretrained_sovits_name = _
35
+
36
+
37
+
38
+ if os.path.exists(f"./weight.json"):
39
+ pass
40
+ else:
41
+ with open(f"./weight.json", 'w', encoding="utf-8") as file:json.dump({'GPT':{},'SoVITS':{}},file)
42
+
43
+ with open(f"./weight.json", 'r', encoding="utf-8") as file:
44
+ weight_data = file.read()
45
+ weight_data=json.loads(weight_data)
46
+ gpt_path = os.environ.get(
47
+ "gpt_path", weight_data.get('GPT',{}).get(version,pretrained_gpt_name))
48
+ sovits_path = os.environ.get(
49
+ "sovits_path", weight_data.get('SoVITS',{}).get(version,pretrained_sovits_name))
50
+ if isinstance(gpt_path,list):
51
+ gpt_path = gpt_path[0]
52
+ if isinstance(sovits_path,list):
53
+ sovits_path = sovits_path[0]
54
+
55
+ # gpt_path = os.environ.get(
56
+ # "gpt_path", pretrained_gpt_name
57
+ # )
58
+ # sovits_path = os.environ.get("sovits_path", pretrained_sovits_name)
59
+ cnhubert_base_path = os.environ.get(
60
+ "cnhubert_base_path", "GPT_SoVITS/pretrained_models/chinese-hubert-base"
61
+ )
62
+ bert_path = os.environ.get(
63
+ "bert_path", "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large"
64
+ )
65
+ infer_ttswebui = os.environ.get("infer_ttswebui", 9872)
66
+ infer_ttswebui = int(infer_ttswebui)
67
+ is_share = os.environ.get("is_share", "False")
68
+ is_share = eval(is_share)
69
+ if "_CUDA_VISIBLE_DEVICES" in os.environ:
70
+ os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
71
+ is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
72
+ punctuation = set(['!', '?', '…', ',', '.', '-'," "])
73
+ import gradio as gr
74
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
75
+ import numpy as np
76
+ import librosa
77
+ from feature_extractor import cnhubert
78
+
79
+ cnhubert.cnhubert_base_path = cnhubert_base_path
80
+
81
+ from module.models import SynthesizerTrn
82
+ from AR.models.t2s_lightning_module import Text2SemanticLightningModule
83
+ from text import cleaned_text_to_sequence
84
+ from text.cleaner import clean_text
85
+ from time import time as ttime
86
+ from module.mel_processing import spectrogram_torch
87
+ from tools.my_utils import load_audio
88
+ from tools.i18n.i18n import I18nAuto, scan_language_list
89
+
90
+ language=os.environ.get("language","Auto")
91
+ language=sys.argv[-1] if sys.argv[-1] in scan_language_list() else language
92
+ i18n = I18nAuto(language=language)
93
+
94
+ # os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 确保直接启动推理UI时也能够设置。
95
+
96
+ if torch.cuda.is_available():
97
+ device = "cuda"
98
+ else:
99
+ device = "cpu"
100
+
101
+ dict_language_v1 = {
102
+ i18n("中文"): "all_zh",#全部按中文识别
103
+ i18n("英文"): "en",#全部按英文识别#######不变
104
+ i18n("日文"): "all_ja",#全部按日文识别
105
+ i18n("中英混合"): "zh",#按中英混合识别####不变
106
+ i18n("日英混合"): "ja",#按日英混合识别####不变
107
+ i18n("多语种混合"): "auto",#多语种启动切分识别语种
108
+ }
109
+ dict_language_v2 = {
110
+ i18n("中文"): "all_zh",#全部按中文识别
111
+ i18n("英文"): "en",#全部按英文识别#######不变
112
+ i18n("日文"): "all_ja",#全部按日文识别
113
+ i18n("粤语"): "all_yue",#全部按中文识别
114
+ i18n("韩文"): "all_ko",#全部按韩文识别
115
+ i18n("中英混合"): "zh",#按中英混合识别####不变
116
+ i18n("日英混合"): "ja",#按日英混合识别####不变
117
+ i18n("粤英混合"): "yue",#按粤英混合识别####不变
118
+ i18n("韩英混合"): "ko",#按韩英混合识别####不变
119
+ i18n("多语种混合"): "auto",#多语种启动切分识别语种
120
+ i18n("多语种混合(粤语)"): "auto_yue",#多语种启动切分识别语种
121
+ }
122
+ dict_language = dict_language_v1 if version =='v1' else dict_language_v2
123
+
124
+ tokenizer = AutoTokenizer.from_pretrained(bert_path)
125
+ bert_model = AutoModelForMaskedLM.from_pretrained(bert_path)
126
+ if is_half == True:
127
+ bert_model = bert_model.half().to(device)
128
+ else:
129
+ bert_model = bert_model.to(device)
130
+
131
+
132
+ def get_bert_feature(text, word2ph):
133
+ with torch.no_grad():
134
+ inputs = tokenizer(text, return_tensors="pt")
135
+ for i in inputs:
136
+ inputs[i] = inputs[i].to(device)
137
+ res = bert_model(**inputs, output_hidden_states=True)
138
+ res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
139
+ assert len(word2ph) == len(text)
140
+ phone_level_feature = []
141
+ for i in range(len(word2ph)):
142
+ repeat_feature = res[i].repeat(word2ph[i], 1)
143
+ phone_level_feature.append(repeat_feature)
144
+ phone_level_feature = torch.cat(phone_level_feature, dim=0)
145
+ return phone_level_feature.T
146
+
147
+
148
+ class DictToAttrRecursive(dict):
149
+ def __init__(self, input_dict):
150
+ super().__init__(input_dict)
151
+ for key, value in input_dict.items():
152
+ if isinstance(value, dict):
153
+ value = DictToAttrRecursive(value)
154
+ self[key] = value
155
+ setattr(self, key, value)
156
+
157
+ def __getattr__(self, item):
158
+ try:
159
+ return self[item]
160
+ except KeyError:
161
+ raise AttributeError(f"Attribute {item} not found")
162
+
163
+ def __setattr__(self, key, value):
164
+ if isinstance(value, dict):
165
+ value = DictToAttrRecursive(value)
166
+ super(DictToAttrRecursive, self).__setitem__(key, value)
167
+ super().__setattr__(key, value)
168
+
169
+ def __delattr__(self, item):
170
+ try:
171
+ del self[item]
172
+ except KeyError:
173
+ raise AttributeError(f"Attribute {item} not found")
174
+
175
+
176
+ ssl_model = cnhubert.get_model()
177
+ if is_half == True:
178
+ ssl_model = ssl_model.half().to(device)
179
+ else:
180
+ ssl_model = ssl_model.to(device)
181
+
182
+
183
+ def change_sovits_weights(sovits_path,prompt_language=None,text_language=None):
184
+ global vq_model, hps, version, dict_language
185
+ dict_s2 = torch.load(sovits_path, map_location="cpu")
186
+ hps = dict_s2["config"]
187
+ hps = DictToAttrRecursive(hps)
188
+ hps.model.semantic_frame_rate = "25hz"
189
+ if dict_s2['weight']['enc_p.text_embedding.weight'].shape[0] == 322:
190
+ hps.model.version = "v1"
191
+ else:
192
+ hps.model.version = "v2"
193
+ version = hps.model.version
194
+ # print("sovits版本:",hps.model.version)
195
+ vq_model = SynthesizerTrn(
196
+ hps.data.filter_length // 2 + 1,
197
+ hps.train.segment_size // hps.data.hop_length,
198
+ n_speakers=hps.data.n_speakers,
199
+ **hps.model
200
+ )
201
+ if ("pretrained" not in sovits_path):
202
+ del vq_model.enc_q
203
+ if is_half == True:
204
+ vq_model = vq_model.half().to(device)
205
+ else:
206
+ vq_model = vq_model.to(device)
207
+ vq_model.eval()
208
+ print(vq_model.load_state_dict(dict_s2["weight"], strict=False))
209
+ dict_language = dict_language_v1 if version =='v1' else dict_language_v2
210
+ with open("./weight.json")as f:
211
+ data=f.read()
212
+ data=json.loads(data)
213
+ data["SoVITS"][version]=sovits_path
214
+ with open("./weight.json","w")as f:f.write(json.dumps(data))
215
+ if prompt_language is not None and text_language is not None:
216
+ if prompt_language in list(dict_language.keys()):
217
+ prompt_text_update, prompt_language_update = {'__type__':'update'}, {'__type__':'update', 'value':prompt_language}
218
+ else:
219
+ prompt_text_update = {'__type__':'update', 'value':''}
220
+ prompt_language_update = {'__type__':'update', 'value':i18n("中文")}
221
+ if text_language in list(dict_language.keys()):
222
+ text_update, text_language_update = {'__type__':'update'}, {'__type__':'update', 'value':text_language}
223
+ else:
224
+ text_update = {'__type__':'update', 'value':''}
225
+ text_language_update = {'__type__':'update', 'value':i18n("中文")}
226
+ return {'__type__':'update', 'choices':list(dict_language.keys())}, {'__type__':'update', 'choices':list(dict_language.keys())}, prompt_text_update, prompt_language_update, text_update, text_language_update
227
+
228
+
229
+
230
+ change_sovits_weights(sovits_path)
231
+
232
+
233
+ def change_gpt_weights(gpt_path):
234
+ global hz, max_sec, t2s_model, config
235
+ hz = 50
236
+ dict_s1 = torch.load(gpt_path, map_location="cpu")
237
+ config = dict_s1["config"]
238
+ max_sec = config["data"]["max_sec"]
239
+ t2s_model = Text2SemanticLightningModule(config, "****", is_train=False)
240
+ t2s_model.load_state_dict(dict_s1["weight"])
241
+ if is_half == True:
242
+ t2s_model = t2s_model.half()
243
+ t2s_model = t2s_model.to(device)
244
+ t2s_model.eval()
245
+ total = sum([param.nelement() for param in t2s_model.parameters()])
246
+ print("Number of parameter: %.2fM" % (total / 1e6))
247
+ with open("./weight.json")as f:
248
+ data=f.read()
249
+ data=json.loads(data)
250
+ data["GPT"][version]=gpt_path
251
+ with open("./weight.json","w")as f:f.write(json.dumps(data))
252
+
253
+
254
+ change_gpt_weights(gpt_path)
255
+
256
+
257
+ def get_spepc(hps, filename):
258
+ audio = load_audio(filename, int(hps.data.sampling_rate))
259
+ audio = torch.FloatTensor(audio)
260
+ maxx=audio.abs().max()
261
+ if(maxx>1):audio/=min(2,maxx)
262
+ audio_norm = audio
263
+ audio_norm = audio_norm.unsqueeze(0)
264
+ spec = spectrogram_torch(
265
+ audio_norm,
266
+ hps.data.filter_length,
267
+ hps.data.sampling_rate,
268
+ hps.data.hop_length,
269
+ hps.data.win_length,
270
+ center=False,
271
+ )
272
+ return spec
273
+
274
+ def clean_text_inf(text, language, version):
275
+ phones, word2ph, norm_text = clean_text(text, language, version)
276
+ phones = cleaned_text_to_sequence(phones, version)
277
+ return phones, word2ph, norm_text
278
+
279
+ dtype=torch.float16 if is_half == True else torch.float32
280
+ def get_bert_inf(phones, word2ph, norm_text, language):
281
+ language=language.replace("all_","")
282
+ if language == "zh":
283
+ bert = get_bert_feature(norm_text, word2ph).to(device)#.to(dtype)
284
+ else:
285
+ bert = torch.zeros(
286
+ (1024, len(phones)),
287
+ dtype=torch.float16 if is_half == True else torch.float32,
288
+ ).to(device)
289
+
290
+ return bert
291
+
292
+
293
+ splits = {",", "。", "?", "!", ",", ".", "?", "!", "~", ":", ":", "—", "…", }
294
+
295
+
296
+ def get_first(text):
297
+ pattern = "[" + "".join(re.escape(sep) for sep in splits) + "]"
298
+ text = re.split(pattern, text)[0].strip()
299
+ return text
300
+
301
+ from text import chinese
302
+ def get_phones_and_bert(text,language,version):
303
+ if language in {"en", "all_zh", "all_ja", "all_ko", "all_yue"}:
304
+ language = language.replace("all_","")
305
+ if language == "en":
306
+ LangSegment.setfilters(["en"])
307
+ formattext = " ".join(tmp["text"] for tmp in LangSegment.getTexts(text))
308
+ else:
309
+ # 因无法区别中日韩文汉字,以用户输入为准
310
+ formattext = text
311
+ while " " in formattext:
312
+ formattext = formattext.replace(" ", " ")
313
+ if language == "zh":
314
+ if re.search(r'[A-Za-z]', formattext):
315
+ formattext = re.sub(r'[a-z]', lambda x: x.group(0).upper(), formattext)
316
+ formattext = chinese.mix_text_normalize(formattext)
317
+ return get_phones_and_bert(formattext,"zh",version)
318
+ else:
319
+ phones, word2ph, norm_text = clean_text_inf(formattext, language, version)
320
+ bert = get_bert_feature(norm_text, word2ph).to(device)
321
+ elif language == "yue" and re.search(r'[A-Za-z]', formattext):
322
+ formattext = re.sub(r'[a-z]', lambda x: x.group(0).upper(), formattext)
323
+ formattext = chinese.mix_text_normalize(formattext)
324
+ return get_phones_and_bert(formattext,"yue",version)
325
+ else:
326
+ phones, word2ph, norm_text = clean_text_inf(formattext, language, version)
327
+ bert = torch.zeros(
328
+ (1024, len(phones)),
329
+ dtype=torch.float16 if is_half == True else torch.float32,
330
+ ).to(device)
331
+ elif language in {"zh", "ja", "ko", "yue", "auto", "auto_yue"}:
332
+ textlist=[]
333
+ langlist=[]
334
+ LangSegment.setfilters(["zh","ja","en","ko"])
335
+ if language == "auto":
336
+ for tmp in LangSegment.getTexts(text):
337
+ langlist.append(tmp["lang"])
338
+ textlist.append(tmp["text"])
339
+ elif language == "auto_yue":
340
+ for tmp in LangSegment.getTexts(text):
341
+ if tmp["lang"] == "zh":
342
+ tmp["lang"] = "yue"
343
+ langlist.append(tmp["lang"])
344
+ textlist.append(tmp["text"])
345
+ else:
346
+ for tmp in LangSegment.getTexts(text):
347
+ if tmp["lang"] == "en":
348
+ langlist.append(tmp["lang"])
349
+ else:
350
+ # 因无法区别中日韩文汉字,以用户输入为准
351
+ langlist.append(language)
352
+ textlist.append(tmp["text"])
353
+ print(textlist)
354
+ print(langlist)
355
+ phones_list = []
356
+ bert_list = []
357
+ norm_text_list = []
358
+ for i in range(len(textlist)):
359
+ lang = langlist[i]
360
+ phones, word2ph, norm_text = clean_text_inf(textlist[i], lang, version)
361
+ bert = get_bert_inf(phones, word2ph, norm_text, lang)
362
+ phones_list.append(phones)
363
+ norm_text_list.append(norm_text)
364
+ bert_list.append(bert)
365
+ bert = torch.cat(bert_list, dim=1)
366
+ phones = sum(phones_list, [])
367
+ norm_text = ''.join(norm_text_list)
368
+
369
+ return phones,bert.to(dtype),norm_text
370
+
371
+
372
+ def merge_short_text_in_array(texts, threshold):
373
+ if (len(texts)) < 2:
374
+ return texts
375
+ result = []
376
+ text = ""
377
+ for ele in texts:
378
+ text += ele
379
+ if len(text) >= threshold:
380
+ result.append(text)
381
+ text = ""
382
+ if (len(text) > 0):
383
+ if len(result) == 0:
384
+ result.append(text)
385
+ else:
386
+ result[len(result) - 1] += text
387
+ return result
388
+
389
+ ##ref_wav_path+prompt_text+prompt_language+text(单个)+text_language+top_k+top_p+temperature
390
+ # cache_tokens={}#暂未实现清理机制
391
+ cache= {}
392
+ def get_tts_wav(ref_wav_path, prompt_text, prompt_language, text, text_language, how_to_cut=i18n("不切"), top_k=20, top_p=0.6, temperature=0.6, ref_free = False,speed=1,if_freeze=False,inp_refs=123):
393
+ global cache
394
+ if ref_wav_path:pass
395
+ else:gr.Warning(i18n('请上传参考音频'))
396
+ if text:pass
397
+ else:gr.Warning(i18n('请填入推理文本'))
398
+ t = []
399
+ if prompt_text is None or len(prompt_text) == 0:
400
+ ref_free = True
401
+ t0 = ttime()
402
+ prompt_language = dict_language[prompt_language]
403
+ text_language = dict_language[text_language]
404
+
405
+
406
+ if not ref_free:
407
+ prompt_text = prompt_text.strip("\n")
408
+ if (prompt_text[-1] not in splits): prompt_text += "。" if prompt_language != "en" else "."
409
+ print(i18n("实际输入的参考文本:"), prompt_text)
410
+ text = text.strip("\n")
411
+ if (text[0] not in splits and len(get_first(text)) < 4): text = "。" + text if text_language != "en" else "." + text
412
+
413
+ print(i18n("实际输入的目标文本:"), text)
414
+ zero_wav = np.zeros(
415
+ int(hps.data.sampling_rate * 0.3),
416
+ dtype=np.float16 if is_half == True else np.float32,
417
+ )
418
+ if not ref_free:
419
+ with torch.no_grad():
420
+ wav16k, sr = librosa.load(ref_wav_path, sr=16000)
421
+ if (wav16k.shape[0] > 160000 or wav16k.shape[0] < 48000):
422
+ gr.Warning(i18n("参考音频在3~10秒范围外,请更换!"))
423
+ raise OSError(i18n("参考音频在3~10秒范围外,请更换!"))
424
+ wav16k = torch.from_numpy(wav16k)
425
+ zero_wav_torch = torch.from_numpy(zero_wav)
426
+ if is_half == True:
427
+ wav16k = wav16k.half().to(device)
428
+ zero_wav_torch = zero_wav_torch.half().to(device)
429
+ else:
430
+ wav16k = wav16k.to(device)
431
+ zero_wav_torch = zero_wav_torch.to(device)
432
+ wav16k = torch.cat([wav16k, zero_wav_torch])
433
+ ssl_content = ssl_model.model(wav16k.unsqueeze(0))[
434
+ "last_hidden_state"
435
+ ].transpose(
436
+ 1, 2
437
+ ) # .float()
438
+ codes = vq_model.extract_latent(ssl_content)
439
+ prompt_semantic = codes[0, 0]
440
+ prompt = prompt_semantic.unsqueeze(0).to(device)
441
+
442
+ t1 = ttime()
443
+ t.append(t1-t0)
444
+
445
+ if (how_to_cut == i18n("凑四句一切")):
446
+ text = cut1(text)
447
+ elif (how_to_cut == i18n("凑50字一切")):
448
+ text = cut2(text)
449
+ elif (how_to_cut == i18n("按中文句号。切")):
450
+ text = cut3(text)
451
+ elif (how_to_cut == i18n("按英文句号.切")):
452
+ text = cut4(text)
453
+ elif (how_to_cut == i18n("按标点符号切")):
454
+ text = cut5(text)
455
+ while "\n\n" in text:
456
+ text = text.replace("\n\n", "\n")
457
+ print(i18n("实际输入的目标文本(切句后):"), text)
458
+ texts = text.split("\n")
459
+ texts = process_text(texts)
460
+ texts = merge_short_text_in_array(texts, 5)
461
+ audio_opt = []
462
+ if not ref_free:
463
+ phones1,bert1,norm_text1=get_phones_and_bert(prompt_text, prompt_language, version)
464
+
465
+ for i_text,text in enumerate(texts):
466
+ # 解决输入目标文本的空行导致报错的问题
467
+ if (len(text.strip()) == 0):
468
+ continue
469
+ if (text[-1] not in splits): text += "。" if text_language != "en" else "."
470
+ print(i18n("实际输入的目标文本(每句):"), text)
471
+ phones2,bert2,norm_text2=get_phones_and_bert(text, text_language, version)
472
+ print(i18n("前端处理后的文本(每句):"), norm_text2)
473
+ if not ref_free:
474
+ bert = torch.cat([bert1, bert2], 1)
475
+ all_phoneme_ids = torch.LongTensor(phones1+phones2).to(device).unsqueeze(0)
476
+ else:
477
+ bert = bert2
478
+ all_phoneme_ids = torch.LongTensor(phones2).to(device).unsqueeze(0)
479
+
480
+ bert = bert.to(device).unsqueeze(0)
481
+ all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)
482
+
483
+ t2 = ttime()
484
+ # cache_key="%s-%s-%s-%s-%s-%s-%s-%s"%(ref_wav_path,prompt_text,prompt_language,text,text_language,top_k,top_p,temperature)
485
+ # print(cache.keys(),if_freeze)
486
+ if(i_text in cache and if_freeze==True):pred_semantic=cache[i_text]
487
+ else:
488
+ with torch.no_grad():
489
+ pred_semantic, idx = t2s_model.model.infer_panel(
490
+ all_phoneme_ids,
491
+ all_phoneme_len,
492
+ None if ref_free else prompt,
493
+ bert,
494
+ # prompt_phone_len=ph_offset,
495
+ top_k=top_k,
496
+ top_p=top_p,
497
+ temperature=temperature,
498
+ early_stop_num=hz * max_sec,
499
+ )
500
+ pred_semantic = pred_semantic[:, -idx:].unsqueeze(0)
501
+ cache[i_text]=pred_semantic
502
+ t3 = ttime()
503
+ refers=[]
504
+ if(inp_refs):
505
+ for path in inp_refs:
506
+ try:
507
+ refer = get_spepc(hps, path.name).to(dtype).to(device)
508
+ refers.append(refer)
509
+ except:
510
+ traceback.print_exc()
511
+ if(len(refers)==0):refers = [get_spepc(hps, ref_wav_path).to(dtype).to(device)]
512
+ audio = (vq_model.decode(pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refers,speed=speed).detach().cpu().numpy()[0, 0])
513
+ max_audio=np.abs(audio).max()#简单防止16bit爆音
514
+ if max_audio>1:audio/=max_audio
515
+ audio_opt.append(audio)
516
+ audio_opt.append(zero_wav)
517
+ t4 = ttime()
518
+ t.extend([t2 - t1,t3 - t2, t4 - t3])
519
+ t1 = ttime()
520
+ print("%.3f\t%.3f\t%.3f\t%.3f" %
521
+ (t[0], sum(t[1::3]), sum(t[2::3]), sum(t[3::3]))
522
+ )
523
+ yield hps.data.sampling_rate, (np.concatenate(audio_opt, 0) * 32768).astype(
524
+ np.int16
525
+ )
526
+
527
+
528
+ def split(todo_text):
529
+ todo_text = todo_text.replace("……", "。").replace("——", ",")
530
+ if todo_text[-1] not in splits:
531
+ todo_text += "。"
532
+ i_split_head = i_split_tail = 0
533
+ len_text = len(todo_text)
534
+ todo_texts = []
535
+ while 1:
536
+ if i_split_head >= len_text:
537
+ break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
538
+ if todo_text[i_split_head] in splits:
539
+ i_split_head += 1
540
+ todo_texts.append(todo_text[i_split_tail:i_split_head])
541
+ i_split_tail = i_split_head
542
+ else:
543
+ i_split_head += 1
544
+ return todo_texts
545
+
546
+
547
+ def cut1(inp):
548
+ inp = inp.strip("\n")
549
+ inps = split(inp)
550
+ split_idx = list(range(0, len(inps), 4))
551
+ split_idx[-1] = None
552
+ if len(split_idx) > 1:
553
+ opts = []
554
+ for idx in range(len(split_idx) - 1):
555
+ opts.append("".join(inps[split_idx[idx]: split_idx[idx + 1]]))
556
+ else:
557
+ opts = [inp]
558
+ opts = [item for item in opts if not set(item).issubset(punctuation)]
559
+ return "\n".join(opts)
560
+
561
+
562
+ def cut2(inp):
563
+ inp = inp.strip("\n")
564
+ inps = split(inp)
565
+ if len(inps) < 2:
566
+ return inp
567
+ opts = []
568
+ summ = 0
569
+ tmp_str = ""
570
+ for i in range(len(inps)):
571
+ summ += len(inps[i])
572
+ tmp_str += inps[i]
573
+ if summ > 50:
574
+ summ = 0
575
+ opts.append(tmp_str)
576
+ tmp_str = ""
577
+ if tmp_str != "":
578
+ opts.append(tmp_str)
579
+ # print(opts)
580
+ if len(opts) > 1 and len(opts[-1]) < 50: ##如果最后一个太短了,和前一个合一起
581
+ opts[-2] = opts[-2] + opts[-1]
582
+ opts = opts[:-1]
583
+ opts = [item for item in opts if not set(item).issubset(punctuation)]
584
+ return "\n".join(opts)
585
+
586
+
587
+ def cut3(inp):
588
+ inp = inp.strip("\n")
589
+ opts = ["%s" % item for item in inp.strip("。").split("。")]
590
+ opts = [item for item in opts if not set(item).issubset(punctuation)]
591
+ return "\n".join(opts)
592
+
593
+ def cut4(inp):
594
+ inp = inp.strip("\n")
595
+ opts = ["%s" % item for item in inp.strip(".").split(".")]
596
+ opts = [item for item in opts if not set(item).issubset(punctuation)]
597
+ return "\n".join(opts)
598
+
599
+
600
+ # contributed by https://github.com/AI-Hobbyist/GPT-SoVITS/blob/main/GPT_SoVITS/inference_webui.py
601
+ def cut5(inp):
602
+ inp = inp.strip("\n")
603
+ punds = {',', '.', ';', '?', '!', '、', ',', '。', '?', '!', ';', ':', '…'}
604
+ mergeitems = []
605
+ items = []
606
+
607
+ for i, char in enumerate(inp):
608
+ if char in punds:
609
+ if char == '.' and i > 0 and i < len(inp) - 1 and inp[i - 1].isdigit() and inp[i + 1].isdigit():
610
+ items.append(char)
611
+ else:
612
+ items.append(char)
613
+ mergeitems.append("".join(items))
614
+ items = []
615
+ else:
616
+ items.append(char)
617
+
618
+ if items:
619
+ mergeitems.append("".join(items))
620
+
621
+ opt = [item for item in mergeitems if not set(item).issubset(punds)]
622
+ return "\n".join(opt)
623
+
624
+
625
+ def custom_sort_key(s):
626
+ # 使用正则表达式提取字符串中的数字部分和非数字部分
627
+ parts = re.split('(\d+)', s)
628
+ # 将数字部分转换为整数,非数字部分保持不变
629
+ parts = [int(part) if part.isdigit() else part for part in parts]
630
+ return parts
631
+
632
+ def process_text(texts):
633
+ _text=[]
634
+ if all(text in [None, " ", "\n",""] for text in texts):
635
+ raise ValueError(i18n("请输入有效文本"))
636
+ for text in texts:
637
+ if text in [None, " ", ""]:
638
+ pass
639
+ else:
640
+ _text.append(text)
641
+ return _text
642
+
643
+
644
+ def change_choices():
645
+ SoVITS_names, GPT_names = get_weights_names(GPT_weight_root, SoVITS_weight_root)
646
+ return {"choices": sorted(SoVITS_names, key=custom_sort_key), "__type__": "update"}, {"choices": sorted(GPT_names, key=custom_sort_key), "__type__": "update"}
647
+
648
+
649
+ SoVITS_weight_root=["SoVITS_weights_v2","SoVITS_weights"]
650
+ GPT_weight_root=["GPT_weights_v2","GPT_weights"]
651
+ for path in SoVITS_weight_root+GPT_weight_root:
652
+ os.makedirs(path,exist_ok=True)
653
+
654
+
655
+ def get_weights_names(GPT_weight_root, SoVITS_weight_root):
656
+ SoVITS_names = [i for i in pretrained_sovits_name]
657
+ for path in SoVITS_weight_root:
658
+ for name in os.listdir(path):
659
+ if name.endswith(".pth"): SoVITS_names.append("%s/%s" % (path, name))
660
+ GPT_names = [i for i in pretrained_gpt_name]
661
+ for path in GPT_weight_root:
662
+ for name in os.listdir(path):
663
+ if name.endswith(".ckpt"): GPT_names.append("%s/%s" % (path, name))
664
+ return SoVITS_names, GPT_names
665
+
666
+
667
+ SoVITS_names, GPT_names = get_weights_names(GPT_weight_root, SoVITS_weight_root)
668
+
669
+ def html_center(text, label='p'):
670
+ return f"""<div style="text-align: center; margin: 100; padding: 50;">
671
+ <{label} style="margin: 0; padding: 0;">{text}</{label}>
672
+ </div>"""
673
+
674
+ def html_left(text, label='p'):
675
+ return f"""<div style="text-align: left; margin: 0; padding: 0;">
676
+ <{label} style="margin: 0; padding: 0;">{text}</{label}>
677
+ </div>"""
678
+
679
+
680
+ with gr.Blocks(title="GPT-SoVITS WebUI") as app:
681
+ gr.Markdown(
682
+ value=i18n("本软件以MIT协议开源, 作者不对软件具备任何控制力, 使用软件者、传播软件导出的声音者自负全责. <br>如不认可该条款, 则不能使用或引用软件包内任何代码和文件. 详见根目录<b>LICENSE</b>.")
683
+ )
684
+ with gr.Group():
685
+ gr.Markdown(html_center(i18n("模型切换"),'h3'))
686
+ with gr.Row():
687
+ GPT_dropdown = gr.Dropdown(label=i18n("GPT模型列表"), choices=sorted(GPT_names, key=custom_sort_key), value=gpt_path, interactive=True, scale=14)
688
+ SoVITS_dropdown = gr.Dropdown(label=i18n("SoVITS模型列表"), choices=sorted(SoVITS_names, key=custom_sort_key), value=sovits_path, interactive=True, scale=14)
689
+ refresh_button = gr.Button(i18n("刷新模型路径"), variant="primary", scale=14)
690
+ refresh_button.click(fn=change_choices, inputs=[], outputs=[SoVITS_dropdown, GPT_dropdown])
691
+ gr.Markdown(html_center(i18n("*请上传并填写参考信息"),'h3'))
692
+ with gr.Row():
693
+ inp_ref = gr.Audio(label=i18n("请上传3~10秒内参考音频,超过会报错!"), type="filepath", scale=13)
694
+ with gr.Column(scale=13):
695
+ ref_text_free = gr.Checkbox(label=i18n("开启无参考文本模式。不填参考文本亦相当于开启。"), value=False, interactive=True, show_label=True)
696
+ gr.Markdown(html_left(i18n("使用无参考文本模式时建议使用微调的GPT,听不清参考音频说的啥(不晓得写啥)可以开。<br>开启后无视填写的参考文本。")))
697
+ prompt_text = gr.Textbox(label=i18n("参考音频的文本"), value="", lines=3, max_lines=3)
698
+ prompt_language = gr.Dropdown(
699
+ label=i18n("参考音频的语种"), choices=list(dict_language.keys()), value=i18n("中文"), scale=14
700
+ )
701
+ inp_refs = gr.File(label=i18n("可选项:通过拖拽多个文件上传多个参考音频(建议同性),平均融合他们的音色。如不填写此项,音色由左侧单个参考音频控制。如是微调模型,建议参考音频全部在微调训练集音色内,底模不用管。"),file_count="multiple",scale=13)
702
+ gr.Markdown(html_center(i18n("*请填写需要合成的目标文本和语种模式"),'h3'))
703
+ with gr.Row():
704
+ with gr.Column(scale=13):
705
+ text = gr.Textbox(label=i18n("需要合成的文本"), value="", lines=26, max_lines=26)
706
+ with gr.Column(scale=7):
707
+ text_language = gr.Dropdown(
708
+ label=i18n("需要合成的语种")+i18n(".限制范围越小判别效果越好。"), choices=list(dict_language.keys()), value=i18n("中文"), scale=1
709
+ )
710
+ how_to_cut = gr.Dropdown(
711
+ label=i18n("怎么切"),
712
+ choices=[i18n("不切"), i18n("凑四句一切"), i18n("凑50字一切"), i18n("按中文句号。切"), i18n("按英文句号.切"), i18n("按标点符号切"), ],
713
+ value=i18n("凑四句一切"),
714
+ interactive=True, scale=1
715
+ )
716
+ gr.Markdown(value=html_center(i18n("语速调整,高为更快")))
717
+ if_freeze=gr.Checkbox(label=i18n("是否直接对上次合成结果调整语速和音色。防止随机性。"), value=False, interactive=True,show_label=True, scale=1)
718
+ speed = gr.Slider(minimum=0.6,maximum=1.65,step=0.05,label=i18n("语速"),value=1,interactive=True, scale=1)
719
+ gr.Markdown(html_center(i18n("GPT采样参数(无参考文本时不要太低。不懂就用默认):")))
720
+ top_k = gr.Slider(minimum=1,maximum=100,step=1,label=i18n("top_k"),value=15,interactive=True, scale=1)
721
+ top_p = gr.Slider(minimum=0,maximum=1,step=0.05,label=i18n("top_p"),value=1,interactive=True, scale=1)
722
+ temperature = gr.Slider(minimum=0,maximum=1,step=0.05,label=i18n("temperature"),value=1,interactive=True, scale=1)
723
+ # with gr.Column():
724
+ # gr.Markdown(value=i18n("手工调整音素。当音素框不为空时使用手工音素输入推理,无视目标文本框。"))
725
+ # phoneme=gr.Textbox(label=i18n("音素框"), value="")
726
+ # get_phoneme_button = gr.Button(i18n("目标文本转音素"), variant="primary")
727
+ with gr.Row():
728
+ inference_button = gr.Button(i18n("合成语音"), variant="primary", size='lg', scale=25)
729
+ output = gr.Audio(label=i18n("输出的语音"), scale=14)
730
+
731
+ inference_button.click(
732
+ get_tts_wav,
733
+ [inp_ref, prompt_text, prompt_language, text, text_language, how_to_cut, top_k, top_p, temperature, ref_text_free,speed,if_freeze,inp_refs],
734
+ [output],
735
+ )
736
+ SoVITS_dropdown.change(change_sovits_weights, [SoVITS_dropdown,prompt_language,text_language], [prompt_language,text_language,prompt_text,prompt_language,text,text_language])
737
+ GPT_dropdown.change(change_gpt_weights, [GPT_dropdown], [])
738
+
739
+ # gr.Markdown(value=i18n("文本切分工具。太长的文本合成出来效果不一定好,所以太长建议先切。合成会根据文本的换行分开合成再拼起来。"))
740
+ # with gr.Row():
741
+ # text_inp = gr.Textbox(label=i18n("需要合成的切分前文本"), value="")
742
+ # button1 = gr.Button(i18n("凑四句一切"), variant="primary")
743
+ # button2 = gr.Button(i18n("凑50字一切"), variant="primary")
744
+ # button3 = gr.Button(i18n("按中文句号。切"), variant="primary")
745
+ # button4 = gr.Button(i18n("按英文句号.切"), variant="primary")
746
+ # button5 = gr.Button(i18n("按标点符号切"), variant="primary")
747
+ # text_opt = gr.Textbox(label=i18n("切分后文本"), value="")
748
+ # button1.click(cut1, [text_inp], [text_opt])
749
+ # button2.click(cut2, [text_inp], [text_opt])
750
+ # button3.click(cut3, [text_inp], [text_opt])
751
+ # button4.click(cut4, [text_inp], [text_opt])
752
+ # button5.click(cut5, [text_inp], [text_opt])
753
+ # gr.Markdown(html_center(i18n("后续将支持转音素、手工修改音素、语音合成分步执行。")))
754
+
755
+ if __name__ == '__main__':
756
+ app.queue(concurrency_count=511, max_size=1022).launch(
757
+ server_name="0.0.0.0",
758
+ inbrowser=True,
759
+ share=True,
760
+ server_port=infer_ttswebui,
761
+ quiet=True,
762
+ )