-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Expand file tree
/
Copy pathwebui.py
More file actions
2026 lines (1902 loc) · 73.6 KB
/
Copy pathwebui.py
File metadata and controls
2026 lines (1902 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import shutil
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("no_proxy", "localhost, 127.0.0.1, ::1")
os.environ.setdefault("weight_root", "assets/weights")
os.environ.setdefault("weight_uvr5_root", "assets/uvr5_weights")
os.environ.setdefault("index_root", "logs")
os.environ.setdefault("outside_index_root", "assets/indices")
os.environ.setdefault("rmvpe_root", "assets/rmvpe")
now_dir = os.getcwd()
tmp = os.path.join(now_dir, "TEMP")
os.makedirs(tmp, exist_ok=True)
os.environ["TEMP"] = tmp
for name in os.listdir(tmp):
if name == "jieba.cache":
continue
path = os.path.join(tmp, name)
delete = (
os.remove if os.path.isfile(path) or os.path.islink(path) else shutil.rmtree
)
try:
delete(path)
except Exception as error:
print(str(error))
from configs.config import Config, GPU_INDEX, GPU_INFOS, GPU_MEMORY, IS_GPU
from infer.vc.modules import VC
from tools.uvr5.webui import uvr
from tools.file_io import read_text
from train.process_ckpt import (
change_info,
extract_small_model,
merge,
show_info,
)
from i18n.i18n import I18nAuto
import torch, platform
import numpy as np
import gradio as gr
import pathlib
import json
from time import sleep
from subprocess import Popen
from random import shuffle
import warnings
import traceback
import threading
import logging
import signal
import socket
import subprocess
import time
logging.getLogger("numba").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
def find_available_port(start_port, host="0.0.0.0"):
"""Return the first bindable TCP port at or above ``start_port``."""
if not 1 <= start_port <= 65535:
raise ValueError(f"Port must be between 1 and 65535, got {start_port}.")
for port in range(start_port, 65536):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((host, port))
return port
except OSError:
continue
raise OSError(
f"No available TCP port from {start_port} through 65535; WebUI was not started."
)
def is_gradio_port_in_use_error(error, port):
"""Recognize Gradio's explicit-port conflict without hiding other launch errors."""
return str(error).startswith(f"Port {port} is in use.")
def launch_webui_with_port_fallback(app, config):
"""Launch Gradio, increasing the requested port until startup succeeds."""
next_port = config.listen_port
queued_app = app.queue(concurrency_count=511, max_size=1022)
while True:
config.listen_port = find_available_port(next_port)
if config.listen_port != next_port:
logger.warning(
"Port %s is occupied; trying port %s instead.",
next_port,
config.listen_port,
)
try:
queued_app.launch(
server_name="0.0.0.0",
inbrowser=not config.noautoopen,
server_port=config.listen_port,
quiet=True,
)
return config.listen_port
except OSError as error:
if not is_gradio_port_in_use_error(error, config.listen_port):
raise
if config.listen_port == 65535:
raise OSError(
"No available TCP port through 65535; WebUI was not started."
) from error
logger.warning(
"Port %s became occupied while Gradio was starting; trying the next port.",
config.listen_port,
)
next_port = config.listen_port + 1
runtime_dirs = (
os.path.join(now_dir, "logs"),
os.environ["weight_root"],
os.environ["weight_uvr5_root"],
os.environ["index_root"],
os.environ["outside_index_root"],
os.environ["rmvpe_root"],
os.path.join(now_dir, "assets", "hubert_base"),
os.path.join(now_dir, "assets", "pretrained"),
os.path.join(now_dir, "assets", "pretrained_v2"),
)
for runtime_dir in runtime_dirs:
os.makedirs(runtime_dir, exist_ok=True)
warnings.filterwarnings("ignore")
torch.manual_seed(114514)
config = Config()
vc = VC(config)
i18n = I18nAuto()
logger.info(i18n)
print(
i18n("当前设备:%s | 推理精度:%s") % (config.device, config.dtype),
flush=True,
)
cuda_graph_status = os.environ.get("RVC_CUDA_GRAPH", "0")
print(f"RVC_CUDA_GRAPH={cuda_graph_status}", flush=True)
logger.info("RVC_CUDA_GRAPH=%s", cuda_graph_status)
# GPU filtering and precision rules are shared with inference/extraction/training.
gpu_infos = list(GPU_INFOS)
gpu_indices = sorted(GPU_INDEX)
if_gpu_ok = IS_GPU
if if_gpu_ok:
gpu_info = "\n".join(gpu_infos)
default_batch_size = max(1, int(min(GPU_MEMORY[i] for i in gpu_indices)) // 2)
else:
gpu_info = i18n("很遗憾您这没有能用的显卡来支持您训练")
default_batch_size = 1
gpus = "-".join(str(i) for i in gpu_indices)
class ToolButton(gr.Button, gr.components.FormComponent):
"""Small button with single emoji as text, fits inside gradio forms"""
def __init__(self, **kwargs):
super().__init__(variant="tool", **kwargs)
def get_block_name(self):
return "button"
weight_root = os.getenv("weight_root")
weight_uvr5_root = os.getenv("weight_uvr5_root")
outside_index_root = os.getenv("outside_index_root")
def weight_names():
return sorted(
name for name in os.listdir(weight_root) if name.endswith(".pth")
)
def refresh_weight_choices(previous_names=None, force=False):
current_names = tuple(weight_names())
if force or current_names != previous_names:
return current_names, change_choices()
return current_names, {"__type__": "update"}
names = weight_names()
uvr5_names = []
for name in os.listdir(weight_uvr5_root):
if name.endswith((".pth", ".ckpt")) or "onnx" in name:
uvr5_names.append(name.replace(".pth", "").replace(".ckpt", ""))
uvr5_names.sort()
def change_choices():
return {"choices": weight_names(), "__type__": "update"}
def clean():
return {"value": "", "__type__": "update"}
sr_dict = {
"32k": 32000,
"40k": 40000,
"48k": 48000,
}
TRAIN_TASK_LOCK = threading.Lock()
TRAIN_TASK = None
def button_update(value=None, variant=None, visible=None):
update = {"__type__": "update"}
if value is not None:
update["value"] = value
if variant is not None:
update["variant"] = variant
if visible is not None:
update["visible"] = visible
return update
def format_status(title, state, detail=""):
lines = ["【%s】" % i18n(title), "%s:%s" % (i18n("状态"), i18n(state))]
if detail:
lines.extend(["", detail.strip()])
return "\n".join(lines)
def format_workflow_status(step, detail="", completed_steps=None, state="运行中"):
completed_steps = completed_steps or []
detail = str(detail).strip()
lines = []
if completed_steps:
lines.append("%s:" % i18n("已完成阶段"))
lines.extend(
"✓ %s:%s" % (i18n(completed_step), i18n("已成功"))
for completed_step in completed_steps
)
if step:
if lines:
lines.append("")
lines.append("%s:%s" % (i18n("当前阶段"), i18n(step)))
if detail:
lines.extend(["", detail])
return format_status(
"一键训练",
state,
"\n".join(lines),
)
def read_log(path, max_lines=40):
try:
lines = [line.rstrip() for line in read_text(path, errors="ignore").splitlines()]
lines = [line for line in lines if line.strip()]
if len(lines) > max_lines:
tail_count = max(0, max_lines - 1)
omitted = len(lines) - tail_count
tail = lines[-tail_count:] if tail_count else []
lines = [i18n("……已省略前%s行,仅显示最新状态") % omitted]
lines.extend(tail)
return "\n".join(lines)
except FileNotFoundError:
return ""
def artifact_names(directory, suffix):
if not os.path.isdir(directory):
return set()
return {
name.split(".")[0]
for name in os.listdir(directory)
if name.lower().endswith(suffix)
}
def validate_preprocess_outputs(exp_dir):
exp_path = os.path.join(now_dir, "logs", exp_dir)
gt_names = artifact_names(os.path.join(exp_path, "0_gt_wavs"), ".wav")
wav16_names = artifact_names(os.path.join(exp_path, "1_16k_wavs"), ".wav")
if not gt_names:
raise RuntimeError(i18n("数据切分没有生成有效训练音频,请检查训练集和数据切分日志"))
if not wav16_names:
raise RuntimeError(i18n("数据切分没有生成16k音频,已停止后续特征提取和训练"))
if not gt_names & wav16_names:
raise RuntimeError(i18n("数据切分输出文件不匹配,已停止后续特征提取和训练"))
def validate_feature_outputs(exp_dir, version, if_f0):
exp_path = os.path.join(now_dir, "logs", exp_dir)
wav16_names = artifact_names(os.path.join(exp_path, "1_16k_wavs"), ".wav")
feature_name = "3_feature256" if version == "v1" else "3_feature768"
feature_names = artifact_names(os.path.join(exp_path, feature_name), ".npy")
matched = wav16_names & feature_names
if not feature_names or not matched:
raise RuntimeError(i18n("HuBERT特征提取没有生成有效结果,已停止训练"))
if if_f0:
f0_names = artifact_names(os.path.join(exp_path, "2a_f0"), ".npy")
f0nsf_names = artifact_names(os.path.join(exp_path, "2b-f0nsf"), ".npy")
matched &= f0_names & f0nsf_names
if not f0_names or not f0nsf_names or not matched:
raise RuntimeError(i18n("F0提取没有生成有效结果,已停止训练"))
return matched
def kill_process(process, process_name=""):
if process is None or process.poll() is not None:
return
pid = process.pid
if platform.system() == "Windows":
subprocess.run(
"taskkill /t /f /pid %s" % pid,
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
else:
try:
os.killpg(os.getpgid(pid), signal.SIGTERM)
except (OSError, ProcessLookupError):
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
for _ in range(10):
if process.poll() is not None:
break
time.sleep(0.1)
if process.poll() is None:
try:
os.killpg(os.getpgid(pid), signal.SIGKILL)
except (OSError, ProcessLookupError):
pass
logger.info(i18n("%s进程已终止") % i18n(process_name))
def begin_train_task(name):
global TRAIN_TASK
with TRAIN_TASK_LOCK:
if TRAIN_TASK is None:
state = {
"name": name,
"processes": [],
"stop_requested": False,
}
TRAIN_TASK = state
return "start", state
return "busy", TRAIN_TASK
def stop_train_task(name):
with TRAIN_TASK_LOCK:
if TRAIN_TASK is None:
return (
format_status(name, "未运行"),
button_update(visible=True),
button_update(visible=False),
)
if TRAIN_TASK["name"] != name:
return (
format_status(
name,
"无法停止",
i18n("%s运行中,请先停止该任务") % i18n(TRAIN_TASK["name"]),
),
button_update(),
button_update(),
)
state = TRAIN_TASK
state["stop_requested"] = True
processes = list(state["processes"])
for process in processes:
kill_process(process, name)
return (
format_status(name, "已停止"),
button_update(visible=True),
button_update(visible=False),
)
def finish_train_task(state):
global TRAIN_TASK
with TRAIN_TASK_LOCK:
if TRAIN_TASK is state:
TRAIN_TASK = None
def train_task_stopped(state):
with TRAIN_TASK_LOCK:
return state["stop_requested"]
def start_train_process(state, cmd):
kwargs = {"shell": True, "cwd": now_dir}
if "train/train.py" in cmd.replace("\\", "/"):
training_env = os.environ.copy()
training_env["RVC_CUDA_GRAPH"] = "0"
kwargs["env"] = training_env
if platform.system() == "Windows":
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
kwargs["start_new_session"] = True
logger.info("%s: %s", i18n("执行命令"), cmd)
process = Popen(cmd, **kwargs)
with TRAIN_TASK_LOCK:
state["processes"].append(process)
stopped = state["stop_requested"]
if stopped:
kill_process(process, state["name"])
return process
def wait_train_processes(
state,
processes,
log_path=None,
title="任务",
format_output=True,
watch_weights=False,
):
last_snapshot = None
last_emit_time = 0
last_weight_names = tuple(weight_names()) if watch_weights else ()
while any(process.poll() is None for process in processes):
if train_task_stopped(state):
for process in processes:
kill_process(process, state["name"])
break
if log_path:
snapshot = read_log(log_path)
current_time = time.monotonic()
current_weight_names = tuple(weight_names()) if watch_weights else ()
weights_changed = watch_weights and current_weight_names != last_weight_names
if (
snapshot != last_snapshot
or weights_changed
or current_time - last_emit_time >= 5
):
yield (
format_status(title, "运行中", snapshot)
if format_output
else snapshot
)
last_snapshot = snapshot
last_emit_time = current_time
last_weight_names = current_weight_names
sleep(1)
with TRAIN_TASK_LOCK:
for process in processes:
if process in state["processes"]:
state["processes"].remove(process)
if log_path:
final_state = "已停止" if train_task_stopped(state) else "正在收尾"
snapshot = read_log(log_path)
yield (
format_status(title, final_state, snapshot)
if format_output
else snapshot
)
if not train_task_stopped(state):
failed = [process.returncode for process in processes if process.returncode != 0]
if failed:
raise RuntimeError(i18n("子进程执行失败,返回码:%s") % failed)
def run_preprocess_dataset(trainset_dir, exp_dir, sr, n_p, state, format_output=True):
sr = sr_dict[sr]
os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
log_path = "%s/logs/%s/preprocess.log" % (now_dir, exp_dir)
with open(log_path, "w", encoding="utf8"):
pass
cmd = '"%s" train/preprocess.py "%s" %s %s "%s/logs/%s" %s %.1f' % (
config.python_cmd,
trainset_dir,
sr,
n_p,
now_dir,
exp_dir,
config.noparallel,
config.preprocess_per,
)
process = start_train_process(state, cmd)
yield from wait_train_processes(
state, [process], log_path, "数据切分", format_output
)
if not train_task_stopped(state):
validate_preprocess_outputs(exp_dir)
def preprocess_dataset(trainset_dir, exp_dir, sr, n_p):
action, state = begin_train_task("数据切分")
if action == "busy":
yield (
format_status(
"数据切分",
"等待中",
i18n("%s运行中,请先停止该任务") % i18n(state["name"]),
),
button_update(),
button_update(),
)
return
final_info = None
try:
yield (
format_status("数据切分", "正在启动"),
button_update(visible=False),
button_update(visible=True),
)
for info in run_preprocess_dataset(trainset_dir, exp_dir, sr, n_p, state):
yield info, button_update(visible=False), button_update(visible=True)
if train_task_stopped(state):
final_info = format_status("数据切分", "已停止")
except Exception:
final_info = format_status("数据切分", "失败", traceback.format_exc())
finally:
finish_train_task(state)
if final_info is None:
final_info = format_status("数据切分", "已完成")
yield final_info, button_update(visible=True), button_update(visible=False)
def stop_preprocess_dataset():
return stop_train_task("数据切分")
# but2.click(extract_f0,[gpus6,np7,f0method8,if_f0_3,trainset_dir4],[info2])
def run_extract_f0_feature(
gpus,
n_p,
f0method,
if_f0,
exp_dir,
version19,
gpus_rmvpe,
state,
format_output=True,
):
if f0method not in ("pm", "rmvpe"):
raise ValueError(i18n("仅支持pm和rmvpe音高提取算法"))
log_path = "%s/logs/%s/extract_f0_feature.log" % (now_dir, exp_dir)
os.makedirs("%s/logs/%s" % (now_dir, exp_dir), exist_ok=True)
validate_preprocess_outputs(exp_dir)
with open(log_path, "w", encoding="utf8"):
pass
if if_f0:
processes = []
rmvpe_devices = [gpu for gpu in gpus_rmvpe.split("-") if gpu != ""]
if f0method == "pm" or (
f0method == "rmvpe" and not rmvpe_devices and not config.dml
):
cmd = (
'"%s" train/dataset/extract_f0.py cpu "%s/logs/%s" %s %s'
% (config.python_cmd, now_dir, exp_dir, n_p, f0method)
)
processes.append(start_train_process(state, cmd))
elif rmvpe_devices:
count = len(rmvpe_devices)
for index, gpu in enumerate(rmvpe_devices):
cmd = (
'"%s" train/dataset/extract_f0.py cuda %s %s %s "%s/logs/%s" %s'
% (
config.python_cmd,
count,
index,
gpu,
now_dir,
exp_dir,
config.is_half,
)
)
processes.append(start_train_process(state, cmd))
else:
cmd = (
'"%s" train/dataset/extract_f0.py dml "%s/logs/%s"'
% (config.python_cmd, now_dir, exp_dir)
)
processes.append(start_train_process(state, cmd))
yield from wait_train_processes(
state, processes, log_path, "F0提取", format_output
)
if train_task_stopped(state):
return
with open(log_path, "w", encoding="utf8"):
pass
feature_gpus = [gpu for gpu in gpus.split("-") if gpu != ""]
processes = []
if feature_gpus:
count = len(feature_gpus)
for index, gpu in enumerate(feature_gpus):
cmd = (
'"%s" train/dataset/extract_hubert_feature.py %s %s %s %s "%s/logs/%s" %s %s'
% (
config.python_cmd,
config.device,
count,
index,
gpu,
now_dir,
exp_dir,
version19,
config.is_half,
)
)
processes.append(start_train_process(state, cmd))
else:
cmd = (
'"%s" train/dataset/extract_hubert_feature.py %s 1 0 "%s/logs/%s" %s %s'
% (
config.python_cmd,
config.device,
now_dir,
exp_dir,
version19,
config.is_half,
)
)
processes.append(start_train_process(state, cmd))
yield from wait_train_processes(
state, processes, log_path, "HuBERT特征", format_output
)
if not train_task_stopped(state):
validate_feature_outputs(exp_dir, version19, if_f0)
def extract_f0_feature(gpus, n_p, f0method, if_f0, exp_dir, version19, gpus_rmvpe):
action, state = begin_train_task("特征提取")
if action == "busy":
yield (
format_status(
"特征提取",
"等待中",
i18n("%s运行中,请先停止该任务") % i18n(state["name"]),
),
button_update(),
button_update(),
)
return
final_info = None
try:
yield (
format_status("特征提取", "正在启动"),
button_update(visible=False),
button_update(visible=True),
)
for info in run_extract_f0_feature(
gpus, n_p, f0method, if_f0, exp_dir, version19, gpus_rmvpe, state
):
yield info, button_update(visible=False), button_update(visible=True)
if train_task_stopped(state):
final_info = format_status("特征提取", "已停止")
except Exception:
final_info = format_status("特征提取", "失败", traceback.format_exc())
finally:
finish_train_task(state)
if final_info is None:
final_info = format_status("特征提取", "已完成")
yield final_info, button_update(visible=True), button_update(visible=False)
def stop_extract_f0_feature():
return stop_train_task("特征提取")
def get_pretrained_models(path_str, f0_str, sr2):
if_pretrained_generator_exist = os.access(
"assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2), os.F_OK
)
if_pretrained_discriminator_exist = os.access(
"assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2), os.F_OK
)
if not if_pretrained_generator_exist:
logger.warning(
i18n("生成器预训练模型不存在,将不使用:assets/pretrained%s/%sG%s.pth"),
path_str,
f0_str,
sr2,
)
if not if_pretrained_discriminator_exist:
logger.warning(
i18n("判别器预训练模型不存在,将不使用:assets/pretrained%s/%sD%s.pth"),
path_str,
f0_str,
sr2,
)
return (
(
"assets/pretrained%s/%sG%s.pth" % (path_str, f0_str, sr2)
if if_pretrained_generator_exist
else ""
),
(
"assets/pretrained%s/%sD%s.pth" % (path_str, f0_str, sr2)
if if_pretrained_discriminator_exist
else ""
),
)
def change_sr2(sr2, if_f0_3, version19):
path_str = "" if version19 == "v1" else "_v2"
f0_str = "f0" if if_f0_3 else ""
return get_pretrained_models(path_str, f0_str, sr2)
def change_version19(sr2, if_f0_3, version19):
path_str = "" if version19 == "v1" else "_v2"
if sr2 == "32k" and version19 == "v1":
sr2 = "40k"
to_return_sr2 = (
{"choices": ["40k", "48k"], "__type__": "update", "value": sr2}
if version19 == "v1"
else {"choices": ["40k", "48k", "32k"], "__type__": "update", "value": sr2}
)
f0_str = "f0" if if_f0_3 else ""
return (
*get_pretrained_models(path_str, f0_str, sr2),
to_return_sr2,
)
def change_f0(if_f0_3, sr2, version19): # f0method8,pretrained_G14,pretrained_D15
path_str = "" if version19 == "v1" else "_v2"
return (
{"visible": if_f0_3, "__type__": "update"},
{"visible": if_f0_3, "__type__": "update"},
*get_pretrained_models(path_str, "f0" if if_f0_3 == True else "", sr2),
)
# but3.click(click_train,[exp_dir1,sr2,if_f0_3,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16])
def run_train_model(
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,
if_save_every_weights18,
version19,
state,
format_output=True,
):
# 生成filelist
exp_dir = "%s/logs/%s" % (now_dir, exp_dir1)
os.makedirs(exp_dir, exist_ok=True)
gt_wavs_dir = "%s/0_gt_wavs" % (exp_dir)
feature_dir = (
"%s/3_feature256" % (exp_dir)
if version19 == "v1"
else "%s/3_feature768" % (exp_dir)
)
if if_f0_3:
f0_dir = "%s/2a_f0" % (exp_dir)
f0nsf_dir = "%s/2b-f0nsf" % (exp_dir)
names = (
set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)])
& set([name.split(".")[0] for name in os.listdir(feature_dir)])
& set([name.split(".")[0] for name in os.listdir(f0_dir)])
& set([name.split(".")[0] for name in os.listdir(f0nsf_dir)])
)
else:
names = set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)]) & set(
[name.split(".")[0] for name in os.listdir(feature_dir)]
)
if not names:
raise RuntimeError(i18n("没有可用于训练的有效音频,请先完成数据切分和特征提取"))
opt = []
for name in names:
if if_f0_3:
opt.append(
"%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"
% (
gt_wavs_dir.replace("\\", "\\\\"),
name,
feature_dir.replace("\\", "\\\\"),
name,
f0_dir.replace("\\", "\\\\"),
name,
f0nsf_dir.replace("\\", "\\\\"),
name,
spk_id5,
)
)
else:
opt.append(
"%s/%s.wav|%s/%s.npy|%s"
% (
gt_wavs_dir.replace("\\", "\\\\"),
name,
feature_dir.replace("\\", "\\\\"),
name,
spk_id5,
)
)
fea_dim = 256 if version19 == "v1" else 768
if if_f0_3:
for _ in range(2):
opt.append(
"%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"
% (now_dir, sr2, now_dir, fea_dim, now_dir, now_dir, spk_id5)
)
else:
for _ in range(2):
opt.append(
"%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s"
% (now_dir, sr2, now_dir, fea_dim, spk_id5)
)
shuffle(opt)
with open("%s/filelist.txt" % exp_dir, "w", encoding="utf8") as f:
f.write("\n".join(opt))
logger.debug(i18n("训练文件列表写入完成"))
# 生成config#无需生成config
# cmd = python_cmd + " 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"
logger.info(i18n("使用显卡:%s"), str(gpus16))
if pretrained_G14 == "":
logger.info(i18n("未使用生成器预训练模型"))
if pretrained_D15 == "":
logger.info(i18n("未使用判别器预训练模型"))
if version19 == "v1" or sr2 == "40k":
config_path = "v1/%s.json" % sr2
else:
config_path = "v2/%s.json" % sr2
config_save_path = os.path.join(exp_dir, "config.json")
if not pathlib.Path(config_save_path).exists():
with open(config_save_path, "w", encoding="utf8") as f:
json.dump(
config.json_config[config_path],
f,
ensure_ascii=False,
indent=4,
sort_keys=True,
)
f.write("\n")
if gpus16:
cmd = (
'"%s" train/train.py -e "%s" -sr %s -f0 %s -bs %s -g %s -te %s -se %s %s %s -l %s -c %s -sw %s -v %s'
% (
config.python_cmd,
exp_dir1,
sr2,
1 if if_f0_3 else 0,
batch_size12,
gpus16,
total_epoch11,
save_epoch10,
"-pg %s" % pretrained_G14 if pretrained_G14 != "" else "",
"-pd %s" % pretrained_D15 if pretrained_D15 != "" else "",
1 if if_save_latest13 == i18n("是") else 0,
1 if if_cache_gpu17 == i18n("是") else 0,
1 if if_save_every_weights18 == i18n("是") else 0,
version19,
)
)
else:
cmd = (
'"%s" 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'
% (
config.python_cmd,
exp_dir1,
sr2,
1 if if_f0_3 else 0,
batch_size12,
total_epoch11,
save_epoch10,
"-pg %s" % pretrained_G14 if pretrained_G14 != "" else "",
"-pd %s" % pretrained_D15 if pretrained_D15 != "" else "",
1 if if_save_latest13 == i18n("是") else 0,
1 if if_cache_gpu17 == i18n("是") else 0,
1 if if_save_every_weights18 == i18n("是") else 0,
version19,
)
)
logger.info("%s: %s", i18n("执行命令"), cmd)
process = start_train_process(state, cmd)
yield from wait_train_processes(
state,
[process],
os.path.join(exp_dir, "train.log"),
"模型训练",
format_output,
True,
)
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,
if_save_every_weights18,
version19,
):
known_models = tuple(weight_names())
action, state = begin_train_task("模型训练")
if action == "busy":
yield (
format_status(
"模型训练",
"等待中",
i18n("%s运行中,请先停止该任务") % i18n(state["name"]),
),
button_update(),
button_update(),
button_update(),
)
return
final_info = None
try:
yield (
format_status("模型训练", "正在启动"),
button_update(visible=False),
button_update(visible=True),
button_update(),
)
for info in run_train_model(
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,
if_save_every_weights18,
version19,
state,
):
known_models, model_update = refresh_weight_choices(known_models)
yield (
info,
button_update(visible=False),
button_update(visible=True),
model_update,
)
if train_task_stopped(state):
final_info = format_status("模型训练", "已停止")
except Exception:
final_info = format_status("模型训练", "失败", traceback.format_exc())
finally:
finish_train_task(state)
if final_info is None:
final_info = format_status("模型训练", "已完成")
model_update = change_choices()
yield (
final_info,
button_update(visible=True),
button_update(visible=False),
model_update,
)
def stop_train_model():
return stop_train_task("模型训练")
# but4.click(train_index, [exp_dir1], info3)
def run_train_index(exp_dir1, version19, state, format_output=True):
exp_dir = os.path.join(now_dir, "logs", exp_dir1)
os.makedirs(exp_dir, exist_ok=True)
log_path = os.path.join(exp_dir, "train_index.log")
with open(log_path, "w", encoding="utf8"):
pass
cmd = (
'"%s" train/train_index.py "%s" %s "%s" %s'
% (
config.python_cmd,
exp_dir1,
version19,
outside_index_root,
config.n_cpu,
)
)
process = start_train_process(state, cmd)
yield from wait_train_processes(