Blane187 commited on
Commit
b1f5bbb
1 Parent(s): 190946c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +801 -1
app.py CHANGED
@@ -1,5 +1,805 @@
1
- import gradio as gr
2
  from Apllio import *
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
 
5
 
 
 
1
  from Apllio import *
2
+ import os
3
+ import sys
4
+ from dotenv import load_dotenv
5
+
6
+ now_dir = os.getcwd()
7
+ sys.path.append(now_dir)
8
+ load_dotenv()
9
+ load_dotenv("sha256.env")
10
+
11
+ if sys.platform == "darwin":
12
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
13
+
14
+ from infer.modules.vc import VC, show_info, hash_similarity
15
+ from infer.modules.uvr5.modules import uvr
16
+ from infer.lib.train.process_ckpt import (
17
+ change_info,
18
+ extract_small_model,
19
+ merge,
20
+ )
21
+ from i18n.i18n import I18nAuto
22
+ from configs import Config
23
+ from sklearn.cluster import MiniBatchKMeans
24
+ import torch, platform
25
+ import numpy as np
26
+ import gradio as gr
27
+ import faiss
28
+ import pathlib
29
+ import json
30
+ from time import sleep
31
+ from subprocess import Popen
32
+ from random import shuffle
33
+ import warnings
34
+ import traceback
35
+ import threading
36
+ import shutil
37
+ import logging
38
+
39
+
40
+ logging.getLogger("numba").setLevel(logging.WARNING)
41
+ logging.getLogger("httpx").setLevel(logging.WARNING)
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ tmp = os.path.join(now_dir, "TEMP")
46
+ shutil.rmtree(tmp, ignore_errors=True)
47
+ os.makedirs(tmp, exist_ok=True)
48
+ os.makedirs(os.path.join(now_dir, "logs"), exist_ok=True)
49
+ os.makedirs(os.path.join(now_dir, "assets/weights"), exist_ok=True)
50
+ os.environ["TEMP"] = tmp
51
+ warnings.filterwarnings("ignore")
52
+ torch.manual_seed(114514)
53
+
54
+
55
+ config = Config()
56
+ vc = VC(config)
57
+
58
+ if not config.nocheck:
59
+ from infer.lib.rvcmd import check_all_assets, download_all_assets
60
+
61
+ if not check_all_assets(update=config.update):
62
+ if config.update:
63
+ download_all_assets(tmpdir=tmp)
64
+ if not check_all_assets(update=config.update):
65
+ logging.error("counld not satisfy all assets needed.")
66
+ exit(1)
67
+
68
+ if config.dml == True:
69
+
70
+ def forward_dml(ctx, x, scale):
71
+ ctx.scale = scale
72
+ res = x.clone().detach()
73
+ return res
74
+
75
+ import fairseq
76
+
77
+ fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml
78
+
79
+ i18n = I18nAuto()
80
+ logger.info(i18n)
81
+ # 判断是否有能用来训练和加速推理的N卡
82
+ ngpu = torch.cuda.device_count()
83
+ gpu_infos = []
84
+ mem = []
85
+ if_gpu_ok = False
86
+
87
+ if torch.cuda.is_available() or ngpu != 0:
88
+ for i in range(ngpu):
89
+ gpu_name = torch.cuda.get_device_name(i)
90
+ if any(
91
+ value in gpu_name.upper()
92
+ for value in [
93
+ "10",
94
+ "16",
95
+ "20",
96
+ "30",
97
+ "40",
98
+ "A2",
99
+ "A3",
100
+ "A4",
101
+ "P4",
102
+ "A50",
103
+ "500",
104
+ "A60",
105
+ "70",
106
+ "80",
107
+ "90",
108
+ "M4",
109
+ "T4",
110
+ "TITAN",
111
+ "4060",
112
+ "L",
113
+ "6000",
114
+ ]
115
+ ):
116
+ # A10#A100#V100#A40#P40#M40#K80#A4500
117
+ if_gpu_ok = True # 至少有一张能用的N卡
118
+ gpu_infos.append("%s\t%s" % (i, gpu_name))
119
+ mem.append(
120
+ int(
121
+ torch.cuda.get_device_properties(i).total_memory
122
+ / 1024
123
+ / 1024
124
+ / 1024
125
+ + 0.4
126
+ )
127
+ )
128
+ if if_gpu_ok and len(gpu_infos) > 0:
129
+ gpu_info = "\n".join(gpu_infos)
130
+ default_batch_size = min(mem) // 2
131
+ else:
132
+ gpu_info = i18n(
133
+ "Unfortunately, there is no compatible GPU available to support your training."
134
+ )
135
+ default_batch_size = 1
136
+ gpus = "-".join([i[0] for i in gpu_infos])
137
+
138
+
139
+ weight_root = os.getenv("weight_root")
140
+ weight_uvr5_root = os.getenv("weight_uvr5_root")
141
+ index_root = os.getenv("index_root")
142
+ outside_index_root = os.getenv("outside_index_root")
143
+
144
+ names = []
145
+ for name in os.listdir(weight_root):
146
+ if name.endswith(".pth"):
147
+ names.append(name)
148
+ index_paths = []
149
+
150
+
151
+ def lookup_indices(index_root):
152
+ global index_paths
153
+ for root, dirs, files in os.walk(index_root, topdown=False):
154
+ for name in files:
155
+ if name.endswith(".index") and "trained" not in name:
156
+ index_paths.append("%s/%s" % (root, name))
157
+
158
+
159
+ lookup_indices(index_root)
160
+ lookup_indices(outside_index_root)
161
+ uvr5_names = []
162
+ for name in os.listdir(weight_uvr5_root):
163
+ if name.endswith(".pth") or "onnx" in name:
164
+ uvr5_names.append(name.replace(".pth", ""))
165
+
166
+
167
+ def change_choices():
168
+ names = []
169
+ for name in os.listdir(weight_root):
170
+ if name.endswith(".pth"):
171
+ names.append(name)
172
+ index_paths = []
173
+ for root, dirs, files in os.walk(index_root, topdown=False):
174
+ for name in files:
175
+ if name.endswith(".index") and "trained" not in name:
176
+ index_paths.append("%s/%s" % (root, name))
177
+ return {"choices": sorted(names), "__type__": "update"}, {
178
+ "choices": sorted(index_paths),
179
+ "__type__": "update",
180
+ }
181
+
182
+
183
+ def clean():
184
+ return {"value": "", "__type__": "update"}
185
+
186
+
187
+ def export_onnx(ModelPath, ExportedPath):
188
+ from rvc.onnx import export_onnx as eo
189
+
190
+ eo(ModelPath, ExportedPath)
191
+
192
+
193
+ sr_dict = {
194
+ "32k": 32000,
195
+ "40k": 40000,
196
+ "48k": 48000,
197
+ }
198
+
199
+
200
+ def if_done(done, p):
201
+ while 1:
202
+ if p.poll() is None:
203
+ sleep(0.5)
204
+ else:
205
+ break
206
+ done[0] = True
207
+
208
+
209
+ def if_done_multi(done, ps):
210
+ while 1:
211
+ # poll==None代表进程未结束
212
+ # 只要有一个进程未结束都不停
213
+ flag = 1
214
+ for p in ps:
215
+ if p.poll() is None:
216
+ flag = 0
217
+ sleep(0.5)
218
+ break
219
+ if flag == 1:
220
+ break
221
+ done[0] = True
222
+
223
+
224
+ def preprocess_dataset(trainset_dir, exp_dir, sr, n_p):
225
+ sr = sr_dict[sr]
226
+ os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
227
+ f = open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "w")
228
+ f.close()
229
+ cmd = '"%s" infer/modules/train/preprocess.py "%s" %s %s "%s/logs/%s" %s %.1f' % (
230
+ config.python_cmd,
231
+ trainset_dir,
232
+ sr,
233
+ n_p,
234
+ now_dir,
235
+ exp_dir,
236
+ config.noparallel,
237
+ config.preprocess_per,
238
+ )
239
+ logger.info("Execute: " + cmd)
240
+ # , stdin=PIPE, stdout=PIPE,stderr=PIPE,cwd=now_dir
241
+ p = Popen(cmd, shell=True)
242
+ # 煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
243
+ done = [False]
244
+ threading.Thread(
245
+ target=if_done,
246
+ args=(
247
+ done,
248
+ p,
249
+ ),
250
+ ).start()
251
+ while 1:
252
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
253
+ yield (f.read())
254
+ sleep(1)
255
+ if done[0]:
256
+ break
257
+ with open("%s/logs/%s/preprocess.log" % (now_dir, exp_dir), "r") as f:
258
+ log = f.read()
259
+ logger.info(log)
260
+ yield log
261
+
262
+
263
+ # but2.click(extract_f0,[gpus6,np7,f0method8,if_f0_3,trainset_dir4],[info2])
264
+ def extract_f0_feature(gpus, n_p, f0method, if_f0, exp_dir, version19, gpus_rmvpe):
265
+ gpus = gpus.split("-")
266
+ os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
267
+ f = open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "w")
268
+ f.close()
269
+ if if_f0:
270
+ if f0method != "rmvpe_gpu":
271
+ cmd = (
272
+ '"%s" infer/modules/train/extract/extract_f0_print.py "%s/logs/%s" %s %s'
273
+ % (
274
+ config.python_cmd,
275
+ now_dir,
276
+ exp_dir,
277
+ n_p,
278
+ f0method,
279
+ )
280
+ )
281
+ logger.info("Execute: " + cmd)
282
+ p = Popen(
283
+ cmd, shell=True, cwd=now_dir
284
+ ) # , stdin=PIPE, stdout=PIPE,stderr=PIPE
285
+ # 煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
286
+ done = [False]
287
+ threading.Thread(
288
+ target=if_done,
289
+ args=(
290
+ done,
291
+ p,
292
+ ),
293
+ ).start()
294
+ else:
295
+ if gpus_rmvpe != "-":
296
+ gpus_rmvpe = gpus_rmvpe.split("-")
297
+ leng = len(gpus_rmvpe)
298
+ ps = []
299
+ for idx, n_g in enumerate(gpus_rmvpe):
300
+ cmd = (
301
+ '"%s" infer/modules/train/extract/extract_f0_rmvpe.py %s %s %s "%s/logs/%s" %s '
302
+ % (
303
+ config.python_cmd,
304
+ leng,
305
+ idx,
306
+ n_g,
307
+ now_dir,
308
+ exp_dir,
309
+ config.is_half,
310
+ )
311
+ )
312
+ logger.info("Execute: " + cmd)
313
+ p = Popen(
314
+ cmd, shell=True, cwd=now_dir
315
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
316
+ ps.append(p)
317
+ # 煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
318
+ done = [False]
319
+ threading.Thread(
320
+ target=if_done_multi, #
321
+ args=(
322
+ done,
323
+ ps,
324
+ ),
325
+ ).start()
326
+ else:
327
+ cmd = (
328
+ config.python_cmd
329
+ + ' infer/modules/train/extract/extract_f0_rmvpe_dml.py "%s/logs/%s" '
330
+ % (
331
+ now_dir,
332
+ exp_dir,
333
+ )
334
+ )
335
+ logger.info("Execute: " + cmd)
336
+ p = Popen(
337
+ cmd, shell=True, cwd=now_dir
338
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
339
+ p.wait()
340
+ done = [True]
341
+ while 1:
342
+ with open(
343
+ "%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r"
344
+ ) as f:
345
+ yield (f.read())
346
+ sleep(1)
347
+ if done[0]:
348
+ break
349
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
350
+ log = f.read()
351
+ logger.info(log)
352
+ yield log
353
+ # 对不同part分别开多进程
354
+ """
355
+ n_part=int(sys.argv[1])
356
+ i_part=int(sys.argv[2])
357
+ i_gpu=sys.argv[3]
358
+ exp_dir=sys.argv[4]
359
+ os.environ["CUDA_VISIBLE_DEVICES"]=str(i_gpu)
360
+ """
361
+ leng = len(gpus)
362
+ ps = []
363
+ for idx, n_g in enumerate(gpus):
364
+ cmd = (
365
+ '"%s" infer/modules/train/extract_feature_print.py %s %s %s %s "%s/logs/%s" %s %s'
366
+ % (
367
+ config.python_cmd,
368
+ config.device,
369
+ leng,
370
+ idx,
371
+ n_g,
372
+ now_dir,
373
+ exp_dir,
374
+ version19,
375
+ config.is_half,
376
+ )
377
+ )
378
+ logger.info("Execute: " + cmd)
379
+ p = Popen(
380
+ cmd, shell=True, cwd=now_dir
381
+ ) # , shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir
382
+ ps.append(p)
383
+ # 煞笔gr, popen read都非得全跑完了再一次性读取, 不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读
384
+ done = [False]
385
+ threading.Thread(
386
+ target=if_done_multi,
387
+ args=(
388
+ done,
389
+ ps,
390
+ ),
391
+ ).start()
392
+ while 1:
393
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
394
+ yield (f.read())
395
+ sleep(1)
396
+ if done[0]:
397
+ break
398
+ with open("%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir), "r") as f:
399
+ log = f.read()
400
+ logger.info(log)
401
+ yield log
402
+
403
+
404
+ def get_pretrained_models(path_str, f0_str, sr2):
405
+ if_pretrained_generator_exist = os.access(
406
+ "assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), os.F_OK
407
+ )
408
+ if_pretrained_discriminator_exist = os.access(
409
+ "assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), os.F_OK
410
+ )
411
+ if not if_pretrained_generator_exist:
412
+ logger.warning(
413
+ "assets/pretrained%s/%sG%s.pth not exist, will not use pretrained model",
414
+ path_str,
415
+ f0_str,
416
+ sr2,
417
+ )
418
+ if not if_pretrained_discriminator_exist:
419
+ logger.warning(
420
+ "assets/pretrained%s/%sD%s.pth not exist, will not use pretrained model",
421
+ path_str,
422
+ f0_str,
423
+ sr2,
424
+ )
425
+ return (
426
+ (
427
+ "assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2)
428
+ if if_pretrained_generator_exist
429
+ else ""
430
+ ),
431
+ (
432
+ "assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2)
433
+ if if_pretrained_discriminator_exist
434
+ else ""
435
+ ),
436
+ )
437
+
438
+
439
+ def change_sr2(sr2, if_f0_3, version19):
440
+ path_str = "" if version19 == "v1" else "_v2"
441
+ f0_str = "f0" if if_f0_3 else ""
442
+ return get_pretrained_models(path_str, f0_str, sr2)
443
+
444
+
445
+ def change_version19(sr2, if_f0_3, version19):
446
+ path_str = "" if version19 == "v1" else "_v2"
447
+ if sr2 == "32k" and version19 == "v1":
448
+ sr2 = "40k"
449
+ to_return_sr2 = (
450
+ {"choices": ["40k", "48k"], "__type__": "update", "value": sr2}
451
+ if version19 == "v1"
452
+ else {"choices": ["40k", "48k", "32k"], "__type__": "update", "value": sr2}
453
+ )
454
+ f0_str = "f0" if if_f0_3 else ""
455
+ return (
456
+ *get_pretrained_models(path_str, f0_str, sr2),
457
+ to_return_sr2,
458
+ )
459
+
460
+
461
+ def change_f0(if_f0_3, sr2, version19): # f0method8,pretrained_G14,pretrained_D15
462
+ path_str = "" if version19 == "v1" else "_v2"
463
+ return (
464
+ {"visible": if_f0_3, "__type__": "update"},
465
+ {"visible": if_f0_3, "__type__": "update"},
466
+ *get_pretrained_models(path_str, "f0" if if_f0_3 == True else "", sr2),
467
+ )
468
+
469
+
470
+ # but3.click(click_train,[exp_dir1,sr2,if_f0_3,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16])
471
+ def click_train(
472
+ exp_dir1,
473
+ sr2,
474
+ if_f0_3,
475
+ spk_id5,
476
+ save_epoch10,
477
+ total_epoch11,
478
+ batch_size12,
479
+ if_save_latest13,
480
+ pretrained_G14,
481
+ pretrained_D15,
482
+ gpus16,
483
+ if_cache_gpu17,
484
+ if_save_every_weights18,
485
+ version19,
486
+ author,
487
+ ):
488
+ # 生成filelist
489
+ exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
490
+ os.makedirs(exp_dir, exist_ok=True)
491
+ gt_wavs_dir = "%s/0_gt_wavs" % (exp_dir)
492
+ feature_dir = (
493
+ "%s/3_feature256" % (exp_dir)
494
+ if version19 == "v1"
495
+ else "%s/3_feature768" % (exp_dir)
496
+ )
497
+ if if_f0_3:
498
+ f0_dir = "%s/2a_f0" % (exp_dir)
499
+ f0nsf_dir = "%s/2b-f0nsf" % (exp_dir)
500
+ names = (
501
+ set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)])
502
+ & set([name.split(".")[0] for name in os.listdir(feature_dir)])
503
+ & set([name.split(".")[0] for name in os.listdir(f0_dir)])
504
+ & set([name.split(".")[0] for name in os.listdir(f0nsf_dir)])
505
+ )
506
+ else:
507
+ names = set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)]) & set(
508
+ [name.split(".")[0] for name in os.listdir(feature_dir)]
509
+ )
510
+ opt = []
511
+ for name in names:
512
+ if if_f0_3:
513
+ opt.append(
514
+ "%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"
515
+ % (
516
+ gt_wavs_dir.replace("\\", "\\\\"),
517
+ name,
518
+ feature_dir.replace("\\", "\\\\"),
519
+ name,
520
+ f0_dir.replace("\\", "\\\\"),
521
+ name,
522
+ f0nsf_dir.replace("\\", "\\\\"),
523
+ name,
524
+ spk_id5,
525
+ )
526
+ )
527
+ else:
528
+ opt.append(
529
+ "%s/%s.wav|%s/%s.npy|%s"
530
+ % (
531
+ gt_wavs_dir.replace("\\", "\\\\"),
532
+ name,
533
+ feature_dir.replace("\\", "\\\\"),
534
+ name,
535
+ spk_id5,
536
+ )
537
+ )
538
+ fea_dim = 256 if version19 == "v1" else 768
539
+ if if_f0_3:
540
+ for _ in range(2):
541
+ opt.append(
542
+ "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s/logs/mute/2a_f0/mute.wav.npy|%s/logs/mute/2b-f0nsf/mute.wav.npy|%s"
543
+ % (now_dir, sr2, now_dir, fea_dim, now_dir, now_dir, spk_id5)
544
+ )
545
+ else:
546
+ for _ in range(2):
547
+ opt.append(
548
+ "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s"
549
+ % (now_dir, sr2, now_dir, fea_dim, spk_id5)
550
+ )
551
+ shuffle(opt)
552
+ with open("%s/filelist.txt" % exp_dir, "w") as f:
553
+ f.write("\n".join(opt))
554
+ logger.debug("Write filelist done")
555
+ logger.info("Use gpus: %s", str(gpus16))
556
+ if pretrained_G14 == "":
557
+ logger.info("No pretrained Generator")
558
+ if pretrained_D15 == "":
559
+ logger.info("No pretrained Discriminator")
560
+ if version19 == "v1" or sr2 == "40k":
561
+ config_path = "v1/%s.json" % sr2
562
+ else:
563
+ config_path = "v2/%s.json" % sr2
564
+ config_save_path = os.path.join(exp_dir, "config.json")
565
+ if not pathlib.Path(config_save_path).exists():
566
+ with open(config_save_path, "w", encoding="utf-8") as f:
567
+ json.dump(
568
+ config.json_config[config_path],
569
+ f,
570
+ ensure_ascii=False,
571
+ indent=4,
572
+ sort_keys=True,
573
+ )
574
+ f.write("\n")
575
+ cmd = (
576
+ '"%s" infer/modules/train/train.py -e "%s" -sr %s -f0 %s -bs %s -te %s -se %s %s %s -l %s -c %s -sw %s -v %s -a "%s"'
577
+ % (
578
+ config.python_cmd,
579
+ exp_dir1,
580
+ sr2,
581
+ 1 if if_f0_3 else 0,
582
+ batch_size12,
583
+ total_epoch11,
584
+ save_epoch10,
585
+ '-pg "%s"' % pretrained_G14 if pretrained_G14 != "" else "",
586
+ '-pd "%s"' % pretrained_D15 if pretrained_D15 != "" else "",
587
+ 1 if if_save_latest13 == i18n("Yes") else 0,
588
+ 1 if if_cache_gpu17 == i18n("Yes") else 0,
589
+ 1 if if_save_every_weights18 == i18n("Yes") else 0,
590
+ version19,
591
+ author,
592
+ )
593
+ )
594
+ if gpus16:
595
+ cmd += ' -g "%s"' % (gpus16)
596
+
597
+ logger.info("Execute: " + cmd)
598
+ p = Popen(cmd, shell=True, cwd=now_dir)
599
+ p.wait()
600
+ return "Training complete. You can check the training logs in the console or the 'train.log' file under the experiment folder."
601
+
602
+
603
+ # but4.click(train_index, [exp_dir1], info3)
604
+ def train_index(exp_dir1, version19):
605
+ # exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
606
+ exp_dir = "logs/%s" % (exp_dir1)
607
+ os.makedirs(exp_dir, exist_ok=True)
608
+ feature_dir = (
609
+ "%s/3_feature256" % (exp_dir)
610
+ if version19 == "v1"
611
+ else "%s/3_feature768" % (exp_dir)
612
+ )
613
+ if not os.path.exists(feature_dir):
614
+ return "请先进行特征提取!"
615
+ listdir_res = list(os.listdir(feature_dir))
616
+ if len(listdir_res) == 0:
617
+ return "请先进行特征提取!"
618
+ infos = []
619
+ npys = []
620
+ for name in sorted(listdir_res):
621
+ phone = np.load("%s/%s" % (feature_dir, name))
622
+ npys.append(phone)
623
+ big_npy = np.concatenate(npys, 0)
624
+ big_npy_idx = np.arange(big_npy.shape[0])
625
+ np.random.shuffle(big_npy_idx)
626
+ big_npy = big_npy[big_npy_idx]
627
+ if big_npy.shape[0] > 2e5:
628
+ infos.append("Trying doing kmeans %s shape to 10k centers." % big_npy.shape[0])
629
+ yield "\n".join(infos)
630
+ try:
631
+ big_npy = (
632
+ MiniBatchKMeans(
633
+ n_clusters=10000,
634
+ verbose=True,
635
+ batch_size=256 * config.n_cpu,
636
+ compute_labels=False,
637
+ init="random",
638
+ )
639
+ .fit(big_npy)
640
+ .cluster_centers_
641
+ )
642
+ except:
643
+ info = traceback.format_exc()
644
+ logger.info(info)
645
+ infos.append(info)
646
+ yield "\n".join(infos)
647
+
648
+ np.save("%s/total_fea.npy" % exp_dir, big_npy)
649
+ n_ivf = min(int(16 * np.sqrt(big_npy.shape[0])), big_npy.shape[0] // 39)
650
+ infos.append("%s,%s" % (big_npy.shape, n_ivf))
651
+ yield "\n".join(infos)
652
+ index = faiss.index_factory(256 if version19 == "v1" else 768, "IVF%s,Flat" % n_ivf)
653
+ # index = faiss.index_factory(256if version19=="v1"else 768, "IVF%s,PQ128x4fs,RFlat"%n_ivf)
654
+ infos.append("training")
655
+ yield "\n".join(infos)
656
+ index_ivf = faiss.extract_index_ivf(index) #
657
+ index_ivf.nprobe = 1
658
+ index.train(big_npy)
659
+ faiss.write_index(
660
+ index,
661
+ "%s/trained_IVF%s_Flat_nprobe_%s_%s_%s.index"
662
+ % (exp_dir, n_ivf, index_ivf.nprobe, exp_dir1, version19),
663
+ )
664
+ infos.append("adding")
665
+ yield "\n".join(infos)
666
+ batch_size_add = 8192
667
+ for i in range(0, big_npy.shape[0], batch_size_add):
668
+ index.add(big_npy[i : i + batch_size_add])
669
+ index_save_path = "%s/added_IVF%s_Flat_nprobe_%s_%s_%s.index" % (
670
+ exp_dir,
671
+ n_ivf,
672
+ index_ivf.nprobe,
673
+ exp_dir1,
674
+ version19,
675
+ )
676
+ faiss.write_index(index, index_save_path)
677
+ infos.append(i18n("Successfully built index into") + " " + index_save_path)
678
+ link_target = "%s/%s_IVF%s_Flat_nprobe_%s_%s_%s.index" % (
679
+ outside_index_root,
680
+ exp_dir1,
681
+ n_ivf,
682
+ index_ivf.nprobe,
683
+ exp_dir1,
684
+ version19,
685
+ )
686
+ try:
687
+ link = os.link if platform.system() == "Windows" else os.symlink
688
+ link(index_save_path, link_target)
689
+ infos.append(i18n("Link index to outside folder") + " " + link_target)
690
+ except:
691
+ infos.append(
692
+ i18n("Link index to outside folder")
693
+ + " "
694
+ + link_target
695
+ + " "
696
+ + i18n("Fail")
697
+ )
698
+
699
+ # faiss.write_index(index, '%s/added_IVF%s_Flat_FastScan_%s.index'%(exp_dir,n_ivf,version19))
700
+ # infos.append("成功构建索引,added_IVF%s_Flat_FastScan_%s.index"%(n_ivf,version19))
701
+ yield "\n".join(infos)
702
+
703
+
704
+ # 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)
705
+ def train1key(
706
+ exp_dir1,
707
+ sr2,
708
+ if_f0_3,
709
+ trainset_dir4,
710
+ spk_id5,
711
+ np7,
712
+ f0method8,
713
+ save_epoch10,
714
+ total_epoch11,
715
+ batch_size12,
716
+ if_save_latest13,
717
+ pretrained_G14,
718
+ pretrained_D15,
719
+ gpus16,
720
+ if_cache_gpu17,
721
+ if_save_every_weights18,
722
+ version19,
723
+ gpus_rmvpe,
724
+ author,
725
+ ):
726
+ infos = []
727
+
728
+ def get_info_str(strr):
729
+ infos.append(strr)
730
+ return "\n".join(infos)
731
+
732
+ # step1:Process data
733
+ yield get_info_str(i18n("Step 1: Processing data"))
734
+ [get_info_str(_) for _ in preprocess_dataset(trainset_dir4, exp_dir1, sr2, np7)]
735
+
736
+ # step2a:提取音高
737
+ yield get_info_str(i18n("step2:Pitch extraction & feature extraction"))
738
+ [
739
+ get_info_str(_)
740
+ for _ in extract_f0_feature(
741
+ gpus16, np7, f0method8, if_f0_3, exp_dir1, version19, gpus_rmvpe
742
+ )
743
+ ]
744
+
745
+ # step3a:Train model
746
+ yield get_info_str(i18n("Step 3a: Model training started"))
747
+ click_train(
748
+ exp_dir1,
749
+ sr2,
750
+ if_f0_3,
751
+ spk_id5,
752
+ save_epoch10,
753
+ total_epoch11,
754
+ batch_size12,
755
+ if_save_latest13,
756
+ pretrained_G14,
757
+ pretrained_D15,
758
+ gpus16,
759
+ if_cache_gpu17,
760
+ if_save_every_weights18,
761
+ version19,
762
+ author,
763
+ )
764
+ yield get_info_str(
765
+ i18n(
766
+ "Training complete. You can check the training logs in the console or the 'train.log' file under the experiment folder."
767
+ )
768
+ )
769
+
770
+ # step3b:训练索引
771
+ [get_info_str(_) for _ in train_index(exp_dir1, version19)]
772
+ yield get_info_str(i18n("All processes have been completed!"))
773
+
774
+
775
+ # ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])
776
+ def change_info_(ckpt_path):
777
+ if not os.path.exists(ckpt_path.replace(os.path.basename(ckpt_path), "train.log")):
778
+ return {"__type__": "update"}, {"__type__": "update"}, {"__type__": "update"}
779
+ try:
780
+ with open(
781
+ ckpt_path.replace(os.path.basename(ckpt_path), "train.log"), "r"
782
+ ) as f:
783
+ info = eval(f.read().strip("\n").split("\n")[0].split("\t")[-1])
784
+ sr, f0 = info["sample_rate"], info["if_f0"]
785
+ version = "v2" if ("version" in info and info["version"] == "v2") else "v1"
786
+ return sr, str(f0), version
787
+ except:
788
+ traceback.print_exc()
789
+ return {"__type__": "update"}, {"__type__": "update"}, {"__type__": "update"}
790
+
791
+
792
+ F0GPUVisible = config.dml == False
793
+
794
+
795
+ def change_f0_method(f0method8):
796
+ if f0method8 == "rmvpe_gpu":
797
+ visible = F0GPUVisible
798
+ else:
799
+ visible = False
800
+ return {"visible": visible, "__type__": "update"}
801
+
802
+
803
 
804
 
805