Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,523 +1,66 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
logging.getLogger("charset_normalizer").setLevel(logging.ERROR)
|
9 |
-
logging.getLogger("torchaudio._extension").setLevel(logging.ERROR)
|
10 |
-
import pdb
|
11 |
|
12 |
-
gpt_path = os.environ.get(
|
13 |
-
"gpt_path", "models/maimai/maimai-e21.ckpt"
|
14 |
-
)
|
15 |
-
sovits_path = os.environ.get("sovits_path", "models/maimai/maimai_e55_s1210.pth")
|
16 |
-
cnhubert_base_path = os.environ.get(
|
17 |
-
"cnhubert_base_path", "pretrained_models/chinese-hubert-base"
|
18 |
-
)
|
19 |
-
bert_path = os.environ.get(
|
20 |
-
"bert_path", "pretrained_models/chinese-roberta-wwm-ext-large"
|
21 |
-
)
|
22 |
-
infer_ttswebui = os.environ.get("infer_ttswebui", 9872)
|
23 |
-
infer_ttswebui = int(infer_ttswebui)
|
24 |
-
if "_CUDA_VISIBLE_DEVICES" in os.environ:
|
25 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
|
26 |
-
is_half = eval(os.environ.get("is_half", "True"))
|
27 |
import gradio as gr
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
from feature_extractor import cnhubert
|
32 |
-
cnhubert.cnhubert_base_path=cnhubert_base_path
|
33 |
-
import ssl
|
34 |
ssl._create_default_https_context = ssl._create_unverified_context
|
35 |
import nltk
|
36 |
-
nltk.download('cmudict')
|
37 |
|
38 |
-
|
39 |
-
from
|
40 |
-
from text import cleaned_text_to_sequence
|
41 |
-
from text.cleaner import clean_text
|
42 |
-
from time import time as ttime
|
43 |
-
from module.mel_processing import spectrogram_torch
|
44 |
-
from my_utils import load_audio
|
45 |
|
46 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
47 |
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
50 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
-
tokenizer = AutoTokenizer.from_pretrained(bert_path)
|
53 |
-
bert_model = AutoModelForMaskedLM.from_pretrained(bert_path)
|
54 |
-
if is_half == True:
|
55 |
-
bert_model = bert_model.half().to(device)
|
56 |
-
else:
|
57 |
-
bert_model = bert_model.to(device)
|
58 |
-
|
59 |
-
|
60 |
-
def get_bert_feature(text, word2ph):
|
61 |
-
with torch.no_grad():
|
62 |
-
inputs = tokenizer(text, return_tensors="pt")
|
63 |
-
for i in inputs:
|
64 |
-
inputs[i] = inputs[i].to(device)
|
65 |
-
res = bert_model(**inputs, output_hidden_states=True)
|
66 |
-
res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
|
67 |
-
assert len(word2ph) == len(text)
|
68 |
-
phone_level_feature = []
|
69 |
-
for i in range(len(word2ph)):
|
70 |
-
repeat_feature = res[i].repeat(word2ph[i], 1)
|
71 |
-
phone_level_feature.append(repeat_feature)
|
72 |
-
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
73 |
-
return phone_level_feature.T
|
74 |
-
|
75 |
-
class DictToAttrRecursive(dict):
|
76 |
-
def __init__(self, input_dict):
|
77 |
-
super().__init__(input_dict)
|
78 |
-
for key, value in input_dict.items():
|
79 |
-
if isinstance(value, dict):
|
80 |
-
value = DictToAttrRecursive(value)
|
81 |
-
self[key] = value
|
82 |
-
setattr(self, key, value)
|
83 |
-
|
84 |
-
def __getattr__(self, item):
|
85 |
-
try:
|
86 |
-
return self[item]
|
87 |
-
except KeyError:
|
88 |
-
raise AttributeError(f"Attribute {item} not found")
|
89 |
-
|
90 |
-
def __setattr__(self, key, value):
|
91 |
-
if isinstance(value, dict):
|
92 |
-
value = DictToAttrRecursive(value)
|
93 |
-
super(DictToAttrRecursive, self).__setitem__(key, value)
|
94 |
-
super().__setattr__(key, value)
|
95 |
-
|
96 |
-
def __delattr__(self, item):
|
97 |
-
try:
|
98 |
-
del self[item]
|
99 |
-
except KeyError:
|
100 |
-
raise AttributeError(f"Attribute {item} not found")
|
101 |
-
|
102 |
-
ssl_model = cnhubert.get_model()
|
103 |
-
if is_half == True:
|
104 |
-
ssl_model = ssl_model.half().to(device)
|
105 |
-
else:
|
106 |
-
ssl_model = ssl_model.to(device)
|
107 |
-
|
108 |
-
def change_sovits_weights(sovits_path):
|
109 |
-
global vq_model,hps
|
110 |
-
dict_s2=torch.load(sovits_path,map_location="cpu")
|
111 |
-
hps=dict_s2["config"]
|
112 |
-
hps = DictToAttrRecursive(hps)
|
113 |
-
hps.model.semantic_frame_rate = "25hz"
|
114 |
-
vq_model = SynthesizerTrn(
|
115 |
-
hps.data.filter_length // 2 + 1,
|
116 |
-
hps.train.segment_size // hps.data.hop_length,
|
117 |
-
n_speakers=hps.data.n_speakers,
|
118 |
-
**hps.model
|
119 |
-
)
|
120 |
-
if("pretrained"not in sovits_path):
|
121 |
-
del vq_model.enc_q
|
122 |
-
if is_half == True:
|
123 |
-
vq_model = vq_model.half().to(device)
|
124 |
-
else:
|
125 |
-
vq_model = vq_model.to(device)
|
126 |
-
vq_model.eval()
|
127 |
-
print(vq_model.load_state_dict(dict_s2["weight"], strict=False))
|
128 |
-
change_sovits_weights(sovits_path)
|
129 |
-
|
130 |
-
def change_gpt_weights(gpt_path):
|
131 |
-
global hz,max_sec,t2s_model,config
|
132 |
-
hz = 50
|
133 |
-
dict_s1 = torch.load(gpt_path, map_location="cpu")
|
134 |
-
config = dict_s1["config"]
|
135 |
-
max_sec = config["data"]["max_sec"]
|
136 |
-
t2s_model = Text2SemanticLightningModule(config, "****", is_train=False)
|
137 |
-
t2s_model.load_state_dict(dict_s1["weight"])
|
138 |
-
if is_half == True:
|
139 |
-
t2s_model = t2s_model.half()
|
140 |
-
t2s_model = t2s_model.to(device)
|
141 |
-
t2s_model.eval()
|
142 |
-
total = sum([param.nelement() for param in t2s_model.parameters()])
|
143 |
-
print("Number of parameter: %.2fM" % (total / 1e6))
|
144 |
-
change_gpt_weights(gpt_path)
|
145 |
-
|
146 |
-
|
147 |
-
def get_spepc(hps, filename):
|
148 |
-
audio = load_audio(filename, int(hps.data.sampling_rate))
|
149 |
-
audio = torch.FloatTensor(audio)
|
150 |
-
audio_norm = audio
|
151 |
-
audio_norm = audio_norm.unsqueeze(0)
|
152 |
-
spec = spectrogram_torch(
|
153 |
-
audio_norm,
|
154 |
-
hps.data.filter_length,
|
155 |
-
hps.data.sampling_rate,
|
156 |
-
hps.data.hop_length,
|
157 |
-
hps.data.win_length,
|
158 |
-
center=False,
|
159 |
-
)
|
160 |
-
return spec
|
161 |
-
|
162 |
-
|
163 |
-
dict_language={
|
164 |
-
("中文"):"zh",
|
165 |
-
("英文"):"en",
|
166 |
-
("日文"):"ja"
|
167 |
-
}
|
168 |
-
|
169 |
-
|
170 |
-
def splite_en_inf(sentence, language):
|
171 |
-
pattern = re.compile(r'[a-zA-Z. ]+')
|
172 |
-
textlist = []
|
173 |
-
langlist = []
|
174 |
-
pos = 0
|
175 |
-
for match in pattern.finditer(sentence):
|
176 |
-
start, end = match.span()
|
177 |
-
if start > pos:
|
178 |
-
textlist.append(sentence[pos:start])
|
179 |
-
langlist.append(language)
|
180 |
-
textlist.append(sentence[start:end])
|
181 |
-
langlist.append("en")
|
182 |
-
pos = end
|
183 |
-
if pos < len(sentence):
|
184 |
-
textlist.append(sentence[pos:])
|
185 |
-
langlist.append(language)
|
186 |
-
|
187 |
-
return textlist, langlist
|
188 |
-
|
189 |
-
|
190 |
-
def clean_text_inf(text, language):
|
191 |
-
phones, word2ph, norm_text = clean_text(text, language)
|
192 |
-
phones = cleaned_text_to_sequence(phones)
|
193 |
-
|
194 |
-
return phones, word2ph, norm_text
|
195 |
-
def get_bert_inf(phones, word2ph, norm_text, language):
|
196 |
-
if language == "zh":
|
197 |
-
bert = get_bert_feature(norm_text, word2ph).to(device)
|
198 |
-
else:
|
199 |
-
bert = torch.zeros(
|
200 |
-
(1024, len(phones)),
|
201 |
-
dtype=torch.float16 if is_half == True else torch.float32,
|
202 |
-
).to(device)
|
203 |
-
|
204 |
-
return bert
|
205 |
-
|
206 |
-
|
207 |
-
def nonen_clean_text_inf(text, language):
|
208 |
-
textlist, langlist = splite_en_inf(text, language)
|
209 |
-
phones_list = []
|
210 |
-
word2ph_list = []
|
211 |
-
norm_text_list = []
|
212 |
-
for i in range(len(textlist)):
|
213 |
-
lang = langlist[i]
|
214 |
-
phones, word2ph, norm_text = clean_text_inf(textlist[i], lang)
|
215 |
-
phones_list.append(phones)
|
216 |
-
if lang == "en" or "ja":
|
217 |
-
pass
|
218 |
-
else:
|
219 |
-
word2ph_list.append(word2ph)
|
220 |
-
norm_text_list.append(norm_text)
|
221 |
-
print(word2ph_list)
|
222 |
-
phones = sum(phones_list, [])
|
223 |
-
word2ph = sum(word2ph_list, [])
|
224 |
-
norm_text = ' '.join(norm_text_list)
|
225 |
-
|
226 |
-
return phones, word2ph, norm_text
|
227 |
-
|
228 |
-
|
229 |
-
def nonen_get_bert_inf(text, language):
|
230 |
-
textlist, langlist = splite_en_inf(text, language)
|
231 |
-
print(textlist)
|
232 |
-
print(langlist)
|
233 |
-
bert_list = []
|
234 |
-
for i in range(len(textlist)):
|
235 |
-
text = textlist[i]
|
236 |
-
lang = langlist[i]
|
237 |
-
phones, word2ph, norm_text = clean_text_inf(text, lang)
|
238 |
-
bert = get_bert_inf(phones, word2ph, norm_text, lang)
|
239 |
-
bert_list.append(bert)
|
240 |
-
bert = torch.cat(bert_list, dim=1)
|
241 |
-
|
242 |
-
return bert
|
243 |
-
|
244 |
-
def get_tts_wav(selected_text, prompt_text, prompt_language, text, text_language,how_to_cut=("不切")):
|
245 |
-
ref_wav_path = text_to_audio_mappings.get(selected_text, "")
|
246 |
-
if not ref_wav_path:
|
247 |
-
print("Audio file not found for the selected text.")
|
248 |
-
return
|
249 |
-
t0 = ttime()
|
250 |
-
prompt_text = prompt_text.strip("\n")
|
251 |
-
prompt_language, text = prompt_language, text.strip("\n")
|
252 |
-
zero_wav = np.zeros(
|
253 |
-
int(hps.data.sampling_rate * 0.3),
|
254 |
-
dtype=np.float16 if is_half == True else np.float32,
|
255 |
-
)
|
256 |
-
with torch.no_grad():
|
257 |
-
wav16k, sr = librosa.load(ref_wav_path, sr=16000)
|
258 |
-
wav16k = torch.from_numpy(wav16k)
|
259 |
-
zero_wav_torch = torch.from_numpy(zero_wav)
|
260 |
-
if is_half == True:
|
261 |
-
wav16k = wav16k.half().to(device)
|
262 |
-
zero_wav_torch = zero_wav_torch.half().to(device)
|
263 |
-
else:
|
264 |
-
wav16k = wav16k.to(device)
|
265 |
-
zero_wav_torch = zero_wav_torch.to(device)
|
266 |
-
wav16k=torch.cat([wav16k,zero_wav_torch])
|
267 |
-
ssl_content = ssl_model.model(wav16k.unsqueeze(0))[
|
268 |
-
"last_hidden_state"
|
269 |
-
].transpose(
|
270 |
-
1, 2
|
271 |
-
) # .float()
|
272 |
-
codes = vq_model.extract_latent(ssl_content)
|
273 |
-
prompt_semantic = codes[0, 0]
|
274 |
-
t1 = ttime()
|
275 |
-
prompt_language = dict_language[prompt_language]
|
276 |
-
text_language = dict_language[text_language]
|
277 |
-
|
278 |
-
if prompt_language == "en":
|
279 |
-
phones1, word2ph1, norm_text1 = clean_text_inf(prompt_text, prompt_language)
|
280 |
-
else:
|
281 |
-
phones1, word2ph1, norm_text1 = nonen_clean_text_inf(prompt_text, prompt_language)
|
282 |
-
if(how_to_cut==("凑五句一切")):text=cut1(text)
|
283 |
-
elif(how_to_cut==("凑50字一切")):text=cut2(text)
|
284 |
-
elif(how_to_cut==("按中文句号。切")):text=cut3(text)
|
285 |
-
elif(how_to_cut==("按英文句号.切")):text=cut4(text)
|
286 |
-
text = text.replace("\n\n","\n").replace("\n\n","\n").replace("\n\n","\n")
|
287 |
-
if(text[-1]not in splits):text+="。"if text_language!="en"else "."
|
288 |
-
texts=text.split("\n")
|
289 |
-
audio_opt = []
|
290 |
-
if prompt_language == "en":
|
291 |
-
bert1 = get_bert_inf(phones1, word2ph1, norm_text1, prompt_language)
|
292 |
-
else:
|
293 |
-
bert1 = nonen_get_bert_inf(prompt_text, prompt_language)
|
294 |
-
|
295 |
-
for text in texts:
|
296 |
-
# 解决输入目标文本的空行导致报错的问题
|
297 |
-
if (len(text.strip()) == 0):
|
298 |
-
continue
|
299 |
-
if text_language == "en":
|
300 |
-
phones2, word2ph2, norm_text2 = clean_text_inf(text, text_language)
|
301 |
-
else:
|
302 |
-
phones2, word2ph2, norm_text2 = nonen_clean_text_inf(text, text_language)
|
303 |
-
|
304 |
-
if text_language == "en":
|
305 |
-
bert2 = get_bert_inf(phones2, word2ph2, norm_text2, text_language)
|
306 |
-
else:
|
307 |
-
bert2 = nonen_get_bert_inf(text, text_language)
|
308 |
-
bert = torch.cat([bert1, bert2], 1)
|
309 |
-
|
310 |
-
all_phoneme_ids = torch.LongTensor(phones1 + phones2).to(device).unsqueeze(0)
|
311 |
-
bert = bert.to(device).unsqueeze(0)
|
312 |
-
all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)
|
313 |
-
prompt = prompt_semantic.unsqueeze(0).to(device)
|
314 |
-
t2 = ttime()
|
315 |
-
with torch.no_grad():
|
316 |
-
# pred_semantic = t2s_model.model.infer(
|
317 |
-
pred_semantic, idx = t2s_model.model.infer_panel(
|
318 |
-
all_phoneme_ids,
|
319 |
-
all_phoneme_len,
|
320 |
-
prompt,
|
321 |
-
bert,
|
322 |
-
# prompt_phone_len=ph_offset,
|
323 |
-
top_k=config["inference"]["top_k"],
|
324 |
-
early_stop_num=hz * max_sec,
|
325 |
-
)
|
326 |
-
t3 = ttime()
|
327 |
-
# print(pred_semantic.shape,idx)
|
328 |
-
pred_semantic = pred_semantic[:, -idx:].unsqueeze(
|
329 |
-
0
|
330 |
-
) # .unsqueeze(0)#mq要多unsqueeze一次
|
331 |
-
refer = get_spepc(hps, ref_wav_path) # .to(device)
|
332 |
-
if is_half == True:
|
333 |
-
refer = refer.half().to(device)
|
334 |
-
else:
|
335 |
-
refer = refer.to(device)
|
336 |
-
# audio = vq_model.decode(pred_semantic, all_phoneme_ids, refer).detach().cpu().numpy()[0, 0]
|
337 |
-
audio = (
|
338 |
-
vq_model.decode(
|
339 |
-
pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refer
|
340 |
-
)
|
341 |
-
.detach()
|
342 |
-
.cpu()
|
343 |
-
.numpy()[0, 0]
|
344 |
-
) ###试试重建不带上prompt部分
|
345 |
-
audio_opt.append(audio)
|
346 |
-
audio_opt.append(zero_wav)
|
347 |
-
t4 = ttime()
|
348 |
-
print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
|
349 |
-
yield hps.data.sampling_rate, (np.concatenate(audio_opt, 0) * 32768).astype(
|
350 |
-
np.int16
|
351 |
-
)
|
352 |
-
|
353 |
-
|
354 |
-
splits = {
|
355 |
-
",",
|
356 |
-
"。",
|
357 |
-
"?",
|
358 |
-
"!",
|
359 |
-
",",
|
360 |
-
".",
|
361 |
-
"?",
|
362 |
-
"!",
|
363 |
-
"~",
|
364 |
-
":",
|
365 |
-
":",
|
366 |
-
"—",
|
367 |
-
"…",
|
368 |
-
} # 不考虑省略号
|
369 |
-
|
370 |
-
|
371 |
-
def split(todo_text):
|
372 |
-
todo_text = todo_text.replace("……", "。").replace("——", ",")
|
373 |
-
if todo_text[-1] not in splits:
|
374 |
-
todo_text += "。"
|
375 |
-
i_split_head = i_split_tail = 0
|
376 |
-
len_text = len(todo_text)
|
377 |
-
todo_texts = []
|
378 |
-
while 1:
|
379 |
-
if i_split_head >= len_text:
|
380 |
-
break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
|
381 |
-
if todo_text[i_split_head] in splits:
|
382 |
-
i_split_head += 1
|
383 |
-
todo_texts.append(todo_text[i_split_tail:i_split_head])
|
384 |
-
i_split_tail = i_split_head
|
385 |
-
else:
|
386 |
-
i_split_head += 1
|
387 |
-
return todo_texts
|
388 |
-
|
389 |
-
|
390 |
-
def cut1(inp):
|
391 |
-
inp = inp.strip("\n")
|
392 |
-
inps = split(inp)
|
393 |
-
split_idx = list(range(0, len(inps), 5))
|
394 |
-
split_idx[-1] = None
|
395 |
-
if len(split_idx) > 1:
|
396 |
-
opts = []
|
397 |
-
for idx in range(len(split_idx) - 1):
|
398 |
-
opts.append("".join(inps[split_idx[idx] : split_idx[idx + 1]]))
|
399 |
-
else:
|
400 |
-
opts = [inp]
|
401 |
-
return "\n".join(opts)
|
402 |
-
|
403 |
-
|
404 |
-
def cut2(inp):
|
405 |
-
inp = inp.strip("\n")
|
406 |
-
inps = split(inp)
|
407 |
-
if len(inps) < 2:
|
408 |
-
return [inp]
|
409 |
-
opts = []
|
410 |
-
summ = 0
|
411 |
-
tmp_str = ""
|
412 |
-
for i in range(len(inps)):
|
413 |
-
summ += len(inps[i])
|
414 |
-
tmp_str += inps[i]
|
415 |
-
if summ > 50:
|
416 |
-
summ = 0
|
417 |
-
opts.append(tmp_str)
|
418 |
-
tmp_str = ""
|
419 |
-
if tmp_str != "":
|
420 |
-
opts.append(tmp_str)
|
421 |
-
if len(opts[-1]) < 50: ##如果最后一个太短了,和前一个合一起
|
422 |
-
opts[-2] = opts[-2] + opts[-1]
|
423 |
-
opts = opts[:-1]
|
424 |
-
return "\n".join(opts)
|
425 |
-
|
426 |
-
|
427 |
-
def cut3(inp):
|
428 |
-
inp = inp.strip("\n")
|
429 |
-
return "\n".join(["%s。" % item for item in inp.strip("。").split("。")])
|
430 |
-
def cut4(inp):
|
431 |
-
inp = inp.strip("\n")
|
432 |
-
return "\n".join(["%s." % item for item in inp.strip(".").split(".")])
|
433 |
-
|
434 |
-
def scan_audio_files(folder_path):
|
435 |
-
""" 扫描指定文件夹获取音频文件列表 """
|
436 |
-
return [f for f in os.listdir(folder_path) if f.endswith('.wav')]
|
437 |
|
438 |
-
def
|
439 |
-
|
440 |
-
|
441 |
-
with open(os.path.join(folder_path, list_file_name), 'r', encoding='utf-8') as file:
|
442 |
-
for line in file:
|
443 |
-
parts = line.strip().split('|')
|
444 |
-
if len(parts) >= 4:
|
445 |
-
audio_file_name = parts[0]
|
446 |
-
text = parts[3]
|
447 |
-
audio_file_path = os.path.join(folder_path, audio_file_name)
|
448 |
-
text_to_audio_mappings[text] = audio_file_path
|
449 |
-
audio_to_text_mappings[audio_file_path] = text
|
450 |
-
return text_to_audio_mappings, audio_to_text_mappings
|
451 |
|
452 |
-
audio_folder_path = 'audio/maimai'
|
453 |
-
text_to_audio_mappings, audio_to_text_mappings = load_audio_text_mappings(audio_folder_path, 'maimai.list')
|
454 |
|
455 |
-
with gr.Blocks(title="
|
456 |
gr.Markdown(value="""
|
457 |
-
# <center
|
458 |
-
|
459 |
-
### <center
|
460 |
-
### <center>【GPT-SoVITS】在线合集:https://www.modelscope.cn/studios/xzjosh/GPT-SoVITS\n
|
461 |
### <center>数据集下载:https://huggingface.co/datasets/XzJosh/audiodataset\n
|
462 |
### <center>声音归属:扇宝 https://space.bilibili.com/698438232\n
|
463 |
-
### <center
|
464 |
### <center>使用本模型请严格遵守法律法规!发布二创作品请标注本项目作者及链接、作品使用GPT-SoVITS AI生成!\n
|
465 |
-
### <center
|
466 |
""")
|
467 |
-
# with gr.Tabs():
|
468 |
|
469 |
with gr.Group():
|
470 |
-
gr.Markdown(value="
|
471 |
with gr.Row():
|
472 |
-
|
473 |
-
ref_audio = gr.Audio(label="参考音频试听")
|
474 |
-
ref_text = gr.Textbox(label="参考音频文本")
|
475 |
-
|
476 |
-
# 定义更新参考文本的函数
|
477 |
-
def update_ref_text_and_audio(selected_text):
|
478 |
-
audio_path = text_to_audio_mappings.get(selected_text, "")
|
479 |
-
return selected_text, audio_path
|
480 |
-
|
481 |
-
# 绑定下拉菜单的变化到更新函数
|
482 |
-
audio_select.change(update_ref_text_and_audio, [audio_select], [ref_text, ref_audio])
|
483 |
-
|
484 |
-
# 其他 Gradio 组件和功能
|
485 |
-
prompt_language = gr.Dropdown(
|
486 |
-
label="参考音频语种", choices=["中文", "英文", "日文"], value="中文"
|
487 |
-
)
|
488 |
-
gr.Markdown(value="*请填写需要合成的目标文本,中英混合选中文,日英混合选日文,暂不支持中日混合。")
|
489 |
-
with gr.Row():
|
490 |
-
text = gr.Textbox(label="需要合成的文本", value="")
|
491 |
-
text_language = gr.Dropdown(
|
492 |
-
label="需要合成的语种", choices=["中文", "英文", "日文"], value="中文"
|
493 |
-
)
|
494 |
-
how_to_cut = gr.Radio(
|
495 |
-
label=("自动切分(长文本建议切分)"),
|
496 |
-
choices=[("不切"),("凑五句一切"),("凑50字一切"),("按中文句号。切"),("按英文句号.切"),],
|
497 |
-
value=("不切"),
|
498 |
-
interactive=True,
|
499 |
-
)
|
500 |
inference_button = gr.Button("合成语音", variant="primary")
|
501 |
output = gr.Audio(label="输出的语音")
|
502 |
inference_button.click(
|
503 |
-
|
504 |
-
[
|
505 |
[output],
|
506 |
)
|
507 |
|
508 |
-
|
509 |
-
gr.Markdown(value="文本切分工具,需要复制。")
|
510 |
-
with gr.Row():
|
511 |
-
text_inp = gr.Textbox(label="需要合成的切分前文本", value="")
|
512 |
-
button1 = gr.Button("凑五句一切", variant="primary")
|
513 |
-
button2 = gr.Button("凑50字一切", variant="primary")
|
514 |
-
button3 = gr.Button("按中文句号。切", variant="primary")
|
515 |
-
button4 = gr.Button("按英文句号.切", variant="primary")
|
516 |
-
text_opt = gr.Textbox(label="切分后文本", value="")
|
517 |
-
button1.click(cut1, [text_inp], [text_opt])
|
518 |
-
button2.click(cut2, [text_inp], [text_opt])
|
519 |
-
button3.click(cut3, [text_inp], [text_opt])
|
520 |
-
button4.click(cut4, [text_inp], [text_opt])
|
521 |
-
|
522 |
app.queue(max_size=10)
|
523 |
app.launch(inbrowser=True)
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
@author:XuMing(xuming624@qq.com)
|
4 |
+
@description:
|
5 |
+
"""
|
6 |
+
import os
|
7 |
+
import ssl
|
|
|
|
|
|
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
import gradio as gr
|
10 |
+
import torch
|
11 |
+
from loguru import logger
|
12 |
+
|
|
|
|
|
|
|
13 |
ssl._create_default_https_context = ssl._create_unverified_context
|
14 |
import nltk
|
|
|
15 |
|
16 |
+
nltk.download('cmudict')
|
17 |
+
from parrots import TextToSpeech
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
20 |
+
logger.info(f"device: {device}")
|
21 |
|
22 |
+
m = TextToSpeech(
|
23 |
+
speaker_model_path="shibing624/parrots-gpt-sovits-speaker-maimai",
|
24 |
+
speaker_name="MaiMai",
|
25 |
+
device="cpu",
|
26 |
+
half=False
|
27 |
)
|
28 |
+
m.predict(
|
29 |
+
text="你好,欢迎来北京。welcome to the city.",
|
30 |
+
text_language="auto",
|
31 |
+
output_path="output_audio.wav"
|
32 |
+
)
|
33 |
+
assert os.path.exists("output_audio.wav")
|
34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
+
def do_tts_wav_predict(text):
|
37 |
+
audio_array = m.predict(text, text_language="auto")
|
38 |
+
yield audio_array
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
|
|
|
|
40 |
|
41 |
+
with gr.Blocks(title="parrots WebUI") as app:
|
42 |
gr.Markdown(value="""
|
43 |
+
# <center>在线语音生成(parrots)--speaker:主播卖卖\n
|
44 |
+
|
45 |
+
### <center>parrots项目:https://github.com/shibing624/parrots\n
|
|
|
46 |
### <center>数据集下载:https://huggingface.co/datasets/XzJosh/audiodataset\n
|
47 |
### <center>声音归属:扇宝 https://space.bilibili.com/698438232\n
|
48 |
+
### <center>模型训练:https://github.com/RVC-Boss/GPT-SoVITS\n
|
49 |
### <center>使用本模型请严格遵守法律法规!发布二创作品请标注本项目作者及链接、作品使用GPT-SoVITS AI生成!\n
|
50 |
+
### <center>⚠️在线端不稳定且生成速度较慢,建议使用parrots本地推理!\n
|
51 |
""")
|
|
|
52 |
|
53 |
with gr.Group():
|
54 |
+
gr.Markdown(value="*请填写需要语音合成的文本")
|
55 |
with gr.Row():
|
56 |
+
text = gr.Textbox(label="需要合成的文本", value="", placeholder="请输入文本", lines=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
inference_button = gr.Button("合成语音", variant="primary")
|
58 |
output = gr.Audio(label="输出的语音")
|
59 |
inference_button.click(
|
60 |
+
do_tts_wav_predict,
|
61 |
+
[text],
|
62 |
[output],
|
63 |
)
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
app.queue(max_size=10)
|
66 |
app.launch(inbrowser=True)
|