rinflan commited on
Commit
918c232
1 Parent(s): 8d0141d

Upload infer-web.py

Browse files
Files changed (1) hide show
  1. infer-web.py +631 -0
infer-web.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from multiprocessing import cpu_count
2
+ import threading
3
+ from time import sleep
4
+ from subprocess import Popen,PIPE,run as runn
5
+ from time import sleep
6
+ import torch, pdb, os,traceback,sys,warnings,shutil,numpy as np,faiss
7
+ #判断是否有能用来训练和加速推理的N卡
8
+ ncpu=cpu_count()
9
+ ngpu=torch.cuda.device_count()
10
+ gpu_infos=[]
11
+ if(torch.cuda.is_available()==False or ngpu==0):if_gpu_ok=False
12
+ else:
13
+ if_gpu_ok = False
14
+ for i in range(ngpu):
15
+ gpu_name=torch.cuda.get_device_name(i)
16
+ if("16"in gpu_name or "MX"in gpu_name):continue
17
+ if("10"in gpu_name or "20"in gpu_name or "30"in gpu_name or "40"in gpu_name or "A50"in gpu_name.upper() or "70"in gpu_name or "80"in gpu_name or "90"in gpu_name or "M4"in gpu_name or "T4"in gpu_name or "TITAN"in gpu_name.upper()):#A10#A100#V100#A40#P40#M40#K80
18
+ if_gpu_ok=True#至少有一张能用的N卡
19
+ gpu_infos.append("%s\t%s"%(i,gpu_name))
20
+ gpu_info="\n".join(gpu_infos)if if_gpu_ok==True and len(gpu_infos)>0 else "很遗憾您这没有能用的显卡来支持您训练"
21
+ gpus="-".join([i[0]for i in gpu_infos])
22
+ now_dir=os.getcwd()
23
+ sys.path.append(now_dir)
24
+ tmp=os.path.join(now_dir,"TEMP")
25
+ shutil.rmtree(tmp,ignore_errors=True)
26
+ os.makedirs(tmp,exist_ok=True)
27
+ os.makedirs(os.path.join(now_dir,"logs"),exist_ok=True)
28
+ os.makedirs(os.path.join(now_dir,"weights"),exist_ok=True)
29
+ os.environ["TEMP"]=tmp
30
+ warnings.filterwarnings("ignore")
31
+ torch.manual_seed(114514)
32
+ from infer_pack.models import SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono
33
+ from scipy.io import wavfile
34
+ from fairseq import checkpoint_utils
35
+ import gradio as gr
36
+ import librosa
37
+ import logging
38
+ from vc_infer_pipeline import VC
39
+ import soundfile as sf
40
+ from config import is_half,device,is_half
41
+ from infer_uvr5 import _audio_pre_
42
+ from my_utils import load_audio
43
+ from train.process_ckpt import show_info,change_info,merge,extract_small_model
44
+ # from trainset_preprocess_pipeline import PreProcess
45
+ logging.getLogger('numba').setLevel(logging.WARNING)
46
+
47
+ class ToolButton(gr.Button, gr.components.FormComponent):
48
+ """Small button with single emoji as text, fits inside gradio forms"""
49
+ def __init__(self, **kwargs):
50
+ super().__init__(variant="tool", **kwargs)
51
+ def get_block_name(self):
52
+ return "button"
53
+
54
+ hubert_model=None
55
+ def load_hubert():
56
+ global hubert_model
57
+ models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(["hubert_base.pt"],suffix="",)
58
+ hubert_model = models[0]
59
+ hubert_model = hubert_model.to(device)
60
+ if(is_half):hubert_model = hubert_model.half()
61
+ else:hubert_model = hubert_model.float()
62
+ hubert_model.eval()
63
+
64
+ weight_root="weights"
65
+ weight_uvr5_root="uvr5_weights"
66
+ names=[]
67
+ for name in os.listdir(weight_root):names.append(name)
68
+ uvr5_names=[]
69
+ for name in os.listdir(weight_uvr5_root):uvr5_names.append(name.replace(".pth",""))
70
+
71
+ def vc_single(sid,input_audio,f0_up_key,f0_file,f0_method,file_index,file_big_npy,index_rate):#spk_item, input_audio0, vc_transform0,f0_file,f0method0
72
+ global tgt_sr,net_g,vc,hubert_model
73
+ if input_audio is None:return "You need to upload an audio", None
74
+ f0_up_key = int(f0_up_key)
75
+ try:
76
+ audio=load_audio(input_audio,16000)
77
+ times = [0, 0, 0]
78
+ if(hubert_model==None):load_hubert()
79
+ if_f0 = cpt.get("f0", 1)
80
+ audio_opt=vc.pipeline(hubert_model,net_g,sid,audio,times,f0_up_key,f0_method,file_index,file_big_npy,index_rate,if_f0,f0_file=f0_file)
81
+ print(times)
82
+ return "Success", (tgt_sr, audio_opt)
83
+ except:
84
+ info=traceback.format_exc()
85
+ print(info)
86
+ return info,(None,None)
87
+
88
+ def vc_multi(sid,dir_path,opt_root,paths,f0_up_key,f0_method,file_index,file_big_npy,index_rate):
89
+ try:
90
+ dir_path=dir_path.strip(" ")#防止小白拷路径头尾带了空格
91
+ opt_root=opt_root.strip(" ")
92
+ os.makedirs(opt_root, exist_ok=True)
93
+ try:
94
+ if(dir_path!=""):paths=[os.path.join(dir_path,name)for name in os.listdir(dir_path)]
95
+ else:paths=[path.name for path in paths]
96
+ except:
97
+ traceback.print_exc()
98
+ paths = [path.name for path in paths]
99
+ infos=[]
100
+ for path in paths:
101
+ info,opt=vc_single(sid,path,f0_up_key,None,f0_method,file_index,file_big_npy,index_rate)
102
+ if(info=="Success"):
103
+ try:
104
+ tgt_sr,audio_opt=opt
105
+ wavfile.write("%s/%s" % (opt_root, os.path.basename(path)), tgt_sr, audio_opt)
106
+ except:
107
+ info=traceback.format_exc()
108
+ infos.append("%s->%s"%(os.path.basename(path),info))
109
+ yield "\n".join(infos)
110
+ yield "\n".join(infos)
111
+ except:
112
+ yield traceback.format_exc()
113
+
114
+ def uvr(model_name,inp_root,save_root_vocal,paths,save_root_ins):
115
+ infos = []
116
+ try:
117
+ inp_root = inp_root.strip(" ").strip("\n")
118
+ save_root_vocal = save_root_vocal.strip(" ").strip("\n")
119
+ save_root_ins = save_root_ins.strip(" ").strip("\n")
120
+ pre_fun = _audio_pre_(model_path=os.path.join(weight_uvr5_root,model_name+".pth"), device=device, is_half=is_half)
121
+ if (inp_root != ""):paths = [os.path.join(inp_root, name) for name in os.listdir(inp_root)]
122
+ else:paths = [path.name for path in paths]
123
+ for name in paths:
124
+ inp_path=os.path.join(inp_root,name)
125
+ try:
126
+ pre_fun._path_audio_(inp_path , save_root_ins,save_root_vocal)
127
+ infos.append("%s->Success"%(os.path.basename(inp_path)))
128
+ yield "\n".join(infos)
129
+ except:
130
+ infos.append("%s->%s" % (os.path.basename(inp_path),traceback.format_exc()))
131
+ yield "\n".join(infos)
132
+ except:
133
+ infos.append(traceback.format_exc())
134
+ yield "\n".join(infos)
135
+ finally:
136
+ try:
137
+ del pre_fun.model
138
+ del pre_fun
139
+ except:
140
+ traceback.print_exc()
141
+ print("clean_empty_cache")
142
+ torch.cuda.empty_cache()
143
+ yield "\n".join(infos)
144
+
145
+ #一个选项卡全局只能有一个音色
146
+ def get_vc(sid):
147
+ global n_spk,tgt_sr,net_g,vc,cpt
148
+ if(sid==""):
149
+ global hubert_model
150
+ print("clean_empty_cache")
151
+ del net_g, n_spk, vc, hubert_model,tgt_sr#,cpt
152
+ hubert_model = net_g=n_spk=vc=hubert_model=tgt_sr=None
153
+ torch.cuda.empty_cache()
154
+ ###楼下不这么折腾清理不干净
155
+ if_f0 = cpt.get("f0", 1)
156
+ if (if_f0 == 1):
157
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=is_half)
158
+ else:
159
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
160
+ del net_g,cpt
161
+ torch.cuda.empty_cache()
162
+ cpt=None
163
+ return {"visible": False, "__type__": "update"}
164
+ person = "%s/%s" % (weight_root, sid)
165
+ print("loading %s"%person)
166
+ cpt = torch.load(person, map_location="cpu")
167
+ tgt_sr = cpt["config"][-1]
168
+ cpt["config"][-3]=cpt["weight"]["emb_g.weight"].shape[0]#n_spk
169
+ if_f0=cpt.get("f0",1)
170
+ if(if_f0==1):
171
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=is_half)
172
+ else:
173
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
174
+ del net_g.enc_q
175
+ print(net_g.load_state_dict(cpt["weight"], strict=False)) # 不加这一行清不干净,真奇葩
176
+ net_g.eval().to(device)
177
+ if (is_half):net_g = net_g.half()
178
+ else:net_g = net_g.float()
179
+ vc = VC(tgt_sr, device, is_half)
180
+ n_spk=cpt["config"][-3]
181
+ return {"visible": True,"maximum": n_spk, "__type__": "update"}
182
+
183
+ def change_choices():return {"choices": sorted(list(os.listdir(weight_root))), "__type__": "update"}
184
+ def clean():return {"value": "", "__type__": "update"}
185
+ def change_f0(if_f0_3,sr2):#np7, f0method8,pretrained_G14,pretrained_D15
186
+ if(if_f0_3=="是"):return {"visible": True, "__type__": "update"},{"visible": True, "__type__": "update"},"pretrained/f0G%s.pth"%sr2,"pretrained/f0D%s.pth"%sr2
187
+ return {"visible": False, "__type__": "update"}, {"visible": False, "__type__": "update"},"pretrained/G%s.pth"%sr2,"pretrained/D%s.pth"%sr2
188
+
189
+ sr_dict={
190
+ "32k":32000,
191
+ "40k":40000,
192
+ "48k":48000,
193
+ }
194
+
195
+ def if_done(done,p):
196
+ while 1:
197
+ if(p.poll()==None):sleep(0.5)
198
+ else:break
199
+ done[0]=True
200
+
201
+
202
+ def if_done_multi(done,ps):
203
+ while 1:
204
+ #poll==None代表进程未结束
205
+ #只要有一个进程未结束都不停
206
+ flag=1
207
+ for p in ps:
208
+ if(p.poll()==None):
209
+ flag = 0
210
+ sleep(0.5)
211
+ break
212
+ if(flag==1):break
213
+ done[0]=True
214
+
215
+ def preprocess_dataset(trainset_dir,exp_dir,sr,n_p=ncpu):
216
+ sr=sr_dict[sr]
217
+ os.makedirs("%s/logs/%s"%(now_dir,exp_dir),exist_ok=True)
218
+ f = open("%s/logs/%s/preprocess.log"%(now_dir,exp_dir), "w")
219
+ f.close()
220
+ cmd="runtime\python.exe trainset_preprocess_pipeline_print.py %s %s %s %s/logs/%s"%(trainset_dir,sr,n_p,now_dir,exp_dir)
221
+ print(cmd)
222
+ p = Popen(cmd, shell=True)#, stdin=PIPE, stdout=PIPE,stderr=PIPE,cwd=now_dir
223
+ ###煞笔gr,popen read都非得全跑完了再一次性读取,不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
224
+ done=[False]
225
+ threading.Thread(target=if_done,args=(done,p,)).start()
226
+ while(1):
227
+ with open("%s/logs/%s/preprocess.log"%(now_dir,exp_dir),"r")as f:yield(f.read())
228
+ sleep(1)
229
+ if(done[0]==True):break
230
+ with open("%s/logs/%s/preprocess.log"%(now_dir,exp_dir), "r")as f:log = f.read()
231
+ print(log)
232
+ yield log
233
+ #but2.click(extract_f0,[gpus6,np7,f0method8,if_f0_3,trainset_dir4],[info2])
234
+ def extract_f0_feature(gpus,n_p,f0method,if_f0,exp_dir):
235
+ gpus=gpus.split("-")#
236
+ os.makedirs("%s/logs/%s"%(now_dir,exp_dir),exist_ok=True)
237
+ f = open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir), "w")
238
+ f.close()
239
+ if(if_f0=="是"):
240
+ cmd="runtime\python.exe extract_f0_print.py %s/logs/%s %s %s"%(now_dir,exp_dir,n_p,f0method)
241
+ print(cmd)
242
+ p = Popen(cmd, shell=True,cwd=now_dir)#, stdin=PIPE, stdout=PIPE,stderr=PIPE
243
+ ###煞笔gr,popen read都非得全跑完了再一次性读取,不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
244
+ done=[False]
245
+ threading.Thread(target=if_done,args=(done,p,)).start()
246
+ while(1):
247
+ with open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir),"r")as f:yield(f.read())
248
+ sleep(1)
249
+ if(done[0]==True):break
250
+ with open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir), "r")as f:log = f.read()
251
+ print(log)
252
+ yield log
253
+ ####对不同part分别开多进程
254
+ '''
255
+ n_part=int(sys.argv[1])
256
+ i_part=int(sys.argv[2])
257
+ i_gpu=sys.argv[3]
258
+ exp_dir=sys.argv[4]
259
+ os.environ["CUDA_VISIBLE_DEVICES"]=str(i_gpu)
260
+ '''
261
+ leng=len(gpus)
262
+ ps=[]
263
+ for idx,n_g in enumerate(gpus):
264
+ cmd="runtime\python.exe extract_feature_print.py %s %s %s %s/logs/%s"%(leng,idx,n_g,now_dir,exp_dir)
265
+ print(cmd)
266
+ p = Popen(cmd, shell=True, cwd=now_dir)#, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
267
+ ps.append(p)
268
+ ###煞笔gr,popen read都非得全跑完了再一次性读取,不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
269
+ done = [False]
270
+ threading.Thread(target=if_done_multi, args=(done, ps,)).start()
271
+ while (1):
272
+ with open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir), "r")as f:yield (f.read())
273
+ sleep(1)
274
+ if (done[0] == True): break
275
+ with open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir), "r")as f:log = f.read()
276
+ print(log)
277
+ yield log
278
+ def change_sr2(sr2,if_f0_3):
279
+ if(if_f0_3=="是"):return "pretrained/f0G%s.pth"%sr2,"pretrained/f0D%s.pth"%sr2
280
+ else:return "pretrained/G%s.pth"%sr2,"pretrained/D%s.pth"%sr2
281
+ #but3.click(click_train,[exp_dir1,sr2,if_f0_3,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16])
282
+ def click_train(exp_dir1,sr2,if_f0_3,spk_id5,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16,if_cache_gpu17):
283
+ #生成filelist
284
+ exp_dir="%s/logs/%s"%(now_dir,exp_dir1)
285
+ os.makedirs(exp_dir,exist_ok=True)
286
+ gt_wavs_dir="%s/0_gt_wavs"%(exp_dir)
287
+ co256_dir="%s/3_feature256"%(exp_dir)
288
+ if(if_f0_3=="是"):
289
+ f0_dir = "%s/2a_f0" % (exp_dir)
290
+ f0nsf_dir="%s/2b-f0nsf"%(exp_dir)
291
+ names=set([name.split(".")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(".")[0]for name in os.listdir(co256_dir)])&set([name.split(".")[0]for name in os.listdir(f0_dir)])&set([name.split(".")[0]for name in os.listdir(f0nsf_dir)])
292
+ else:
293
+ names=set([name.split(".")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(".")[0]for name in os.listdir(co256_dir)])
294
+ opt=[]
295
+ for name in names:
296
+ if (if_f0_3 == "是"):
297
+ opt.append("%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"%(gt_wavs_dir.replace("\\","\\\\"),name,co256_dir.replace("\\","\\\\"),name,f0_dir.replace("\\","\\\\"),name,f0nsf_dir.replace("\\","\\\\"),name,spk_id5))
298
+ else:
299
+ opt.append("%s/%s.wav|%s/%s.npy|%s"%(gt_wavs_dir.replace("\\","\\\\"),name,co256_dir.replace("\\","\\\\"),name,spk_id5))
300
+ with open("%s/filelist.txt"%exp_dir,"w")as f:f.write("\n".join(opt))
301
+ print("write filelist done")
302
+ #生成config#无需生成config
303
+ # cmd = "runtime\python.exe train_nsf_sim_cache_sid_load_pretrain.py -e mi-test -sr 40k -f0 1 -bs 4 -g 0 -te 10 -se 5 -pg pretrained/f0G40k.pth -pd pretrained/f0D40k.pth -l 1 -c 0"
304
+ cmd = "runtime\python.exe train_nsf_sim_cache_sid_load_pretrain.py -e %s -sr %s -f0 %s -bs %s -g %s -te %s -se %s -pg %s -pd %s -l %s -c %s" % (exp_dir1,sr2,1 if if_f0_3=="是"else 0,batch_size12,gpus16,total_epoch11,save_epoch10,pretrained_G14,pretrained_D15,1 if if_save_latest13=="是"else 0,1 if if_cache_gpu17=="是"else 0)
305
+ print(cmd)
306
+ p = Popen(cmd, shell=True, cwd=now_dir)
307
+ p.wait()
308
+ return "训练结束,您可查看控制台训练日志或实验文件夹下的train.log"
309
+ # but4.click(train_index, [exp_dir1], info3)
310
+ def train_index(exp_dir1):
311
+ exp_dir="%s/logs/%s"%(now_dir,exp_dir1)
312
+ os.makedirs(exp_dir,exist_ok=True)
313
+ feature_dir="%s/3_feature256"%(exp_dir)
314
+ if(os.path.exists(feature_dir)==False):return "请先进行特征提取!"
315
+ listdir_res=list(os.listdir(feature_dir))
316
+ if(len(listdir_res)==0):return "请先进行特征提取!"
317
+ npys = []
318
+ for name in sorted(listdir_res):
319
+ phone = np.load("%s/%s" % (feature_dir, name))
320
+ npys.append(phone)
321
+ big_npy = np.concatenate(npys, 0)
322
+ np.save("%s/total_fea.npy"%exp_dir, big_npy)
323
+ n_ivf = big_npy.shape[0] // 39
324
+ infos=[]
325
+ infos.append("%s,%s"%(big_npy.shape,n_ivf))
326
+ yield "\n".join(infos)
327
+ index = faiss.index_factory(256, "IVF%s,Flat"%n_ivf)
328
+ infos.append("training")
329
+ yield "\n".join(infos)
330
+ index_ivf = faiss.extract_index_ivf(index) #
331
+ index_ivf.nprobe = int(np.power(n_ivf,0.3))
332
+ index.train(big_npy)
333
+ faiss.write_index(index, '%s/trained_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))
334
+ infos.append("adding")
335
+ yield "\n".join(infos)
336
+ index.add(big_npy)
337
+ faiss.write_index(index, '%s/added_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))
338
+ infos.append("成功构建索引,added_IVF%s_Flat_nprobe_%s.index"%(n_ivf,index_ivf.nprobe))
339
+ yield "\n".join(infos)
340
+ #but5.click(train1key, [exp_dir1, sr2, if_f0_3, trainset_dir4, spk_id5, gpus6, np7, f0method8, save_epoch10, total_epoch11, batch_size12, if_save_latest13, pretrained_G14, pretrained_D15, gpus16, if_cache_gpu17], info3)
341
+ def train1key(exp_dir1, sr2, if_f0_3, trainset_dir4, spk_id5, gpus6, np7, f0method8, save_epoch10, total_epoch11, batch_size12, if_save_latest13, pretrained_G14, pretrained_D15, gpus16, if_cache_gpu17):
342
+ infos=[]
343
+ def get_info_str(strr):
344
+ infos.append(strr)
345
+ return "\n".join(infos)
346
+ os.makedirs("%s/logs/%s"%(now_dir,exp_dir1),exist_ok=True)
347
+ #########step1:处理数据
348
+ open("%s/logs/%s/preprocess.log"%(now_dir,exp_dir1), "w").close()
349
+ cmd="runtime\python.exe trainset_preprocess_pipeline_print.py %s %s %s %s/logs/%s"%(trainset_dir4,sr_dict[sr2],ncpu,now_dir,exp_dir1)
350
+ yield get_info_str("step1:正在处理数据")
351
+ yield get_info_str(cmd)
352
+ p = Popen(cmd, shell=True)
353
+ p.wait()
354
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir1), "r")as f: print(f.read())
355
+ #########step2a:提取音高
356
+ open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir1), "w")
357
+ if(if_f0_3=="是"):
358
+ yield get_info_str("step2a:正在提取音高")
359
+ cmd="runtime\python.exe extract_f0_print.py %s/logs/%s %s %s"%(now_dir,exp_dir1,np7,f0method8)
360
+ yield get_info_str(cmd)
361
+ p = Popen(cmd, shell=True,cwd=now_dir)
362
+ p.wait()
363
+ with open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir1), "r")as f:print(f.read())
364
+ else:yield get_info_str("step2a:无需提取音高")
365
+ #######step2b:提取特征
366
+ yield get_info_str("step2b:正在提取特征")
367
+ gpus=gpus16.split("-")
368
+ leng=len(gpus)
369
+ ps=[]
370
+ for idx,n_g in enumerate(gpus):
371
+ cmd="runtime\python.exe extract_feature_print.py %s %s %s %s/logs/%s"%(leng,idx,n_g,now_dir,exp_dir1)
372
+ yield get_info_str(cmd)
373
+ p = Popen(cmd, shell=True, cwd=now_dir)#, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
374
+ ps.append(p)
375
+ for p in ps:p.wait()
376
+ with open("%s/logs/%s/extract_f0_feature.log"%(now_dir,exp_dir1), "r")as f:print(f.read())
377
+ #######step3a:训练模型
378
+ yield get_info_str("step3a:正在训练模型")
379
+ #生成filelist
380
+ exp_dir="%s/logs/%s"%(now_dir,exp_dir1)
381
+ gt_wavs_dir="%s/0_gt_wavs"%(exp_dir)
382
+ co256_dir="%s/3_feature256"%(exp_dir)
383
+ if(if_f0_3=="是"):
384
+ f0_dir = "%s/2a_f0" % (exp_dir)
385
+ f0nsf_dir="%s/2b-f0nsf"%(exp_dir)
386
+ names=set([name.split(".")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(".")[0]for name in os.listdir(co256_dir)])&set([name.split(".")[0]for name in os.listdir(f0_dir)])&set([name.split(".")[0]for name in os.listdir(f0nsf_dir)])
387
+ else:
388
+ names=set([name.split(".")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(".")[0]for name in os.listdir(co256_dir)])
389
+ opt=[]
390
+ for name in names:
391
+ if (if_f0_3 == "是"):
392
+ opt.append("%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"%(gt_wavs_dir.replace("\\","\\\\"),name,co256_dir.replace("\\","\\\\"),name,f0_dir.replace("\\","\\\\"),name,f0nsf_dir.replace("\\","\\\\"),name,spk_id5))
393
+ else:
394
+ opt.append("%s/%s.wav|%s/%s.npy|%s"%(gt_wavs_dir.replace("\\","\\\\"),name,co256_dir.replace("\\","\\\\"),name,spk_id5))
395
+ with open("%s/filelist.txt"%exp_dir,"w")as f:f.write("\n".join(opt))
396
+ yield get_info_str("write filelist done")
397
+ cmd = "runtime\python.exe train_nsf_sim_cache_sid_load_pretrain.py -e %s -sr %s -f0 %s -bs %s -g %s -te %s -se %s -pg %s -pd %s -l %s -c %s" % (exp_dir1,sr2,1 if if_f0_3=="是"else 0,batch_size12,gpus16,total_epoch11,save_epoch10,pretrained_G14,pretrained_D15,1 if if_save_latest13=="是"else 0,1 if if_cache_gpu17=="是"else 0)
398
+ yield get_info_str(cmd)
399
+ p = Popen(cmd, shell=True, cwd=now_dir)
400
+ p.wait()
401
+ yield get_info_str("训练结束,您可查看控制台训练日志或实验文件夹下的train.log")
402
+ #######step3b:训练索引
403
+ feature_dir="%s/3_feature256"%(exp_dir)
404
+ npys = []
405
+ listdir_res=list(os.listdir(feature_dir))
406
+ for name in sorted(listdir_res):
407
+ phone = np.load("%s/%s" % (feature_dir, name))
408
+ npys.append(phone)
409
+ big_npy = np.concatenate(npys, 0)
410
+ np.save("%s/total_fea.npy"%exp_dir, big_npy)
411
+ n_ivf = big_npy.shape[0] // 39
412
+ yield get_info_str("%s,%s"%(big_npy.shape,n_ivf))
413
+ index = faiss.index_factory(256, "IVF%s,Flat"%n_ivf)
414
+ yield get_info_str("training index")
415
+ index_ivf = faiss.extract_index_ivf(index) #
416
+ index_ivf.nprobe = int(np.power(n_ivf,0.3))
417
+ index.train(big_npy)
418
+ faiss.write_index(index, '%s/trained_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))
419
+ yield get_info_str("adding index")
420
+ index.add(big_npy)
421
+ faiss.write_index(index, '%s/added_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))
422
+ yield get_info_str("成功构建索引,added_IVF%s_Flat_nprobe_%s.index"%(n_ivf,index_ivf.nprobe))
423
+ yield get_info_str("全流程结束!")
424
+
425
+ # ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])
426
+ def change_info_(ckpt_path):
427
+ if(os.path.exists(ckpt_path.replace(os.path.basename(ckpt_path),"train.log"))==False):return {"__type__": "update"},{"__type__": "update"}
428
+ try:
429
+ with open(ckpt_path.replace(os.path.basename(ckpt_path),"train.log"),"r")as f:
430
+ info=eval(f.read().strip("\n").split("\n")[0].split("\t")[-1])
431
+ sr,f0=info["sample_rate"],info["if_f0"]
432
+ return sr,str(f0)
433
+ except:
434
+ traceback.print_exc()
435
+ return {"__type__": "update"}, {"__type__": "update"}
436
+
437
+
438
+ with gr.Blocks() as app:
439
+ gr.Markdown(value="""
440
+ 本软件以MIT协议开源,作者不对软件具备任何控制力,使用软件者、传播软件导出的声音者自负全责。<br>
441
+ 如不认可该条款,则不能使用或引用软件包内任何代码和文件。详见根目录"使用需遵守的协议-LICENSE.txt"。
442
+ """)
443
+ with gr.Tabs():
444
+ with gr.TabItem("模型推理"):
445
+ with gr.Row():
446
+ sid0 = gr.Dropdown(label="推理音色", choices=names)
447
+ refresh_button = gr.Button("刷新音色列表", variant="primary")
448
+ refresh_button.click(
449
+ fn=change_choices,
450
+ inputs=[],
451
+ outputs=[sid0]
452
+ )
453
+ clean_button = gr.Button("卸载音色省显存", variant="primary")
454
+ spk_item = gr.Slider(minimum=0, maximum=2333, step=1, label='请选择说话人id', value=0, visible=False, interactive=True)
455
+ clean_button.click(
456
+ fn=clean,
457
+ inputs=[],
458
+ outputs=[sid0]
459
+ )
460
+ sid0.change(
461
+ fn=get_vc,
462
+ inputs=[sid0],
463
+ outputs=[spk_item],
464
+ )
465
+ with gr.Group():
466
+ gr.Markdown(value="""
467
+ 男转女推荐+12key,女转男推荐-12key,如果音域爆炸导致音色失真也可以自己调整到合适音域。
468
+ """)
469
+ with gr.Row():
470
+ with gr.Column():
471
+ vc_transform0 = gr.Number(label="变调(整数,半音数量,升八度12降八度-12)", value=0)
472
+ input_audio0 = gr.Textbox(label="输入待处理音频文件路径(默认是正确格式示例)",value="E:\codes\py39\\vits_vc_gpu_train\\todo-songs\冬之花clip1.wav")
473
+ f0method0=gr.Radio(label="选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比", choices=["pm","harvest"],value="pm", interactive=True)
474
+ with gr.Column():
475
+ file_index1 = gr.Textbox(label="特征检索库文件路径",value="E:\codes\py39\\vits_vc_gpu_train\logs\mi-test-1key\\added_IVF677_Flat_nprobe_7.index", interactive=True)
476
+ file_big_npy1 = gr.Textbox(label="特征文件路径",value="E:\codes\py39\\vits_vc_gpu_train\logs\mi-test-1key\\total_fea.npy", interactive=True)
477
+ index_rate1 = gr.Slider(minimum=0, maximum=1,label='检索特征占比', value=1,interactive=True)
478
+ f0_file = gr.File(label="F0曲线文件,可选,一行一个音高,代替默认F0及升降调")
479
+ but0=gr.Button("转换", variant="primary")
480
+ with gr.Column():
481
+ vc_output1 = gr.Textbox(label="输出信息")
482
+ vc_output2 = gr.Audio(label="输出音频(右下角三个点,点了可以下载)")
483
+ but0.click(vc_single, [spk_item, input_audio0, vc_transform0,f0_file,f0method0,file_index1,file_big_npy1,index_rate1], [vc_output1, vc_output2])
484
+ with gr.Group():
485
+ gr.Markdown(value="""
486
+ 批量转换,输入待转换音频文件夹,或上传多个音频文件,在指定文件夹(默认opt)下输出转换的音频。
487
+ """)
488
+ with gr.Row():
489
+ with gr.Column():
490
+ vc_transform1 = gr.Number(label="变调(整数,半音数量,升八度12降八度-12)", value=0)
491
+ opt_input = gr.Textbox(label="指定输出文件夹",value="opt")
492
+ f0method1=gr.Radio(label="选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比", choices=["pm","harvest"],value="pm", interactive=True)
493
+ with gr.Column():
494
+ file_index2 = gr.Textbox(label="特征检索库文件路径",value="E:\codes\py39\\vits_vc_gpu_train\logs\mi-test-1key\\added_IVF677_Flat_nprobe_7.index", interactive=True)
495
+ file_big_npy2 = gr.Textbox(label="特征文件路径",value="E:\codes\py39\\vits_vc_gpu_train\logs\mi-test-1key\\total_fea.npy", interactive=True)
496
+ index_rate2 = gr.Slider(minimum=0, maximum=1,label='检索特征占比', value=1,interactive=True)
497
+ with gr.Column():
498
+ dir_input = gr.Textbox(label="输入待处理音频文件夹路径(去文件管理器地址栏拷就行了)",value="E:\codes\py39\\vits_vc_gpu_train\\todo-songs")
499
+ inputs = gr.File(file_count="multiple", label="也可批量输入音频文件,二选一,优先读文件夹")
500
+ but1=gr.Button("转换", variant="primary")
501
+ vc_output3 = gr.Textbox(label="输出信息")
502
+ but1.click(vc_multi, [spk_item, dir_input,opt_input,inputs, vc_transform1,f0method1,file_index2,file_big_npy2,index_rate2], [vc_output3])
503
+ with gr.TabItem("伴奏人声分离"):
504
+ with gr.Group():
505
+ gr.Markdown(value="""
506
+ 人声伴奏分离批量处理,使用UVR5模型。<br>
507
+ 不带和声用HP2,带和声且提取的人声不需要和声用HP5<br>
508
+ 合格的文件夹路径格式举例:E:\codes\py39\\vits_vc_gpu\白鹭霜华测试样例(去文件管理器地址栏拷就行了)
509
+ """)
510
+ with gr.Row():
511
+ with gr.Column():
512
+ dir_wav_input = gr.Textbox(label="输入待处理音频文件夹路径",value="E:\codes\py39\\vits_vc_gpu_train\\todo-songs")
513
+ wav_inputs = gr.File(file_count="multiple", label="也可批量输入音频文件,二选一,优先读文件夹")
514
+ with gr.Column():
515
+ model_choose = gr.Dropdown(label="模型", choices=uvr5_names)
516
+ opt_vocal_root = gr.Textbox(label="指定输出人声文件夹",value="opt")
517
+ opt_ins_root = gr.Textbox(label="指定输出乐器文件夹",value="opt")
518
+ but2=gr.Button("转换", variant="primary")
519
+ vc_output4 = gr.Textbox(label="输出信息")
520
+ but2.click(uvr, [model_choose, dir_wav_input,opt_vocal_root,wav_inputs,opt_ins_root], [vc_output4])
521
+ with gr.TabItem("训练"):
522
+ gr.Markdown(value="""
523
+ step1:填写实验配置。实验数据放在logs下,每个实验一个文件夹,需手工输入实验名路径,内含实验配置,日志,训练得到的模型文件。
524
+ """)
525
+ with gr.Row():
526
+ exp_dir1 = gr.Textbox(label="输入实验名",value="xxxx")
527
+ sr2 = gr.Radio(label="目标采样率", choices=["32k","40k","48k"],value="40k", interactive=True)
528
+ if_f0_3 = gr.Radio(label="模型是否带音高指导(唱歌一定要,语音可以不要)", choices=["是","否"],value="是", interactive=True)
529
+ with gr.Group():#暂时单人的,后面支持最多4人的#数据处理
530
+ gr.Markdown(value="""
531
+ step2a:自动遍历训练文件夹下所有可解码成音频的文件并进行切片归一化,在实验目录下生成2个wav文件夹;暂时只支持单人训练。
532
+ """)
533
+ with gr.Row():
534
+ trainset_dir4 = gr.Textbox(label="输入训练文件夹路径",value="E:\\xxx\\xxxxx")
535
+ spk_id5 = gr.Slider(minimum=0, maximum=4, step=1, label='请指定说话人id', value=0,interactive=True)
536
+ but1=gr.Button("处理数据", variant="primary")
537
+ info1=gr.Textbox(label="输出信息",value="")
538
+ but1.click(preprocess_dataset,[trainset_dir4,exp_dir1,sr2],[info1])
539
+ with gr.Group():
540
+ gr.Markdown(value="""
541
+ step2b:使用CPU提取音高(如果模型带音高),使用GPU提取特征(选择卡号)
542
+ """)
543
+ with gr.Row():
544
+ with gr.Column():
545
+ gpus6 = gr.Textbox(label="以-分隔输入使用的卡号,例如 0-1-2 使用卡0和卡1和卡2",value=gpus,interactive=True)
546
+ gpu_info9 = gr.Textbox(label="显卡信息",value=gpu_info)
547
+ with gr.Column():
548
+ np7 = gr.Slider(minimum=0, maximum=ncpu, step=1, label='提取音高使用的CPU进程数', value=ncpu,interactive=True)
549
+ f0method8 = gr.Radio(label="选择音高提取算法:输入歌声可用pm提速,高质量语音但CPU差可用dio提速,harvest质量更好但慢", choices=["pm", "harvest","dio"], value="harvest", interactive=True)
550
+ but2=gr.Button("特征提取", variant="primary")
551
+ info2=gr.Textbox(label="���出信息",value="",max_lines=8)
552
+ but2.click(extract_f0_feature,[gpus6,np7,f0method8,if_f0_3,exp_dir1],[info2])
553
+ with gr.Group():
554
+ gr.Markdown(value="""
555
+ step3:填写训练设置,开始训练模型和索引
556
+ """)
557
+ with gr.Row():
558
+ save_epoch10 = gr.Slider(minimum=0, maximum=50, step=1, label='保存频率save_every_epoch', value=5,interactive=True)
559
+ total_epoch11 = gr.Slider(minimum=0, maximum=100, step=1, label='总训练轮数total_epoch', value=10,interactive=True)
560
+ batch_size12 = gr.Slider(minimum=0, maximum=32, step=1, label='batch_size', value=4,interactive=True)
561
+ if_save_latest13 = gr.Radio(label="是否仅保存最新的ckpt文件以节省硬盘空间", choices=["是", "否"], value="否", interactive=True)
562
+ if_cache_gpu17 = gr.Radio(label="是否缓存所有训练集至显存。10min以下小数据可缓存以加速训练,大数据缓存会炸显存也加不了多少速", choices=["是", "否"], value="否", interactive=True)
563
+ with gr.Row():
564
+ pretrained_G14 = gr.Textbox(label="加载预训练底模G路径", value="pretrained/f0G40k.pth",interactive=True)
565
+ pretrained_D15 = gr.Textbox(label="加载预训练底模D路径", value="pretrained/f0D40k.pth",interactive=True)
566
+ sr2.change(change_sr2, [sr2,if_f0_3], [pretrained_G14,pretrained_D15])
567
+ if_f0_3.change(change_f0, [if_f0_3, sr2], [np7, f0method8, pretrained_G14, pretrained_D15])
568
+ gpus16 = gr.Textbox(label="以-分隔输入使用的卡号,例如 0-1-2 使用卡0和卡1和卡2", value=gpus,interactive=True)
569
+ but3 = gr.Button("训练模型", variant="primary")
570
+ but4 = gr.Button("训练特征索引", variant="primary")
571
+ but5 = gr.Button("一键训练", variant="primary")
572
+ info3 = gr.Textbox(label="输出信息", value="",max_lines=10)
573
+ but3.click(click_train,[exp_dir1,sr2,if_f0_3,spk_id5,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16,if_cache_gpu17],info3)
574
+ but4.click(train_index,[exp_dir1],info3)
575
+ but5.click(train1key,[exp_dir1,sr2,if_f0_3,trainset_dir4,spk_id5,gpus6,np7,f0method8,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16,if_cache_gpu17],info3)
576
+
577
+ with gr.TabItem("ckpt处理"):
578
+ with gr.Group():
579
+ gr.Markdown(value="""模型融合,可用于测试音色融合""")
580
+ with gr.Row():
581
+ ckpt_a = gr.Textbox(label="A模型路径", value="", interactive=True)
582
+ ckpt_b = gr.Textbox(label="B模型路径", value="", interactive=True)
583
+ alpha_a = gr.Slider(minimum=0, maximum=1, label='A模型权重', value=0.5, interactive=True)
584
+ with gr.Row():
585
+ sr_ = gr.Radio(label="目标采样率", choices=["32k","40k","48k"],value="40k", interactive=True)
586
+ if_f0_ = gr.Radio(label="模型是否带音高指导", choices=["是","否"],value="是", interactive=True)
587
+ info__ = gr.Textbox(label="要置入的模型信息", value="", max_lines=8, interactive=True)
588
+ name_to_save0=gr.Textbox(label="保存的模型名不带后缀", value="", max_lines=1, interactive=True)
589
+ with gr.Row():
590
+ but6 = gr.Button("融合", variant="primary")
591
+ info4 = gr.Textbox(label="输出信息", value="", max_lines=8)
592
+ but6.click(merge, [ckpt_a,ckpt_b,alpha_a,sr_,if_f0_,info__,name_to_save0], info4)#def merge(path1,path2,alpha1,sr,f0,info):
593
+ with gr.Group():
594
+ gr.Markdown(value="修改模型信息(仅支持weights文件夹下提取的小模型文件)")
595
+ with gr.Row():
596
+ ckpt_path0 = gr.Textbox(label="模型路径", value="", interactive=True)
597
+ info_=gr.Textbox(label="要改的模型信息", value="", max_lines=8, interactive=True)
598
+ name_to_save1=gr.Textbox(label="保存的文件名,默认空为和源文件同名", value="", max_lines=8, interactive=True)
599
+ with gr.Row():
600
+ but7 = gr.Button("修改", variant="primary")
601
+ info5 = gr.Textbox(label="输出信息", value="", max_lines=8)
602
+ but7.click(change_info, [ckpt_path0,info_,name_to_save1], info5)
603
+ with gr.Group():
604
+ gr.Markdown(value="查看模型信息(仅支持weights文件夹下提取的小模型文件)")
605
+ with gr.Row():
606
+ ckpt_path1 = gr.Textbox(label="模型路径", value="", interactive=True)
607
+ but8 = gr.Button("查看", variant="primary")
608
+ info6 = gr.Textbox(label="���出信息", value="", max_lines=8)
609
+ but8.click(show_info, [ckpt_path1], info6)
610
+ with gr.Group():
611
+ gr.Markdown(value="模型提取(输入logs文件夹下大文件模型路径),适用于训一半不想训了模型没有自动提取保存小文件模型,或者想测试中间模型的情况")
612
+ with gr.Row():
613
+ ckpt_path2 = gr.Textbox(label="模型路径", value="E:\codes\py39\logs\mi-test_f0_48k\\G_23333.pth", interactive=True)
614
+ save_name = gr.Textbox(label="保存名", value="", interactive=True)
615
+ sr__ = gr.Radio(label="目标采样率", choices=["32k","40k","48k"],value="40k", interactive=True)
616
+ if_f0__ = gr.Radio(label="模型是否带音高指导,1是0否", choices=["1","0"],value="1", interactive=True)
617
+ info___ = gr.Textbox(label="要置入的模型信息", value="", max_lines=8, interactive=True)
618
+ but9 = gr.Button("提取", variant="primary")
619
+ info7 = gr.Textbox(label="输出信息", value="", max_lines=8)
620
+ ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])
621
+ but9.click(extract_small_model, [ckpt_path2,save_name,sr__,if_f0__,info___], info7)
622
+
623
+ with gr.TabItem("招募音高曲线前端编辑器"):
624
+ gr.Markdown(value="""加开发群联系我647947694""")
625
+ with gr.TabItem("招募实时变声插件开发"):
626
+ gr.Markdown(value="""加开发群联系我647947694""")
627
+ with gr.TabItem("点击查看交流、问题反馈群号"):
628
+ gr.Markdown(value="""259421308""")
629
+
630
+ # app.launch(server_name="0.0.0.0",server_port=7860)
631
+ app.queue(concurrency_count=511, max_size=1022).launch(server_name="127.0.0.1",inbrowser=True,server_port=7865,quiet=True,share=True)