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|
+
"""
|
| 4 |
+
受 GPT-SoVITS 启发
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import os.path as osp
|
| 9 |
+
import re
|
| 10 |
+
import logging
|
| 11 |
+
from time import time as ttime
|
| 12 |
+
from warnings import warn
|
| 13 |
+
|
| 14 |
+
logging.getLogger("markdown_it").setLevel(logging.ERROR)
|
| 15 |
+
logging.getLogger("urllib3").setLevel(logging.ERROR)
|
| 16 |
+
logging.getLogger("httpcore").setLevel(logging.ERROR)
|
| 17 |
+
logging.getLogger("httpx").setLevel(logging.ERROR)
|
| 18 |
+
logging.getLogger("asyncio").setLevel(logging.ERROR)
|
| 19 |
+
logging.getLogger("charset_normalizer").setLevel(logging.ERROR)
|
| 20 |
+
logging.getLogger("torchaudio._extension").setLevel(logging.ERROR)
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
import librosa
|
| 26 |
+
import numpy as np
|
| 27 |
+
import LangSegment
|
| 28 |
+
import gradio as gr
|
| 29 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
| 30 |
+
from feature_extractor import cnhubert
|
| 31 |
+
|
| 32 |
+
from module.models import SynthesizerTrn
|
| 33 |
+
from module.mel_processing import spectrogram_torch
|
| 34 |
+
from AR.models.t2s_lightning_module import Text2SemanticLightningModule
|
| 35 |
+
from text import cleaned_text_to_sequence
|
| 36 |
+
from text.cleaner import clean_text
|
| 37 |
+
from my_utils import load_audio
|
| 38 |
+
from tools.i18n.i18n import I18nAuto
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_pretrain_model_path(env_name, log_file, def_path):
|
| 42 |
+
""" 获取预训练模型路径
|
| 43 |
+
env_name: 从环境变量获取,第一优先级
|
| 44 |
+
log_file: 记录在文本文件内,第二优先级
|
| 45 |
+
def_path: 传参,第三优先级
|
| 46 |
+
"""
|
| 47 |
+
if osp.isfile(log_file):
|
| 48 |
+
def_path = open(log_file, 'r', encoding="utf-8").read()
|
| 49 |
+
pretrain_path = os.environ.get(env_name, def_path)
|
| 50 |
+
return pretrain_path
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 54 |
+
device = 'cpu'
|
| 55 |
+
|
| 56 |
+
gpt_path = get_pretrain_model_path('gpt_path', "./gweight.txt",
|
| 57 |
+
"GPT_SoVITS/pretrained_models/s1bert25hz-2kh-longer-epoch=68e-step=50232.ckpt")
|
| 58 |
+
|
| 59 |
+
sovits_path = get_pretrain_model_path('sovits_path', "./sweight.txt",
|
| 60 |
+
"GPT_SoVITS/pretrained_models/s2G488k.pth")
|
| 61 |
+
|
| 62 |
+
cnhubert_base_path = get_pretrain_model_path("cnhubert_base_path", '', "GPT_SoVITS/pretrained_models/chinese-hubert-base")
|
| 63 |
+
|
| 64 |
+
bert_path = get_pretrain_model_path("bert_path", '', "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large")
|
| 65 |
+
|
| 66 |
+
vc_webui_port = int(os.environ.get("vc_webui_port", 9888)) # specify gradio port
|
| 67 |
+
print(f'port: {vc_webui_port}')
|
| 68 |
+
|
| 69 |
+
is_share = eval(os.environ.get("is_share", "False"))
|
| 70 |
+
|
| 71 |
+
if "_CUDA_VISIBLE_DEVICES" in os.environ:
|
| 72 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
|
| 73 |
+
|
| 74 |
+
# is_half = eval(os.environ.get("is_half", "True")) and not torch.backends.mps.is_available()
|
| 75 |
+
is_half = False
|
| 76 |
+
|
| 77 |
+
os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 确保直接启动推理UI时也能够设置。
|
| 78 |
+
|
| 79 |
+
cnhubert.cnhubert_base_path = cnhubert_base_path
|
| 80 |
+
|
| 81 |
+
i18n = I18nAuto()
|
| 82 |
+
|
| 83 |
+
tokenizer = AutoTokenizer.from_pretrained(bert_path)
|
| 84 |
+
bert_model = AutoModelForMaskedLM.from_pretrained(bert_path)
|
| 85 |
+
if is_half:
|
| 86 |
+
bert_model = bert_model.half().to(device)
|
| 87 |
+
else:
|
| 88 |
+
bert_model = bert_model.to(device)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_bert_feature(text, word2ph):
|
| 92 |
+
with torch.no_grad():
|
| 93 |
+
inputs = tokenizer(text, return_tensors="pt")
|
| 94 |
+
for i in inputs:
|
| 95 |
+
inputs[i] = inputs[i].to(device)
|
| 96 |
+
res = bert_model(**inputs, output_hidden_states=True)
|
| 97 |
+
res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
|
| 98 |
+
assert len(word2ph) == len(text)
|
| 99 |
+
phone_level_feature = []
|
| 100 |
+
for i in range(len(word2ph)):
|
| 101 |
+
repeat_feature = res[i].repeat(word2ph[i], 1)
|
| 102 |
+
phone_level_feature.append(repeat_feature)
|
| 103 |
+
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
| 104 |
+
return phone_level_feature.T
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class DictToAttrRecursive(dict):
|
| 108 |
+
def __init__(self, input_dict):
|
| 109 |
+
super().__init__(input_dict)
|
| 110 |
+
for key, value in input_dict.items():
|
| 111 |
+
if isinstance(value, dict):
|
| 112 |
+
value = DictToAttrRecursive(value)
|
| 113 |
+
self[key] = value
|
| 114 |
+
setattr(self, key, value)
|
| 115 |
+
|
| 116 |
+
def __getattr__(self, item):
|
| 117 |
+
try:
|
| 118 |
+
return self[item]
|
| 119 |
+
except KeyError:
|
| 120 |
+
raise AttributeError(f"Attribute {item} not found")
|
| 121 |
+
|
| 122 |
+
def __setattr__(self, key, value):
|
| 123 |
+
if isinstance(value, dict):
|
| 124 |
+
value = DictToAttrRecursive(value)
|
| 125 |
+
super(DictToAttrRecursive, self).__setitem__(key, value)
|
| 126 |
+
super().__setattr__(key, value)
|
| 127 |
+
|
| 128 |
+
def __delattr__(self, item):
|
| 129 |
+
try:
|
| 130 |
+
del self[item]
|
| 131 |
+
except KeyError:
|
| 132 |
+
raise AttributeError(f"Attribute {item} not found")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
ssl_model = cnhubert.get_model()
|
| 136 |
+
if is_half:
|
| 137 |
+
ssl_model = ssl_model.half().to(device)
|
| 138 |
+
else:
|
| 139 |
+
ssl_model = ssl_model.to(device)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def change_sovits_weights(sovits_path):
|
| 143 |
+
global vq_model, hps
|
| 144 |
+
dict_s2 = torch.load(sovits_path, map_location="cpu")
|
| 145 |
+
hps = dict_s2["config"]
|
| 146 |
+
hps = DictToAttrRecursive(hps)
|
| 147 |
+
hps.model.semantic_frame_rate = "25hz"
|
| 148 |
+
vq_model = SynthesizerTrn(
|
| 149 |
+
hps.data.filter_length // 2 + 1,
|
| 150 |
+
hps.train.segment_size // hps.data.hop_length,
|
| 151 |
+
n_speakers=hps.data.n_speakers,
|
| 152 |
+
**hps.model
|
| 153 |
+
)
|
| 154 |
+
if ("pretrained" not in sovits_path):
|
| 155 |
+
del vq_model.enc_q
|
| 156 |
+
if is_half == True:
|
| 157 |
+
vq_model = vq_model.half().to(device)
|
| 158 |
+
else:
|
| 159 |
+
vq_model = vq_model.to(device)
|
| 160 |
+
vq_model.eval()
|
| 161 |
+
print(vq_model.load_state_dict(dict_s2["weight"], strict=False))
|
| 162 |
+
with open("./sweight.txt", "w", encoding="utf-8") as f:
|
| 163 |
+
f.write(sovits_path)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
change_sovits_weights(sovits_path)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def change_gpt_weights(gpt_path):
|
| 170 |
+
global hz, max_sec, t2s_model, config
|
| 171 |
+
hz = 50
|
| 172 |
+
dict_s1 = torch.load(gpt_path, map_location="cpu")
|
| 173 |
+
config = dict_s1["config"]
|
| 174 |
+
max_sec = config["data"]["max_sec"]
|
| 175 |
+
t2s_model = Text2SemanticLightningModule(config, "****", is_train=False)
|
| 176 |
+
t2s_model.load_state_dict(dict_s1["weight"])
|
| 177 |
+
if is_half == True:
|
| 178 |
+
t2s_model = t2s_model.half()
|
| 179 |
+
t2s_model = t2s_model.to(device)
|
| 180 |
+
t2s_model.eval()
|
| 181 |
+
total = sum([param.nelement() for param in t2s_model.parameters()])
|
| 182 |
+
print("Number of parameter: %.2fM" % (total / 1e6))
|
| 183 |
+
with open("./gweight.txt", "w", encoding="utf-8") as f: f.write(gpt_path)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
change_gpt_weights(gpt_path)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def get_spepc(hps, filename):
|
| 190 |
+
audio = load_audio(filename, int(hps.data.sampling_rate))
|
| 191 |
+
audio = torch.FloatTensor(audio)
|
| 192 |
+
audio_norm = audio
|
| 193 |
+
audio_norm = audio_norm.unsqueeze(0)
|
| 194 |
+
spec = spectrogram_torch(
|
| 195 |
+
audio_norm,
|
| 196 |
+
hps.data.filter_length,
|
| 197 |
+
hps.data.sampling_rate,
|
| 198 |
+
hps.data.hop_length,
|
| 199 |
+
hps.data.win_length,
|
| 200 |
+
center=False,
|
| 201 |
+
)
|
| 202 |
+
return spec
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
dict_language = {
|
| 206 |
+
i18n("中文"): "all_zh",#全部按中文识别
|
| 207 |
+
i18n("英文"): "en",#全部按英文识别#######不变
|
| 208 |
+
i18n("日文"): "all_ja",#全部按日文识别
|
| 209 |
+
i18n("中英混合"): "zh",#按中英混合识别####不变
|
| 210 |
+
i18n("日英混合"): "ja",#按日英混合识别####不变
|
| 211 |
+
i18n("多语种混合"): "auto",#多语种启动切分识别语种
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# def clean_text_inf(text, language):
|
| 216 |
+
# phones, word2ph, norm_text = clean_text(text, language)
|
| 217 |
+
# phones = cleaned_text_to_sequence(phones)
|
| 218 |
+
# return phones, word2ph, norm_text
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def clean_text_inf(text, language):
|
| 222 |
+
"""
|
| 223 |
+
text: 字符串
|
| 224 |
+
language: 所属语言
|
| 225 |
+
|
| 226 |
+
return:
|
| 227 |
+
phones: 音素 id 序列
|
| 228 |
+
word2ph: 每个字转音素后,对应的个数,对于中文,就是声韵母,因此是全是 2 的 list
|
| 229 |
+
norm_text: 归一化后文本
|
| 230 |
+
"""
|
| 231 |
+
formattext = ""
|
| 232 |
+
language = language.replace("all_","")
|
| 233 |
+
for tmp in LangSegment.getTexts(text):
|
| 234 |
+
if language == "ja":
|
| 235 |
+
if tmp["lang"] == language or tmp["lang"] == "zh":
|
| 236 |
+
formattext += tmp["text"] + " "
|
| 237 |
+
continue
|
| 238 |
+
if tmp["lang"] == language:
|
| 239 |
+
formattext += tmp["text"] + " "
|
| 240 |
+
while " " in formattext:
|
| 241 |
+
formattext = formattext.replace(" ", " ")
|
| 242 |
+
phones, word2ph, norm_text = clean_text(formattext, language)
|
| 243 |
+
# print(f'音素: {phones}')
|
| 244 |
+
phones = cleaned_text_to_sequence(phones) # 统一了中、英、日等
|
| 245 |
+
# print(f'音素 id: {phones}')
|
| 246 |
+
return phones, word2ph, norm_text
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
dtype=torch.float16 if is_half == True else torch.float32
|
| 250 |
+
def get_bert_inf(phones, word2ph, norm_text, language):
|
| 251 |
+
language=language.replace("all_","")
|
| 252 |
+
if language == "zh":
|
| 253 |
+
bert = get_bert_feature(norm_text, word2ph).to(device)#.to(dtype)
|
| 254 |
+
else:
|
| 255 |
+
bert = torch.zeros(
|
| 256 |
+
(1024, len(phones)),
|
| 257 |
+
dtype=torch.float16 if is_half == True else torch.float32,
|
| 258 |
+
).to(device)
|
| 259 |
+
|
| 260 |
+
return bert
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
splits = {",", "。", "?", "!", ",", ".", "?", "!", "~", ":", ":", "—", "…", }
|
| 264 |
+
|
| 265 |
+
def split(todo_text):
|
| 266 |
+
todo_text = todo_text.replace("……", "。").replace("——", ",")
|
| 267 |
+
if todo_text[-1] not in splits:
|
| 268 |
+
todo_text += "。"
|
| 269 |
+
i_split_head = i_split_tail = 0
|
| 270 |
+
len_text = len(todo_text)
|
| 271 |
+
todo_texts = []
|
| 272 |
+
while 1:
|
| 273 |
+
if i_split_head >= len_text:
|
| 274 |
+
break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
|
| 275 |
+
if todo_text[i_split_head] in splits:
|
| 276 |
+
i_split_head += 1
|
| 277 |
+
todo_texts.append(todo_text[i_split_tail:i_split_head])
|
| 278 |
+
i_split_tail = i_split_head
|
| 279 |
+
else:
|
| 280 |
+
i_split_head += 1
|
| 281 |
+
return todo_texts
|
| 282 |
+
|
| 283 |
+
def custom_sort_key(s):
|
| 284 |
+
# 使用正则表达式提取字符串中的数字部分和非数字部分
|
| 285 |
+
parts = re.split('(\d+)', s)
|
| 286 |
+
# 将数字部分转换为整数,非数字部分保持不变
|
| 287 |
+
parts = [int(part) if part.isdigit() else part for part in parts]
|
| 288 |
+
return parts
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def change_choices():
|
| 292 |
+
SoVITS_names, GPT_names = get_weights_names()
|
| 293 |
+
return {"choices": sorted(SoVITS_names, key=custom_sort_key), "__type__": "update"}, {"choices": sorted(GPT_names, key=custom_sort_key), "__type__": "update"}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
pretrained_sovits_name = "GPT_SoVITS/pretrained_models/s2G488k.pth"
|
| 297 |
+
pretrained_gpt_name = "GPT_SoVITS/pretrained_models/s1bert25hz-2kh-longer-epoch=68e-step=50232.ckpt"
|
| 298 |
+
SoVITS_weight_root = "SoVITS_weights"
|
| 299 |
+
GPT_weight_root = "GPT_weights"
|
| 300 |
+
os.makedirs(SoVITS_weight_root, exist_ok=True)
|
| 301 |
+
os.makedirs(GPT_weight_root, exist_ok=True)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def get_weights_names():
|
| 305 |
+
SoVITS_names = [pretrained_sovits_name]
|
| 306 |
+
for name in os.listdir(SoVITS_weight_root):
|
| 307 |
+
if name.endswith(".pth"): SoVITS_names.append("%s/%s" % (SoVITS_weight_root, name))
|
| 308 |
+
GPT_names = [pretrained_gpt_name]
|
| 309 |
+
for name in os.listdir(GPT_weight_root):
|
| 310 |
+
if name.endswith(".ckpt"): GPT_names.append("%s/%s" % (GPT_weight_root, name))
|
| 311 |
+
return SoVITS_names, GPT_names
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
SoVITS_names, GPT_names = get_weights_names()
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@torch.no_grad()
|
| 318 |
+
def get_code_from_ssl(ssl):
|
| 319 |
+
ssl = vq_model.ssl_proj(ssl)
|
| 320 |
+
quantized, codes, commit_loss, quantized_list = vq_model.quantizer(ssl)
|
| 321 |
+
# print(codes.shape, codes.dtype) # [n_q, B, T]
|
| 322 |
+
return codes.transpose(0, 1) # [B, n_q, T]
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@torch.no_grad()
|
| 326 |
+
def get_code_from_wav(wav_path):
|
| 327 |
+
wav16k, sr = librosa.load(wav_path, sr=16000)
|
| 328 |
+
if (wav16k.shape[0] > 160000 or wav16k.shape[0] < 48000):
|
| 329 |
+
# raise OSError(i18n("参考音频在3~10秒范围外,请更换!"))
|
| 330 |
+
warn(i18n("参考音频在3~10秒范围外,请更换!"))
|
| 331 |
+
wav16k = torch.from_numpy(wav16k)
|
| 332 |
+
if is_half == True:
|
| 333 |
+
wav16k = wav16k.half().to(device)
|
| 334 |
+
else:
|
| 335 |
+
wav16k = wav16k.to(device)
|
| 336 |
+
ssl_content = ssl_model.model(wav16k.unsqueeze(0))[
|
| 337 |
+
"last_hidden_state"
|
| 338 |
+
].transpose(
|
| 339 |
+
1, 2
|
| 340 |
+
) # .float()
|
| 341 |
+
codes = get_code_from_ssl(ssl_content) # [B, n_q, T]
|
| 342 |
+
|
| 343 |
+
prompt_semantic = codes[0, 0]
|
| 344 |
+
return prompt_semantic
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def splite_en_inf(sentence, language):
|
| 348 |
+
pattern = re.compile(r'[a-zA-Z ]+')
|
| 349 |
+
textlist = []
|
| 350 |
+
langlist = []
|
| 351 |
+
pos = 0
|
| 352 |
+
for match in pattern.finditer(sentence):
|
| 353 |
+
start, end = match.span()
|
| 354 |
+
if start > pos:
|
| 355 |
+
textlist.append(sentence[pos:start])
|
| 356 |
+
langlist.append(language)
|
| 357 |
+
textlist.append(sentence[start:end])
|
| 358 |
+
langlist.append("en")
|
| 359 |
+
pos = end
|
| 360 |
+
if pos < len(sentence):
|
| 361 |
+
textlist.append(sentence[pos:])
|
| 362 |
+
langlist.append(language)
|
| 363 |
+
# Merge punctuation into previous word
|
| 364 |
+
for i in range(len(textlist)-1, 0, -1):
|
| 365 |
+
if re.match(r'^[\W_]+$', textlist[i]):
|
| 366 |
+
textlist[i-1] += textlist[i]
|
| 367 |
+
del textlist[i]
|
| 368 |
+
del langlist[i]
|
| 369 |
+
# Merge consecutive words with the same language tag
|
| 370 |
+
i = 0
|
| 371 |
+
while i < len(langlist) - 1:
|
| 372 |
+
if langlist[i] == langlist[i+1]:
|
| 373 |
+
textlist[i] += textlist[i+1]
|
| 374 |
+
del textlist[i+1]
|
| 375 |
+
del langlist[i+1]
|
| 376 |
+
else:
|
| 377 |
+
i += 1
|
| 378 |
+
|
| 379 |
+
return textlist, langlist
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def nonen_clean_text_inf(text, language):
|
| 383 |
+
if(language!="auto"):
|
| 384 |
+
textlist, langlist = splite_en_inf(text, language)
|
| 385 |
+
else:
|
| 386 |
+
textlist=[]
|
| 387 |
+
langlist=[]
|
| 388 |
+
for tmp in LangSegment.getTexts(text):
|
| 389 |
+
langlist.append(tmp["lang"])
|
| 390 |
+
textlist.append(tmp["text"])
|
| 391 |
+
phones_list = []
|
| 392 |
+
word2ph_list = []
|
| 393 |
+
norm_text_list = []
|
| 394 |
+
for i in range(len(textlist)):
|
| 395 |
+
lang = langlist[i]
|
| 396 |
+
phones, word2ph, norm_text = clean_text_inf(textlist[i], lang)
|
| 397 |
+
phones_list.append(phones)
|
| 398 |
+
if lang == "zh":
|
| 399 |
+
word2ph_list.append(word2ph)
|
| 400 |
+
norm_text_list.append(norm_text)
|
| 401 |
+
print(word2ph_list)
|
| 402 |
+
phones = sum(phones_list, [])
|
| 403 |
+
word2ph = sum(word2ph_list, [])
|
| 404 |
+
norm_text = ' '.join(norm_text_list)
|
| 405 |
+
|
| 406 |
+
return phones, word2ph, norm_text
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def get_cleaned_text_final(text,language):
|
| 410 |
+
if language in {"en","all_zh","all_ja"}:
|
| 411 |
+
phones, word2ph, norm_text = clean_text_inf(text, language)
|
| 412 |
+
elif language in {"zh", "ja","auto"}:
|
| 413 |
+
phones, word2ph, norm_text = nonen_clean_text_inf(text, language)
|
| 414 |
+
return phones, word2ph, norm_text
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
@torch.no_grad()
|
| 418 |
+
def vc_main(wav_path, text, language, prompt_wav, noise_scale=0.5):
|
| 419 |
+
""" Voice Conversion
|
| 420 |
+
wav_path: 待变声的源音频
|
| 421 |
+
text: 对应文本
|
| 422 |
+
language: 对应语言
|
| 423 |
+
prompt_wav: 目标人声
|
| 424 |
+
"""
|
| 425 |
+
language = dict_language[language]
|
| 426 |
+
|
| 427 |
+
phones, word2ph, norm_text = get_cleaned_text_final(text, language)
|
| 428 |
+
|
| 429 |
+
spec = get_spepc(hps, prompt_wav)
|
| 430 |
+
codes = get_code_from_wav(wav_path)[None, None] # 必须是 3D, [n_q, B, T]
|
| 431 |
+
ge = vq_model.ref_enc(spec) # [B, D, T/1]
|
| 432 |
+
quantized = vq_model.quantizer.decode(codes) # [B, D, T]
|
| 433 |
+
if hps.model.semantic_frame_rate == "25hz":
|
| 434 |
+
quantized = F.interpolate(
|
| 435 |
+
quantized, size=int(quantized.shape[-1] * 2), mode="nearest"
|
| 436 |
+
)
|
| 437 |
+
_, m_p, logs_p, y_mask = vq_model.enc_p(
|
| 438 |
+
quantized, torch.LongTensor([quantized.shape[-1]]),
|
| 439 |
+
torch.LongTensor(phones)[None], torch.LongTensor([len(phones)]), ge
|
| 440 |
+
)
|
| 441 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
| 442 |
+
z = vq_model.flow(z_p, y_mask, g=ge, reverse=True)
|
| 443 |
+
o = vq_model.dec((z * y_mask)[:, :, :], g=ge) # [B, D=1, T], torch.float32 (-1, 1)
|
| 444 |
+
audio = o.detach().cpu().numpy()[0, 0]
|
| 445 |
+
max_audio = np.abs(audio).max() # 简单防止16bit爆音
|
| 446 |
+
if max_audio > 1:
|
| 447 |
+
audio /= max_audio
|
| 448 |
+
yield hps.data.sampling_rate, (audio * 32768).astype(np.int16)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
with gr.Blocks(title="GPT-SoVITS-VC WebUI") as app:
|
| 452 |
+
|
| 453 |
+
gr.Markdown(
|
| 454 |
+
value=i18n("本软件以MIT协议开源, 作者不对软件具备任何控制力, 使用软件者、传播软件导出的声音者自负全责. <br>如不认可该条款, 则不能使用或引用软件包内任何代码和文件. 详见根目录<b>LICENSE</b>.")
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
with gr.Group():
|
| 458 |
+
gr.Markdown(value=i18n("模型切换"))
|
| 459 |
+
|
| 460 |
+
with gr.Row():
|
| 461 |
+
GPT_dropdown = gr.Dropdown(label=i18n("GPT模型列表"), choices=sorted(GPT_names, key=custom_sort_key), value=gpt_path, interactive=True)
|
| 462 |
+
SoVITS_dropdown = gr.Dropdown(label=i18n("SoVITS模型列表"), choices=sorted(SoVITS_names, key=custom_sort_key), value=sovits_path, interactive=True)
|
| 463 |
+
refresh_button = gr.Button(i18n("刷新模型路径"), variant="primary")
|
| 464 |
+
refresh_button.click(fn=change_choices, inputs=[], outputs=[SoVITS_dropdown, GPT_dropdown])
|
| 465 |
+
SoVITS_dropdown.change(change_sovits_weights, [SoVITS_dropdown], [])
|
| 466 |
+
GPT_dropdown.change(change_gpt_weights, [GPT_dropdown], [])
|
| 467 |
+
|
| 468 |
+
gr.Markdown(value=i18n("* 请上传目标音色音频,要求说话人单一,声音干净"))
|
| 469 |
+
with gr.Row():
|
| 470 |
+
inp_ref = gr.Audio(label=i18n("请上传 3~10 秒内参考音频,超过会报警!"), type="filepath")
|
| 471 |
+
|
| 472 |
+
gr.Markdown(value=i18n("* 请填写需要变声/转换的源音频,以及对应文本"))
|
| 473 |
+
with gr.Row():
|
| 474 |
+
src_audio = gr.Audio(label=i18n('源音频'), type='filepath')
|
| 475 |
+
text = gr.Textbox(label=i18n("源音频对应文本"), value="")
|
| 476 |
+
text_language = gr.Dropdown(
|
| 477 |
+
label=i18n("文本语种"), choices=[i18n("中文"), i18n("英文"), i18n("日文"), i18n("中英混合"), i18n("日英混合"), i18n("多语种混合")], value=i18n("中文")
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
inference_button = gr.Button(i18n("合成语音"), variant="primary")
|
| 481 |
+
output = gr.Audio(label=i18n("变声后"))
|
| 482 |
+
|
| 483 |
+
inference_button.click(
|
| 484 |
+
vc_main,
|
| 485 |
+
[src_audio, text, text_language, inp_ref],
|
| 486 |
+
[output],
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
app.queue().launch(
|
| 490 |
+
share=False,
|
| 491 |
+
show_error=True,
|
| 492 |
+
)
|