forked from svc-develop-team/so-vits-svc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
1627 lines (1483 loc) · 88 KB
/
app.py
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
# ==================================================================================
# reference from
# https://www.yuque.com/umoubuton/ueupp5/sdahi7m5m6r0ur1r#zMbpu
# ==================================================================================
import ast
import datetime
import glob
import json
import logging
import multiprocessing
import os
import re
import shutil
import subprocess
import traceback
import zipfile
from itertools import chain
from pathlib import Path
import gradio as gr
import librosa
import numpy as np
import soundfile as sf
import torch
import yaml
import utils
# from auto_slicer import AutoSlicer
from compress_model import removeOptimizer
from tools.infer.infer_tool_webui import Svc
from onnxexport.model_onnx import SynthesizerTrn
from tools.infer.tts_voices import SUPPORTED_LANGUAGES
from tools.webui.release_packing import release_packing
from utils import mix_model
os.environ["PATH"] += os.pathsep + os.path.join(os.getcwd(), "ffmpeg", "bin")
logging.getLogger('numba').setLevel(logging.WARNING)
logging.getLogger('markdown_it').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.getLogger('matplotlib').setLevel(logging.WARNING)
# Some directories
workdir = "logs/44k"
second_dir = "models"
diff_second_dir = "models/diffusion"
diff_workdir = "logs/44k/diffusion"
config_dir = "configs/"
dataset_dir = "dataset/44k"
raw_path = "dataset_raw"
raw_wavs_path = "raw"
models_backup_path = 'models_backup'
root_dir = "checkpoints"
default_settings_file = "settings.yaml"
current_mode = ""
# Some global variables
debug = False
precheck_ok = False
model = None
sovits_params = {}
diff_params = {}
# Some dicts for mapping
MODEL_TYPE = {
"vec768l12": 768,
"vec256l9": 256,
"hubertsoft": 256,
"whisper-ppg": 1024,
"cnhubertlarge": 1024,
"dphubert": 768,
"wavlmbase+": 768,
"whisper-ppg-large": 1280
}
ENCODER_PRETRAIN = {
"vec256l9": "pretrain/checkpoint_best_legacy_500.pt",
"vec768l12": "pretrain/checkpoint_best_legacy_500.pt",
"hubertsoft": "pretrain/hubert-soft-0d54a1f4.pt",
"whisper-ppg": "pretrain/medium.pt",
"cnhubertlarge": "pretrain/chinese-hubert-large-fairseq-ckpt.pt",
"dphubert": "pretrain/DPHuBERT-sp0.75.pth",
"wavlmbase+": "pretrain/WavLM-Base+.pt",
"whisper-ppg-large": "pretrain/large-v2.pt"
}
class Config:
def __init__(self, path, type):
self.path = path
self.type = type
def read(self):
if self.type == "json":
with open(self.path, 'r') as f:
return json.load(f)
if self.type == "yaml":
with open(self.path, 'r') as f:
return yaml.safe_load(f)
def save(self, content):
if self.type == "json":
with open(self.path, 'w') as f:
json.dump(content, f, indent=4)
if self.type == "yaml":
with open(self.path, 'w') as f:
yaml.safe_dump(content, f, default_flow_style=False, sort_keys=False)
class ReleasePacker:
def __init__(self, speaker, model):
self.speaker = speaker
self.model = model
self.output_path = os.path.join("release_packs", f"{speaker}_release.zip")
self.file_list = []
def remove_temp(self, path):
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
if os.path.isfile(file_path) and not filename.endswith(".zip"):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path, ignore_errors=True)
def add_file(self, file_paths):
self.file_list.extend(file_paths)
def spk_to_dict(self):
spk_string = self.speaker.replace(',', ',')
spk_string = spk_string.replace(' ', '')
_spk = spk_string.split(',')
return {_spk: index for index, _spk in enumerate(_spk)}
def generate_config(self, diff_model, config_origin):
_config_origin = Config(os.path.join(config_read_dir, config_origin), "json")
_template = Config("release_packs/config_template.json", "json")
_d_template = Config("release_packs/diffusion_template.yaml", "yaml")
orig_config = _config_origin.read()
config_template = _template.read()
diff_config_template = _d_template.read()
spk_dict = self.spk_to_dict()
_net = torch.load(os.path.join(ckpt_read_dir, self.model), map_location='cpu')
emb_dim, model_dim = _net['model'].get('emb_g.weight', torch.empty(0, 0)).size()
vol_emb = _net['model'].get('emb_vol.weight')
if vol_emb is not None:
config_template["train"]["vol_aug"] = config_template["model"]["vol_embedding"] = True
# Keep the spk_dict length same as emb_dim
if emb_dim > len(spk_dict):
for i in range(emb_dim - len(spk_dict)):
spk_dict[f"spk{i}"] = len(spk_dict)
if emb_dim < len(spk_dict):
for i in range(len(spk_dict) - emb_dim):
spk_dict.popitem()
self.speaker = ','.join(spk_dict.keys())
config_template['model']['ssl_dim'] = config_template["model"]["filter_channels"] = config_template["model"][
"gin_channels"] = model_dim
config_template['model']['n_speakers'] = diff_config_template['model']['n_spk'] = emb_dim
config_template['spk'] = diff_config_template['spk'] = spk_dict
encoder = [k for k, v in MODEL_TYPE.items() if v == model_dim]
if orig_config['model']['speech_encoder'] in encoder:
config_template['model']['speech_encoder'] = orig_config['model']['speech_encoder']
else:
raise Exception("Config is not compatible with the model")
if diff_model != "no_diff":
_diff = torch.load(os.path.join(diff_read_dir, diff_model), map_location='cpu')
_, diff_dim = _diff["model"].get("unit_embed.weight", torch.empty(0, 0)).size()
if diff_dim == 256:
diff_config_template['data']['encoder'] = 'hubertsoft'
diff_config_template['data']['encoder_out_channels'] = 256
elif diff_dim == 768:
diff_config_template['data']['encoder'] = 'vec768l12'
diff_config_template['data']['encoder_out_channels'] = 768
elif diff_dim == 1024:
diff_config_template['data']['encoder'] = 'whisper-ppg'
diff_config_template['data']['encoder_out_channels'] = 1024
with open("release_packs/install.txt", 'w') as f:
f.write(str(self.file_list) + '#' + str(self.speaker))
_template.save(config_template)
_d_template.save(diff_config_template)
def unpack(self, zip_file):
with zipfile.ZipFile(zip_file, 'r') as zipf:
zipf.extractall("release_packs")
def formatted_install(self, install_txt):
with open(install_txt, 'r') as f:
content = f.read()
file_list, speaker = content.split('#')
self.speaker = speaker
file_list = ast.literal_eval(file_list)
self.file_list = file_list
for _, target_path in self.file_list:
if target_path != "install.txt" and target_path != "":
shutil.move(os.path.join("release_packs", target_path), target_path)
self.remove_temp("release_packs")
return self.speaker
def pack(self):
with zipfile.ZipFile(self.output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for file_path, target_path in self.file_list:
if os.path.isfile(file_path):
zipf.write(file_path, arcname=target_path)
def debug_change():
global debug
debug = debug_button.value
def get_default_settings():
global sovits_params, diff_params, second_dir_enable
config_file = Config(default_settings_file, "yaml")
default_settings = config_file.read()
sovits_params = default_settings['sovits_params']
diff_params = default_settings['diff_params']
webui_settings = default_settings['webui_settings']
second_dir_enable = webui_settings['second_dir']
return sovits_params, diff_params, second_dir_enable
def webui_change(read_second_dir):
global second_dir_enable
config_file = Config(default_settings_file, "yaml")
default_settings = config_file.read()
second_dir_enable = default_settings['webui_settings']['second_dir'] = read_second_dir
config_file.save(default_settings)
def get_current_mode():
global current_mode
current_mode = "当前模式:独立目录模式,将从'./models/'读取模型文件" if second_dir_enable else "当前模式:工作目录模式,将从'./logs/44k'读取模型文件"
return current_mode
def save_default_settings(log_interval, eval_interval, keep_ckpts, batch_size, learning_rate, amp_dtype, all_in_mem,
num_workers, cache_all_data, cache_device, diff_amp_dtype, diff_batch_size, diff_lr,
diff_interval_log, diff_interval_val, diff_force_save, diff_k_step_max):
config_file = Config(default_settings_file, "yaml")
default_settings = config_file.read()
default_settings['sovits_params']['log_interval'] = int(log_interval)
default_settings['sovits_params']['eval_interval'] = int(eval_interval)
default_settings['sovits_params']['keep_ckpts'] = int(keep_ckpts)
default_settings['sovits_params']['batch_size'] = int(batch_size)
default_settings['sovits_params']['learning_rate'] = float(learning_rate)
default_settings['sovits_params']['amp_dtype'] = str(amp_dtype)
default_settings['sovits_params']['all_in_mem'] = all_in_mem
default_settings['diff_params']['num_workers'] = int(num_workers)
default_settings['diff_params']['cache_all_data'] = cache_all_data
default_settings['diff_params']['cache_device'] = str(cache_device)
default_settings['diff_params']['amp_dtype'] = str(diff_amp_dtype)
default_settings['diff_params']['diff_batch_size'] = int(diff_batch_size)
default_settings['diff_params']['diff_lr'] = float(diff_lr)
default_settings['diff_params']['diff_interval_log'] = int(diff_interval_log)
default_settings['diff_params']['diff_interval_val'] = int(diff_interval_val)
default_settings['diff_params']['diff_force_save'] = int(diff_force_save)
default_settings['diff_params']['diff_k_step_max'] = diff_k_step_max
config_file.save(default_settings)
return "成功保存默认配置"
def get_model_info(choice_ckpt):
pthfile = os.path.join(ckpt_read_dir, choice_ckpt)
net = torch.load(pthfile, map_location=torch.device('cpu')) # cpu load to avoid using gpu memory
spk_emb = net["model"].get("emb_g.weight")
if spk_emb is None:
return "所选模型缺少emb_g.weight,你可能选择了一个底模"
_layer = spk_emb.size(1)
encoder = [k for k, v in MODEL_TYPE.items() if v == _layer] # 通过维度对应编码器
encoder.sort()
if encoder == ["hubertsoft", "vec256l9"]:
encoder = ["vec256l9 / hubertsoft"]
if encoder == ["cnhubertlarge", "whisper-ppg"]:
encoder = ["whisper-ppg / cnhubertlarge"]
if encoder == ["dphubert", "vec768l12", "wavlmbase+"]:
encoder = ["vec768l12 / dphubert / wavlmbase+"]
return encoder[0]
def load_json_encoder(config_choice, choice_ckpt):
if config_choice == "no_config":
return "未启用自动加载,请手动选择配置文件"
if choice_ckpt == "no_model":
return "请先选择模型"
config_file = Config(os.path.join(config_read_dir, config_choice), "json")
config = config_file.read()
try:
# 比对配置文件中的模型维度与该encoder的实际维度是否对应,防止古神语
config_encoder = config["model"].get("speech_encoder", "no_encoder")
config_dim = config["model"]["ssl_dim"]
# 旧版配置文件自动匹配
if config_encoder == "no_encoder":
config_encoder = config["model"]["speech_encoder"] = "vec256l9" if config_dim == 256 else "vec768l12"
config_file.save(config)
correct_dim = MODEL_TYPE.get(config_encoder, "unknown")
if config_dim != correct_dim:
return "配置文件中的编码器与模型维度不匹配"
return config_encoder
except Exception as e:
return f"出错了: {e}"
def auto_load(choice_ckpt):
global second_dir_enable
model_output_msg = get_model_info(choice_ckpt)
json_output_msg = config_choice = ""
choice_ckpt_name, _ = os.path.splitext(choice_ckpt)
if second_dir_enable:
all_config = [json for json in os.listdir(second_dir) if json.endswith(".json")]
for config in all_config:
config_fname, _ = os.path.splitext(config)
if config_fname == choice_ckpt_name:
config_choice = config
json_output_msg = load_json_encoder(config, choice_ckpt)
else:
# all_config = [json for json in os.listdir(config_dir) if json=="config.json"]
config = "config.json"
if os.path.exists(os.path.join(config_read_dir, config)):
config_choice = config
json_output_msg = load_json_encoder(config_choice, choice_ckpt)
if json_output_msg != "":
return model_output_msg, config_choice, json_output_msg
else:
return model_output_msg, "no_config", ""
# else:
# return model_output_msg, "no_config", ""
def auto_load_diff(diff_model):
global second_dir_enable
if second_dir_enable is False:
return "no_diff_config"
all_diff_config = [yaml for yaml in os.listdir(second_dir) if yaml.endswith(".yaml")]
for config in all_diff_config:
config_fname, _ = os.path.splitext(config)
diff_fname, _ = os.path.splitext(diff_model)
if config_fname == diff_fname:
return config
return "no_diff_config"
def load_model_func(ckpt_name, cluster_name, config_name, enhance, diff_model_name, diff_config_name, only_diffusion,
use_spk_mix, using_device, method, speedup, cl_num):
global model
config_path = os.path.join(config_read_dir, config_name) if not only_diffusion else "configs/config.json"
diff_config_path = os.path.join(config_read_dir,
diff_config_name) if diff_config_name != "no_diff_config" else "configs/diffusion.yaml"
ckpt_path = os.path.join(ckpt_read_dir, ckpt_name)
cluster_path = os.path.join(ckpt_read_dir, cluster_name)
diff_model_path = os.path.join(diff_read_dir, diff_model_name)
k_step_max = 1000
if not only_diffusion:
config = Config(config_path, "json").read()
if diff_model_name != "no_diff":
_diff = Config(diff_config_path, "yaml")
_content = _diff.read()
diff_spk = _content.get('spk', {})
diff_spk_choice = spk_choice = next(iter(diff_spk), "未检测到音色")
if not only_diffusion:
if _content['data'].get('encoder_out_channels') != config["model"].get('ssl_dim'):
return "扩散模型维度与主模型不匹配,请确保两个模型使用的是同一个编码器", gr.Dropdown.update(choices=[],
value=""), 0, None
_content["infer"]["speedup"] = int(speedup)
_content["infer"]["method"] = str(method)
k_step_max = _content["model"].get('k_step_max', 0) if _content["model"].get('k_step_max', 0) != 0 else 1000
_diff.save(_content)
if not only_diffusion:
net = torch.load(ckpt_path, map_location=torch.device('cpu'))
# 读取模型各维度并比对,还有小可爱无视提示硬要加载底模的就返回个未初始张量
emb_dim, model_dim = net["model"].get("emb_g.weight", torch.empty(0, 0)).size()
if emb_dim > config["model"]["n_speakers"]:
return "模型说话人数量与emb维度不匹配", gr.Dropdown.update(choices=[], value=""), 0, None
if model_dim != config["model"]["ssl_dim"]:
return "配置文件与模型不匹配", gr.Dropdown.update(choices=[], value=""), 0, None
encoder = config["model"]["speech_encoder"]
spk_dict = config.get('spk', {})
spk_choice = next(iter(spk_dict), "未检测到音色")
else:
spk_dict = diff_spk
spk_choice = diff_spk_choice
fr = cluster_name.endswith(".pkl") # 如果是pkl后缀就启用特征检索
shallow_diffusion = diff_model_name != "no_diff" # 加载了扩散模型就启用浅扩散
device = cuda[using_device] if "CUDA" in using_device else using_device
model = Svc(ckpt_path,
config_path,
device=device if device != "Auto" else None,
cluster_model_path=cluster_path,
nsf_hifigan_enhance=enhance,
diffusion_model_path=diff_model_path,
diffusion_config_path=diff_config_path,
shallow_diffusion=shallow_diffusion,
only_diffusion=only_diffusion,
spk_mix_enable=use_spk_mix,
feature_retrieval=fr)
spk_list = list(spk_dict.keys())
if not only_diffusion:
clip = 25 if encoder == "whisper-ppg" or encoder == "whisper-ppg-large" else cl_num # Whisper必须强制切片25秒
device_name = torch.cuda.get_device_properties(model.dev).name if "cuda" in str(model.dev) else str(model.dev)
sovits_msg = f"模型被成功加载到了{device_name}上\n"
else:
clip = cl_num
sovits_msg = "启用全扩散推理,未加载So-VITS模型\n"
index_or_kmeans = "特征索引" if fr else "聚类模型"
clu_load = "未加载" if cluster_name == "no_clu" else cluster_name
diff_load = "未加载" if diff_model_name == "no_diff" else f"{diff_model_name} | 采样器: {method} | 加速倍数:{int(speedup)} | 最大浅扩散步数:{k_step_max}"
output_msg = f"{sovits_msg}{index_or_kmeans}:{clu_load}\n扩散模型:{diff_load}"
return (
output_msg,
gr.Dropdown.update(choices=spk_list, value=spk_choice),
clip,
gr.Slider.update(value=100 if k_step_max > 100 else k_step_max, minimum=speedup, maximum=k_step_max)
)
def model_empty_cache():
global model
if model is None:
return sid.update(choices=[], value=""), "没有模型需要卸载!"
else:
model.unload_model()
model = None
torch.cuda.empty_cache()
return sid.update(choices=[], value=""), "模型卸载完毕!"
def get_file_options(directory, extension):
return [file for file in os.listdir(directory) if file.endswith(extension)]
def load_options():
ckpt_list = [file for file in get_file_options(ckpt_read_dir, ".pth") if
not file.startswith("D_") or file == "G_0.pth"]
config_list = get_file_options(config_read_dir, ".json")
cluster_list = ["no_clu"] + get_file_options(ckpt_read_dir, ".pt") + get_file_options(ckpt_read_dir,
".pkl") # 聚类和特征检索模型
diff_list = ["no_diff"] + get_file_options(diff_read_dir, ".pt")
diff_config_list = ["no_diff_config"] + get_file_options(config_read_dir, ".yaml")
return ckpt_list, config_list, cluster_list, diff_list, diff_config_list
def refresh_options():
global ckpt_read_dir, config_read_dir, diff_read_dir, current_mode
ckpt_read_dir = second_dir if second_dir_enable else workdir
config_read_dir = second_dir if second_dir_enable else config_dir
diff_read_dir = diff_second_dir if second_dir_enable else diff_workdir
ckpt_list, config_list, cluster_list, diff_list, diff_config_list = load_options()
current_mode = get_current_mode()
return (
choice_ckpt.update(choices=ckpt_list),
config_choice.update(choices=config_list),
cluster_choice.update(choices=cluster_list),
diff_choice.update(choices=diff_list),
diff_config_choice.update(choices=diff_config_list),
mode_caption.update(value=f"""{current_mode},可在页面底端切换模式""")
)
def source_change(use_microphone):
if use_microphone:
return vc_input3.update(source="microphone")
else:
return vc_input3.update(source="upload")
def vc_infer(output_format, sid, input_audio, sr, input_audio_path, 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):
if np.issubdtype(input_audio.dtype, np.integer):
input_audio = (input_audio / np.iinfo(input_audio.dtype).max).astype(np.float32)
if len(input_audio.shape) > 1:
input_audio = librosa.to_mono(input_audio.transpose(1, 0))
if sr != 44100:
input_audio = librosa.resample(input_audio, orig_sr=sr, target_sr=44100)
sf.write("temp.wav", input_audio, 44100, format="wav")
_audio = model.slice_inference(
"temp.wav",
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()
if not os.path.exists("results"):
os.makedirs("results")
key = "auto" if auto_f0 else f"{int(vc_transform)}key"
cluster = "_" if cluster_ratio == 0 else f"_{cluster_ratio}_"
isdiffusion = "sovits"
if model.shallow_diffusion:
isdiffusion = "sovdiff"
if model.only_diffusion:
isdiffusion = "diff"
# Gradio上传的filepath因为未知原因会有一个无意义的固定后缀,这里去掉
truncated_basename = Path(input_audio_path).stem[:-6] if Path(input_audio_path).stem[-6:] == "-0-100" else Path(
input_audio_path).stem
output_file_name = f'{truncated_basename}_{sid}_{key}{cluster}{isdiffusion}.{output_format}'
output_file_path = os.path.join("results", output_file_name)
if os.path.exists(output_file_path):
count = 1
while os.path.exists(output_file_path):
output_file_name = f'{truncated_basename}_{sid}_{key}{cluster}{isdiffusion}_{str(count)}.{output_format}'
output_file_path = os.path.join("results", output_file_name)
count += 1
sf.write(output_file_path, _audio, model.target_sample, format=output_format)
return output_file_path
def vc_fn(output_format, 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, progress=gr.Progress(track_tqdm=True)):
global model
try:
if input_audio is None:
return "你还没有上传音频", None
if model is None:
return "你还没有加载模型", None
if getattr(model, 'cluster_model', None) is None and model.feature_retrieval is False:
if cluster_ratio != 0:
return "你还未加载聚类或特征检索模型,无法启用聚类/特征检索混合比例", None
audio, sr = sf.read(input_audio)
output_file_path = vc_infer(output_format, sid, audio, sr, 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)
os.remove("temp.wav")
return "Success", output_file_path
except Exception as e:
if debug:
traceback.print_exc()
raise gr.Error(e)
def vc_batch_fn(output_format, sid, input_audio_files, 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, progress=gr.Progress()):
global model
try:
if input_audio_files is None or len(input_audio_files) == 0:
return "你还没有上传音频"
if model is None:
return "你还没有加载模型"
if getattr(model, 'cluster_model', None) is None and model.feature_retrieval is False:
if cluster_ratio != 0:
return "你还未加载聚类或特征检索模型,无法启用聚类/特征检索混合比例", None
_output = []
for file_obj in progress.tqdm(input_audio_files, desc="Inferencing"):
print(f"Start processing: {file_obj.name}")
input_audio_path = file_obj.name
audio, sr = sf.read(input_audio_path)
output_file_path = vc_infer(output_format, sid, sr, audio, input_audio_path, 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)
_output.append(output_file_path)
return "批量推理完成,音频已经被保存到results文件夹"
except Exception as e:
if debug:
traceback.print_exc()
raise gr.Error(e)
def tts_fn(_text, _gender, _lang, _rate, _volume, output_format, sid, 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, progress=gr.Progress(track_tqdm=True)):
global model
try:
if model is None:
return "你还没有加载模型", None
if getattr(model, 'cluster_model', None) is None and model.feature_retrieval is False:
if cluster_ratio != 0:
return "你还未加载聚类或特征检索模型,无法启用聚类/特征检索混合比例", None
_rate = f"+{int(_rate * 100)}%" if _rate >= 0 else f"{int(_rate * 100)}%"
_volume = f"+{int(_volume * 100)}%" if _volume >= 0 else f"{int(_volume * 100)}%"
cmd = [r"python", "tools/infer/tts.py", _text, _lang, _rate, _volume]
if _lang == "Auto":
_gender = "Male" if _gender == "男" else "Female"
subprocess.run([*cmd, _gender])
else:
subprocess.run(cmd)
target_sr = 44100
y, sr = librosa.load("tts.wav")
resampled_y = librosa.resample(y, orig_sr=sr, target_sr=target_sr)
sf.write("tts.wav", resampled_y, target_sr, subtype="PCM_16")
input_audio = "tts.wav"
audio, sr = sf.read(input_audio)
output_file_path = vc_infer(output_format, sid, audio, sr, 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)
# os.remove("tts.wav")
return "Success", output_file_path
except Exception as e:
if debug:
traceback.print_exc()
raise gr.Error(e)
def load_raw_dirs():
global precheck_ok
precheck_ok = False
allowed_pattern = re.compile(r'^[a-zA-Z0-9_@#$%^&()_+\-=\s\.]*$')
illegal_files = illegal_dataset = []
for root, dirs, files in os.walk(raw_path):
for dir in dirs:
if not allowed_pattern.match(dir):
illegal_dataset.append(dir)
if illegal_dataset:
return f"数据集文件夹名只能包含数字、字母、下划线,以下文件夹不符合要求,请改名后再试:\n{illegal_dataset}"
if root != raw_path: # 只处理子文件夹内的文件
for file in files:
if not allowed_pattern.match(file) and file not in illegal_files:
illegal_files.append(file)
if not file.lower().endswith('.wav') and file not in illegal_files:
illegal_files.append(file)
if illegal_files:
return f"数据集文件名只能包含数字、字母、下划线,且必须是.wav格式,以下文件不符合要求,请改名后再试:\n{illegal_files}"
spk_dirs = [entry.name for entry in os.scandir(raw_path) if entry.is_dir()]
if spk_dirs:
precheck_ok = True
return spk_dirs
else:
return "未找到数据集,请检查dataset_raw文件夹"
def dataset_preprocess(encoder, f0_predictor, use_diff, vol_aug, skip_loudnorm, num_processes):
if precheck_ok:
diff_arg = "--use_diff" if use_diff else ""
vol_aug_arg = "--vol_aug" if vol_aug else ""
skip_loudnorm_arg = "--skip_loudnorm" if skip_loudnorm else ""
preprocess_commands = [
r".\workenv\python.exe resample.py %s" % (skip_loudnorm_arg),
r".\workenv\python.exe preprocess_flist_config.py --speech_encoder %s %s" % (encoder, vol_aug_arg),
r".\workenv\python.exe preprocess_hubert_f0.py --num_processes %s --f0_predictor %s %s" % (
num_processes, f0_predictor, diff_arg)
]
accumulated_output = ""
# 清空dataset
dataset = os.listdir(dataset_dir)
if len(dataset) != 0:
for dir in dataset:
dataset_spk_dir = os.path.join(dataset_dir, str(dir))
if os.path.isdir(dataset_spk_dir):
shutil.rmtree(dataset_spk_dir)
accumulated_output += f"Deleting previous dataset: {dir}\n"
for command in preprocess_commands:
try:
result = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True,
text=True)
accumulated_output += f"Command: {command}, Using Encoder: {encoder}, Using f0 Predictor: {f0_predictor}\n"
yield accumulated_output, None
progress_line = None
for line in result.stdout:
if r"it/s" in line or r"s/it" in line: # 防止进度条刷屏
progress_line = line
else:
accumulated_output += line
if progress_line is None:
yield accumulated_output, None
else:
yield accumulated_output + progress_line, None
result.communicate()
except subprocess.CalledProcessError as e:
result = e.output
accumulated_output += f"Error: {result}\n"
yield accumulated_output, None
if progress_line is not None:
accumulated_output += progress_line
accumulated_output += '-' * 50 + '\n'
yield accumulated_output, None
config_path = "configs/config.json"
with open(config_path, 'r') as f:
config = json.load(f)
spk_name = config.get('spk', None)
yield accumulated_output, gr.Textbox.update(value=spk_name)
else:
yield "数据集识别未通过,请先识别数据集并确保没有报错信息", None
def regenerate_config(encoder, vol_aug):
if precheck_ok is False:
return "数据集识别未通过,请检查识别结果的报错信息"
vol_aug_arg = "--vol_aug" if vol_aug else ""
cmd = r".\workenv\python.exe preprocess_flist_config.py --speech_encoder %s %s" % (encoder, vol_aug_arg)
output = ""
try:
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, text=True)
for line in result.stdout:
output += line
output += "Regenerate config file successfully."
except subprocess.CalledProcessError as e:
result = e.output
output += f"Error: {result}\n"
return output
def clear_output():
return gr.Textbox.update(value="Cleared!>_<")
def get_available_encoder():
current_pretrain = os.listdir("pretrain")
current_pretrain = [("pretrain/" + model) for model in current_pretrain]
encoder_list = []
for encoder, path in ENCODER_PRETRAIN.items():
if path in current_pretrain:
encoder_list.append(encoder)
return encoder_list
def config_fn(log_interval, eval_interval, keep_ckpts, batch_size, lr, amp_dtype, all_in_mem, diff_num_workers,
diff_cache_all_data, diff_batch_size, diff_lr, diff_interval_log, diff_interval_val, diff_cache_device,
diff_amp_dtype, diff_force_save, diff_k_step_max):
if amp_dtype == "fp16" or amp_dtype == "bf16":
fp16_run = True
else:
fp16_run = False
amp_dtype = "fp16"
config_origin = Config("configs/config.json", "json")
diff_config = Config("configs/diffusion.yaml", "yaml")
config_data = config_origin.read()
config_data['train']['log_interval'] = int(log_interval)
config_data['train']['eval_interval'] = int(eval_interval)
config_data['train']['keep_ckpts'] = int(keep_ckpts)
config_data['train']['batch_size'] = int(batch_size)
config_data['train']['learning_rate'] = float(lr)
config_data['train']['fp16_run'] = fp16_run
config_data['train']['half_type'] = str(amp_dtype)
config_data['train']['all_in_mem'] = all_in_mem
config_origin.save(config_data)
diff_config_data = diff_config.read()
diff_config_data['train']['num_workers'] = int(diff_num_workers)
diff_config_data['train']['cache_all_data'] = diff_cache_all_data
diff_config_data['train']['batch_size'] = int(diff_batch_size)
diff_config_data['train']['lr'] = float(diff_lr)
diff_config_data['train']['interval_log'] = int(diff_interval_log)
diff_config_data['train']['interval_val'] = int(diff_interval_val)
diff_config_data['train']['cache_device'] = str(diff_cache_device)
diff_config_data['train']['amp_dtype'] = str(diff_amp_dtype)
diff_config_data['train']['interval_force_save'] = int(diff_force_save)
diff_config_data['model']['k_step_max'] = 100 if diff_k_step_max else 0
diff_config.save(diff_config_data)
return "配置文件写入完成"
def check_dataset(dataset_path):
if not os.listdir(dataset_path):
return "数据集不存在,请检查dataset文件夹"
no_npy_pt_files = True
for root, dirs, files in os.walk(dataset_path):
for file in files:
if file.endswith('.npy') or file.endswith('.pt'):
no_npy_pt_files = False
break
if no_npy_pt_files:
return "数据集中未检测到f0和hubert文件,可能是预处理未完成"
return None
def training(gpu_selection, encoder):
config_file = Config("configs/config.json", "json")
config_data = config_file.read()
vol_emb = config_data["model"]["vol_embedding"]
dataset_warn = check_dataset(dataset_dir)
if dataset_warn is not None:
return dataset_warn
PRETRAIN = {
"vec256l9": ("D_0.pth", "G_0.pth", "pre_trained_model"),
"vec768l12": (
"D_0.pth", "G_0.pth", "pre_trained_model/768l12/vol_emb" if vol_emb else "pre_trained_model/768l12"),
"hubertsoft": ("D_0.pth", "G_0.pth", "pre_trained_model/hubertsoft"),
"whisper-ppg": ("D_0.pth", "G_0.pth", "pre_trained_model/whisper-ppg"),
"cnhubertlarge": ("D_0.pth", "G_0.pth", "pre_trained_model/cnhubertlarge"),
"dphubert": ("D_0.pth", "G_0.pth", "pre_trained_model/dphubert"),
"wavlmbase+": ("D_0.pth", "G_0.pth", "pre_trained_model/wavlmbase+"),
"whisper-ppg-large": ("D_0.pth", "G_0.pth", "pre_trained_model/whisper-ppg-large")
}
if encoder not in PRETRAIN:
return "未知编码器"
d_0_file, g_0_file, encoder_model_path = PRETRAIN[encoder]
d_0_path = os.path.join(encoder_model_path, d_0_file)
g_0_path = os.path.join(encoder_model_path, g_0_file)
timestamp = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')
new_backup_folder = os.path.join(models_backup_path, str(timestamp))
output_msg = ""
if os.listdir(workdir) != ['diffusion']:
os.makedirs(new_backup_folder, exist_ok=True)
for file in os.listdir(workdir):
if file != "diffusion":
shutil.move(os.path.join(workdir, file), os.path.join(new_backup_folder, file))
if os.path.isfile(g_0_path) and os.path.isfile(d_0_path):
shutil.copy(d_0_path, os.path.join(workdir, "D_0.pth"))
shutil.copy(g_0_path, os.path.join(workdir, "G_0.pth"))
output_msg += f"成功装载预训练模型,编码器:{encoder}\n"
else:
output_msg += f"{encoder}的预训练模型不存在,未装载预训练模型\n"
cmd = r"set CUDA_VISIBLE_DEVICES=%s && .\workenv\python.exe train.py -c configs/config.json -m 44k" % (
gpu_selection)
subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", cmd])
output_msg += "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
return output_msg
def continue_training(gpu_selection, encoder):
dataset_warn = check_dataset(dataset_dir)
if dataset_warn is not None:
return dataset_warn
if encoder == "":
return "请先选择预处理对应的编码器"
all_files = os.listdir(workdir)
model_files = [f for f in all_files if f.startswith('G_') and f.endswith('.pth')]
if len(model_files) == 0:
return "你还没有已开始的训练"
cmd = r"set CUDA_VISIBLE_DEVICES=%s && .\workenv\python.exe train.py -c configs/config.json -m 44k" % (
gpu_selection)
subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", cmd])
return "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
def kmeans_training(kmeans_gpu):
if not os.listdir(dataset_dir):
return "数据集不存在,请检查dataset文件夹"
cmd = r".\workenv\python.exe cluster/train_cluster.py --gpu" if kmeans_gpu else r".\workenv\python.exe cluster/train_cluster.py"
subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", cmd])
return "已经在新的终端窗口开始训练,训练聚类模型不会输出日志,CPU训练一般需要5-10分钟左右"
def index_training():
if not os.listdir(dataset_dir):
return "数据集不存在,请检查dataset文件夹"
cmd = r".\workenv\python.exe train_index.py -c configs/config.json"
subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", cmd])
return "已经在新的终端窗口开始训练"
def diff_training(encoder, k_step_max):
if not os.listdir(dataset_dir):
return "数据集不存在,请检查dataset文件夹"
timestamp = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')
new_backup_folder = os.path.join(models_backup_path, "diffusion", str(timestamp))
if len(os.listdir(diff_workdir)) != 0:
os.makedirs(new_backup_folder, exist_ok=True)
for file in os.listdir(diff_workdir):
shutil.move(os.path.join(diff_workdir, file), os.path.join(new_backup_folder, file))
DIFF_PRETRAIN = {
"768-kstepmax100": "pre_trained_model/diffusion/768l12/max100/model_0.pt",
"vec768l12": "pre_trained_model/diffusion/768l12/model_0.pt",
"hubertsoft": "pre_trained_model/diffusion/hubertsoft/model_0.pt",
"whisper-ppg": "pre_trained_model/diffusion/whisper-ppg/model_0.pt"
}
if encoder not in DIFF_PRETRAIN:
return "你所选的编码器暂时不支持训练扩散模型"
if k_step_max:
encoder = "768-kstepmax100"
diff_pretrained_model = DIFF_PRETRAIN[encoder]
shutil.copy(diff_pretrained_model, os.path.join(diff_workdir, "model_0.pt"))
subprocess.Popen(
["cmd", "/c", "start", "cmd", "/k", r".\workenv\python.exe train_diff.py -c configs/diffusion.yaml"])
output_message = "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
if encoder == "768-kstepmax100":
output_message += "\n正在进行100步深度的浅扩散训练,已加载底模"
else:
output_message += f"\n正在进行完整深度的扩散训练,编码器{encoder}"
return output_message
def diff_continue_training(encoder):
if not os.listdir(dataset_dir):
return "数据集不存在,请检查dataset文件夹"
if encoder == "":
return "请先选择预处理对应的编码器"
all_files = os.listdir(diff_workdir)
model_files = [f for f in all_files if f.endswith('.pt')]
if len(model_files) == 0:
return "你还没有已开始的训练"
subprocess.Popen(
["cmd", "/c", "start", "cmd", "/k", r".\workenv\python.exe train_diff.py -c configs/diffusion.yaml"])
return "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
def upload_mix_append_file(files, sfiles):
try:
if (sfiles is None):
file_paths = [file.name for file in files]
else:
file_paths = [file.name for file in chain(files, sfiles)]
p = {file: 100 for file in file_paths}
return file_paths, mix_model_output1.update(value=json.dumps(p, indent=2))
except Exception as e:
if debug:
traceback.print_exc()
raise gr.Error(e)
def mix_submit_click(js, mode):
try:
assert js.lstrip() != ""
modes = {"凸组合": 0, "线性组合": 1}
mode = modes[mode]
data = json.loads(js)
data = list(data.items())
model_path, mix_rate = zip(*data)
path = mix_model(model_path, mix_rate, mode)
return f"成功,文件被保存在了{path}"
except Exception as e:
if debug:
traceback.print_exc()
raise gr.Error(e)
def updata_mix_info(files):
try:
if files is None:
return mix_model_output1.update(value="")
p = {file.name: 100 for file in files}
return mix_model_output1.update(value=json.dumps(p, indent=2))
except Exception as e:
if debug:
traceback.print_exc()
raise gr.Error(e)
def pth_identify():
if not os.path.exists(root_dir):
return f"未找到{root_dir}文件夹,请先创建一个{root_dir}文件夹并按第一步流程操作"
model_dirs = [d for d in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, d))]
if not model_dirs:
return f"未在{root_dir}文件夹中找到模型文件夹,请确保每个模型和配置文件都被放置在单独的文件夹中"
valid_model_dirs = []
for path in model_dirs:
pth_files = glob.glob(f"{root_dir}/{path}/*.pth")
json_files = glob.glob(f"{root_dir}/{path}/*.json")
if len(pth_files) != 1 or len(json_files) != 1:
return f"错误: 在{root_dir}/{path}中找到了{len(pth_files)}个.pth文件和{len(json_files)}个.json文件。应当确保每个文件夹内有且只有一个.pth文件和.json文件"
valid_model_dirs.append(path)
return f"成功识别了{len(valid_model_dirs)}个模型:{valid_model_dirs}"
def onnx_export():
model_dirs = [d for d in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, d))]
try:
for path in model_dirs:
pth_files = glob.glob(f"{root_dir}/{path}/*.pth")
json_files = glob.glob(f"{root_dir}/{path}/*.json")
model_file = pth_files[0]
json_file = json_files[0]
device = torch.device("cpu")
hps = utils.get_hparams_from_file(json_file)
SVCVITS = SynthesizerTrn(
hps.data.filter_length // 2 + 1,
hps.train.segment_size // hps.data.hop_length,
**hps.model)
_ = utils.load_checkpoint(model_file, SVCVITS, None)
_ = SVCVITS.eval().to(device)
for i in SVCVITS.parameters():
i.requires_grad = False
n_frame = 10
test_hidden_unit = torch.rand(1, n_frame, 256)
test_pitch = torch.rand(1, n_frame)
test_mel2ph = torch.arange(0, n_frame, dtype=torch.int64)[
None] # torch.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).unsqueeze(0)
test_uv = torch.ones(1, n_frame, dtype=torch.float32)
test_noise = torch.randn(1, 192, n_frame)
test_sid = torch.LongTensor([0])
input_names = ["c", "f0", "mel2ph", "uv", "noise", "sid"]
output_names = ["audio", ]
onnx_file = os.path.splitext(model_file)[0] + ".onnx"
torch.onnx.export(SVCVITS,
(
test_hidden_unit.to(device),
test_pitch.to(device),
test_mel2ph.to(device),
test_uv.to(device),
test_noise.to(device),
test_sid.to(device)
),
onnx_file,
dynamic_axes={
"c": [0, 1],
"f0": [1],
"mel2ph": [1],
"uv": [1],
"noise": [2],
},
do_constant_folding=False,
opset_version=16,
verbose=False,