Update webUI.py

This commit is contained in:
umoubuton 2023-06-09 18:57:22 +08:00 committed by GitHub
parent 4551c16634
commit a9f0d25273
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 96 additions and 28 deletions

124
webUI.py
View File

@ -22,6 +22,7 @@ import time
import traceback
from itertools import chain
from utils import mix_model
from compress_model import removeOptimizer
logging.getLogger('numba').setLevel(logging.WARNING)
logging.getLogger('markdown_it').setLevel(logging.WARNING)
@ -74,18 +75,38 @@ def updata_mix_info(files):
if debug: traceback.print_exc()
raise gr.Error(e)
def modelAnalysis(model_path,config_path,cluster_model_path,device,enhance):
def modelAnalysis(model_path,config_path,cluster_model_path,device,enhance,diff_model_path,diff_config_path,only_diffusion,use_spk_mix):
global model
try:
device = cuda[device] if "CUDA" in device else device
model = Svc(model_path.name, config_path.name, device=device if device!="Auto" else None, cluster_model_path = cluster_model_path.name if cluster_model_path != None else "",nsf_hifigan_enhance=enhance)
cluster_filepath = os.path.split(cluster_model_path.name) if cluster_model_path is not None else "no_cluster"
fr = ".pkl" in cluster_filepath[1]
#model = Svc(model_path.name, config_path.name, device=device if device!="Auto" else None, cluster_model_path = cluster_model_path.name if cluster_model_path != None else "",nsf_hifigan_enhance=enhance)
model = Svc(model_path.name,
config_path.name,
device=device if device != "Auto" else None,
cluster_model_path = cluster_model_path.name if cluster_model_path is not None else "",
nsf_hifigan_enhance=enhance,
diffusion_model_path = diff_model_path.name if diff_model_path is not None else "",
diffusion_config_path = diff_config_path.name if diff_config_path is not None else "",
shallow_diffusion = True if diff_model_path is not None else False,
only_diffusion = only_diffusion,
spk_mix_enable = use_spk_mix,
feature_retrieval = fr
)
spks = list(model.spk2id.keys())
device_name = torch.cuda.get_device_properties(model.dev).name if "cuda" in str(model.dev) else str(model.dev)
msg = f"成功加载模型到设备{device_name}\n"
if cluster_model_path is None:
msg += "未加载聚类模型\n"
msg += "未加载聚类模型或特征检索模型\n"
elif fr:
msg += f"特征检索模型{cluster_filepath[1]}加载成功\n"
else:
msg += f"聚类模型{cluster_model_path.name}加载成功\n"
msg += f"聚类模型{cluster_filepath[1]}加载成功\n"
if diff_model_path is None:
msg += "未加载扩散模型\n"
else:
msg += f"扩散模型{diff_model_path.name}加载成功\n"
msg += "当前模型的可用音色:\n"
for i in spks:
msg += i + " "
@ -105,39 +126,55 @@ def modelUnload():
torch.cuda.empty_cache()
return sid.update(choices = [],value=""),"模型卸载完毕!"
def vc_fn(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,f0_predictor,enhancer_adaptive_key,cr_threshold):
def vc_fn(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,f0_predictor,enhancer_adaptive_key,cr_threshold,k_step,use_spk_mix,second_encoding,loudness_envelope_adjustment):
global model
try:
if input_audio is None:
raise gr.Error("你需要上传音频")
return "You need to upload an audio", None
if model is None:
raise gr.Error("你需要指定模型")
return "You need to upload an model", None
print(input_audio)
sampling_rate, audio = input_audio
# print(audio.shape,sampling_rate)
print(audio.shape,sampling_rate)
audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
print(audio.dtype)
if len(audio.shape) > 1:
audio = librosa.to_mono(audio.transpose(1, 0))
temp_path = "temp.wav"
soundfile.write(temp_path, audio, sampling_rate, format="wav")
_audio = model.slice_inference(temp_path, sid, vc_transform, slice_db, cluster_ratio, auto_f0, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,f0_predictor,enhancer_adaptive_key,cr_threshold)
_audio = model.slice_inference(
temp_path,
sid,
vc_transform,
slice_db,
cluster_ratio,
auto_f0,
noise_scale,
pad_seconds,
cl_num,
lg_num,
lgr_num,
f0_predictor,
enhancer_adaptive_key,
cr_threshold,
k_step,
use_spk_mix,
second_encoding,
loudness_envelope_adjustment,
)
model.clear_empty()
os.remove(temp_path)
#构建保存文件的路径并保存到results文件夹内
try:
timestamp = str(int(time.time()))
filename = sid + "_" + timestamp + ".wav"
output_file = os.path.join("./results", filename)
soundfile.write(output_file, _audio, model.target_sample, format="wav")
return f"推理成功音频文件保存为results/{filename}", (model.target_sample, _audio)
except Exception as e:
if debug: traceback.print_exc()
return f"文件保存失败,请手动保存", (model.target_sample, _audio)
timestamp = str(int(time.time()))
if not os.path.exists("results"):
os.makedirs("results")
output_file = os.path.join("results", sid + "_" + timestamp + ".wav")
soundfile.write(output_file, _audio, model.target_sample, format="wav")
return "Success", output_file
except Exception as e:
if debug: traceback.print_exc()
raise gr.Error(e)
def tts_func(_text,_rate,_voice):
#使用edge-tts把文字转成音频
# voice = "zh-CN-XiaoyiNeural"#女性,较高音
@ -189,6 +226,17 @@ def vc_fn2(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, nois
os.remove(save_path2)
return a,b
def model_compression(_model):
if _model == "":
return "请先选择要压缩的模型"
else:
model_path = os.path.split(_model.name)
filename, extension = os.path.splitext(model_path[1])
output_model_name = f"{filename}_compressed{extension}"
output_path = os.path.join(os.getcwd(), output_model_name)
removeOptimizer(_model.name, output_path)
return f"模型已成功被保存在了{output_path}"
def debug_change():
global debug
debug = debug_button.value
@ -210,11 +258,16 @@ with gr.Blocks(
gr.Markdown(value="""
<font size=2> 模型设置</font>
""")
model_path = gr.File(label="选择模型文件")
config_path = gr.File(label="选择配置文件")
cluster_model_path = gr.File(label="选择聚类模型文件(没有可以不选)")
device = gr.Dropdown(label="推理设备默认为自动选择CPU和GPU", choices=["Auto",*cuda.keys(),"CPU"], value="Auto")
with gr.Row():
model_path = gr.File(label="选择模型文件")
config_path = gr.File(label="选择配置文件")
with gr.Row():
diff_model_path = gr.File(label="选择扩散模型文件")
diff_config_path = gr.File(label="选择扩散模型配置文件")
cluster_model_path = gr.File(label="选择聚类模型或特征检索文件(没有可以不选)")
device = gr.Dropdown(label="推理设备默认为自动选择CPU和GPU", choices=["Auto",*cuda.keys(),"cpu"], value="Auto")
enhance = gr.Checkbox(label="是否使用NSF_HIFIGAN增强,该选项对部分训练集少的模型有一定的音质增强效果,但是对训练好的模型有反面效果,默认关闭", value=False)
only_diffusion = gr.Checkbox(label="是否使用全扩散推理开启后将不使用So-VITS模型仅使用扩散模型进行完整扩散推理默认关闭", value=False)
with gr.Column():
gr.Markdown(value="""
<font size=3>左侧文件全部选择完毕后(全部文件模块显示download)点击加载模型进行解析</font>
@ -233,9 +286,10 @@ with gr.Blocks(
auto_f0 = gr.Checkbox(label="自动f0预测配合聚类模型f0预测效果更好,会导致变调功能失效(仅限转换语音,歌声勾选此项会究极跑调)", value=False)
f0_predictor = gr.Dropdown(label="选择F0预测器,可选择crepe,pm,dio,harvest,默认为pm(注意crepe为原F0使用均值滤波器)", choices=["pm","dio","harvest","crepe"], value="pm")
vc_transform = gr.Number(label="变调整数可以正负半音数量升高八度就是12", value=0)
cluster_ratio = gr.Number(label="聚类模型混合比例0-1之间0即不启用聚类。使用聚类模型能提升音色相似度但会导致咬字下降如果使用建议0.5左右)", value=0)
cluster_ratio = gr.Number(label="聚类模型/特征检索混合比例0-1之间0即不启用聚类/特征检索。使用聚类/特征检索能提升音色相似度但会导致咬字下降如果使用建议0.5左右)", value=0)
slice_db = gr.Number(label="切片阈值", value=-40)
noise_scale = gr.Number(label="noise_scale 建议不要动,会影响音质,玄学参数", value=0.4)
k_step = gr.Slider(label="浅扩散步数,只有使用了扩散模型才有效,步数越大越接近扩散模型的结果", value=100, minimum = 1, maximum = 1000)
with gr.Column():
pad_seconds = gr.Number(label="推理音频pad秒数由于未知原因开头结尾会有异响pad一小段静音段后就不会出现", value=0.5)
cl_num = gr.Number(label="音频自动切片0为不切片单位为秒(s)", value=0)
@ -243,6 +297,9 @@ with gr.Blocks(
lgr_num = gr.Number(label="自动音频切片后需要舍弃每段切片的头尾。该参数设置交叉长度保留的比例范围0-1,左开右闭", value=0.75)
enhancer_adaptive_key = gr.Number(label="使增强器适应更高的音域(单位为半音数)|默认为0", value=0)
cr_threshold = gr.Number(label="F0过滤阈值只有启动crepe时有效. 数值范围从0-1. 降低该值可减少跑调概率,但会增加哑音", value=0.05)
loudness_envelope_adjustment = gr.Number(label="输入源响度包络替换输出响度包络融合比例越靠近1越使用输出响度包络", value = 0)
second_encoding = gr.Checkbox(label = "二次编码,浅扩散前会对原始音频进行二次编码,玄学选项,效果时好时差,默认关闭", value=False)
use_spk_mix = gr.Checkbox(label = "动态声线融合", value = False, interactive = False)
with gr.Tabs():
with gr.TabItem("音频转音频"):
vc_input3 = gr.Audio(label="选择音频")
@ -278,7 +335,7 @@ with gr.Blocks(
</font>
""")
mix_model_path = gr.Files(label="选择需要混合模型文件")
mix_model_upload_button = gr.UploadButton("选择/追加需要混合模型文件", file_count="multiple", variant="primary")
mix_model_upload_button = gr.UploadButton("选择/追加需要混合模型文件", file_count="multiple")
mix_model_output1 = gr.Textbox(
label="混合比例调整,单位/%",
interactive = True
@ -291,6 +348,17 @@ with gr.Blocks(
mix_model_path.change(updata_mix_info,[mix_model_path],[mix_model_output1])
mix_model_upload_button.upload(upload_mix_append_file, [mix_model_upload_button,mix_model_path], [mix_model_path,mix_model_output1])
mix_submit.click(mix_submit_click, [mix_model_output1,mix_mode], [mix_model_output2])
with gr.TabItem("模型压缩工具"):
gr.Markdown(value="""
该工具可以实现对模型的体积压缩**不影响模型推理功能**的情况下将原本约600M的So-VITS模型压缩至约200M, 大大减少了硬盘的压力
**注意压缩后的模型将无法继续训练请在确认封炉后再压缩**
""")
model_to_compress = gr.File(label="模型上传")
compress_model_btn = gr.Button("压缩模型", variant="primary")
compress_model_output = gr.Textbox(label="输出信息", value="")
compress_model_btn.click(model_compression, [model_to_compress], [compress_model_output])
with gr.Tabs():
@ -300,10 +368,10 @@ with gr.Blocks(
<font size=2> WebUI设置</font>
""")
debug_button = gr.Checkbox(label="Debug模式如果向社区反馈BUG需要打开打开后控制台可以显示具体错误提示", value=debug)
vc_submit.click(vc_fn, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,f0_predictor,enhancer_adaptive_key,cr_threshold], [vc_output1, vc_output2])
vc_submit.click(vc_fn, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,f0_predictor,enhancer_adaptive_key,cr_threshold,k_step,use_spk_mix,second_encoding,loudness_envelope_adjustment], [vc_output1, vc_output2])
vc_submit2.click(vc_fn2, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,text2tts,tts_rate,tts_voice,f0_predictor,enhancer_adaptive_key,cr_threshold], [vc_output1, vc_output2])
debug_button.change(debug_change,[],[])
model_load_button.click(modelAnalysis,[model_path,config_path,cluster_model_path,device,enhance],[sid,sid_output])
model_load_button.click(modelAnalysis,[model_path,config_path,cluster_model_path,device,enhance,diff_model_path,diff_config_path,only_diffusion,use_spk_mix],[sid,sid_output])
model_unload_button.click(modelUnload,[],[sid,sid_output])
app.launch()